-
Notifications
You must be signed in to change notification settings - Fork 241
/
ZeissLSMReader.java
2567 lines (2272 loc) · 83.6 KB
/
ZeissLSMReader.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.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import loci.common.DataTools;
import loci.common.DateTools;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.common.Region;
import loci.common.services.DependencyException;
import loci.common.services.ServiceFactory;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.ImageTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import loci.formats.services.MDBService;
import loci.formats.tiff.IFD;
import loci.formats.tiff.IFDList;
import loci.formats.tiff.PhotoInterp;
import loci.formats.tiff.TiffCompression;
import loci.formats.tiff.TiffConstants;
import loci.formats.tiff.TiffParser;
import ome.xml.model.primitives.Color;
import ome.xml.model.primitives.Timestamp;
import ome.units.quantity.Length;
import ome.units.quantity.Time;
import ome.units.UNITS;
/**
* ZeissLSMReader is the file format reader for Zeiss LSM files.
*
* @author Eric Kjellman egkjellman at wisc.edu
* @author Melissa Linkert melissa at glencoesoftware.com
* @author Curtis Rueden ctrueden at wisc.edu
*/
public class ZeissLSMReader extends FormatReader {
// -- Constants --
public static final String[] MDB_SUFFIX = {"mdb"};
/** Tag identifying a Zeiss LSM file. */
private static final int ZEISS_ID = 34412;
/** Data types. */
private static final int TYPE_SUBBLOCK = 0;
private static final int TYPE_ASCII = 2;
private static final int TYPE_LONG = 4;
private static final int TYPE_RATIONAL = 5;
private static final int TYPE_DATE = 6;
private static final int TYPE_BOOLEAN = 7;
/** Subblock types. */
private static final int SUBBLOCK_RECORDING = 0x10000000;
private static final int SUBBLOCK_LASER = 0x50000000;
private static final int SUBBLOCK_TRACK = 0x40000000;
private static final int SUBBLOCK_DETECTION_CHANNEL = 0x70000000;
private static final int SUBBLOCK_ILLUMINATION_CHANNEL = 0x90000000;
private static final int SUBBLOCK_BEAM_SPLITTER = 0xb0000000;
private static final int SUBBLOCK_DATA_CHANNEL = 0xd0000000;
private static final int SUBBLOCK_TIMER = 0x12000000;
private static final int SUBBLOCK_MARKER = 0x14000000;
private static final int SUBBLOCK_END = (int) 0xffffffff;
/** Data types. */
private static final int RECORDING_NAME = 0x10000001;
private static final int RECORDING_DESCRIPTION = 0x10000002;
private static final int RECORDING_OBJECTIVE = 0x10000004;
private static final int RECORDING_ZOOM = 0x10000016;
private static final int RECORDING_SAMPLE_0TIME = 0x10000036;
private static final int RECORDING_CAMERA_BINNING = 0x10000052;
private static final int TRACK_ACQUIRE = 0x40000006;
private static final int TRACK_TIME_BETWEEN_STACKS = 0x4000000b;
private static final int LASER_NAME = 0x50000001;
private static final int LASER_ACQUIRE = 0x50000002;
private static final int LASER_POWER = 0x50000003;
private static final int CHANNEL_DETECTOR_GAIN = 0x70000003;
private static final int CHANNEL_PINHOLE_DIAMETER = 0x70000009;
private static final int CHANNEL_AMPLIFIER_GAIN = 0x70000005;
private static final int CHANNEL_FILTER_SET = 0x7000000f;
private static final int CHANNEL_FILTER = 0x70000010;
private static final int CHANNEL_ACQUIRE = 0x7000000b;
private static final int CHANNEL_NAME = 0x70000014;
private static final int ILLUM_CHANNEL_NAME = 0x90000001;
private static final int ILLUM_CHANNEL_ATTENUATION = 0x90000002;
private static final int ILLUM_CHANNEL_WAVELENGTH = 0x90000003;
private static final int ILLUM_CHANNEL_ACQUIRE = 0x90000004;
private static final int START_TIME = 0x10000036;
private static final int DATA_CHANNEL_NAME = 0xd0000001;
private static final int DATA_CHANNEL_ACQUIRE = 0xd0000017;
private static final int BEAM_SPLITTER_FILTER = 0xb0000002;
private static final int BEAM_SPLITTER_FILTER_SET = 0xb0000003;
/** Drawing element types. */
private static final int TEXT = 13;
private static final int LINE = 14;
private static final int SCALE_BAR = 15;
private static final int OPEN_ARROW = 16;
private static final int CLOSED_ARROW = 17;
private static final int RECTANGLE = 18;
private static final int ELLIPSE = 19;
private static final int CLOSED_POLYLINE = 20;
private static final int OPEN_POLYLINE = 21;
private static final int CLOSED_BEZIER = 22;
private static final int OPEN_BEZIER = 23;
private static final int CIRCLE = 24;
private static final int PALETTE = 25;
private static final int POLYLINE_ARROW = 26;
private static final int BEZIER_WITH_ARROW = 27;
private static final int ANGLE = 28;
private static final int CIRCLE_3POINT = 29;
// -- Static fields --
private static final ImmutableMap<Integer, String> METADATA_KEYS =
createKeys();
// -- Fields --
private double pixelSizeX, pixelSizeY, pixelSizeZ;
private byte[][][] lut = null;
private List<Double> timestamps;
private String[] lsmFilenames;
private List<IFDList> ifdsList;
private transient TiffParser tiffParser;
private int nextLaser = 0, nextDetector = 0;
private int nextFilter = 0, nextDichroicChannel = 0, nextDichroic = 0;
private int nextIllumChannel = 0, nextDetectChannel = 0;
private boolean splitPlanes = false;
private double zoom;
private List<String> imageNames;
private String binning;
private List<Double> xCoordinates, yCoordinates, zCoordinates;
private int dimensionM, dimensionP;
private int rotations, phases, illuminations;
private Map<String, Integer> seriesCounts;
private String userName;
private String[][] channelNames;
private double originX, originY, originZ;
private int totalROIs = 0;
private int prevPlane = -1;
private int prevChannel = 0;
private byte[] prevBuf = null;
private Region prevRegion = null;
private Map<Integer, String> acquiredDate =
new HashMap<Integer, String>();
private Color[] channelColor;
private transient boolean isSIM = false;
// -- Constructor --
/** Constructs a new Zeiss LSM reader. */
public ZeissLSMReader() {
super("Zeiss Laser-Scanning Microscopy", new String[] {"lsm", "mdb"});
domains = new String[] {FormatTools.LM_DOMAIN};
hasCompanionFiles = true;
suffixSufficient = false;
datasetDescription = "One or more .lsm files; if multiple .lsm files " +
"are present, an .mdb file should also be present";
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#getOptimalTileWidth() */
public int getOptimalWidth() {
FormatTools.assertId(currentId, true, 1);
try {
return (int) ifdsList.get(getSeries()).get(0).getTileWidth();
}
catch (FormatException e) {
LOGGER.debug("Could not retrieve tile width", e);
}
return super.getOptimalTileWidth();
}
/* @see loci.formats.IFormatReader#getOptimalTileHeight() */
@Override
public int getOptimalTileHeight() {
FormatTools.assertId(currentId, true, 1);
try {
return (int) ifdsList.get(getSeries()).get(0).getTileLength();
}
catch (FormatException e) {
LOGGER.debug("Could not retrieve tile height", e);
}
return super.getOptimalTileHeight();
}
/* @see loci.formats.IFormatReader#isSingleFile(String) */
@Override
public boolean isSingleFile(String id) throws FormatException, IOException {
if (checkSuffix(id, MDB_SUFFIX)) return false;
return isGroupFiles() ? getMDBFile(id) != null : true;
}
/* @see loci.formats.IFormatReader#close(boolean) */
@Override
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
pixelSizeX = pixelSizeY = pixelSizeZ = 0;
lut = null;
timestamps = null;
lsmFilenames = null;
ifdsList = null;
tiffParser = null;
nextLaser = nextDetector = 0;
nextFilter = nextDichroicChannel = nextDichroic = 0;
nextIllumChannel = nextDetectChannel = 0;
splitPlanes = false;
zoom = 0;
imageNames = null;
binning = null;
totalROIs = 0;
prevPlane = -1;
prevChannel = 0;
prevBuf = null;
prevRegion = null;
xCoordinates = null;
yCoordinates = null;
zCoordinates = null;
dimensionM = 0;
dimensionP = 0;
rotations = 0;
phases = 0;
illuminations = 0;
seriesCounts = null;
originX = originY = originZ = 0d;
userName = null;
acquiredDate.clear();
channelNames = null;
channelColor = null;
isSIM = false;
}
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
@Override
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockLen = 4096;
if (!FormatTools.validStream(stream, blockLen, false)) return false;
TiffParser parser = new TiffParser(stream);
if (parser.isValidHeader()) {
return parser.getIFDOffsets().length > 1;
}
stream.seek(4);
if (stream.readShort() == 0x5374) {
String check =
stream.readString((int) (blockLen - stream.getFilePointer()));
return check.indexOf("ID") > 0;
}
return false;
}
/* @see loci.formats.IFormatReader#fileGroupOption(String) */
@Override
public int fileGroupOption(String id) throws FormatException, IOException {
return checkSuffix(id, MDB_SUFFIX) ||
!new Location(id).getName().startsWith("spim_") ? FormatTools.MUST_GROUP :
FormatTools.CAN_GROUP;
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
@Override
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
if (noPixels) {
if (checkSuffix(currentId, MDB_SUFFIX)) return new String[] {currentId};
return null;
}
if (lsmFilenames == null) return new String[] {currentId};
if (lsmFilenames.length == 1 && currentId.equals(lsmFilenames[0])) {
return lsmFilenames;
}
return new String[] {currentId, getLSMFileFromSeries(getSeries())};
}
/* @see loci.formats.IFormatReader#get8BitLookupTable() */
@Override
public byte[][] get8BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
if (lut == null || lut[getSeries()] == null ||
getPixelType() != FormatTools.UINT8)
{
return null;
}
byte[][] b = new byte[3][];
b[0] = lut[getSeries()][prevChannel * 3];
b[1] = lut[getSeries()][prevChannel * 3 + 1];
b[2] = lut[getSeries()][prevChannel * 3 + 2];
return b;
}
/* @see loci.formats.IFormatReader#get16BitLookupTable() */
@Override
public short[][] get16BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
if (lut == null || lut[getSeries()] == null ||
getPixelType() != FormatTools.UINT16 || channelColor == null)
{
return null;
}
short[][] s = new short[3][65536];
Color color = channelColor[prevChannel];
for (int j=0; j<s[0].length; j++) {
s[0][j] = (short) ((color.getRed() / 255.0) * j);
s[1][j] = (short) ((color.getGreen() / 255.0) * j);
s[2][j] = (short) ((color.getBlue() / 255.0) * j);
}
return s;
}
/* @see loci.formats.IFormatReader#setCoreIndex(int) */
@Override
public void setCoreIndex(int coreIndex) {
if (coreIndex != getCoreIndex()) {
prevBuf = null;
prevPlane = -1;
prevRegion = null;
}
super.setCoreIndex(coreIndex);
}
/* @see loci.formats.IFormatReader#setSeries(int) */
@Override
public void setSeries(int series) {
if (series != getSeries()) {
prevBuf = null;
prevPlane = -1;
prevRegion = null;
}
super.setSeries(series);
}
/**
* @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);
if (getSeriesCount() > 1) {
in.close();
in = new RandomAccessInputStream(getLSMFileFromSeries(getSeries()));
in.order(!isLittleEndian());
tiffParser = new TiffParser(in);
}
else if (tiffParser == null) {
tiffParser = new TiffParser(in);
}
IFDList ifds = ifdsList.get(getSeries());
if (splitPlanes && getSizeC() > 1 && ifds.size() == getSizeZ() * getSizeT())
{
int bpp = FormatTools.getBytesPerPixel(getPixelType());
int plane = no / getSizeC();
int c = no % getSizeC();
Region region = new Region(x, y, w, h);
if (prevPlane != plane || prevBuf == null ||
prevBuf.length < w * h * bpp * getSizeC() || !region.equals(prevRegion))
{
prevBuf = new byte[w * h * bpp * getSizeC()];
tiffParser.getSamples(ifds.get(plane), prevBuf, x, y, w, h);
prevPlane = plane;
prevRegion = region;
}
ImageTools.splitChannels(
prevBuf, buf, c, getSizeC(), bpp, false, false, w * h * bpp);
prevChannel = c;
}
else {
tiffParser.getSamples(ifds.get(no), buf, x, y, w, h);
prevChannel = getZCTCoords(no)[1];
}
if (getSeriesCount() > 1) in.close();
return buf;
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
if (checkSuffix(id, MDB_SUFFIX)) {
lsmFilenames = parseMDB(id);
}
else lsmFilenames = new String[] {id};
if (lsmFilenames == null || lsmFilenames.length == 0) {
throw new FormatException("LSM files were not found.");
}
totalROIs = 0;
timestamps = new ArrayList<Double>();
imageNames = new ArrayList<String>();
xCoordinates = new ArrayList<Double>();
yCoordinates = new ArrayList<Double>();
zCoordinates = new ArrayList<Double>();
seriesCounts = new HashMap<String, Integer>();
int seriesCount = 0;
final List<String> validFiles = new ArrayList<String>();
for (String filename : lsmFilenames) {
try {
int extraSeries = getExtraSeries(filename);
seriesCounts.put(filename, extraSeries);
seriesCount += extraSeries;
validFiles.add(filename);
}
catch (IOException e) {
LOGGER.debug("Failed to parse " + filename, e);
}
}
lsmFilenames = validFiles.toArray(new String[validFiles.size()]);
core.clear();
for (int c=0; c<seriesCount; c++) {
CoreMetadata ms = new CoreMetadata();
core.add(ms);
}
channelNames = new String[seriesCount][];
ifdsList = new ArrayList<IFDList>();
for (int series = 0; series < seriesCount; series++) {
ifdsList.add(null);
}
int realSeries = 0;
for (int i=0; i<lsmFilenames.length; i++) {
try (RandomAccessInputStream stream = new RandomAccessInputStream(lsmFilenames[i], 16)){
int count = seriesCounts.get(lsmFilenames[i]);
TiffParser tp = new TiffParser(stream);
Boolean littleEndian = tp.checkHeader();
long[] ifdOffsets = tp.getIFDOffsets();
int ifdsPerSeries = (ifdOffsets.length / 2) / count;
int offset = 0;
Object zeissTag = null;
for (int s=0; s<count; s++, realSeries++) {
CoreMetadata ms = core.get(realSeries);
ms.littleEndian = littleEndian;
IFDList ifds = new IFDList();
while (ifds.size() < ifdsPerSeries) {
tp.setDoCaching(offset == 0);
IFD ifd = tp.getIFD(ifdOffsets[offset]);
if (offset == 0) zeissTag = ifd.get(ZEISS_ID);
if (offset > 0 && ifds.isEmpty()) {
ifd.putIFDValue(ZEISS_ID, zeissTag);
}
ifds.add(ifd);
if (zeissTag != null) offset += 2;
else offset++;
}
for (IFD ifd : ifds) {
tp.fillInIFD(ifd);
}
ifdsList.set(realSeries, ifds);
}
} catch (IOException e) {
throw e;
}
}
MetadataStore store = makeFilterMetadata();
lut = new byte[ifdsList.size()][][];
long[] previousStripOffsets = null;
for (int series=0; series<ifdsList.size(); series++) {
// IFD ordering is ZPT, so reset state if we have multiple timepoints
// this prevents offsets from being confused when the first offset in
// the next series is legitimately smaller than the last offset in
// the previous series
if (series > 0 && getSizeT() > 1) {
previousStripOffsets = null;
}
IFDList ifds = ifdsList.get(series);
for (IFD ifd : ifds) {
// check that predictor is set to 1 if anything other
// than LZW compression is used
if (ifd.getCompression() != TiffCompression.LZW) {
ifd.putIFDValue(IFD.PREDICTOR, 1);
}
}
// fix the offsets for > 4 GB files
RandomAccessInputStream s = null;
try {
s = new RandomAccessInputStream(getLSMFileFromSeries(series));
for (int i=0; i<ifds.size(); i++) {
long[] stripOffsets = ifds.get(i).getStripOffsets();
if (stripOffsets == null || (i != 0 &&
previousStripOffsets == null)) {
throw new FormatException(
"Strip offsets are missing; this is an invalid file.");
}
else if (i == 0 && previousStripOffsets == null) {
previousStripOffsets = stripOffsets;
continue;
}
boolean neededAdjustment = false;
for (int j=0; j<stripOffsets.length; j++) {
if (j >= previousStripOffsets.length) break;
if (stripOffsets[j] < previousStripOffsets[j]) {
stripOffsets[j] = (previousStripOffsets[j] & ~0xffffffffL) |
(stripOffsets[j] & 0xffffffffL);
if (stripOffsets[j] < previousStripOffsets[j]) {
long newOffset = stripOffsets[j] + 0x100000000L;
if (newOffset < s.length()) {
stripOffsets[j] = newOffset;
}
}
neededAdjustment = true;
}
if (neededAdjustment) {
ifds.get(i).putIFDValue(IFD.STRIP_OFFSETS, stripOffsets);
}
}
previousStripOffsets = stripOffsets;
}
initMetadata(series);
} catch (IOException e) {
throw e;
} finally {
if (s != null) s.close();
}
}
for (int i=0; i<getSeriesCount(); i++) {
CoreMetadata ms = core.get(i);
ms.imageCount = ms.sizeZ * ms.sizeC * ms.sizeT;
}
MetadataTools.populatePixels(store, this, true);
for (int series=0; series<ifdsList.size(); series++) {
setSeries(series);
if (series < imageNames.size()) {
store.setImageName(imageNames.get(series), series);
}
if (acquiredDate.containsKey(series)) {
store.setImageAcquisitionDate(new Timestamp(
acquiredDate.get(series)), series);
}
}
setSeries(0);
}
// -- Helper methods --
private String getMDBFile(String id) throws FormatException, IOException {
Location parentFile = new Location(id).getAbsoluteFile().getParentFile();
String[] fileList = parentFile.list();
for (int i=0; i<fileList.length; i++) {
if (fileList[i].startsWith(".")) continue;
if (checkSuffix(fileList[i], MDB_SUFFIX)) {
Location file =
new Location(parentFile, fileList[i]).getAbsoluteFile();
if (file.isDirectory()) continue;
// make sure that the .mdb references this .lsm
String[] lsms = parseMDB(file.getAbsolutePath());
if (lsms == null) return null;
for (String lsm : lsms) {
if (id.endsWith(lsm) || lsm.endsWith(id)) {
return file.getAbsolutePath();
}
}
}
}
return null;
}
private int getEffectiveSeries(int currentSeries) {
int seriesCount = 0;
for (int i=0; i<lsmFilenames.length; i++) {
Integer count = seriesCounts.get(lsmFilenames[i]);
if (count == null) count = 1;
seriesCount += count;
if (seriesCount > currentSeries) return i;
}
return -1;
}
private String getLSMFileFromSeries(int currentSeries) {
int effectiveSeries = getEffectiveSeries(currentSeries);
return effectiveSeries < 0 ? null : lsmFilenames[effectiveSeries];
}
private int getExtraSeries(String file) throws FormatException, IOException {
if (in != null) in.close();
in = new RandomAccessInputStream(file, 16);
boolean littleEndian = in.read() == TiffConstants.LITTLE;
in.order(littleEndian);
tiffParser = new TiffParser(in);
IFD ifd = tiffParser.getFirstIFD();
RandomAccessInputStream ras = getCZTag(ifd);
if (ras == null) return 1;
ras.order(littleEndian);
ras.seek(264);
dimensionP = ras.readInt();
dimensionM = ras.readInt();
ras.close();
int nSeries = dimensionM * dimensionP;
return nSeries <= 0 ? 1 : nSeries;
}
private int getPosition(int currentSeries) {
int effectiveSeries = getEffectiveSeries(currentSeries);
int firstPosition = 0;
for (int i=0; i<effectiveSeries; i++) {
firstPosition += seriesCounts.get(lsmFilenames[i]);
}
return currentSeries - firstPosition;
}
private RandomAccessInputStream getCZTag(IFD ifd)
throws FormatException, IOException
{
// get TIF_CZ_LSMINFO structure
short[] s = ifd.getIFDShortArray(ZEISS_ID);
if (s == null) {
LOGGER.warn("Invalid Zeiss LSM file. Tag {} not found.", ZEISS_ID);
TiffReader reader = new TiffReader();
reader.setId(getLSMFileFromSeries(getSeries()));
core.set(getSeries(), reader.getCoreMetadataList().get(0));
reader.close();
return null;
}
byte[] cz = new byte[s.length];
for (int i=0; i<s.length; i++) {
cz[i] = (byte) s[i];
}
RandomAccessInputStream ras = new RandomAccessInputStream(cz);
ras.order(isLittleEndian());
return ras;
}
protected void initMetadata(int series) throws FormatException, IOException {
setSeries(series);
IFDList ifds = ifdsList.get(series);
IFD ifd = ifds.get(0);
in.close();
in = new RandomAccessInputStream(getLSMFileFromSeries(series), 16);
in.order(isLittleEndian());
tiffParser = new TiffParser(in);
PhotoInterp photo = ifd.getPhotometricInterpretation();
int samples = ifd.getSamplesPerPixel();
CoreMetadata ms = core.get(series);
ms.sizeX = (int) ifd.getImageWidth();
ms.sizeY = (int) ifd.getImageLength();
ms.rgb = samples > 1 || photo == PhotoInterp.RGB;
ms.interleaved = false;
ms.sizeC = isRGB() ? samples : 1;
ms.pixelType = ifd.getPixelType();
// Known DataType values suggest that uint32 data is not possible.
// We know that some TIFF metadata (e.g. RowsPerStrip) is missing
// or incorrect for many .lsm files, and a uint32 pixel type here
// suggests that the SampleFormat tag is missing.
// For now, assume that all 32 bit data is floating point.
if (ms.pixelType == FormatTools.UINT32) {
ms.pixelType = FormatTools.FLOAT;
}
ms.imageCount = ifds.size();
ms.sizeZ = getImageCount();
ms.sizeT = 1;
LOGGER.info("Reading LSM metadata for series #{}", series);
MetadataStore store = makeFilterMetadata();
int instrument = getEffectiveSeries(series);
String imageName = getLSMFileFromSeries(series);
if (imageName.indexOf('.') != -1) {
imageName = imageName.substring(0, imageName.lastIndexOf("."));
}
if (imageName.indexOf(File.separator) != -1) {
imageName =
imageName.substring(imageName.lastIndexOf(File.separator) + 1);
}
if (lsmFilenames.length != getSeriesCount()) {
imageName += " #" + (getPosition(series) + 1);
}
// link Instrument and Image
store.setImageID(MetadataTools.createLSID("Image", series), series);
String instrumentID = MetadataTools.createLSID("Instrument", instrument);
store.setInstrumentID(instrumentID, instrument);
store.setImageInstrumentRef(instrumentID, series);
RandomAccessInputStream ras = getCZTag(ifd);
if (ras == null) {
imageNames.add(imageName);
return;
}
ras.seek(16);
ms.sizeZ = ras.readInt();
ras.skipBytes(4);
ms.sizeT = ras.readInt();
int dataType = ras.readInt();
switch (dataType) {
case 2:
addSeriesMeta("DataType", "12 bit unsigned integer");
break;
case 5:
addSeriesMeta("DataType", "32 bit float");
break;
case 0:
addSeriesMeta("DataType", "varying data types");
break;
default:
addSeriesMeta("DataType", "8 bit unsigned integer");
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
ras.seek(0);
addSeriesMeta("MagicNumber ", ras.readInt());
addSeriesMeta("StructureSize", ras.readInt());
addSeriesMeta("DimensionX", ras.readInt());
addSeriesMeta("DimensionY", ras.readInt());
ras.seek(32);
addSeriesMeta("ThumbnailX", ras.readInt());
addSeriesMeta("ThumbnailY", ras.readInt());
// pixel sizes are stored in meters, we need them in microns
pixelSizeX = ras.readDouble() * 1000000;
pixelSizeY = ras.readDouble() * 1000000;
pixelSizeZ = ras.readDouble() * 1000000;
addSeriesMeta("VoxelSizeX", pixelSizeX);
addSeriesMeta("VoxelSizeY", pixelSizeY);
addSeriesMeta("VoxelSizeZ", pixelSizeZ);
originX = ras.readDouble() * 1000000;
originY = ras.readDouble() * 1000000;
originZ = ras.readDouble() * 1000000;
addSeriesMeta("OriginX", originX);
addSeriesMeta("OriginY", originY);
addSeriesMeta("OriginZ", originZ);
}
else ras.seek(88);
int scanType = ras.readShort();
switch (scanType) {
case 0:
addSeriesMeta("ScanType", "x-y-z scan");
ms.dimensionOrder = "XYZCT";
break;
case 1:
addSeriesMeta("ScanType", "z scan (x-z plane)");
ms.dimensionOrder = "XYZCT";
break;
case 2:
addSeriesMeta("ScanType", "line scan");
ms.dimensionOrder = "XYZCT";
break;
case 3:
addSeriesMeta("ScanType", "time series x-y");
ms.dimensionOrder = "XYTCZ";
break;
case 4:
addSeriesMeta("ScanType", "time series x-z");
ms.dimensionOrder = "XYZTC";
break;
case 5:
addSeriesMeta("ScanType", "time series 'Mean of ROIs'");
ms.dimensionOrder = "XYTCZ";
break;
case 6:
addSeriesMeta("ScanType", "time series x-y-z");
ms.dimensionOrder = "XYZTC";
break;
case 7:
addSeriesMeta("ScanType", "spline scan");
ms.dimensionOrder = "XYCTZ";
break;
case 8:
addSeriesMeta("ScanType", "spline scan x-z");
ms.dimensionOrder = "XYCZT";
break;
case 9:
addSeriesMeta("ScanType", "time series spline plane x-z");
ms.dimensionOrder = "XYTCZ";
break;
case 10:
addSeriesMeta("ScanType", "point mode");
ms.dimensionOrder = "XYZCT";
break;
default:
addSeriesMeta("ScanType", "x-y-z scan");
ms.dimensionOrder = "XYZCT";
}
ms.indexed = lut != null && lut[series] != null;
if (isIndexed()) {
ms.rgb = false;
}
if (getSizeC() == 0) ms.sizeC = 1;
if (isRGB()) {
// shuffle C to front of order string
ms.dimensionOrder = getDimensionOrder().replaceAll("C", "");
ms.dimensionOrder = getDimensionOrder().replaceAll("XY", "XYC");
}
if (getEffectiveSizeC() == 0) {
ms.imageCount = getSizeZ() * getSizeT();
}
else {
ms.imageCount = getSizeZ() * getSizeT() * getEffectiveSizeC();
}
if (getImageCount() != ifds.size()) {
int diff = getImageCount() - ifds.size();
ms.imageCount = ifds.size();
if (diff % getSizeZ() == 0) {
ms.sizeT -= (diff / getSizeZ());
}
else if (diff % getSizeT() == 0) {
ms.sizeZ -= (diff / getSizeT());
}
else if (getSizeZ() > 1) {
ms.sizeZ = ifds.size();
ms.sizeT = 1;
}
else if (getSizeT() > 1) {
ms.sizeT = ifds.size();
ms.sizeZ = 1;
}
}
if (getSizeZ() == 0) ms.sizeZ = getImageCount();
if (getSizeT() == 0) ms.sizeT = getImageCount() / getSizeZ();
long channelColorsOffset = 0;
long timeStampOffset = 0;
long eventListOffset = 0;
long scanInformationOffset = 0;
long channelWavelengthOffset = 0;
long applicationTagOffset = 0;
channelColor = new Color[getSizeC()];
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
int spectralScan = ras.readShort();
if (spectralScan != 1) {
addSeriesMeta("SpectralScan", "no spectral scan");
}
else addSeriesMeta("SpectralScan", "acquired with spectral scan");
int type = ras.readInt();
switch (type) {
case 1:
addSeriesMeta("DataType2", "calculated data");
break;
case 2:
addSeriesMeta("DataType2", "animation");
break;
default:
addSeriesMeta("DataType2", "original scan data");
}
long[] overlayOffsets = new long[9];
String[] overlayKeys = new String[] {"VectorOverlay", "InputLut",
"OutputLut", "ROI", "BleachROI", "MeanOfRoisOverlay",
"TopoIsolineOverlay", "TopoProfileOverlay", "LinescanOverlay"};
overlayOffsets[0] = ras.readInt();
overlayOffsets[1] = ras.readInt();
overlayOffsets[2] = ras.readInt();
channelColorsOffset = ras.readInt();
addSeriesMeta("TimeInterval", ras.readDouble());
ras.skipBytes(4);
scanInformationOffset = ras.readInt();
applicationTagOffset = ras.readInt();
timeStampOffset = ras.readInt();
eventListOffset = ras.readInt();
overlayOffsets[3] = ras.readInt();
overlayOffsets[4] = ras.readInt();
ras.skipBytes(4);
addSeriesMeta("DisplayAspectX", ras.readDouble());
addSeriesMeta("DisplayAspectY", ras.readDouble());
addSeriesMeta("DisplayAspectZ", ras.readDouble());
addSeriesMeta("DisplayAspectTime", ras.readDouble());
overlayOffsets[5] = ras.readInt();
overlayOffsets[6] = ras.readInt();
overlayOffsets[7] = ras.readInt();
overlayOffsets[8] = ras.readInt();
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.NO_OVERLAYS)
{
for (int i=0; i<overlayOffsets.length; i++) {
parseOverlays(series, overlayOffsets[i], overlayKeys[i], store);
}
}
addSeriesMeta("ToolbarFlags", ras.readInt());
channelWavelengthOffset = ras.readInt();
ras.skipBytes(64);
}
else ras.skipBytes(182);
if (getSizeC() > 1) {
if (!splitPlanes) splitPlanes = isRGB();
ms.rgb = false;
if (splitPlanes) ms.imageCount *= getSizeC();
}
// NB: the Zeiss LSM 5.5 specification indicates that there should be
// 15 32-bit integers here; however, there are actually 16 32-bit
// integers before the tile position offset.
// We have confirmed with Zeiss that this is correct, and the 6.0
// specification was updated to contain the correct information.
// rotations and phases may be reversed