-
Notifications
You must be signed in to change notification settings - Fork 238
/
FormatTools.java
1801 lines (1595 loc) · 59.1 KB
/
FormatTools.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* #%L
* BSD implementations of Bio-Formats readers and writers
* %%
* Copyright (C) 2005 - 2015 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* 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 loci.formats;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Vector;
import loci.common.Constants;
import loci.common.DateTools;
import loci.common.RandomAccessInputStream;
import loci.common.ReflectException;
import loci.common.ReflectedUniverse;
import loci.common.services.DependencyException;
import loci.common.services.ServiceException;
import loci.common.services.ServiceFactory;
import loci.formats.meta.DummyMetadata;
import loci.formats.meta.MetadataRetrieve;
import loci.formats.meta.MetadataStore;
import loci.formats.services.OMEXMLService;
import loci.formats.services.OMEXMLServiceImpl;
import ome.xml.model.enums.EnumerationException;
import ome.xml.model.enums.UnitsLength;
import ome.xml.model.primitives.PrimitiveNumber;
import ome.xml.model.primitives.PositiveFloat;
import ome.xml.model.primitives.PositiveInteger;
import ome.xml.model.primitives.Timestamp;
import ome.units.unit.Unit;
import ome.units.quantity.Angle;
import ome.units.quantity.ElectricPotential;
import ome.units.quantity.Frequency;
import ome.units.quantity.Length;
import ome.units.quantity.Power;
import ome.units.quantity.Pressure;
import ome.units.quantity.Temperature;
import ome.units.quantity.Time;
import ome.units.UNITS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A utility class for format reader and writer implementations.
*/
public final class FormatTools {
protected static final Logger LOGGER =
LoggerFactory.getLogger(FormatTools.class);
// -- Constants - pixel types --
/** Identifies the <i>INT8</i> data type used to store pixel values. */
public static final int INT8 = 0;
/** Identifies the <i>UINT8</i> data type used to store pixel values. */
public static final int UINT8 = 1;
/** Identifies the <i>INT16</i> data type used to store pixel values. */
public static final int INT16 = 2;
/** Identifies the <i>UINT16</i> data type used to store pixel values. */
public static final int UINT16 = 3;
/** Identifies the <i>INT32</i> data type used to store pixel values. */
public static final int INT32 = 4;
/** Identifies the <i>UINT32</i> data type used to store pixel values. */
public static final int UINT32 = 5;
/** Identifies the <i>FLOAT</i> data type used to store pixel values. */
public static final int FLOAT = 6;
/** Identifies the <i>DOUBLE</i> data type used to store pixel values. */
public static final int DOUBLE = 7;
/** Identifies the <i>BIT</i> data type used to store pixel values. */
public static final int BIT = 8;
/** Human readable pixel type. */
private static final String[] pixelTypes = makePixelTypes();
static String[] makePixelTypes() {
String[] pixelTypes = new String[9];
pixelTypes[INT8] = "int8";
pixelTypes[UINT8] = "uint8";
pixelTypes[INT16] = "int16";
pixelTypes[UINT16] = "uint16";
pixelTypes[INT32] = "int32";
pixelTypes[UINT32] = "uint32";
pixelTypes[FLOAT] = "float";
pixelTypes[DOUBLE] = "double";
pixelTypes[BIT] = "bit";
return pixelTypes;
}
// -- Constants - dimensional labels --
/**
* Identifies the <i>Channel</i> dimensional type,
* representing a generic channel dimension.
*/
public static final String CHANNEL = "Channel";
/**
* Identifies the <i>Spectra</i> dimensional type,
* representing a dimension consisting of spectral channels.
*/
public static final String SPECTRA = "Spectra";
/**
* Identifies the <i>Lifetime</i> dimensional type,
* representing a dimension consisting of a lifetime histogram.
*/
public static final String LIFETIME = "Lifetime";
/**
* Identifies the <i>Polarization</i> dimensional type,
* representing a dimension consisting of polarization states.
*/
public static final String POLARIZATION = "Polarization";
/**
* Identifies the <i>Phase</i> dimensional type,
* representing a dimension consisting of phases.
*/
public static final String PHASE = "Phase";
/**
* Identifies the <i>Frequency</i> dimensional type,
* representing a dimension consisting of frequencies.
*/
public static final String FREQUENCY = "Frequency";
/**
* Identifies the <i>Rotation</i> dimensional type,
* representing a dimension consisting of rotations.
*/
public static final String ROTATION = "Rotation";
/**
* Identifies the <i>Illumination</i> dimensional type,
* representing a dimension consisting of illuminations.
*/
public static final String ILLUMINATION = "Illumination";
// -- Constants - miscellaneous --
/** File grouping options. */
public static final int MUST_GROUP = 0;
public static final int CAN_GROUP = 1;
public static final int CANNOT_GROUP = 2;
/** Patterns to be used when constructing a pattern for output filenames. */
public static final String SERIES_NUM = "%s";
public static final String SERIES_NAME = "%n";
public static final String CHANNEL_NUM = "%c";
public static final String CHANNEL_NAME = "%w";
public static final String Z_NUM = "%z";
public static final String T_NUM = "%t";
public static final String TIMESTAMP = "%A";
public static final String TILE_X = "%x";
public static final String TILE_Y = "%y";
public static final String TILE_NUM = "%m";
// -- Constants - versioning --
public static final Properties VERSION_PROPERTIES = loadProperties();
/** Current VCS revision. */
public static final String VCS_REVISION =
VERSION_PROPERTIES.getProperty("vcs.revision");
/** Current VCS revision (short form). */
public static final String VCS_SHORT_REVISION =
VERSION_PROPERTIES.getProperty("vcs.shortrevision");
/** Date on which this release was built. */
public static final String DATE = VERSION_PROPERTIES.getProperty("date");
/** Year in which this release was built. */
public static final String YEAR = VERSION_PROPERTIES.getProperty("year");
/** Version number of this release. */
public static final String VERSION =
VERSION_PROPERTIES.getProperty("release.version");
public static final String PROPERTY_FILE = "version.properties";
static Properties loadProperties() {
Properties properties = new Properties();
try {
InputStream propertyFile = Class.forName(
"loci.formats.FormatTools").getResourceAsStream(PROPERTY_FILE);
properties.load(propertyFile);
}
catch (ClassNotFoundException e) {
LOGGER.debug("Failed to load version properties", e);
}
catch (IOException e) {
LOGGER.debug("Failed to load version properties", e);
}
return properties;
}
// -- Constants - domains --
/** Identifies the high content screening domain. */
public static final String HCS_DOMAIN = "High-Content Screening (HCS)";
/** Identifies the light microscopy domain. */
public static final String LM_DOMAIN = "Light Microscopy";
/** Identifies the electron microscopy domain. */
public static final String EM_DOMAIN = "Electron Microscopy (EM)";
/** Identifies the scanning probe microscopy domain. */
public static final String SPM_DOMAIN = "Scanning Probe Microscopy (SPM)";
/** Identifies the scanning electron microscopy domain. */
public static final String SEM_DOMAIN = "Scanning Electron Microscopy (SEM)";
/** Identifies the fluorescence-lifetime domain. */
public static final String FLIM_DOMAIN = "Fluorescence-Lifetime Imaging";
/** Identifies the medical imaging domain. */
public static final String MEDICAL_DOMAIN = "Medical Imaging";
/** Identifies the histology domain. */
public static final String HISTOLOGY_DOMAIN = "Histology";
/** Identifies the gel and blot imaging domain. */
public static final String GEL_DOMAIN = "Gel/Blot Imaging";
/** Identifies the astronomy domain. */
public static final String ASTRONOMY_DOMAIN = "Astronomy";
/**
* Identifies the graphics domain.
* This includes formats used exclusively by analysis software.
*/
public static final String GRAPHICS_DOMAIN = "Graphics";
/** Identifies an unknown domain. */
public static final String UNKNOWN_DOMAIN = "Unknown";
/** List of non-graphics domains. */
public static final String[] NON_GRAPHICS_DOMAINS = new String[] {
LM_DOMAIN, EM_DOMAIN, SPM_DOMAIN, SEM_DOMAIN, FLIM_DOMAIN, MEDICAL_DOMAIN,
HISTOLOGY_DOMAIN, GEL_DOMAIN, ASTRONOMY_DOMAIN, HCS_DOMAIN, UNKNOWN_DOMAIN
};
/** List of non-HCS domains. */
public static final String[] NON_HCS_DOMAINS = new String[] {
LM_DOMAIN, EM_DOMAIN, SPM_DOMAIN, SEM_DOMAIN, FLIM_DOMAIN, MEDICAL_DOMAIN,
HISTOLOGY_DOMAIN, GEL_DOMAIN, ASTRONOMY_DOMAIN, UNKNOWN_DOMAIN
};
/**
* List of domains that do not require special handling. Domains that
* require special handling are {@link #GRAPHICS_DOMAIN} and
* {@link #HCS_DOMAIN}.
*/
public static final String[] NON_SPECIAL_DOMAINS = new String[] {
LM_DOMAIN, EM_DOMAIN, SPM_DOMAIN, SEM_DOMAIN, FLIM_DOMAIN, MEDICAL_DOMAIN,
HISTOLOGY_DOMAIN, GEL_DOMAIN, ASTRONOMY_DOMAIN, UNKNOWN_DOMAIN
};
/** List of all supported domains. */
public static final String[] ALL_DOMAINS = new String[] {
HCS_DOMAIN, LM_DOMAIN, EM_DOMAIN, SPM_DOMAIN, SEM_DOMAIN, FLIM_DOMAIN,
MEDICAL_DOMAIN, HISTOLOGY_DOMAIN, GEL_DOMAIN, ASTRONOMY_DOMAIN,
GRAPHICS_DOMAIN, UNKNOWN_DOMAIN
};
// -- Constants - web pages --
/** URL of Bio-Formats web page. */
public static final String URL_BIO_FORMATS =
"http://www.openmicroscopy.org/site/products/bio-formats";
/** URL of 'Bio-Formats as a Java Library' web page. */
public static final String URL_BIO_FORMATS_LIBRARIES =
"http://www.openmicroscopy.org/site/support/bio-formats/developers/java-library.html";
/** URL of OME-TIFF web page. */
public static final String URL_OME_TIFF =
"http://www.openmicroscopy.org/site/support/ome-model/ome-tiff/";
// -- Constructor --
private FormatTools() { }
// -- Utility methods - dimensional positions --
/**
* Gets the rasterized index corresponding
* to the given Z, C and T coordinates (real sizes).
*/
public static int getIndex(IFormatReader reader, int z, int c, int t) {
String order = reader.getDimensionOrder();
int zSize = reader.getSizeZ();
int cSize = reader.getEffectiveSizeC();
int tSize = reader.getSizeT();
int num = reader.getImageCount();
return getIndex(order, zSize, cSize, tSize, num, z, c, t);
}
/**
* Gets the rasterized index corresponding to the given Z, C, T,
* ModuloZ, ModuloC and ModuloT coordinates (effective sizes). Note
* that the Z, C and T coordinates take the modulo dimension sizes
* into account. The effective size for each of these dimensions is
* limited to the total size of the dimension divided by the modulo
* size.
*/
public static int getIndex(IFormatReader reader, int z, int c, int t,
int moduloZ, int moduloC, int moduloT) {
String order = reader.getDimensionOrder();
int zSize = reader.getSizeZ();
int cSize = reader.getEffectiveSizeC();
int tSize = reader.getSizeT();
int moduloZSize = reader.getModuloZ().length();
int moduloCSize = reader.getModuloC().length();
int moduloTSize = reader.getModuloT().length();
int num = reader.getImageCount();
return getIndex(order,
zSize, cSize, tSize,
moduloZSize, moduloCSize, moduloTSize,
num,
z, c, t,
moduloZ, moduloC, moduloT);
}
/**
* Gets the rasterized index corresponding
* to the given Z, C and T coordinates (real sizes).
*
* @param order Dimension order.
* @param zSize Total number of focal planes (real size).
* @param cSize Total number of channels (real size).
* @param tSize Total number of time points (real size).
* @param num Total number of image planes (zSize * cSize * tSize),
* specified as a consistency check.
* @param z Z coordinate of ZCT coordinate triple to convert to 1D index (real size).
* @param c C coordinate of ZCT coordinate triple to convert to 1D index (real size).
* @param t T coordinate of ZCT coordinate triple to convert to 1D index (real size).
*/
public static int getIndex(String order, int zSize, int cSize, int tSize,
int num, int z, int c, int t)
{
// check DimensionOrder
if (order == null) {
throw new IllegalArgumentException("Dimension order is null");
}
if (!order.startsWith("XY") && !order.startsWith("YX")) {
throw new IllegalArgumentException("Invalid dimension order: " + order);
}
int iz = order.indexOf("Z") - 2;
int ic = order.indexOf("C") - 2;
int it = order.indexOf("T") - 2;
if (iz < 0 || iz > 2 || ic < 0 || ic > 2 || it < 0 || it > 2) {
throw new IllegalArgumentException("Invalid dimension order: " + order);
}
// check SizeZ
if (zSize <= 0) {
throw new IllegalArgumentException("Invalid Z size: " + zSize);
}
if (z < 0 || z >= zSize) {
throw new IllegalArgumentException("Invalid Z index: " + z + "/" + zSize);
}
// check SizeC
if (cSize <= 0) {
throw new IllegalArgumentException("Invalid C size: " + cSize);
}
if (c < 0 || c >= cSize) {
throw new IllegalArgumentException("Invalid C index: " + c + "/" + cSize);
}
// check SizeT
if (tSize <= 0) {
throw new IllegalArgumentException("Invalid T size: " + tSize);
}
if (t < 0 || t >= tSize) {
throw new IllegalArgumentException("Invalid T index: " + t + "/" + tSize);
}
// check image count
if (num <= 0) {
throw new IllegalArgumentException("Invalid image count: " + num);
}
if (num != zSize * cSize * tSize) {
// if this happens, there is probably a bug in metadata population --
// either one of the ZCT sizes, or the total number of images --
// or else the input file is invalid
throw new IllegalArgumentException("ZCT size vs image count mismatch " +
"(sizeZ=" + zSize + ", sizeC=" + cSize + ", sizeT=" + tSize +
", total=" + num + ")");
}
// assign rasterization order
int v0 = iz == 0 ? z : (ic == 0 ? c : t);
int v1 = iz == 1 ? z : (ic == 1 ? c : t);
int v2 = iz == 2 ? z : (ic == 2 ? c : t);
int len0 = iz == 0 ? zSize : (ic == 0 ? cSize : tSize);
int len1 = iz == 1 ? zSize : (ic == 1 ? cSize : tSize);
return v0 + v1 * len0 + v2 * len0 * len1;
}
/**
* Gets the rasterized index corresponding to the given Z, C, T,
* ModuloZ, ModuloC, ModuloT coordinates (effective sizes). Note
* that the Z, C and T coordinates take the modulo dimension sizes
* into account. The effective size for each of these dimensions is
* limited to the total size of the dimension divided by the modulo
* size.
*
* @param order Dimension order.
* @param zSize Total number of focal planes (real size).
* @param cSize Total number of channels (real size).
* @param tSize Total number of time points (real size).
* @param moduloZSize Total number of ModuloZ planes (real size).
* @param moduloCSize Total number of ModuloC planes (real size).
* @param moduloTSize Total number of ModuloT planes (real size).
* @param num Total number of image planes (zSize * cSize * tSize),
* specified as a consistency check.
* @param z Z coordinate of ZCTmZmCmT coordinate sextuple to convert to 1D index (effective size).
* @param c C coordinate of ZCTmZmCmT coordinate sextuple to convert to 1D index (effective size).
* @param t T coordinate of ZCTmZmCmT coordinate sextuple to convert to 1D index (effective size).
* @param moduloZ ModuloZ coordinate of ZCTmZmCmT coordinate sextuple to convert to 1D index (effective size).
* @param moduloC ModuloC coordinate of ZCTmZmCmT coordinate sextuple to convert to 1D index (effective size).
* @param moduloT ModuloT coordinate of ZCTmZmCmT coordinate sextuple to convert to 1D index (effective size).
*/
public static int getIndex(String order,
int zSize, int cSize, int tSize,
int moduloZSize, int moduloCSize, int moduloTSize,
int num,
int z, int c, int t,
int moduloZ, int moduloC, int moduloT) {
return getIndex(order,
zSize,
cSize,
tSize,
num,
(z * moduloZSize) + moduloZ,
(c * moduloCSize) + moduloC,
(t * moduloTSize) + moduloT);
}
/**
* Gets the Z, C and T coordinates corresponding
* to the given rasterized index value (real sizes).
*/
public static int[] getZCTCoords(IFormatReader reader, int index) {
String order = reader.getDimensionOrder();
int zSize = reader.getSizeZ();
int cSize = reader.getEffectiveSizeC();
int tSize = reader.getSizeT();
int num = reader.getImageCount();
return getZCTCoords(order, zSize, cSize, tSize, num, index);
}
/**
* Gets the Z, C, T, ModuloZ, ModuloC and ModuloZ coordinates
* corresponding to the given rasterized index value (effective
* sizes). Note that the Z, C and T coordinates are not the same as
* those returned by getZCTCoords(IFormatReader, int) because the
* size of the modulo dimensions is taken into account. The
* effective size for each of these dimensions is limited to the
* total size of the dimension divided by the modulo size.
*/
public static int[] getZCTModuloCoords(IFormatReader reader, int index) {
String order = reader.getDimensionOrder();
int zSize = reader.getSizeZ();
int cSize = reader.getEffectiveSizeC();
int tSize = reader.getSizeT();
int moduloZSize = reader.getModuloZ().length();
int moduloCSize = reader.getModuloC().length();
int moduloTSize = reader.getModuloT().length();
int num = reader.getImageCount();
return getZCTCoords(order, zSize, cSize, tSize, moduloZSize, moduloCSize, moduloTSize, num, index);
}
/**
* Gets the Z, C and T coordinates corresponding to the given rasterized
* index value (real sizes).
*
* @param order Dimension order.
* @param zSize Total number of focal planes (real size).
* @param cSize Total number of channels (real size).
* @param tSize Total number of time points (real size).
* @param num Total number of image planes (zSize * cSize * tSize),
* specified as a consistency check.
* @param index 1D (rasterized) index to convert to ZCT coordinate triple.
*/
public static int[] getZCTCoords(String order,
int zSize, int cSize, int tSize, int num, int index)
{
// check DimensionOrder
if (order == null) {
throw new IllegalArgumentException("Dimension order is null");
}
if (!order.startsWith("XY") && !order.startsWith("YX")) {
throw new IllegalArgumentException("Invalid dimension order: " + order);
}
int iz = order.indexOf("Z") - 2;
int ic = order.indexOf("C") - 2;
int it = order.indexOf("T") - 2;
if (iz < 0 || iz > 2 || ic < 0 || ic > 2 || it < 0 || it > 2) {
throw new IllegalArgumentException("Invalid dimension order: " + order);
}
// check SizeZ
if (zSize <= 0) {
throw new IllegalArgumentException("Invalid Z size: " + zSize);
}
// check SizeC
if (cSize <= 0) {
throw new IllegalArgumentException("Invalid C size: " + cSize);
}
// check SizeT
if (tSize <= 0) {
throw new IllegalArgumentException("Invalid T size: " + tSize);
}
// check image count
if (num <= 0) {
throw new IllegalArgumentException("Invalid image count: " + num);
}
if (num != zSize * cSize * tSize) {
// if this happens, there is probably a bug in metadata population --
// either one of the ZCT sizes, or the total number of images --
// or else the input file is invalid
throw new IllegalArgumentException("ZCT size vs image count mismatch " +
"(sizeZ=" + zSize + ", sizeC=" + cSize + ", sizeT=" + tSize +
", total=" + num + ")");
}
if (index < 0 || index >= num) {
throw new IllegalArgumentException("Invalid image index: " +
index + "/" + num);
}
// assign rasterization order
int len0 = iz == 0 ? zSize : (ic == 0 ? cSize : tSize);
int len1 = iz == 1 ? zSize : (ic == 1 ? cSize : tSize);
//int len2 = iz == 2 ? sizeZ : (ic == 2 ? sizeC : sizeT);
int v0 = index % len0;
int v1 = index / len0 % len1;
int v2 = index / len0 / len1;
int z = iz == 0 ? v0 : (iz == 1 ? v1 : v2);
int c = ic == 0 ? v0 : (ic == 1 ? v1 : v2);
int t = it == 0 ? v0 : (it == 1 ? v1 : v2);
return new int[] {z, c, t};
}
/**
* Gets the Z, C and T coordinates corresponding to the given
* rasterized index value. Note that the Z, C and T coordinates are
* not the same as those returned by getZCTCoords(String, int, int,
* int, int, int) because the size of the modulo dimensions is taken
* into account. The effective size for each of these dimensions is
* limited to the total size of the dimension divided by the modulo
* size.
*
* @param order Dimension order.
* @param zSize Total number of focal planes (real size).
* @param cSize Total number of channels (real size).
* @param tSize Total number of time points (real size).
* @param moduloZSize Total number of ModuloZ planes (real size).
* @param moduloCSize Total number of ModuloC planes (real size).
* @param moduloTSize Total number of ModuloT planes (real size).
* @param num Total number of image planes (zSize * cSize * tSize),
* specified as a consistency check.
* @param index 1D (rasterized) index to convert to ZCT coordinate triple.
*/
public static int[] getZCTCoords(String order,
int zSize, int cSize, int tSize,
int moduloZSize, int moduloCSize, int moduloTSize,
int num, int index) {
int[] coords = getZCTCoords(order, zSize, cSize, tSize, num, index);
return new int[] {
coords[0] / moduloZSize,
coords[1] / moduloCSize,
coords[2] / moduloTSize,
coords[0] % moduloZSize,
coords[1] % moduloCSize,
coords[2] % moduloTSize
};
}
/**
* Converts index from the given dimension order to the reader's native one.
* This method is useful for shuffling the planar order around
* (rather than eassigning ZCT sizes as {@link DimensionSwapper} does).
*
* @throws FormatException Never actually thrown.
*/
public static int getReorderedIndex(IFormatReader reader,
String newOrder, int newIndex) throws FormatException
{
String origOrder = reader.getDimensionOrder();
int zSize = reader.getSizeZ();
int cSize = reader.getEffectiveSizeC();
int tSize = reader.getSizeT();
int num = reader.getImageCount();
return getReorderedIndex(origOrder, newOrder,
zSize, cSize, tSize, num, newIndex);
}
/**
* Converts index from one dimension order to another.
* This method is useful for shuffling the planar order around
* (rather than eassigning ZCT sizes as {@link DimensionSwapper} does).
*
* @param origOrder Original dimension order.
* @param newOrder New dimension order.
* @param zSize Total number of focal planes (real size).
* @param cSize Total number of channels (real size).
* @param tSize Total number of time points (real size).
* @param num Total number of image planes (zSize * cSize * tSize),
* specified as a consistency check.
* @param newIndex 1D (rasterized) index according to new dimension order.
* @return rasterized index according to original dimension order.
*/
public static int getReorderedIndex(String origOrder, String newOrder,
int zSize, int cSize, int tSize, int num, int newIndex)
{
int[] zct = getZCTCoords(newOrder, zSize, cSize, tSize, num, newIndex);
return getIndex(origOrder,
zSize, cSize, tSize, num, zct[0], zct[1], zct[2]);
}
/**
* Computes a unique 1-D index corresponding
* to the given multidimensional position.
* @param lengths the maximum value for each positional dimension
* @param pos position along each dimensional axis
* @return rasterized index value
*/
public static int positionToRaster(int[] lengths, int[] pos) {
int offset = 1;
int raster = 0;
for (int i=0; i<pos.length; i++) {
raster += offset * pos[i];
offset *= lengths[i];
}
return raster;
}
/**
* Computes a unique N-D position corresponding
* to the given rasterized index value.
* @param lengths the maximum value at each positional dimension
* @param raster rasterized index value
* @return position along each dimensional axis
*/
public static int[] rasterToPosition(int[] lengths, int raster) {
return rasterToPosition(lengths, raster, new int[lengths.length]);
}
/**
* Computes a unique N-D position corresponding
* to the given rasterized index value.
* @param lengths the maximum value at each positional dimension
* @param raster rasterized index value
* @param pos preallocated position array to populate with the result
* @return position along each dimensional axis
*/
public static int[] rasterToPosition(int[] lengths, int raster, int[] pos) {
int offset = 1;
for (int i=0; i<pos.length; i++) {
int offset1 = offset * lengths[i];
int q = i < pos.length - 1 ? raster % offset1 : raster;
pos[i] = q / offset;
raster -= q;
offset = offset1;
}
return pos;
}
/**
* Computes the number of raster values for a positional array
* with the given lengths.
*/
public static int getRasterLength(int[] lengths) {
int len = 1;
for (int i=0; i<lengths.length; i++) len *= lengths[i];
return len;
}
// -- Utility methods - pixel types --
/**
* Takes a string value and maps it to one of the pixel type enumerations.
* @param pixelTypeAsString the pixel type as a string.
* @return type enumeration value for use with class constants.
*/
public static int pixelTypeFromString(String pixelTypeAsString) {
String lowercaseTypeAsString = pixelTypeAsString.toLowerCase();
for (int i = 0; i < pixelTypes.length; i++) {
if (pixelTypes[i].equals(lowercaseTypeAsString)) return i;
}
throw new IllegalArgumentException("Unknown type: '" +
pixelTypeAsString + "'");
}
/**
* Takes a pixel type value and gets a corresponding string representation.
* @param pixelType the pixel type.
* @return string value for human-readable output.
*/
public static String getPixelTypeString(int pixelType) {
if (pixelType < 0 || pixelType >= pixelTypes.length) {
throw new IllegalArgumentException("Unknown pixel type: " + pixelType);
}
return pixelTypes[pixelType];
}
/**
* Retrieves how many bytes per pixel the current plane or section has.
* @param pixelType the pixel type as retrieved from
* {@link IFormatReader#getPixelType()}.
* @return the number of bytes per pixel.
* @see IFormatReader#getPixelType()
*/
public static int getBytesPerPixel(int pixelType) {
switch (pixelType) {
case INT8:
case UINT8:
case BIT:
return 1;
case INT16:
case UINT16:
return 2;
case INT32:
case UINT32:
case FLOAT:
return 4;
case DOUBLE:
return 8;
}
throw new IllegalArgumentException("Unknown pixel type: " + pixelType);
}
/**
* Retrieves the number of bytes per pixel in the current plane.
* @param pixelType the pixel type, as a String.
* @return the number of bytes per pixel.
* @see #pixelTypeFromString(String)
* @see #getBytesPerPixel(int)
*/
public static int getBytesPerPixel(String pixelType) {
return getBytesPerPixel(pixelTypeFromString(pixelType));
}
/**
* Determines whether the given reader represents any floating point data.
* @param reader the reader to check
* @return true if any of the reader's series have a floating point pixel type
* @see #isFloatingPoint(int)
*/
public static boolean isFloatingPoint(IFormatReader reader) {
int originalSeries = reader.getSeries();
for (int s=0; s<reader.getSeriesCount(); s++) {
reader.setSeries(s);
if (isFloatingPoint(reader.getPixelType())) {
reader.setSeries(originalSeries);
return true;
}
}
reader.setSeries(originalSeries);
return false;
}
/**
* Determines whether the given pixel type is floating point or integer.
* @param pixelType the pixel type as retrieved from
* {@link IFormatReader#getPixelType()}.
* @return true if the pixel type is floating point.
* @see IFormatReader#getPixelType()
*/
public static boolean isFloatingPoint(int pixelType) {
switch (pixelType) {
case INT8:
case UINT8:
case INT16:
case UINT16:
case INT32:
case UINT32:
case BIT:
return false;
case FLOAT:
case DOUBLE:
return true;
}
throw new IllegalArgumentException("Unknown pixel type: " + pixelType);
}
/**
* Determines whether the given pixel type is signed or unsigned.
* @param pixelType the pixel type as retrieved from
* {@link IFormatReader#getPixelType()}.
* @return true if the pixel type is signed.
* @see IFormatReader#getPixelType()
*/
public static boolean isSigned(int pixelType) {
switch (pixelType) {
case INT8:
case INT16:
case INT32:
case FLOAT:
case DOUBLE:
return true;
case UINT8:
case UINT16:
case UINT32:
case BIT:
return false;
}
throw new IllegalArgumentException("Unknown pixel type: " + pixelType);
}
/**
* Returns an appropriate pixel type given the number of bytes per pixel.
*
* @param bytes number of bytes per pixel.
* @param signed whether or not the pixel type should be signed.
* @param fp whether or not these are floating point pixels.
*/
public static int pixelTypeFromBytes(int bytes, boolean signed, boolean fp)
throws FormatException
{
switch (bytes) {
case 1:
return signed ? INT8 : UINT8;
case 2:
return signed ? INT16: UINT16;
case 4:
return fp ? FLOAT : signed ? INT32: UINT32;
case 8:
return DOUBLE;
default:
throw new FormatException("Unsupported byte depth: " + bytes);
}
}
// -- Utility methods - sanity checking
/**
* Asserts that the current file is either null, or not, according to the
* given flag. If the assertion fails, an IllegalStateException is thrown.
* @param currentId File name to test.
* @param notNull True iff id should be non-null.
* @param depth How far back in the stack the calling method is; this name
* is reported as part of the exception message, if available. Use zero
* to suppress output of the calling method name.
*/
public static void assertId(String currentId, boolean notNull, int depth) {
String msg = null;
if (currentId == null && notNull) {
msg = "Current file should not be null; call setId(String) first";
}
else if (currentId != null && !notNull) {
msg = "Current file should be null, but is '" +
currentId + "'; call close() first";
}
if (msg == null) return;
StackTraceElement[] ste = new Exception().getStackTrace();
String header;
if (depth > 0 && ste.length > depth) {
String c = ste[depth].getClassName();
if (c.startsWith("loci.formats.")) {
c = c.substring(c.lastIndexOf(".") + 1);
}
header = c + "." + ste[depth].getMethodName() + ": ";
}
else header = "";
throw new IllegalStateException(header + msg);
}
/**
* Convenience method for checking that the plane number, tile size and
* buffer sizes are all valid for the given reader.
* If 'bufLength' is less than 0, then the buffer length check is not
* performed.
*/
public static void checkPlaneParameters(IFormatReader r, int no,
int bufLength, int x, int y, int w, int h) throws FormatException
{
assertId(r.getCurrentFile(), true, 2);
checkPlaneNumber(r, no);
checkTileSize(r, x, y, w, h);
if (bufLength >= 0) checkBufferSize(r, bufLength, w, h);
}
/** Checks that the given plane number is valid for the given reader. */
public static void checkPlaneNumber(IFormatReader r, int no)
throws FormatException
{
int imageCount = r.getImageCount();
if (no < 0 || no >= imageCount) {
throw new FormatException("Invalid image number: " + no +
" (series=" + r.getSeries() + ", imageCount=" + imageCount + ")");
}
}
/** Checks that the given tile size is valid for the given reader. */
public static void checkTileSize(IFormatReader r, int x, int y, int w, int h)
throws FormatException
{
int width = r.getSizeX();
int height = r.getSizeY();
if (x < 0 || y < 0 || w < 0 || h < 0 || (x + w) > width ||
(y + h) > height)
{
throw new FormatException("Invalid tile size: x=" + x + ", y=" + y +
", w=" + w + ", h=" + h);
}
}
public static void checkBufferSize(IFormatReader r, int len)
throws FormatException
{
checkBufferSize(r, len, r.getSizeX(), r.getSizeY());
}
/**
* Checks that the given buffer size is large enough to hold a w * h
* image as returned by the given reader.
* @throws FormatException if the buffer is too small
*/
public static void checkBufferSize(IFormatReader r, int len, int w, int h)
throws FormatException
{
int size = getPlaneSize(r, w, h);
if (size > len) {
throw new FormatException("Buffer too small (got " + len +
", expected " + size + ").");
}
}
/**
* Returns true if the given RandomAccessInputStream conatins at least
* 'len' bytes.
*/
public static boolean validStream(RandomAccessInputStream stream, int len,
boolean littleEndian) throws IOException
{
stream.seek(0);
stream.order(littleEndian);
return stream.length() >= len;
}
/** Returns the size in bytes of a single plane. */
public static int getPlaneSize(IFormatReader r) {
return getPlaneSize(r, r.getSizeX(), r.getSizeY());
}
/** Returns the size in bytes of a w * h tile. */