forked from bigdataviewer/bigdataviewer-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
N5GenericImageLoader.java
383 lines (349 loc) · 13.3 KB
/
N5GenericImageLoader.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
/*
* #%L
* BigDataViewer core classes with minimal dependencies
* %%
* Copyright (C) 2012 - 2016 Tobias Pietzsch, Stephan Saalfeld, Stephan Preibisch,
* Jean-Yves Tinevez, HongKee Moon, Johannes Schindelin, Curtis Rueden, John Bogovic
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package bdv.img.n5;
import bdv.AbstractViewerSetupImgLoader;
import bdv.ViewerImgLoader;
import bdv.cache.CacheControl;
import bdv.img.cache.SimpleCacheArrayLoader;
import bdv.img.cache.VolatileGlobalCellCache;
import bdv.util.ConstantRandomAccessible;
import bdv.util.MipmapTransforms;
import mpicbg.spim.data.generic.sequence.AbstractSequenceDescription;
import mpicbg.spim.data.generic.sequence.BasicViewSetup;
import mpicbg.spim.data.generic.sequence.ImgLoaderHint;
import mpicbg.spim.data.sequence.MultiResolutionImgLoader;
import mpicbg.spim.data.sequence.MultiResolutionSetupImgLoader;
import mpicbg.spim.data.sequence.VoxelDimensions;
import net.imglib2.*;
import net.imglib2.cache.queue.BlockingFetchQueues;
import net.imglib2.cache.queue.FetcherThreads;
import net.imglib2.cache.volatiles.CacheHints;
import net.imglib2.cache.volatiles.LoadingStrategy;
import net.imglib2.img.basictypeaccess.volatiles.array.*;
import net.imglib2.img.cell.CellGrid;
import net.imglib2.img.cell.CellImg;
import net.imglib2.realtransform.AffineTransform3D;
import net.imglib2.type.NativeType;
import net.imglib2.type.numeric.integer.*;
import net.imglib2.type.numeric.real.DoubleType;
import net.imglib2.type.numeric.real.FloatType;
import net.imglib2.type.volatiles.*;
import net.imglib2.util.Cast;
import net.imglib2.view.Views;
import org.janelia.saalfeldlab.n5.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.function.Function;
import static bdv.img.n5.BdvN5Format.*;
public class N5GenericImageLoader implements ViewerImgLoader, MultiResolutionImgLoader
{
private N5Reader n5;
// TODO: it would be good if this would not be needed
// find available setups from the n5
private final AbstractSequenceDescription< ?, ?, ? > seq;
/**
* Maps setup id to {@link SetupImgLoader}.
*/
private final Map< Integer, SetupImgLoader > setupImgLoaders = new HashMap<>();
public N5GenericImageLoader( final N5Reader n5, final AbstractSequenceDescription< ?, ?, ? > sequenceDescription )
{
this.n5 = n5;
this.seq = sequenceDescription;
}
private volatile boolean isOpen = false;
private FetcherThreads fetchers;
private VolatileGlobalCellCache cache;
private void open()
{
if ( !isOpen )
{
synchronized ( this )
{
if ( isOpen )
return;
try
{
int maxNumLevels = 0;
final List< ? extends BasicViewSetup > setups = seq.getViewSetupsOrdered();
for ( final BasicViewSetup setup : setups )
{
final int setupId = setup.getId();
final SetupImgLoader setupImgLoader = createSetupImgLoader( setupId );
setupImgLoaders.put( setupId, setupImgLoader );
maxNumLevels = Math.max( maxNumLevels, setupImgLoader.numMipmapLevels() );
}
final int numFetcherThreads = Math.max( 1, Runtime.getRuntime().availableProcessors() );
final BlockingFetchQueues< Callable< ? > > queue = new BlockingFetchQueues<>( maxNumLevels, numFetcherThreads );
fetchers = new FetcherThreads( queue, numFetcherThreads );
cache = new VolatileGlobalCellCache( queue );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
isOpen = true;
}
}
}
/**
* Clear the cache. Images that were obtained from
* this loader before {@link #close()} will stop working. Requesting images
* after {@link #close()} will cause the n5 to be reopened (with a
* new cache).
*/
public void close()
{
if ( isOpen )
{
synchronized ( this )
{
if ( !isOpen )
return;
fetchers.shutdown();
cache.clearCache();
isOpen = false;
}
}
}
@Override
public SetupImgLoader getSetupImgLoader( final int setupId )
{
open();
return setupImgLoaders.get( setupId );
}
private < T extends NativeType< T >, V extends Volatile< T > & NativeType< V > > SetupImgLoader< T, V > createSetupImgLoader( final int setupId ) throws IOException
{
final String pathName = getPathName( setupId );
final DataType dataType = n5.getAttribute( pathName, DATA_TYPE_KEY, DataType.class );
switch ( dataType )
{
case UINT8:
return Cast.unchecked( new SetupImgLoader<>( setupId, new UnsignedByteType(), new VolatileUnsignedByteType() ) );
case UINT16:
return Cast.unchecked( new SetupImgLoader<>( setupId, new UnsignedShortType(), new VolatileUnsignedShortType() ) );
case UINT32:
return Cast.unchecked( new SetupImgLoader<>( setupId, new UnsignedIntType(), new VolatileUnsignedIntType() ) );
case UINT64:
return Cast.unchecked( new SetupImgLoader<>( setupId, new UnsignedLongType(), new VolatileUnsignedLongType() ) );
case INT8:
return Cast.unchecked( new SetupImgLoader<>( setupId, new ByteType(), new VolatileByteType() ) );
case INT16:
return Cast.unchecked( new SetupImgLoader<>( setupId, new ShortType(), new VolatileShortType() ) );
case INT32:
return Cast.unchecked( new SetupImgLoader<>( setupId, new IntType(), new VolatileIntType() ) );
case INT64:
return Cast.unchecked( new SetupImgLoader<>( setupId, new LongType(), new VolatileLongType() ) );
case FLOAT32:
return Cast.unchecked( new SetupImgLoader<>( setupId, new FloatType(), new VolatileFloatType() ) );
case FLOAT64:
return Cast.unchecked( new SetupImgLoader<>( setupId, new DoubleType(), new VolatileDoubleType() ) );
}
return null;
}
@Override
public CacheControl getCacheControl()
{
open();
return cache;
}
public class SetupImgLoader< T extends NativeType< T >, V extends Volatile< T > & NativeType< V > >
extends AbstractViewerSetupImgLoader< T, V >
implements MultiResolutionSetupImgLoader< T >
{
private final int setupId;
private final double[][] mipmapResolutions;
private final AffineTransform3D[] mipmapTransforms;
public SetupImgLoader( final int setupId, final T type, final V volatileType ) throws IOException
{
super( type, volatileType );
this.setupId = setupId;
final String pathName = getPathName( setupId );
mipmapResolutions = n5.getAttribute( pathName, DOWNSAMPLING_FACTORS_KEY, double[][].class );
mipmapTransforms = new AffineTransform3D[ mipmapResolutions.length ];
for ( int level = 0; level < mipmapResolutions.length; level++ )
mipmapTransforms[ level ] = MipmapTransforms.getMipmapTransformDefault( mipmapResolutions[ level ] );
}
@Override
public RandomAccessibleInterval< V > getVolatileImage( final int timepointId, final int level, final ImgLoaderHint... hints )
{
return prepareCachedImage( timepointId, level, LoadingStrategy.BUDGETED, volatileType );
}
@Override
public RandomAccessibleInterval< T > getImage( final int timepointId, final int level, final ImgLoaderHint... hints )
{
return prepareCachedImage( timepointId, level, LoadingStrategy.BLOCKING, type );
}
@Override
public Dimensions getImageSize( final int timepointId, final int level )
{
try
{
final String pathName = getPathName( setupId, timepointId, level );
final DatasetAttributes attributes = n5.getDatasetAttributes( pathName );
return new FinalDimensions( attributes.getDimensions() );
}
catch( Exception e )
{
return null;
}
}
@Override
public double[][] getMipmapResolutions()
{
return mipmapResolutions;
}
@Override
public AffineTransform3D[] getMipmapTransforms()
{
return mipmapTransforms;
}
@Override
public int numMipmapLevels()
{
return mipmapResolutions.length;
}
@Override
public VoxelDimensions getVoxelSize( final int timepointId )
{
return null;
}
/**
* Create a {@link CellImg} backed by the cache.
*/
private < T extends NativeType< T > > RandomAccessibleInterval< T > prepareCachedImage( final int timepointId, final int level, final LoadingStrategy loadingStrategy, final T type )
{
try
{
final String pathName = getPathName( setupId, timepointId, level );
final DatasetAttributes attributes = n5.getDatasetAttributes( pathName );
final long[] dimensions = attributes.getDimensions();
final int[] cellDimensions = attributes.getBlockSize();
final CellGrid grid = new CellGrid( dimensions, cellDimensions );
final int priority = numMipmapLevels() - 1 - level;
final CacheHints cacheHints = new CacheHints( loadingStrategy, priority, false );
final SimpleCacheArrayLoader< ? > loader = createCacheArrayLoader( n5, pathName );
return cache.createImg( grid, timepointId, setupId, level, cacheHints, loader, type );
}
catch ( IOException e )
{
System.err.println( String.format(
"image data for timepoint %d setup %d level %d could not be found.",
timepointId, setupId, level ) );
return Views.interval(
new ConstantRandomAccessible<>( type.createVariable(), 3 ),
new FinalInterval( 1, 1, 1 ) );
}
}
}
private static class N5CacheArrayLoader< A > implements SimpleCacheArrayLoader< A >
{
private final N5Reader n5;
private final String pathName;
private final DatasetAttributes attributes;
private final Function< DataBlock< ? >, A > createArray;
N5CacheArrayLoader( final N5Reader n5, final String pathName, final DatasetAttributes attributes, final Function< DataBlock< ? >, A > createArray )
{
this.n5 = n5;
this.pathName = pathName;
this.attributes = attributes;
this.createArray = createArray;
}
@Override
public A loadArray( final long[] gridPosition ) throws IOException
{
DataBlock< ? > block = n5.readBlock( pathName, attributes, gridPosition );
if ( block == null )
{
final int[] blockSize = attributes.getBlockSize();
final int n = blockSize[ 0 ] * blockSize[ 1 ] * blockSize[ 2 ];
switch ( attributes.getDataType() )
{
case UINT8:
case INT8:
return createArray.apply( new ByteArrayDataBlock( blockSize, gridPosition, new byte[ n ] ) );
case UINT16:
case INT16:
return createArray.apply( new ShortArrayDataBlock( blockSize, gridPosition, new short[ n ] ) );
case UINT32:
case INT32:
return createArray.apply( new IntArrayDataBlock( blockSize, gridPosition, new int[ n ] ) );
case UINT64:
case INT64:
return createArray.apply( new LongArrayDataBlock( blockSize, gridPosition, new long[ n ] ) );
case FLOAT32:
return createArray.apply( new FloatArrayDataBlock( blockSize, gridPosition, new float[ n ] ) );
case FLOAT64:
return createArray.apply( new DoubleArrayDataBlock( blockSize, gridPosition, new double[ n ] ) );
default:
throw new IllegalArgumentException();
}
}
else
{
return createArray.apply( block );
}
}
}
public static SimpleCacheArrayLoader< ? > createCacheArrayLoader( final N5Reader n5, final String pathName ) throws IOException
{
final DatasetAttributes attributes = n5.getDatasetAttributes( pathName );
switch ( attributes.getDataType() )
{
case UINT8:
case INT8:
return new N5CacheArrayLoader<>( n5, pathName, attributes,
dataBlock -> new VolatileByteArray( Cast.unchecked( dataBlock.getData() ), true ) );
case UINT16:
case INT16:
return new N5CacheArrayLoader<>( n5, pathName, attributes,
dataBlock -> new VolatileShortArray( Cast.unchecked( dataBlock.getData() ), true ) );
case UINT32:
case INT32:
return new N5CacheArrayLoader<>( n5, pathName, attributes,
dataBlock -> new VolatileIntArray( Cast.unchecked( dataBlock.getData() ), true ) );
case UINT64:
case INT64:
return new N5CacheArrayLoader<>( n5, pathName, attributes,
dataBlock -> new VolatileLongArray( Cast.unchecked( dataBlock.getData() ), true ) );
case FLOAT32:
return new N5CacheArrayLoader<>( n5, pathName, attributes,
dataBlock -> new VolatileFloatArray( Cast.unchecked( dataBlock.getData() ), true ) );
case FLOAT64:
return new N5CacheArrayLoader<>( n5, pathName, attributes,
dataBlock -> new VolatileDoubleArray( Cast.unchecked( dataBlock.getData() ), true ) );
default:
throw new IllegalArgumentException();
}
}
}