Skip to content

Commit 1f3cb53

Browse files
authored
Merge pull request #14 from scijava/scijava/scijava-ops-demo/init
Initialize Ops Howtos
2 parents 0458b28 + b9dedb1 commit 1f3cb53

5 files changed

Lines changed: 295 additions & 48 deletions

File tree

imagej/imagej-ops2-tutorial/docs/OpCurrency.md renamed to imagej/imagej-ops2-tutorial/docs/OpBestPractices.md

Lines changed: 71 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,71 @@
1-
# Writing Small, Easy, Modular Ops
1+
# Best Practices When Writing Ops
22

3-
SciJava Ops is designed for modularity, extensibility, and granularity - by writing your Ops on the smallest functional elements possible, you'll allow SciJava Ops to lift your Op to new image types, enable parallelism, and more without any additional effort!
3+
SciJava Ops is designed for modularity, extensibility, and granularity - you can exploit these aspects by adhering to the following guidelines when writing Ops:
4+
5+
## Using Dependencies
6+
7+
If you are writing an Op that performs many intermediate operations, there's a good chance someone else has written (and even optimized) some or all of them.
8+
9+
If not there's a great chance that others would benefit from you writing them separately so that they can reuse your work!
10+
11+
To accomodate this separation, Ops can reuse other Ops by declaring Op dependencies. When Ops returns an instance of your Op, it will also find and instantiate all of your dependencies!
12+
13+
To illustrate how this might work, here's a trivial example of an Op that computes the mean of a `double[]`:
14+
15+
```java
16+
17+
import org.scijava.ops.spi.OpDependency;
18+
19+
/**
20+
* A simple mean calculator
21+
*
22+
* @implNote op names="stats.mean"
23+
*/
24+
class DoubleMeanOp implements Function<double[], Double> {
25+
26+
@OpDependency(name="stats.sum")
27+
public Function<double[], Double> sumOp;
28+
29+
@OpDependency(name="stats.size")
30+
public Function<double[], Double> sizeOp;
31+
32+
public Double apply(final double[] inArray) {
33+
final Double sum = sumOp.apply(inArray);
34+
final Double size = sizeOp.apply(inArray);
35+
return sum / size;
36+
}
37+
}
38+
```
39+
In this example, the two `OpDependency` Ops already exist within the SciJava Ops Engine module - but if they didn't, you'd define them just like any other Op:
40+
41+
```java
42+
/**
43+
* A simple summer
44+
*
45+
* @implNote op names="stats.sum"
46+
*/
47+
class DoubleSumOp implements Function<double[], Double> {
48+
public Double apply(final double[] inArray) {
49+
double sum = 0;
50+
for (double v : inArray) {
51+
sum += v;
52+
}
53+
return i;
54+
}
55+
}
56+
57+
/**
58+
* A simple size calculator
59+
*
60+
* @implNote op names="stats.size"
61+
*/
62+
class DoubleSizeOp implements Function<double[], Double> {
63+
public Double apply(final double[] inArray) {
64+
return inArray.length;
65+
}
66+
}
67+
68+
```
469

570
## Element-wise Ops
671

@@ -13,10 +78,11 @@ Simple pixel-wise operations like addition, inversion, and more can be written o
1378
* @implNote op names="pixel.op"
1479
*/
1580
class <T extends RealType<T>> MyPixelwiseOp implements Computers.Arity2<T, T, T> {
81+
1682
@Override
17-
public void compute(final T in1, final T in2, final T out) {
18-
... pixelwise computation here ...
19-
}
83+
public void compute(final T in1, final T in2, final T out) {
84+
... pixelwise computation here ...
85+
}
2086
}
2187
```
2288

@@ -81,46 +147,3 @@ ArrayImg<DoubleType> output = ...
81147

82148
ops.op("neighborhood.op").arity2().input(input, shape).output(output).compute()
83149
```
84-
85-
## Using dependencies
86-
87-
Even when your Op must be run on entire Images, you can use Op Dependencies to promote extensibility, reusability and flexibility.
88-
89-
For example, if your Op must iterate over some algorithm n times, consider internalizing the algorithm within a separate Op, and make it a depedency, like shown below:
90-
91-
```java
92-
import org.scijava.ops.spi.OpDependency;
93-
94-
95-
/**
96-
* An Op that needs to run on the whole image
97-
*
98-
* @implNote op names="iterating.op"
99-
*/
100-
class<I, O> MultiPassOp implements Computers.Arity1<Img<I>,Img<O>>{
101-
102-
@OpDependency(name = "internal.Op")
103-
private final Computers.Arity1<Img<I>, Img<O>> iteration;
104-
105-
@Override
106-
public void compute(final Img<I> input, final Img<O> container){
107-
for(int i=0; i < numItrs; i++){
108-
iteration.compute(input, container);
109-
}
110-
}
111-
112-
}
113-
114-
/**
115-
* An Op that executes a single iteration of some iterative process
116-
* @implNote op names="internal.Op"
117-
*/
118-
class<I, O> IterationOp implements Computers.Arity1<Img<I>,Img<O>>{
119-
120-
@Override
121-
public void compute(final Img<I> input, final Img<O> container){
122-
...perform an iteration...
123-
}
124-
125-
}
126-
```

