-
Notifications
You must be signed in to change notification settings - Fork 242
/
LeicaReader.java
1702 lines (1457 loc) · 54.1 KB
/
LeicaReader.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
* OME Bio-Formats package for reading and converting biological file formats.
* %%
* Copyright (C) 2005 - 2017 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
package loci.formats.in;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import loci.common.DataTools;
import loci.common.DateTools;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.formats.AxisGuesser;
import loci.formats.CoreMetadata;
import loci.formats.FilePattern;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import loci.formats.tiff.IFD;
import loci.formats.tiff.IFDList;
import loci.formats.tiff.TiffConstants;
import loci.formats.tiff.TiffParser;
import ome.xml.model.enums.Correction;
import ome.xml.model.enums.Immersion;
import ome.xml.model.primitives.Color;
import ome.xml.model.primitives.Timestamp;
import ome.units.quantity.ElectricPotential;
import ome.units.quantity.Length;
import ome.units.quantity.Time;
import ome.units.UNITS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableMap;
/**
* LeicaReader is the file format reader for Leica files.
*
* @author Melissa Linkert melissa at glencoesoftware.com
*/
public class LeicaReader extends FormatReader {
// -- Constants -
private static final Logger LOGGER =
LoggerFactory.getLogger(LeicaReader.class);
public static final String[] LEI_SUFFIX = {"lei"};
/** All Leica TIFFs have this tag. */
private static final int LEICA_MAGIC_TAG = 33923;
/** Format for dates. */
private static final String DATE_FORMAT = "yyyy:MM:dd,HH:mm:ss";
/** IFD tags. */
private static final Integer SERIES = 10;
private static final Integer IMAGES = 15;
private static final Integer DIMDESCR = 20;
private static final Integer FILTERSET = 30;
private static final Integer TIMEINFO = 40;
private static final Integer SCANNERSET = 50;
private static final Integer EXPERIMENT = 60;
private static final Integer LUTDESC = 70;
private static final Integer CHANDESC = 80;
private static final Integer SEQUENTIALSET = 90;
private static final Integer SEQ_SCANNERSET = 200;
private static final Integer SEQ_FILTERSET = 700;
private static final int SEQ_SCANNERSET_END = 300;
private static final int SEQ_FILTERSET_END = 800;
private static final ImmutableMap<Integer, String> DIMENSION_NAMES =
makeDimensionTable();
// -- Fields --
protected IFDList ifds;
/** Array of IFD-like structures containing metadata. */
protected IFDList headerIFDs;
/** Helper readers. */
protected MinimalTiffReader tiff;
/** Array of image file names. */
protected List<String>[] files;
/** Number of series in the file. */
private int numSeries;
/** Name of current LEI file */
private String leiFilename;
/** Length of each file name. */
private int fileLength;
private boolean[] valid;
private String[][] timestamps;
private List<String> seriesNames;
private List<String> seriesDescriptions;
private int lastPlane = 0, nameLength = 0;
private double[][] physicalSizes;
private double[] pinhole, exposureTime;
private int nextDetector = 0, nextChannel = 0;
private List<Integer> activeChannelIndices = new ArrayList<Integer>();
private boolean sequential = false;
private List[] channelNames;
private List[] emWaves;
private List[] exWaves;
private boolean[][] cutInPopulated;
private boolean[][] cutOutPopulated;
private boolean[][] filterRefPopulated;
private List<Detector> detectors = new ArrayList<Detector>();
private int[] tileWidth, tileHeight;
private Color[][] channelColor;
// -- Constructor --
/** Constructs a new Leica reader. */
public LeicaReader() {
super("Leica", new String[] {"lei", "tif", "tiff", "raw"});
domains = new String[] {FormatTools.LM_DOMAIN};
hasCompanionFiles = true;
datasetDescription = "One .lei file with at least one .tif/.tiff file " +
"and an optional .txt file";
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isSingleFile(String) */
@Override
public boolean isSingleFile(String id) throws FormatException, IOException {
return false;
}
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
@Override
public boolean isThisType(String name, boolean open) {
if (checkSuffix(name, LEI_SUFFIX)) return true;
if (!checkSuffix(name, TiffReader.TIFF_SUFFIXES) &&
!checkSuffix(name, "raw"))
{
return false;
}
if (!open) return false; // not allowed to touch the file system
// check for that there is an .lei file in the same directory
String prefix = name;
if (prefix.indexOf('.') != -1) {
prefix = prefix.substring(0, prefix.lastIndexOf("."));
}
Location lei = new Location(prefix + ".lei");
if (!lei.exists()) {
lei = new Location(prefix + ".LEI");
while (!lei.exists() && prefix.indexOf('_') != -1) {
prefix = prefix.substring(0, prefix.lastIndexOf("_"));
lei = new Location(prefix + ".lei");
if (!lei.exists()) lei = new Location(prefix + ".LEI");
}
}
return lei.exists();
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
@Override
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
TiffParser tp = new TiffParser(stream);
IFD ifd = tp.getFirstIFD();
if (ifd == null) return false;
return ifd.containsKey(Integer.valueOf(LEICA_MAGIC_TAG));
}
/* @see loci.formats.IFormatReader#get8BitLookupTable() */
@Override
public byte[][] get8BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
try {
int index = (int) Math.min(lastPlane, files[getSeries()].size() - 1);
tiff.setId(files[getSeries()].get(index));
return tiff.get8BitLookupTable();
}
catch (FormatException e) {
LOGGER.debug("Failed to retrieve lookup table", e);
}
catch (IOException e) {
LOGGER.debug("Failed to retrieve lookup table", e);
}
return null;
}
/* @see loci.formats.IFormatReader#get16BitLookupTable() */
@Override
public short[][] get16BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
try {
int index = (int) Math.min(lastPlane, files[getSeries()].size() - 1);
tiff.setId(files[getSeries()].get(index));
return tiff.get16BitLookupTable();
}
catch (FormatException e) {
LOGGER.debug("Failed to retrieve lookup table", e);
}
catch (IOException e) {
LOGGER.debug("Failed to retrieve lookup table", e);
}
return null;
}
/* @see loci.formats.IFormatReader#fileGroupOption(String) */
@Override
public int fileGroupOption(String id) throws FormatException, IOException {
return FormatTools.MUST_GROUP;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
@Override
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
lastPlane = no;
int fileIndex = no < files[getSeries()].size() ? no : 0;
int planeIndex = no < files[getSeries()].size() ? 0 : no;
String filename = (String) files[getSeries()].get(fileIndex);
if (new Location(filename).exists()) {
if (checkSuffix(filename, TiffReader.TIFF_SUFFIXES)) {
tiff.setId(filename);
return tiff.openBytes(planeIndex, buf, x, y, w, h);
}
else {
try (RandomAccessInputStream s = new RandomAccessInputStream(filename)) {
s.seek(planeIndex * FormatTools.getPlaneSize(this));
readPlane(s, x, y, w, h, buf);
}
}
}
// imitate Leica's software and return a blank plane if the
// appropriate TIFF file is missing
return buf;
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
@Override
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
final List<String> v = new ArrayList<String>();
if (leiFilename != null) v.add(leiFilename);
if (!noPixels && files != null) {
for (Object file : files[getSeries()]) {
if (file != null && new Location((String) file).exists()) {
v.add((String) file);
}
}
}
return v.toArray(new String[v.size()]);
}
/* @see loci.formats.IFormatReader#close(boolean) */
@Override
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (tiff != null) tiff.close(fileOnly);
if (!fileOnly) {
leiFilename = null;
files = null;
ifds = headerIFDs = null;
tiff = null;
seriesNames = null;
numSeries = 0;
lastPlane = 0;
physicalSizes = null;
seriesDescriptions = null;
pinhole = exposureTime = null;
nextDetector = 0;
nextChannel = 0;
sequential = false;
activeChannelIndices.clear();
channelNames = null;
emWaves = null;
exWaves = null;
cutInPopulated = null;
cutOutPopulated = null;
filterRefPopulated = null;
detectors.clear();
}
}
/* @see loci.formats.IFormatReader#getOptimalTileWidth() */
@Override
public int getOptimalTileWidth() {
FormatTools.assertId(currentId, true, 1);
if (tileWidth != null && tileWidth[getSeries()] != 0) {
return tileWidth[getSeries()];
}
return super.getOptimalTileWidth();
}
/* @see loci.formats.IFormatReader#getOptimalTileHeight() */
@Override
public int getOptimalTileHeight() {
FormatTools.assertId(currentId, true, 1);
if (tileHeight != null && tileHeight[getSeries()] != 0) {
return tileHeight[getSeries()];
}
return super.getOptimalTileHeight();
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
close();
String leiFile = findLEIFile(id);
if (leiFile == null || leiFile.trim().length() == 0 ||
new Location(leiFile).isDirectory())
{
if (checkSuffix(id, TiffReader.TIFF_SUFFIXES)) {
super.initFile(id);
TiffReader r = new TiffReader();
r.setMetadataStore(getMetadataStore());
r.setId(id);
core = new ArrayList<CoreMetadata>(r.getCoreMetadataList());
metadataStore = r.getMetadataStore();
final Map<String, Object> globalMetadata = r.getGlobalMetadata();
for (final Map.Entry<String, Object> entry : globalMetadata.entrySet()) {
addGlobalMeta(entry.getKey(), entry.getValue());
}
r.close();
files = new List[] {new ArrayList<String>()};
files[0].add(id);
tiff = new MinimalTiffReader();
return;
}
else {
throw new FormatException("LEI file not found.");
}
}
// parse the LEI file
super.initFile(leiFile);
leiFilename =
new File(leiFile).exists()? new Location(leiFile).getAbsolutePath() : id;
in = new RandomAccessInputStream(leiFile);
byte[] data = null;
try {
data = new byte[(int) in.length()];
in.read(data);
}
finally {
in.close();
}
in = new RandomAccessInputStream(data);
MetadataLevel metadataLevel = metadataOptions.getMetadataLevel();
seriesNames = new ArrayList<String>();
byte[] fourBytes = new byte[4];
in.read(fourBytes);
core.get(0).littleEndian = (fourBytes[0] == TiffConstants.LITTLE &&
fourBytes[1] == TiffConstants.LITTLE &&
fourBytes[2] == TiffConstants.LITTLE &&
fourBytes[3] == TiffConstants.LITTLE);
boolean realLittleEndian = isLittleEndian();
in.order(isLittleEndian());
LOGGER.info("Reading metadata blocks");
in.skipBytes(8);
int addr = in.readInt();
headerIFDs = new IFDList();
while (addr != 0) {
IFD ifd = new IFD();
headerIFDs.add(ifd);
in.seek(addr + 4);
int tag = in.readInt();
while (tag != 0) {
// create the IFD structure
int offset = in.readInt();
long pos = in.getFilePointer();
in.seek(offset + 12);
int size = in.readInt();
ifd.putIFDValue(tag, in.getFilePointer());
in.seek(pos);
tag = in.readInt();
}
addr = in.readInt();
}
numSeries = headerIFDs.size();
tileWidth = new int[numSeries];
tileHeight = new int[numSeries];
core.clear();
for (int i=0; i<numSeries; i++) {
core.add(new CoreMetadata());
}
files = new List[numSeries];
channelNames = new List[getSeriesCount()];
emWaves = new List[getSeriesCount()];
exWaves = new List[getSeriesCount()];
cutInPopulated = new boolean[getSeriesCount()][];
cutOutPopulated = new boolean[getSeriesCount()][];
filterRefPopulated = new boolean[getSeriesCount()][];
for (int i=0; i<getSeriesCount(); i++) {
channelNames[i] = new ArrayList();
emWaves[i] = new ArrayList();
exWaves[i] = new ArrayList();
}
// determine the length of a filename
LOGGER.info("Parsing metadata blocks");
core.get(0).littleEndian = !isLittleEndian();
int seriesIndex = 0;
int invalidCount = 0;
valid = new boolean[numSeries];
timestamps = new String[headerIFDs.size()][];
for (int i=0; i<headerIFDs.size(); i++) {
IFD ifd = headerIFDs.get(i);
valid[i] = true;
if (ifd.get(SERIES) != null) {
long offset = ((Long) ifd.get(SERIES)).longValue();
in.seek(offset + 8);
nameLength = in.readInt() * 2;
}
in.seek(((Long) ifd.get(IMAGES)).longValue());
parseFilenames(i);
if (!valid[i]) invalidCount++;
}
numSeries -= invalidCount;
if (numSeries <= 0) {
throw new FormatException("TIFF files not found");
}
int[] count = new int[getSeriesCount()];
for (int i=0; i<getSeriesCount(); i++) {
count[i] = core.get(i).imageCount;
}
final List<String>[] tempFiles = files;
IFDList tempIFDs = headerIFDs;
core = new ArrayList<CoreMetadata>(numSeries);
files = new List[numSeries];
headerIFDs = new IFDList();
int index = 0;
core.clear();
for (int i=0; i<numSeries; i++) {
CoreMetadata ms = new CoreMetadata();
while (index < valid.length && !valid[index]) index++;
if (index >= valid.length) {
break;
}
ms.imageCount = count[index];
files[i] = tempFiles[index];
Collections.sort(files[i]);
headerIFDs.add(tempIFDs.get(index));
index++;
core.add(ms);
}
tiff = new MinimalTiffReader();
LOGGER.info("Populating metadata");
if (headerIFDs == null) headerIFDs = ifds;
seriesDescriptions = new ArrayList<String>();
physicalSizes = new double[headerIFDs.size()][5];
pinhole = new double[headerIFDs.size()];
exposureTime = new double[headerIFDs.size()];
channelColor = new Color[headerIFDs.size()][];
for (int i=0; i<headerIFDs.size(); i++) {
IFD ifd = headerIFDs.get(i);
CoreMetadata ms = core.get(i);
ms.littleEndian = isLittleEndian();
setSeries(i);
Integer[] keys = ifd.keySet().toArray(new Integer[ifd.size()]);
Arrays.sort(keys);
for (Integer key : keys) {
long offset = ((Long) ifd.get(key)).longValue();
in.seek(offset);
if (key.equals(SERIES)) {
parseSeriesTag();
}
else if (key.equals(IMAGES)) {
parseImageTag(i);
}
else if (key.equals(DIMDESCR)) {
parseDimensionTag(i);
}
else if (key.equals(TIMEINFO) && metadataLevel != MetadataLevel.MINIMUM)
{
parseTimeTag(i);
}
else if (key.equals(EXPERIMENT) &&
metadataLevel != MetadataLevel.MINIMUM)
{
parseExperimentTag();
}
else if (key.equals(LUTDESC)) {
parseLUT(i);
}
else if (key.equals(CHANDESC) && metadataLevel != MetadataLevel.MINIMUM)
{
parseChannelTag();
}
}
ms.orderCertain = true;
ms.littleEndian = isLittleEndian();
ms.falseColor = true;
ms.metadataComplete = true;
ms.interleaved = false;
String filename = (String) files[i].get(0);
if (checkSuffix(filename, TiffReader.TIFF_SUFFIXES)) {
try (RandomAccessInputStream s = new RandomAccessInputStream(filename, 16)) {
TiffParser parser = new TiffParser(s);
parser.setDoCaching(false);
IFD firstIFD = parser.getFirstIFD();
parser.fillInIFD(firstIFD);
ms.sizeX = (int) firstIFD.getImageWidth();
ms.sizeY = (int) firstIFD.getImageLength();
// override the .lei pixel type, in case a TIFF file was overwritten
ms.pixelType = firstIFD.getPixelType();
// don't worry about changing the endianness when it
// won't affect the pixel data
if (FormatTools.getBytesPerPixel(ms.pixelType) > 1) {
ms.littleEndian = firstIFD.isLittleEndian();
}
else {
ms.littleEndian = realLittleEndian;
}
tileWidth[i] = (int) firstIFD.getTileWidth();
tileHeight[i] = (int) firstIFD.getTileLength();
}
}
else {
ms.littleEndian = realLittleEndian;
}
}
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
CoreMetadata ms = core.get(i);
if (getSizeZ() == 0) ms.sizeZ = 1;
if (getSizeT() == 0) ms.sizeT = 1;
if (getSizeC() == 0) ms.sizeC = 1;
if (getImageCount() == 0) ms.imageCount = 1;
if (getImageCount() == 1 && getSizeZ() * getSizeT() > 1) {
ms.sizeZ = 1;
ms.sizeT = 1;
}
if (getSizeY() == 1 || getSizeY() == getSizeZ() ||
getSizeY() == getSizeT())
{
// XZ or XT scan
if (getSizeZ() > 1 && getImageCount() == getSizeC() * getSizeT()) {
ms.sizeY = getSizeZ();
ms.sizeZ = 1;
}
else if (getSizeT() > 1 && getImageCount() == getSizeC() * getSizeZ()) {
ms.sizeY = getSizeT();
ms.sizeT = 1;
}
}
if (isRGB()) ms.indexed = false;
ms.dimensionOrder =
MetadataTools.makeSaneDimensionOrder(getDimensionOrder());
}
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
// Ensure we populate Image names before returning due to a possible
// minimum metadata level.
for (int i=0; i<getSeriesCount(); i++) {
store.setImageName(seriesNames.get(i), i);
}
if (metadataLevel == MetadataLevel.MINIMUM) return;
for (int i=0; i<getSeriesCount(); i++) {
CoreMetadata ms = core.get(i);
IFD ifd = headerIFDs.get(i);
long firstPlane = 0;
if (i < timestamps.length && timestamps[i] != null &&
timestamps[i].length > 0)
{
firstPlane = DateTools.getTime(timestamps[i][0], DATE_FORMAT, ":");
String date = DateTools.formatDate(timestamps[i][0], DATE_FORMAT);
if (date != null) {
store.setImageAcquisitionDate(new Timestamp(date), i);
}
}
store.setImageDescription(seriesDescriptions.get(i), i);
String instrumentID = MetadataTools.createLSID("Instrument", i);
store.setInstrumentID(instrumentID, i);
// parse instrument data
nextDetector = 0;
nextChannel = 0;
detectors.clear();
cutInPopulated[i] = new boolean[ms.sizeC];
cutOutPopulated[i] = new boolean[ms.sizeC];
filterRefPopulated[i] = new boolean[ms.sizeC];
Integer[] keys = ifd.keySet().toArray(new Integer[ifd.size()]);
Arrays.sort(keys);
int nextInstrumentBlock = 1;
sequential = DataTools.indexOf(keys, SEQ_SCANNERSET) != -1;
for (Integer key : keys) {
if (key.equals(FILTERSET) || key.equals(SCANNERSET) ||
key.equals(SEQ_SCANNERSET) || key.equals(SEQ_FILTERSET) ||
(key > SEQ_SCANNERSET && key < SEQ_SCANNERSET_END) ||
(key > SEQ_FILTERSET && key < SEQ_FILTERSET_END))
{
if (sequential && (key.equals(FILTERSET) || key.equals(SCANNERSET))) {
continue;
}
long offset = ((Long) ifd.get(key)).longValue();
in.seek(offset);
setSeries(i);
parseInstrumentData(store, nextInstrumentBlock++);
}
}
activeChannelIndices.clear();
// link Instrument and Image
store.setImageInstrumentRef(instrumentID, i);
Length sizeX = FormatTools.getPhysicalSizeX(physicalSizes[i][0]);
Length sizeY = FormatTools.getPhysicalSizeY(physicalSizes[i][1]);
Length sizeZ = FormatTools.getPhysicalSizeZ(physicalSizes[i][2]);
if (sizeX != null) {
store.setPixelsPhysicalSizeX(sizeX, i);
}
if (sizeY != null) {
store.setPixelsPhysicalSizeY(sizeY, i);
}
if (sizeZ != null) {
store.setPixelsPhysicalSizeZ(sizeZ, i);
}
if ((int) physicalSizes[i][4] > 0) {
store.setPixelsTimeIncrement(new Time(physicalSizes[i][4], UNITS.SECOND), i);
}
for (int j=0; j<ms.imageCount; j++) {
if (timestamps[i] != null && j < timestamps[i].length) {
long time = DateTools.getTime(timestamps[i][j], DATE_FORMAT, ":");
double elapsedTime = (double) (time - firstPlane) / 1000;
store.setPlaneDeltaT(new Time(elapsedTime, UNITS.SECOND), i, j);
if (exposureTime[i] > 0) {
store.setPlaneExposureTime(new Time(exposureTime[i], UNITS.SECOND), i, j);
}
}
}
}
setSeries(0);
}
// -- Helper methods --
/** Find the .lei file that belongs to the same dataset as the given file. */
private String findLEIFile(String baseFile)
throws FormatException, IOException
{
if (checkSuffix(baseFile, LEI_SUFFIX)) {
return baseFile;
}
else if (checkSuffix(baseFile, TiffReader.TIFF_SUFFIXES) && isGroupFiles())
{
// need to find the associated .lei file
if (ifds == null) super.initFile(baseFile);
in = new RandomAccessInputStream(baseFile, 16);
TiffParser tp = new TiffParser(in);
in.order(tp.checkHeader().booleanValue());
in.seek(0);
LOGGER.info("Finding companion file name");
// open the TIFF file and look for the "Image Description" field
ifds = tp.getMainIFDs();
if (ifds == null) throw new FormatException("No IFDs found");
String descr = ifds.get(0).getComment();
// remove anything of the form "[blah]"
descr = descr.replaceAll("\\[.*.\\]\n", "");
// each remaining line in descr is a (key, value) pair,
// where '=' separates the key from the value
String lei =
baseFile.substring(0, baseFile.lastIndexOf(File.separator) + 1);
StringBuilder suffix = new StringBuilder();
StringTokenizer lines = new StringTokenizer(descr, "\n");
String line = null, key = null, value = null;
while (lines.hasMoreTokens()) {
line = lines.nextToken();
if (line.indexOf('=') == -1) continue;
key = line.substring(0, line.indexOf('=')).trim();
value = line.substring(line.indexOf('=') + 1).trim();
addGlobalMeta(key, value);
if (key.startsWith("Series Name")) {
suffix.append(value);
}
}
lei += suffix.toString();
// now open the LEI file
Location l = new Location(lei).getAbsoluteFile();
if (l.exists()) {
return lei;
}
else {
if (!lei.endsWith("lei") && !lei.endsWith("LEI")) {
lei = lei.substring(0, lei.lastIndexOf(".") + 1);
String test = lei + "lei";
if (new Location(test).exists()) {
return test;
}
test = lei + "LEI";
if (new Location(test).exists()) {
return test;
}
}
l = l.getParentFile();
String[] list = l.list();
for (int i=0; i<list.length; i++) {
if (checkSuffix(list[i], LEI_SUFFIX)) {
return new Location(l.getAbsolutePath(), list[i]).getAbsolutePath();
}
}
}
}
else if (checkSuffix(baseFile, "raw") && isGroupFiles()) {
// check for that there is an .lei file in the same directory
String prefix = baseFile;
if (prefix.indexOf('.') != -1) {
prefix = prefix.substring(0, prefix.lastIndexOf("."));
}
Location lei = new Location(prefix + ".lei");
if (!lei.exists()) {
lei = new Location(prefix + ".LEI");
while (!lei.exists() && prefix.indexOf('_') != -1) {
prefix = prefix.substring(0, prefix.lastIndexOf("_"));
lei = new Location(prefix + ".lei");
if (!lei.exists()) lei = new Location(prefix + ".LEI");
}
}
if (lei.exists()) return lei.getAbsolutePath();
}
return null;
}
private String[] getTIFFList() {
File dirFile = new File(currentId).getAbsoluteFile();
String[] listing = null;
if (dirFile.exists()) {
listing = dirFile.getParentFile().list();
}
else {
listing = Location.getIdMap().keySet().toArray(new String[0]);
}
Arrays.sort(listing);
final List<String> list = new ArrayList<String>();
for (int k=0; k<listing.length; k++) {
if (checkSuffix(listing[k], TiffReader.TIFF_SUFFIXES)) {
list.add(listing[k]);
}
}
return list.toArray(new String[list.size()]);
}
private void parseFilenames(int seriesIndex) throws IOException {
int maxPlanes = 0;
final List<String> f = new ArrayList<String>();
int tempImages = in.readInt();
if (((long) tempImages * nameLength) > in.length()) {
in.order(!isLittleEndian());
tempImages = in.readInt();
in.order(isLittleEndian());
}
CoreMetadata ms = core.get(seriesIndex);
ms.sizeX = in.readInt();
ms.sizeY = in.readInt();
in.skipBytes(4);
int samplesPerPixel = in.readInt();
ms.rgb = samplesPerPixel > 1;
ms.sizeC = samplesPerPixel;
boolean tiffsExist = false;
String dirPrefix = new Location(currentId).getAbsoluteFile().getParent();
if (!dirPrefix.endsWith(File.separator)) dirPrefix += File.separator;
String prefix = "";
for (int j=0; j<tempImages; j++) {
// read in each filename
prefix = getString(nameLength);
f.add(dirPrefix + prefix);
// test to make sure the path is valid
Location test = new Location(f.get(f.size() - 1)).getAbsoluteFile();
LOGGER.debug("Expected to find TIFF file {}", test.getAbsolutePath());
if (!test.exists()) {
LOGGER.debug(" file does not exist");
}
if (!tiffsExist) tiffsExist = test.exists();
}
// all of the TIFF files were renamed
if (!tiffsExist) {
// Strategy for handling renamed files:
// 1) Assume that files for each series follow a pattern.
// 2) Assign each file group to the first series with the correct count.
LOGGER.info("Handling renamed TIFF files");
String[] listing = getTIFFList();
// grab the file patterns
final List<String> filePatterns = new ArrayList<String>();
for (String q : listing) {
Location l = new Location(q).getAbsoluteFile();
if (!l.exists()) {
l = new Location(dirPrefix, q).getAbsoluteFile();
}
FilePattern pattern = new FilePattern(l);
if (!pattern.isValid()) continue;
AxisGuesser guess = new AxisGuesser(pattern, "XYZCT", 1, 1, 1, false);
String fp = pattern.getPattern();
if (guess.getAxisCountS() >= 1) {
String pre = pattern.getPrefix(guess.getAxisCountS());
final List<String> fileList = new ArrayList<String>();
for (int n=0; n<listing.length; n++) {
Location p = new Location(dirPrefix, listing[n]);
if (p.getAbsolutePath().startsWith(pre)) {
fileList.add(listing[n]);
}
}
fp = FilePattern.findPattern(l.getAbsolutePath(), dirPrefix,
fileList.toArray(new String[fileList.size()]));
}
if (fp != null && !filePatterns.contains(fp)) {
filePatterns.add(fp);
}
}
for (String q : filePatterns) {
String[] pattern = new FilePattern(q).getFiles();
if (pattern.length == tempImages) {
// make sure that this pattern hasn't already been used
boolean validPattern = true;
for (int n=0; n<seriesIndex; n++) {
if (files[n] == null) continue;
if (files[n].contains(pattern[0])) {
validPattern = false;
break;
}
}
if (validPattern) {
files[seriesIndex] = new ArrayList<String>();
files[seriesIndex].addAll(Arrays.asList(pattern));
}
}
}
}
else {
files[seriesIndex] = f;
// invalidate any previous series that tried to use this set of files
for (int s=0; s<seriesIndex; s++) {
if (files[s] != null) {
if (files[s].get(0).equals(f.get(0))) {
valid[s] = false;
files[s] = null;
}
}
}
}
if (files[seriesIndex] == null) valid[seriesIndex] = false;
else {
ms.imageCount = files[seriesIndex].size();