‎imagej/imagej-ops2-tutorial/src/main/java/module-info.java‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,12 @@
6161

6262
provides org.scijava.ops.spi.OpCollection with
6363
net.imagej.ops2.tutorial.OpAdaptation,
64+
net.imagej.ops2.tutorial.OpDependencies,
6465
net.imagej.ops2.tutorial.OpParallelization,
66+
net.imagej.ops2.tutorial.OpPriorities,
6567
net.imagej.ops2.tutorial.OpReduction,
6668
net.imagej.ops2.tutorial.OpSimplification,
6769
net.imagej.ops2.tutorial.ReportingProgress,
70+
net.imagej.ops2.tutorial.UsingNils,
6871
net.imagej.ops2.tutorial.WritingOpCollections;
6972
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
2+
package net.imagej.ops2.tutorial;
3+
4+
import java.util.Arrays;
5+
import java.util.function.Function;
6+
7+
import org.scijava.ops.api.OpEnvironment;
8+
import org.scijava.ops.spi.OpCollection;
9+
import org.scijava.ops.spi.OpDependency;
10+
import org.scijava.ops.spi.OpMethod;
11+
12+
/**
13+
* A simple showcase of an Op that uses an {@link OpDependency}. Using
14+
* {@link OpDependency}s to break up your code into simple, reusable blocks, Ops
15+
* become more modular and enable specialization for unseen types.
16+
*
17+
* @author Gabriel Selzer
18+
*/
19+
public class OpDependencies implements OpCollection {
20+
21+
/**
22+
* An Op that computes the size of a {@link double[]}
23+
*/
24+
@OpMethod(names = "stats.size", type = Function.class)
25+
public static double size(final double[] inArray) {
26+
return inArray.length;
27+
}
28+
29+
/**
30+
* An Op that computes the sum of a {@link double[]}
31+
*/
32+
@OpMethod(names = "stats.sum", type = Function.class)
33+
public static double sum(final double[] inArray) {
34+
return Arrays.stream(inArray).sum();
35+
}
36+
37+
/**
38+
* An Op that computes the mean of a {@link double[]}
39+
*/
40+
@OpMethod(names = "stats.mean", type = Function.class)
41+
public static double mean( //
42+
@OpDependency(name = "stats.sum") Function<double[], Double> sumOp, //
43+
@OpDependency(name = "stats.size") Function<double[], Double> sizeOp, //
44+
final double[] inArray)
45+
{
46+
return sumOp.apply(inArray) / sizeOp.apply(inArray);
47+
}
48+
49+
public static void main(String... args) {
50+
OpEnvironment ops = OpEnvironment.getEnvironment();
51+
// The mean of this array is 3.0
52+
double[] arr = {1.0, 2.0, 3.0, 4.0, 5.0};
53+
54+
// Note that we call only deal with the "stats.mean" Op - the Engine takes care of matching the dependencies for us!
55+
double mean = ops.unary("stats.mean").input(arr).outType(Double.class).apply();
56+
57+
System.out.println("The mean of array " + Arrays.toString(arr) + " is " + mean);
58+
59+
60+
}
61+
62+
}
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
/*-
2+
* #%L
3+
* ImageJ1 software for multidimensional image processing and analysis.
4+
* %%
5+
* Copyright (C) 2013 - 2023 ImageJ2 developers.
6+
* %%
7+
* Redistribution and use in source and binary forms, with or without
8+
* modification, are permitted provided that the following conditions are met:
9+
*
10+
* 0. Redistributions of source code must retain the above copyright notice,
11+
* this list of conditions and the following disclaimer.
12+
* 1. Redistributions in binary form must reproduce the above copyright notice,
13+
* this list of conditions and the following disclaimer in the documentation
14+
* and/or other materials provided with the distribution.
15+
*
16+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
20+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26+
* POSSIBILITY OF SUCH DAMAGE.
27+
* #L%
28+
*/
29+
30+
package net.imagej.ops2.tutorial;
31+
32+
import java.util.ArrayList;
33+
import java.util.Arrays;
34+
import java.util.List;
35+
import java.util.SortedSet;
36+
import java.util.TreeSet;
37+
import java.util.function.Function;
38+
39+
import org.scijava.ops.api.OpEnvironment;
40+
import org.scijava.ops.spi.OpCollection;
41+
import org.scijava.ops.spi.OpField;
42+
import org.scijava.priority.Priority;
43+
44+
/**
45+
* A tutorial showing how you can use Op priorities to implement Ops that take
46+
* precedence over others in certain scenarios
47+
*
48+
* @author Gabriel Selzer
49+
*/
50+
public class OpPriorities implements OpCollection {
51+
52+
@OpField(names = "tutorial.priority")
53+
public final Function<Iterable<Integer>, String> iterableFunc = //
54+
n -> {
55+
int max = Integer.MIN_VALUE;
56+
for (Integer object : n) {
57+
if (object > max) max = object;
58+
}
59+
return "This maximum (Iterable Op): " + max;
60+
};
61+
62+
@OpField(names = "tutorial.priority", priority = Priority.HIGH)
63+
public final Function<SortedSet<Integer>, String> listFunc = //
64+
n -> "This maximum (SortedSet Op): " + n.last();
65+
66+
/**
67+
* Many algorithms are able to achieve performance improvements on a
68+
* particular task by making some assumptions. For example, we might write a
69+
* baseline "maximum" Op that works on java.lang.Iterable, which covers a lot
70+
* of types, but we could do a lot better a TreeSet by using the
71+
* SortedSet.last() method. Thus, we can write two different Ops, and get
72+
* different outputs depending on whether the input is a SortedSet or
73+
* something else.
74+
*/
75+
public static void main(String... args) {
76+
OpEnvironment ops = OpEnvironment.getEnvironment();
77+
// Say we have a Collection of numbers
78+
var ourNumbers = Arrays.asList(4, 8, 2, 3);
79+
80+
// ArrayList is not a SortedSet, so it will use our Iterable Op
81+
List<Integer> list = new ArrayList<>(ourNumbers);
82+
String resultForAllIterables = ops.unary("tutorial.priority") //
83+
.input(list) //
84+
.outType(String.class) //
85+
.apply();
86+
System.out.println(resultForAllIterables);
87+
88+
// TreeSet is a SortedSet, so it could use both our Iterable Op and our
89+
// SortedSet Op. The SortedSet Op doesn't have to loop through the data, so
90+
// we want to use that one for performance. To do that, we set the priority
91+
// of that Op higher!
92+
TreeSet<Integer> set = new TreeSet<>(ourNumbers);
93+
String resultForATreeSet = ops.unary("tutorial.priority") //
94+
.input(set) //
95+
.outType(String.class) //
96+
.apply();
97+
System.out.println(resultForATreeSet);
98+
}
99+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
2+
package net.imagej.ops2.tutorial;
3+
4+
import org.scijava.function.Producer;
5+
import org.scijava.ops.api.OpEnvironment;
6+
import org.scijava.ops.spi.OpCollection;
7+
import org.scijava.ops.spi.OpField;
8+
import org.scijava.types.Nil;
9+
10+
import net.imglib2.img.Img;
11+
import net.imglib2.img.array.ArrayImgs;
12+
import net.imglib2.type.numeric.integer.UnsignedByteType;
13+
import net.imglib2.type.numeric.real.DoubleType;
14+
15+
/**
16+
* ImageJ Ops2 allows users to take advantage of the strong type safety of the
17+
* Java language, which can provide benefits in certainty and efficiency. The
18+
* downside of this is verbosity, especially in obtaining generically-typed
19+
* outputs from OpBuilder calls.
20+
* <p>
21+
* Luckily, SciJava Ops allows you to specify the generic types of outputs using
22+
* the {@link Nil} type, as shown in this tutorial.
23+
*
24+
* @author Gabriel Selzer
25+
*/
26+
public class UsingNils implements OpCollection {
27+
28+
/**
29+
* This Op returns a 10x10 image of unsigned bytes
30+
*/
31+
@OpField(names = "tutorial.nils")
32+
public final Producer<Img<UnsignedByteType>> imgOfBytes = //
33+
() -> ArrayImgs.unsignedBytes(10, 10);
34+
35+
/**
36+
* This Op returns a 10x10 image of doubles
37+
*/
38+
@OpField(names = "tutorial.nils")
39+
public final Producer<Img<DoubleType>> imgOfDoubles = //
40+
() -> ArrayImgs.doubles(10, 10);
41+
42+
public static void main(String... args) {
43+
OpEnvironment ops = OpEnvironment.getEnvironment();
44+
45+
// The following is the syntax used to create a Nil that encodes the type we
46+
// want. Namely, if we want to ensure that the return is an Img<DoubleType>,
47+
// we put that type as the generic type of the Nil:
48+
Nil<Img<DoubleType>> outType = new Nil<>() {};
49+
50+
// By passing a Nil as the output type, instead of as a class, we guarantee
51+
// the generic typing of the output. Note that the Nil allows us to
52+
// differentiate between the two Ops above, one of which would instead
53+
// return an ArrayImg of unsigned bytes.
54+
Img<DoubleType> out = ops.nullary("tutorial.nils").outType(outType)
55+
.create();
56+
57+
System.out.println("Found an image " + out + " of doubles!");
58+
}
59+
60+
}

0 commit comments

Comments
 (0)