use of ome.units.quantity.Temperature in project bioformats by openmicroscopy.
the class MetamorphReader method initFile.
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
if (checkSuffix(id, ND_SUFFIX)) {
LOGGER.info("Initializing " + id);
// find an associated STK file
String stkFile = id.substring(0, id.lastIndexOf("."));
if (stkFile.indexOf(File.separatorChar) != -1) {
stkFile = stkFile.substring(stkFile.lastIndexOf(File.separator) + 1);
}
Location parent = new Location(id).getAbsoluteFile().getParentFile();
LOGGER.info("Looking for STK file in {}", parent.getAbsolutePath());
String[] dirList = parent.list(true);
Arrays.sort(dirList);
for (String f : dirList) {
int underscore = f.indexOf('_');
if (underscore < 0)
underscore = f.indexOf('.');
if (underscore < 0)
underscore = f.length();
String prefix = f.substring(0, underscore);
if ((f.equals(stkFile) || stkFile.startsWith(prefix)) && checkSuffix(f, STK_SUFFIX)) {
stkFile = new Location(parent.getAbsolutePath(), f).getAbsolutePath();
break;
}
}
if (!checkSuffix(stkFile, STK_SUFFIX)) {
throw new FormatException("STK file not found in " + parent.getAbsolutePath() + ".");
}
super.initFile(stkFile);
} else
super.initFile(id);
Location ndfile = null;
if (checkSuffix(id, ND_SUFFIX))
ndfile = new Location(id);
else if (canLookForND && isGroupFiles()) {
// an STK file was passed to initFile
// let's check the parent directory for an .nd file
Location stk = new Location(id).getAbsoluteFile();
String stkName = stk.getName();
String stkPrefix = stkName;
if (stkPrefix.indexOf('_') >= 0) {
stkPrefix = stkPrefix.substring(0, stkPrefix.indexOf('_') + 1);
}
Location parent = stk.getParentFile();
String[] list = parent.list(true);
int matchingChars = 0;
for (String f : list) {
if (checkSuffix(f, ND_SUFFIX)) {
String prefix = f.substring(0, f.lastIndexOf("."));
if (prefix.indexOf('_') >= 0) {
prefix = prefix.substring(0, prefix.indexOf('_') + 1);
}
if (stkName.startsWith(prefix) || prefix.equals(stkPrefix)) {
int charCount = 0;
for (int i = 0; i < f.length(); i++) {
if (i >= stkName.length()) {
break;
}
if (f.charAt(i) == stkName.charAt(i)) {
charCount++;
} else {
break;
}
}
if (charCount > matchingChars || (charCount == matchingChars && f.charAt(charCount) == '.')) {
ndfile = new Location(parent, f).getAbsoluteFile();
matchingChars = charCount;
}
}
}
}
}
String creationTime = null;
if (ndfile != null && ndfile.exists() && (fileGroupOption(id) == FormatTools.MUST_GROUP || isGroupFiles())) {
// parse key/value pairs from .nd file
int zc = getSizeZ(), cc = getSizeC(), tc = getSizeT();
int nstages = 0;
String z = null, c = null, t = null;
final List<Boolean> hasZ = new ArrayList<Boolean>();
waveNames = new ArrayList<String>();
stageNames = new ArrayList<String>();
boolean useWaveNames = true;
ndFilename = ndfile.getAbsolutePath();
String[] lines = DataTools.readFile(ndFilename).split("\n");
boolean globalDoZ = true;
boolean doTimelapse = false;
StringBuilder currentValue = new StringBuilder();
String key = "";
for (String line : lines) {
int comma = line.indexOf(',');
if (comma <= 0) {
currentValue.append("\n");
currentValue.append(line);
continue;
}
String value = currentValue.toString();
addGlobalMeta(key, value);
if (key.equals("NZSteps"))
z = value;
else if (key.equals("DoTimelapse")) {
doTimelapse = Boolean.parseBoolean(value);
} else if (key.equals("NWavelengths"))
c = value;
else if (key.equals("NTimePoints"))
t = value;
else if (key.startsWith("WaveDoZ")) {
hasZ.add(Boolean.parseBoolean(value));
} else if (key.startsWith("WaveName")) {
String waveName = value.substring(1, value.length() - 1);
if (waveName.equals("Both lasers") || waveName.startsWith("DUAL")) {
bizarreMultichannelAcquisition = true;
}
waveNames.add(waveName);
} else if (key.startsWith("Stage")) {
stageNames.add(value);
} else if (key.startsWith("StartTime")) {
creationTime = value;
} else if (key.equals("ZStepSize")) {
value = value.replace(',', '.');
stepSize = Double.parseDouble(value);
} else if (key.equals("NStagePositions")) {
nstages = Integer.parseInt(value);
} else if (key.equals("WaveInFileName")) {
useWaveNames = Boolean.parseBoolean(value);
} else if (key.equals("DoZSeries")) {
globalDoZ = Boolean.parseBoolean(value);
}
key = line.substring(1, comma - 1).trim();
currentValue.delete(0, currentValue.length());
currentValue.append(line.substring(comma + 1).trim());
}
if (!globalDoZ) {
for (int i = 0; i < hasZ.size(); i++) {
hasZ.set(i, false);
}
}
if (z != null)
zc = Integer.parseInt(z);
if (c != null)
cc = Integer.parseInt(c);
if (t != null)
tc = Integer.parseInt(t);
else if (!doTimelapse) {
tc = 1;
}
if (cc == 0)
cc = 1;
if (cc == 1 && bizarreMultichannelAcquisition) {
cc = 2;
}
if (tc == 0) {
tc = 1;
}
int numFiles = cc * tc;
if (nstages > 0)
numFiles *= nstages;
// determine series count
int stagesCount = nstages == 0 ? 1 : nstages;
int seriesCount = stagesCount;
firstSeriesChannels = new boolean[cc];
Arrays.fill(firstSeriesChannels, true);
boolean differentZs = false;
for (int i = 0; i < cc; i++) {
boolean hasZ1 = i < hasZ.size() && hasZ.get(i);
boolean hasZ2 = i != 0 && (i - 1 < hasZ.size()) && hasZ.get(i - 1);
if (i > 0 && hasZ1 != hasZ2 && globalDoZ) {
if (!differentZs)
seriesCount *= 2;
differentZs = true;
}
}
int channelsInFirstSeries = cc;
if (differentZs) {
channelsInFirstSeries = 0;
for (int i = 0; i < cc; i++) {
if ((!hasZ.get(0) && i == 0) || (hasZ.get(0) && hasZ.get(i))) {
channelsInFirstSeries++;
} else
firstSeriesChannels[i] = false;
}
}
stks = new String[seriesCount][];
if (seriesCount == 1)
stks[0] = new String[numFiles];
else if (differentZs) {
for (int i = 0; i < stagesCount; i++) {
stks[i * 2] = new String[channelsInFirstSeries * tc];
stks[i * 2 + 1] = new String[(cc - channelsInFirstSeries) * tc];
}
} else {
for (int i = 0; i < stks.length; i++) {
stks[i] = new String[numFiles / stks.length];
}
}
String prefix = ndfile.getPath();
prefix = prefix.substring(prefix.lastIndexOf(File.separator) + 1, prefix.lastIndexOf("."));
// build list of STK files
boolean anyZ = hasZ.contains(Boolean.TRUE);
int[] pt = new int[seriesCount];
for (int i = 0; i < tc; i++) {
for (int s = 0; s < stagesCount; s++) {
for (int j = 0; j < cc; j++) {
boolean validZ = j >= hasZ.size() || hasZ.get(j);
int seriesNdx = s * (seriesCount / stagesCount);
if ((seriesCount != 1 && (!validZ || (hasZ.size() > 0 && !hasZ.get(0)))) || (nstages == 0 && ((!validZ && cc > 1) || seriesCount > 1))) {
if (anyZ && j > 0 && seriesNdx < seriesCount - 1 && (!validZ || !hasZ.get(0))) {
seriesNdx++;
}
}
if (seriesNdx >= stks.length || seriesNdx >= pt.length || pt[seriesNdx] >= stks[seriesNdx].length) {
continue;
}
stks[seriesNdx][pt[seriesNdx]] = prefix;
if (j < waveNames.size() && waveNames.get(j) != null) {
stks[seriesNdx][pt[seriesNdx]] += "_w" + (j + 1);
if (useWaveNames) {
String waveName = waveNames.get(j);
// If there are underscores in the wavelength name, translate
// them to hyphens. (See #558)
waveName = waveName.replace('_', '-');
// If there are slashes (forward or backward) in the wavelength
// name, translate them to hyphens. (See #5922)
waveName = waveName.replace('/', '-');
waveName = waveName.replace('\\', '-');
waveName = waveName.replace('(', '-');
waveName = waveName.replace(')', '-');
stks[seriesNdx][pt[seriesNdx]] += waveName;
}
}
if (nstages > 0) {
stks[seriesNdx][pt[seriesNdx]] += "_s" + (s + 1);
}
if (tc > 1 || doTimelapse) {
stks[seriesNdx][pt[seriesNdx]] += "_t" + (i + 1) + ".STK";
} else
stks[seriesNdx][pt[seriesNdx]] += ".STK";
pt[seriesNdx]++;
}
}
}
ndfile = ndfile.getAbsoluteFile();
for (int s = 0; s < stks.length; s++) {
for (int f = 0; f < stks[s].length; f++) {
Location l = new Location(ndfile.getParent(), stks[s][f]);
stks[s][f] = getRealSTKFile(l);
}
}
String file = locateFirstValidFile();
if (file == null) {
throw new FormatException("Unable to locate at least one valid STK file!");
}
RandomAccessInputStream s = new RandomAccessInputStream(file, 16);
TiffParser tp = new TiffParser(s);
IFD ifd = tp.getFirstIFD();
CoreMetadata ms0 = core.get(0);
s.close();
ms0.sizeX = (int) ifd.getImageWidth();
ms0.sizeY = (int) ifd.getImageLength();
if (bizarreMultichannelAcquisition) {
ms0.sizeX /= 2;
}
ms0.sizeZ = hasZ.size() > 0 && !hasZ.get(0) ? 1 : zc;
ms0.sizeC = cc;
ms0.sizeT = tc;
ms0.imageCount = getSizeZ() * getSizeC() * getSizeT();
ms0.dimensionOrder = "XYZCT";
if (stks != null && stks.length > 1) {
// Note that core can't be replaced with newCore until the end of this block.
ArrayList<CoreMetadata> newCore = new ArrayList<CoreMetadata>();
for (int i = 0; i < stks.length; i++) {
CoreMetadata ms = new CoreMetadata();
newCore.add(ms);
ms.sizeX = getSizeX();
ms.sizeY = getSizeY();
ms.sizeZ = getSizeZ();
ms.sizeC = getSizeC();
ms.sizeT = getSizeT();
ms.pixelType = getPixelType();
ms.imageCount = getImageCount();
ms.dimensionOrder = getDimensionOrder();
ms.rgb = isRGB();
ms.littleEndian = isLittleEndian();
ms.interleaved = isInterleaved();
ms.orderCertain = true;
}
if (stks.length > nstages) {
for (int j = 0; j < stagesCount; j++) {
int idx = j * 2 + 1;
CoreMetadata midx = newCore.get(idx);
CoreMetadata pmidx = newCore.get(j * 2);
pmidx.sizeC = stks[j * 2].length / getSizeT();
midx.sizeC = stks[idx].length / midx.sizeT;
midx.sizeZ = hasZ.size() > 1 && hasZ.get(1) && core.get(0).sizeZ == 1 ? zc : 1;
pmidx.imageCount = pmidx.sizeC * pmidx.sizeT * pmidx.sizeZ;
midx.imageCount = midx.sizeC * midx.sizeT * midx.sizeZ;
}
}
core = newCore;
}
}
if (stks == null) {
stkReaders = new MetamorphReader[1][1];
stkReaders[0][0] = new MetamorphReader();
stkReaders[0][0].setCanLookForND(false);
} else {
stkReaders = new MetamorphReader[stks.length][];
for (int i = 0; i < stks.length; i++) {
stkReaders[i] = new MetamorphReader[stks[i].length];
for (int j = 0; j < stkReaders[i].length; j++) {
stkReaders[i][j] = new MetamorphReader();
stkReaders[i][j].setCanLookForND(false);
if (j > 0) {
stkReaders[i][j].setMetadataOptions(new DefaultMetadataOptions(MetadataLevel.MINIMUM));
}
}
}
}
// check stage labels for plate data
int rows = 0;
int cols = 0;
Map<String, Integer> rowMap = null;
Map<String, Integer> colMap = null;
isHCS = true;
if (null == stageLabels) {
isHCS = false;
} else {
Set<Map.Entry<Integer, Integer>> uniqueWells = new HashSet<Map.Entry<Integer, Integer>>();
rowMap = new HashMap<String, Integer>();
colMap = new HashMap<String, Integer>();
for (String label : stageLabels) {
if (null == label) {
isHCS = false;
break;
}
Map.Entry<Integer, Integer> wellCoords = getWellCoords(label);
if (null == wellCoords) {
isHCS = false;
break;
}
uniqueWells.add(wellCoords);
rowMap.put(label, wellCoords.getKey());
colMap.put(label, wellCoords.getValue());
}
if (uniqueWells.size() != stageLabels.length) {
isHCS = false;
} else {
rows = Collections.max(rowMap.values());
cols = Collections.max(colMap.values());
CoreMetadata c = core.get(0);
core.clear();
c.sizeZ = 1;
c.sizeT = 1;
c.imageCount = 1;
for (int s = 0; s < uniqueWells.size(); s++) {
CoreMetadata toAdd = new CoreMetadata(c);
if (s > 0) {
toAdd.seriesMetadata.clear();
}
core.add(toAdd);
}
seriesToIFD = true;
}
}
List<String> timestamps = null;
MetamorphHandler handler = null;
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
if (isHCS) {
store.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
store.setPlateRows(new PositiveInteger(rows), 0);
store.setPlateColumns(new PositiveInteger(cols), 0);
store.setPlateRowNamingConvention(NamingConvention.LETTER, 0);
store.setPlateColumnNamingConvention(NamingConvention.NUMBER, 0);
}
int nextObjective = 0;
String instrumentID = MetadataTools.createLSID("Instrument", 0);
String detectorID = MetadataTools.createLSID("Detector", 0, 0);
store.setInstrumentID(instrumentID, 0);
store.setDetectorID(detectorID, 0, 0);
store.setDetectorType(getDetectorType("Other"), 0, 0);
for (int i = 0; i < getSeriesCount(); i++) {
setSeries(i);
// do not reparse the same XML for every well
if (i == 0 || !isHCS) {
handler = new MetamorphHandler(getSeriesMetadata());
}
if (isHCS) {
String label = stageLabels[i];
String wellID = MetadataTools.createLSID("Well", 0, i);
store.setWellID(wellID, 0, i);
store.setWellColumn(new NonNegativeInteger(colMap.get(label)), 0, i);
store.setWellRow(new NonNegativeInteger(rowMap.get(label)), 0, i);
store.setWellSampleID(MetadataTools.createLSID("WellSample", 0, i, 0), 0, i, 0);
store.setWellSampleImageRef(MetadataTools.createLSID("Image", i), 0, i, 0);
store.setWellSampleIndex(new NonNegativeInteger(i), 0, i, 0);
}
store.setImageInstrumentRef(instrumentID, i);
String comment = getFirstComment(i);
if (i == 0 || !isHCS) {
if (comment != null && comment.startsWith("<MetaData>")) {
try {
XMLTools.parseXML(XMLTools.sanitizeXML(comment), handler);
} catch (IOException e) {
}
}
}
if (creationTime != null) {
String date = DateTools.formatDate(creationTime, SHORT_DATE_FORMAT, ".");
if (date != null) {
store.setImageAcquisitionDate(new Timestamp(date), 0);
}
}
store.setImageName(makeImageName(i).trim(), i);
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) {
continue;
}
store.setImageDescription("", i);
store.setImagingEnvironmentTemperature(new Temperature(handler.getTemperature(), UNITS.CELSIUS), i);
if (sizeX == null)
sizeX = handler.getPixelSizeX();
if (sizeY == null)
sizeY = handler.getPixelSizeY();
Length physicalSizeX = FormatTools.getPhysicalSizeX(sizeX);
Length physicalSizeY = FormatTools.getPhysicalSizeY(sizeY);
if (physicalSizeX != null) {
store.setPixelsPhysicalSizeX(physicalSizeX, i);
}
if (physicalSizeY != null) {
store.setPixelsPhysicalSizeY(physicalSizeY, i);
}
if (zDistances != null) {
stepSize = zDistances[0];
} else {
List<Double> zPositions = new ArrayList<Double>();
final List<Double> uniqueZ = new ArrayList<Double>();
for (IFD ifd : ifds) {
MetamorphHandler zPlaneHandler = new MetamorphHandler();
String zComment = ifd.getComment();
if (zComment != null && zComment.startsWith("<MetaData>")) {
try {
XMLTools.parseXML(XMLTools.sanitizeXML(zComment), zPlaneHandler);
} catch (IOException e) {
}
}
zPositions = zPlaneHandler.getZPositions();
for (Double z : zPositions) {
if (!uniqueZ.contains(z))
uniqueZ.add(z);
}
}
if (uniqueZ.size() > 1 && uniqueZ.size() == getSizeZ()) {
BigDecimal lastZ = BigDecimal.valueOf(uniqueZ.get(uniqueZ.size() - 1));
BigDecimal firstZ = BigDecimal.valueOf(uniqueZ.get(0));
BigDecimal zRange = (lastZ.subtract(firstZ)).abs();
BigDecimal zSize = BigDecimal.valueOf((double) (getSizeZ() - 1));
MathContext mc = new MathContext(10, RoundingMode.HALF_UP);
stepSize = zRange.divide(zSize, mc).doubleValue();
}
}
Length physicalSizeZ = FormatTools.getPhysicalSizeZ(stepSize);
if (physicalSizeZ != null) {
store.setPixelsPhysicalSizeZ(physicalSizeZ, i);
}
if (handler.getLensNA() != 0 || handler.getLensRI() != 0) {
String objectiveID = MetadataTools.createLSID("Objective", 0, nextObjective);
store.setObjectiveID(objectiveID, 0, nextObjective);
if (handler.getLensNA() != 0) {
store.setObjectiveLensNA(handler.getLensNA(), 0, nextObjective);
}
store.setObjectiveSettingsID(objectiveID, i);
if (handler.getLensRI() != 0) {
store.setObjectiveSettingsRefractiveIndex(handler.getLensRI(), i);
}
nextObjective++;
}
int waveIndex = 0;
for (int c = 0; c < getEffectiveSizeC(); c++) {
if (firstSeriesChannels == null || (stageNames != null && stageNames.size() == getSeriesCount())) {
waveIndex = c;
} else if (firstSeriesChannels != null) {
int s = i % 2;
while (firstSeriesChannels[waveIndex] == (s == 1) && waveIndex < firstSeriesChannels.length) {
waveIndex++;
}
}
if (waveNames != null && waveIndex < waveNames.size()) {
store.setChannelName(waveNames.get(waveIndex).trim(), i, c);
}
if (handler.getBinning() != null)
binning = handler.getBinning();
if (binning != null) {
store.setDetectorSettingsBinning(getBinning(binning), i, c);
}
if (handler.getReadOutRate() != 0) {
store.setDetectorSettingsReadOutRate(new Frequency(handler.getReadOutRate(), UNITS.HERTZ), i, c);
}
if (gain == null) {
gain = handler.getGain();
}
if (gain != null) {
store.setDetectorSettingsGain(gain, i, c);
}
store.setDetectorSettingsID(detectorID, i, c);
if (wave != null && waveIndex < wave.length) {
Length wavelength = FormatTools.getWavelength(wave[waveIndex]);
if ((int) wave[waveIndex] >= 1) {
// link LightSource to Image
int laserIndex = i * getEffectiveSizeC() + c;
String lightSourceID = MetadataTools.createLSID("LightSource", 0, laserIndex);
store.setLaserID(lightSourceID, 0, laserIndex);
store.setChannelLightSourceSettingsID(lightSourceID, i, c);
store.setLaserType(getLaserType("Other"), 0, laserIndex);
store.setLaserLaserMedium(getLaserMedium("Other"), 0, laserIndex);
if (wavelength != null) {
store.setChannelLightSourceSettingsWavelength(wavelength, i, c);
}
}
}
waveIndex++;
}
timestamps = handler.getTimestamps();
for (int t = 0; t < timestamps.size(); t++) {
String date = DateTools.convertDate(DateTools.getTime(timestamps.get(t), SHORT_DATE_FORMAT, "."), DateTools.UNIX, SHORT_DATE_FORMAT + ".SSS");
addSeriesMetaList("timestamp", date);
}
long startDate = 0;
if (timestamps.size() > 0) {
startDate = DateTools.getTime(timestamps.get(0), SHORT_DATE_FORMAT, ".");
}
final Length positionX = handler.getStagePositionX();
final Length positionY = handler.getStagePositionY();
final List<Double> exposureTimes = handler.getExposures();
if (exposureTimes.size() == 0) {
for (int p = 0; p < getImageCount(); p++) {
exposureTimes.add(exposureTime);
}
} else if (exposureTimes.size() == 1 && exposureTimes.size() < getSizeC()) {
for (int c = 1; c < getSizeC(); c++) {
MetamorphHandler channelHandler = new MetamorphHandler();
String channelComment = getComment(i, c);
if (channelComment != null && channelComment.startsWith("<MetaData>")) {
try {
XMLTools.parseXML(XMLTools.sanitizeXML(channelComment), channelHandler);
} catch (IOException e) {
}
}
final List<Double> channelExpTime = channelHandler.getExposures();
exposureTimes.add(channelExpTime.get(0));
}
}
int lastFile = -1;
IFDList lastIFDs = null;
IFD lastIFD = null;
double distance = zStart;
TiffParser tp = null;
RandomAccessInputStream stream = null;
for (int p = 0; p < getImageCount(); p++) {
int[] coords = getZCTCoords(p);
Double deltaT = 0d;
Double expTime = exposureTime;
Double xmlZPosition = null;
int fileIndex = getIndex(0, coords[1], coords[2]) / getSizeZ();
if (fileIndex >= 0) {
String file = stks == null ? currentId : stks[i][fileIndex];
if (file != null) {
if (fileIndex != lastFile) {
if (stream != null) {
stream.close();
}
stream = new RandomAccessInputStream(file, 16);
tp = new TiffParser(stream);
tp.checkHeader();
IFDList f = tp.getIFDs();
if (f.size() > 0) {
lastFile = fileIndex;
lastIFDs = f;
} else {
file = null;
stks[i][fileIndex] = null;
}
}
}
if (file != null) {
lastIFD = lastIFDs.get(p % lastIFDs.size());
Object commentEntry = lastIFD.get(IFD.IMAGE_DESCRIPTION);
if (commentEntry != null) {
if (commentEntry instanceof String) {
comment = (String) commentEntry;
} else if (commentEntry instanceof TiffIFDEntry) {
comment = tp.getIFDValue((TiffIFDEntry) commentEntry).toString();
}
}
if (comment != null)
comment = comment.trim();
if (comment != null && comment.startsWith("<MetaData>")) {
String[] lines = comment.split("\n");
timestamps = new ArrayList<String>();
for (String line : lines) {
line = line.trim();
if (line.startsWith("<prop")) {
int firstQuote = line.indexOf("\"") + 1;
int lastQuote = line.lastIndexOf("\"");
String key = line.substring(firstQuote, line.indexOf("\"", firstQuote));
String value = line.substring(line.lastIndexOf("\"", lastQuote - 1) + 1, lastQuote);
if (key.equals("z-position")) {
xmlZPosition = new Double(value);
} else if (key.equals("acquisition-time-local")) {
timestamps.add(value);
}
}
}
}
}
}
int index = 0;
if (timestamps.size() > 0) {
if (coords[2] < timestamps.size())
index = coords[2];
String stamp = timestamps.get(index);
long ms = DateTools.getTime(stamp, SHORT_DATE_FORMAT, ".");
deltaT = (ms - startDate) / 1000.0;
} else if (internalStamps != null && p < internalStamps.length) {
long delta = internalStamps[p] - internalStamps[0];
deltaT = delta / 1000.0;
if (coords[2] < exposureTimes.size())
index = coords[2];
}
if (index == 0 && p > 0 && exposureTimes.size() > 0) {
index = coords[1] % exposureTimes.size();
}
if (index < exposureTimes.size()) {
expTime = exposureTimes.get(index);
}
if (deltaT != null) {
store.setPlaneDeltaT(new Time(deltaT, UNITS.SECOND), i, p);
}
if (expTime != null) {
store.setPlaneExposureTime(new Time(expTime, UNITS.SECOND), i, p);
}
if (stageX != null && p < stageX.length) {
store.setPlanePositionX(stageX[p], i, p);
} else if (positionX != null) {
store.setPlanePositionX(positionX, i, p);
}
if (stageY != null && p < stageY.length) {
store.setPlanePositionY(stageY[p], i, p);
} else if (positionY != null) {
store.setPlanePositionY(positionY, i, p);
}
if (zDistances != null && p < zDistances.length) {
if (p > 0) {
if (zDistances[p] != 0d)
distance += zDistances[p];
else
distance += zDistances[0];
}
final Length zPos = new Length(distance, UNITS.REFERENCEFRAME);
store.setPlanePositionZ(zPos, i, p);
} else if (xmlZPosition != null) {
final Length zPos = new Length(xmlZPosition, UNITS.REFERENCEFRAME);
store.setPlanePositionZ(zPos, i, p);
}
}
if (stream != null) {
stream.close();
}
}
setSeries(0);
}
use of ome.units.quantity.Temperature in project bioformats by openmicroscopy.
the class NativeND2Reader method populateMetadataStore.
private void populateMetadataStore(ND2Handler handler) throws FormatException {
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
String filename = new Location(getCurrentFile()).getName();
if (handler != null) {
ArrayList<String> posNames = handler.getPositionNames();
int nameWidth = String.valueOf(getSeriesCount()).length();
for (int i = 0; i < getSeriesCount(); i++) {
String seriesSuffix = String.format("(series %0" + nameWidth + "d)", i + 1);
String suffix = (i < posNames.size() && !posNames.get(i).equals("")) ? posNames.get(i) : seriesSuffix;
String name = filename + " " + suffix;
store.setImageName(name.trim(), i);
}
}
colors = new int[getEffectiveSizeC()];
ArrayList<String> channelNames = null;
if (handler != null) {
channelNames = handler.getChannelNames();
if (channelNames.size() < getEffectiveSizeC() && backupHandler != null) {
channelNames = backupHandler.getChannelNames();
} else if (channelNames.size() < getEffectiveSizeC()) {
channelNames = textChannelNames;
}
for (int c = 0; c < getEffectiveSizeC(); c++) {
if (c < channelNames.size()) {
String channelName = channelNames.get(c);
Integer channelColor = channelColors.get(channelName);
colors[c] = channelColor == null ? 0 : channelColor.intValue();
}
}
}
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) {
return;
}
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
for (int i = 0; i < getSeriesCount(); i++) {
// link Instrument and Image
store.setImageInstrumentRef(instrumentID, i);
// set the channel color
for (int c = 0; c < getEffectiveSizeC(); c++) {
int red = colors[c] & 0xff;
int green = (colors[c] & 0xff00) >> 8;
int blue = (colors[c] & 0xff0000) >> 16;
// doing so can prevent the image from displaying correctly
if (red != 0 || green != 0 || blue != 0) {
// always set the alpha to 255, otherwise the colors may not appear
store.setChannelColor(new Color(red, green, blue, 255), i, c);
}
}
}
// populate Dimensions data
if (handler != null) {
for (int i = 0; i < getSeriesCount(); i++) {
double sizeX = handler.getPixelSizeX();
double sizeY = handler.getPixelSizeY();
double sizeZ = handler.getPixelSizeZ();
if (trueSizeX > 0) {
store.setPixelsPhysicalSizeX(FormatTools.getPhysicalSizeX(trueSizeX), i);
} else {
Length size = FormatTools.getPhysicalSizeX(sizeX);
if (size != null) {
store.setPixelsPhysicalSizeX(size, i);
}
}
if (trueSizeY > 0) {
store.setPixelsPhysicalSizeY(FormatTools.getPhysicalSizeY(trueSizeY), i);
} else if (trueSizeX > 0) {
// if the X size is set, assume X and Y are equal
store.setPixelsPhysicalSizeY(FormatTools.getPhysicalSizeY(trueSizeX), i);
} else {
Length size = FormatTools.getPhysicalSizeY(sizeY);
if (size == null) {
// if the X size is set, assume X and Y are equal
size = FormatTools.getPhysicalSizeY(sizeX);
}
if (size != null) {
store.setPixelsPhysicalSizeY(size, i);
}
}
if (trueSizeZ != null && trueSizeZ > 0) {
store.setPixelsPhysicalSizeZ(FormatTools.getPhysicalSizeZ(trueSizeZ), i);
} else {
Length size = FormatTools.getPhysicalSizeZ(sizeZ);
if (size != null) {
store.setPixelsPhysicalSizeZ(size, i);
}
}
}
}
// populate PlaneTiming and StagePosition data
if (handler != null && handler.getExposureTimes().size() > 0) {
exposureTime = handler.getExposureTimes();
}
int zcPlanes = getImageCount() / ((split ? getSizeC() : 1) * getSizeT());
for (int i = 0; i < getSeriesCount(); i++) {
if (tsT.size() > 0) {
setSeries(i);
for (int n = 0; n < getImageCount(); n++) {
int[] coords = getZCTCoords(n);
int stampIndex = getIndex(coords[0], split ? 0 : coords[1], 0);
stampIndex += (coords[2] * getSeriesCount() + i) * zcPlanes;
if (tsT.size() == getImageCount())
stampIndex = n;
else if (tsT.size() == getSizeZ()) {
stampIndex = coords[0];
}
if (stampIndex < tsT.size()) {
double stamp = tsT.get(stampIndex).doubleValue();
store.setPlaneDeltaT(new Time(stamp, UNITS.SECOND), i, n);
}
int index = i * getSizeC() + coords[1];
if (exposureTime.size() == getSizeC()) {
index = coords[1];
}
if (exposureTime != null && index < exposureTime.size() && exposureTime.get(index) != null) {
store.setPlaneExposureTime(new Time(exposureTime.get(index), UNITS.SECOND), i, n);
}
}
}
if (handler != null) {
if (posX == null)
posX = handler.getXPositions();
if (posY == null)
posY = handler.getYPositions();
if (posZ == null)
posZ = handler.getZPositions();
}
String pos = "for position";
for (int n = 0; n < getImageCount(); n++) {
int[] coords = getZCTCoords(n);
int index = coords[0];
index += (coords[2] * getSeriesCount() + i) * zcPlanes;
if (posX != null) {
if (index >= posX.size())
index = i;
if (index < posX.size()) {
String key = "X position ";
store.setPlanePositionX(posX.get(index), i, n);
addSeriesMetaList(key, posX.get(index));
addGlobalMetaList(key + pos, posX.get(index));
}
}
if (posY != null) {
if (index < posY.size()) {
String key = "Y position ";
store.setPlanePositionY(posY.get(index), i, n);
addSeriesMetaList(key, posY.get(index));
addGlobalMetaList(key + pos, posY.get(index));
}
}
if (posZ != null) {
if (index < posZ.size()) {
store.setPlanePositionZ(posZ.get(index), i, n);
String key = "Z position " + pos + ", plane";
addSeriesMetaList(key, posZ.get(index));
addGlobalMetaList(key, posZ.get(index));
}
}
}
}
if (handler == null) {
setSeries(0);
return;
}
String detectorID = MetadataTools.createLSID("Detector", 0, 0);
store.setDetectorID(detectorID, 0, 0);
store.setDetectorModel(handler.getCameraModel(), 0, 0);
store.setDetectorType(getDetectorType("Other"), 0, 0);
ArrayList<String> modality = handler.getModalities();
ArrayList<String> binning = handler.getBinnings();
ArrayList<Double> speed = handler.getSpeeds();
ArrayList<Double> gain = handler.getGains();
ArrayList<Double> temperature = handler.getTemperatures();
ArrayList<Double> exWave = handler.getExcitationWavelengths();
ArrayList<Double> emWave = handler.getEmissionWavelengths();
ArrayList<Integer> power = handler.getPowers();
ArrayList<Hashtable<String, String>> rois = handler.getROIs();
if (backupHandler != null) {
if (emWave.size() == 0) {
emWave = backupHandler.getEmissionWavelengths();
}
if (exWave.size() == 0) {
exWave = backupHandler.getExcitationWavelengths();
}
}
for (int i = 0; i < getSeriesCount(); i++) {
for (int c = 0; c < getEffectiveSizeC(); c++) {
int index = c;
Double pinholeSize = handler.getPinholeSize();
if (pinholeSize != null) {
store.setChannelPinholeSize(new Length(pinholeSize, UNITS.MICROMETER), i, c);
}
if (index < channelNames.size()) {
String channelName = channelNames.get(index);
store.setChannelName(channelName, i, c);
} else if (channelNames.size() >= getEffectiveSizeC()) {
store.setChannelName(channelNames.get(c), i, c);
}
if (index < modality.size()) {
store.setChannelAcquisitionMode(getAcquisitionMode(modality.get(index)), i, c);
}
if (index < emWave.size() || index < textEmissionWavelengths.size()) {
Double value = index < emWave.size() ? emWave.get(index) : textEmissionWavelengths.get(index);
Length emission = FormatTools.getEmissionWavelength(value);
if (emission != null) {
store.setChannelEmissionWavelength(emission, i, c);
}
} else if (emWave.size() > 0 || textEmissionWavelengths.size() > 0) {
store.setChannelColor(new Color(255, 255, 255, 255), i, c);
}
if (index < exWave.size()) {
Length excitation = FormatTools.getExcitationWavelength(exWave.get(index));
if (excitation != null) {
store.setChannelExcitationWavelength(excitation, i, c);
}
}
if (index < binning.size()) {
store.setDetectorSettingsBinning(getBinning(binning.get(index)), i, c);
}
if (index < gain.size()) {
store.setDetectorSettingsGain(gain.get(index), i, c);
}
if (index < speed.size()) {
store.setDetectorSettingsReadOutRate(new Frequency(speed.get(index), UNITS.HERTZ), i, c);
}
store.setDetectorSettingsID(detectorID, i, c);
}
}
for (int i = 0; i < getSeriesCount(); i++) {
if (i * getSizeC() < temperature.size()) {
Double temp = temperature.get(i * getSizeC());
store.setImagingEnvironmentTemperature(new Temperature(temp, UNITS.CELSIUS), i);
}
}
// populate DetectorSettings
Double voltage = handler.getVoltage();
if (voltage != null) {
store.setDetectorSettingsVoltage(new ElectricPotential(voltage, UNITS.VOLT), 0, 0);
}
// populate Objective
Double na = handler.getNumericalAperture();
if (na != null) {
store.setObjectiveLensNA(na, 0, 0);
}
Double mag = handler.getMagnification();
if (mag != null) {
store.setObjectiveCalibratedMagnification(mag, 0, 0);
}
store.setObjectiveModel(handler.getObjectiveModel(), 0, 0);
String immersion = handler.getImmersion();
if (immersion == null)
immersion = "Other";
store.setObjectiveImmersion(getImmersion(immersion), 0, 0);
String correction = handler.getCorrection();
if (correction == null || correction.length() == 0)
correction = "Other";
store.setObjectiveCorrection(getCorrection(correction), 0, 0);
// link Objective to Image
String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
store.setObjectiveID(objectiveID, 0, 0);
if (refractiveIndex == null) {
refractiveIndex = handler.getRefractiveIndex();
}
for (int i = 0; i < getSeriesCount(); i++) {
store.setObjectiveSettingsID(objectiveID, i);
if (refractiveIndex != null) {
store.setObjectiveSettingsRefractiveIndex(refractiveIndex, i);
}
}
setSeries(0);
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.NO_OVERLAYS) {
return;
}
handler.populateROIs(store);
}
use of ome.units.quantity.Temperature in project bioformats by openmicroscopy.
the class MicromanagerReader method populateMetadata.
private void populateMetadata() throws FormatException, IOException {
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
for (int i = 0; i < positions.size(); i++) {
Position p = positions.get(i);
if (p.time != null) {
String date = DateTools.formatDate(p.time, DATE_FORMAT);
if (date != null) {
store.setImageAcquisitionDate(new Timestamp(date), i);
}
}
if (positions.size() > 1) {
Location parent = new Location(p.metadataFile).getParentFile();
store.setImageName(parent.getName(), i);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
store.setImageDescription(p.comment, i);
// link Instrument and Image
store.setImageInstrumentRef(instrumentID, i);
for (int c = 0; c < p.channels.length; c++) {
store.setChannelName(p.channels[c], i, c);
}
Length sizeX = FormatTools.getPhysicalSizeX(p.pixelSize);
Length sizeY = FormatTools.getPhysicalSizeY(p.pixelSize);
Length sizeZ = FormatTools.getPhysicalSizeZ(p.sliceThickness);
if (sizeX != null) {
store.setPixelsPhysicalSizeX(sizeX, i);
}
if (sizeY != null) {
store.setPixelsPhysicalSizeY(sizeY, i);
}
if (sizeZ != null) {
store.setPixelsPhysicalSizeZ(sizeZ, i);
}
int nextStamp = 0;
for (int q = 0; q < getImageCount(); q++) {
store.setPlaneExposureTime(p.exposureTime, i, q);
String tiff = positions.get(getSeries()).getFile(q);
if (tiff != null && new Location(tiff).exists() && nextStamp < p.timestamps.length && p.timestamps[nextStamp] != null) {
store.setPlaneDeltaT(new Time(p.timestamps[nextStamp++], UNITS.MILLISECOND), i, q);
}
if (p.positions != null && q < p.positions.length) {
if (p.positions[q][0] != null) {
store.setPlanePositionX(new Length(p.positions[q][0], UNITS.MICROMETER), i, q);
}
if (p.positions[q][1] != null) {
store.setPlanePositionY(new Length(p.positions[q][1], UNITS.MICROMETER), i, q);
}
if (p.positions[q][2] != null) {
store.setPlanePositionZ(new Length(p.positions[q][2], UNITS.MICROMETER), i, q);
}
}
}
String serialNumber = p.detectorID;
p.detectorID = MetadataTools.createLSID("Detector", 0, i);
for (int c = 0; c < p.channels.length; c++) {
store.setDetectorSettingsBinning(getBinning(p.binning), i, c);
store.setDetectorSettingsGain(new Double(p.gain), i, c);
if (c < p.voltage.size()) {
store.setDetectorSettingsVoltage(new ElectricPotential(p.voltage.get(c), UNITS.VOLT), i, c);
}
store.setDetectorSettingsID(p.detectorID, i, c);
}
store.setDetectorID(p.detectorID, 0, i);
if (p.detectorModel != null) {
store.setDetectorModel(p.detectorModel, 0, i);
}
if (serialNumber != null) {
store.setDetectorSerialNumber(serialNumber, 0, i);
}
if (p.detectorManufacturer != null) {
store.setDetectorManufacturer(p.detectorManufacturer, 0, i);
}
if (p.cameraMode == null)
p.cameraMode = "Other";
store.setDetectorType(getDetectorType(p.cameraMode), 0, i);
store.setImagingEnvironmentTemperature(new Temperature(p.temperature, UNITS.CELSIUS), i);
}
}
}
use of ome.units.quantity.Temperature in project bioformats by openmicroscopy.
the class ZeissCZIReader method initFile.
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
parser = XMLTools.createBuilder();
// switch to the master file if this is part of a multi-file dataset
int lastDot = id.lastIndexOf(".");
String base = lastDot < 0 ? id : id.substring(0, lastDot);
if (base.endsWith(")") && isGroupFiles()) {
LOGGER.info("Checking for master file");
int lastFileSeparator = base.lastIndexOf(File.separator);
int end = base.lastIndexOf(" (");
if (end < 0 || end < lastFileSeparator) {
end = base.lastIndexOf("(");
}
if (end > 0 && end > lastFileSeparator) {
base = base.substring(0, end) + ".czi";
if (new Location(base).exists()) {
LOGGER.info("Initializing master file {}", base);
initFile(base);
return;
}
}
}
CoreMetadata ms0 = core.get(0);
ms0.littleEndian = true;
pixels = new HashMap<Integer, String>();
segments = new ArrayList<Segment>();
planes = new ArrayList<SubBlock>();
readSegments(id);
// check if we have the master file in a multi-file dataset
// file names are not stored in the files; we have to rely on a
// specific naming convention:
//
// master_file.czi
// master_file (1).czi
// master_file (2).czi
// ...
//
// the number of files is also not stored, so we have to manually check
// for all files with a matching name
Location file = new Location(id).getAbsoluteFile();
base = file.getName();
lastDot = base.lastIndexOf(".");
if (lastDot >= 0) {
base = base.substring(0, lastDot);
}
Location parent = file.getParentFile();
String[] list = parent.list(true);
for (String f : list) {
if (f.startsWith(base + "(") || f.startsWith(base + " (")) {
String part = f.substring(f.lastIndexOf("(") + 1, f.lastIndexOf(")"));
try {
pixels.put(Integer.parseInt(part), new Location(parent, f).getAbsolutePath());
} catch (NumberFormatException e) {
LOGGER.debug("{} not included in multi-file dataset", f);
}
}
}
Integer[] keys = pixels.keySet().toArray(new Integer[pixels.size()]);
Arrays.sort(keys);
for (Integer key : keys) {
readSegments(pixels.get(key));
}
calculateDimensions();
if (planes.size() == 0) {
throw new FormatException("Pixel data could not be found; this file may be corrupted");
}
int firstX = planes.get(0).x;
int firstY = planes.get(0).y;
if (getSizeC() == 0) {
ms0.sizeC = 1;
}
if (getSizeZ() == 0) {
ms0.sizeZ = 1;
}
if (getSizeT() == 0) {
ms0.sizeT = 1;
}
if (getImageCount() == 0) {
ms0.imageCount = ms0.sizeZ * ms0.sizeT;
}
int originalC = getSizeC();
convertPixelType(planes.get(0).directoryEntry.pixelType);
// remove any invalid SubBlocks
int bpp = FormatTools.getBytesPerPixel(getPixelType());
if (isRGB()) {
bpp *= (getSizeC() / originalC);
}
int fullResBlockCount = planes.size();
for (int i = 0; i < planes.size(); i++) {
long planeSize = (long) planes.get(i).x * planes.get(i).y * bpp;
int compression = planes.get(i).directoryEntry.compression;
if (compression == UNCOMPRESSED || compression == JPEGXR) {
long size = planes.get(i).dataSize;
if (size < planeSize || planeSize >= Integer.MAX_VALUE || size < 0) {
// check for reduced resolution in the pyramid
DimensionEntry[] entries = planes.get(i).directoryEntry.dimensionEntries;
int pyramidType = planes.get(i).directoryEntry.pyramidType;
if ((pyramidType == 1 || pyramidType == 2 || compression == JPEGXR) && (compression == JPEGXR || size == entries[0].storedSize * entries[1].storedSize * bpp)) {
int scale = planes.get(i).x / entries[0].storedSize;
if (scale == 1 || (((scale % 2) == 0 || (scale % 3) == 0) && allowAutostitching())) {
if (scale > 1 && scaleFactor == 0) {
scaleFactor = scale % 2 == 0 ? 2 : 3;
}
planes.get(i).coreIndex = 0;
while (scale > 1) {
scale /= scaleFactor;
planes.get(i).coreIndex++;
}
if (planes.get(i).coreIndex > maxResolution) {
maxResolution = planes.get(i).coreIndex;
}
} else {
LOGGER.trace("removing block #{}; calculated size = {}, recorded size = {}, scale = {}", i, planeSize, size, scale);
planes.remove(i);
i--;
}
} else {
LOGGER.trace("removing block #{}; calculated size = {}, recorded size = {}", i, planeSize, size);
planes.remove(i);
i--;
}
fullResBlockCount--;
} else {
scanDim = (int) (size / planeSize);
}
} else {
byte[] pixels = planes.get(i).readPixelData();
if (pixels.length < planeSize || planeSize >= Integer.MAX_VALUE) {
LOGGER.trace("removing block #{}; calculated size = {}, decoded size = {}", i, planeSize, pixels.length);
planes.remove(i);
i--;
} else {
scanDim = (int) (pixels.length / planeSize);
}
}
}
if (getSizeZ() == 0) {
ms0.sizeZ = 1;
}
if (getSizeC() == 0) {
ms0.sizeC = 1;
}
if (getSizeT() == 0) {
ms0.sizeT = 1;
}
// set modulo annotations
// rotations -> modulo Z
// illuminations -> modulo C
// phases -> modulo T
LOGGER.trace("rotations = {}", rotations);
LOGGER.trace("illuminations = {}", illuminations);
LOGGER.trace("phases = {}", phases);
LOGGER.trace("positions = {}", positions);
LOGGER.trace("acquisitions = {}", acquisitions);
LOGGER.trace("mosaics = {}", mosaics);
LOGGER.trace("angles = {}", angles);
ms0.moduloZ.step = ms0.sizeZ;
ms0.moduloZ.end = ms0.sizeZ * (rotations - 1);
ms0.moduloZ.type = FormatTools.ROTATION;
ms0.sizeZ *= rotations;
ms0.moduloC.step = ms0.sizeC;
ms0.moduloC.end = ms0.sizeC * (illuminations - 1);
ms0.moduloC.type = FormatTools.ILLUMINATION;
ms0.moduloC.parentType = FormatTools.CHANNEL;
ms0.sizeC *= illuminations;
ms0.moduloT.step = ms0.sizeT;
ms0.moduloT.end = ms0.sizeT * (phases - 1);
ms0.moduloT.type = FormatTools.PHASE;
ms0.sizeT *= phases;
// finish populating the core metadata
int seriesCount = positions * acquisitions * angles;
int originalMosaicCount = mosaics;
if (maxResolution == 0) {
seriesCount *= mosaics;
} else {
prestitched = true;
}
ms0.imageCount = getSizeZ() * (isRGB() ? getSizeC() / 3 : getSizeC()) * getSizeT();
LOGGER.trace("Size Z = {}", getSizeZ());
LOGGER.trace("Size C = {}", getSizeC());
LOGGER.trace("Size T = {}", getSizeT());
LOGGER.trace("is RGB = {}", isRGB());
LOGGER.trace("calculated image count = {}", ms0.imageCount);
LOGGER.trace("number of available planes = {}", planes.size());
LOGGER.trace("prestitched = {}", prestitched);
LOGGER.trace("scanDim = {}", scanDim);
int calculatedSeries = fullResBlockCount / getImageCount();
if (((mosaics == seriesCount) || (positions == seriesCount)) && ((seriesCount == calculatedSeries) || (maxResolution > 0 && seriesCount * mosaics == calculatedSeries)) && prestitched != null && prestitched) {
boolean equalTiles = true;
for (SubBlock plane : planes) {
if (plane.x != planes.get(0).x || plane.y != planes.get(0).y) {
equalTiles = false;
break;
}
}
if ((getSizeX() > planes.get(0).x || (getSizeX() == planes.get(0).x && calculatedSeries == seriesCount * mosaics * positions)) && !equalTiles && allowAutostitching()) {
// image was fused; treat the mosaics as a single image
seriesCount = 1;
positions = 1;
acquisitions = 1;
mosaics = 1;
angles = 1;
} else {
int newX = planes.get(planes.size() - 1).x;
int newY = planes.get(planes.size() - 1).y;
if (allowAutostitching() && (ms0.sizeX < newX || ms0.sizeY < newY)) {
prestitched = true;
mosaics = 1;
} else {
prestitched = maxResolution > 0;
}
ms0.sizeX = newX;
ms0.sizeY = newY;
}
} else if (!allowAutostitching() && calculatedSeries > seriesCount) {
ms0.sizeX = firstX;
ms0.sizeY = firstY;
prestitched = true;
}
if (ms0.imageCount * seriesCount > planes.size() * scanDim && planes.size() > 0) {
if (planes.size() != ms0.imageCount && planes.size() != ms0.sizeT && (planes.size() % (seriesCount * getSizeZ())) == 0) {
if (!isGroupFiles() && planes.size() == (ms0.imageCount * seriesCount) / positions) {
seriesCount /= positions;
positions = 1;
}
} else if (planes.size() == ms0.sizeT || planes.size() == ms0.imageCount || (!isGroupFiles() && positions > 1)) {
positions = 1;
acquisitions = 1;
mosaics = 1;
angles = 1;
seriesCount = 1;
} else if (seriesCount > mosaics && mosaics > 1 && prestitched != null && prestitched) {
seriesCount /= mosaics;
mosaics = 1;
}
}
ms0.dimensionOrder = "XYCZT";
ArrayList<Integer> pixelTypes = new ArrayList<Integer>();
pixelTypes.add(planes.get(0).directoryEntry.pixelType);
if (maxResolution == 0) {
for (SubBlock plane : planes) {
if (!pixelTypes.contains(plane.directoryEntry.pixelType)) {
pixelTypes.add(plane.directoryEntry.pixelType);
}
plane.pixelTypeIndex = pixelTypes.indexOf(plane.directoryEntry.pixelType);
}
if (seriesCount * pixelTypes.size() > 1) {
core.clear();
for (int j = 0; j < pixelTypes.size(); j++) {
for (int i = 0; i < seriesCount; i++) {
CoreMetadata add = new CoreMetadata(ms0);
if (pixelTypes.size() > 1) {
int newC = originalC / pixelTypes.size();
add.sizeC = newC;
add.imageCount = add.sizeZ * add.sizeT;
add.rgb = false;
convertPixelType(add, pixelTypes.get(j));
}
core.add(add);
}
}
}
}
if (seriesCount > 1 || maxResolution > 0) {
core.clear();
for (int i = 0; i < seriesCount; i++) {
CoreMetadata add = new CoreMetadata(ms0);
add.resolutionCount = maxResolution + 1;
core.add(add);
for (int r = 0; r < maxResolution; r++) {
CoreMetadata resolution = new CoreMetadata(add);
resolution.resolutionCount = 1;
core.add(resolution);
}
}
}
assignPlaneIndices();
if (maxResolution > 0) {
tileWidth = new int[core.size()];
tileHeight = new int[core.size()];
for (int s = 0; s < core.size(); ) {
if (s > 0) {
core.get(s).sizeX = 0;
core.get(s).sizeY = 0;
calculateDimensions(s, true);
}
if (originalMosaicCount > 1) {
// calculate total stitched size if the image was not fused
int minRow = Integer.MAX_VALUE;
int maxRow = Integer.MIN_VALUE;
int minCol = Integer.MAX_VALUE;
int maxCol = Integer.MIN_VALUE;
int x = 0, y = 0;
int lastX = 0, lastY = 0;
for (SubBlock plane : planes) {
if (plane.coreIndex != s) {
continue;
}
if (x == 0 && y == 0) {
x = plane.x;
y = plane.y;
}
if (plane.row < minRow) {
minRow = plane.row;
}
if (plane.row > maxRow) {
maxRow = plane.row;
}
if (plane.col < minCol) {
minCol = plane.col;
}
if (plane.col > maxCol) {
maxCol = plane.col;
}
if (plane.x > tileWidth[s]) {
tileWidth[s] = plane.x;
}
if (plane.y > tileHeight[s]) {
tileHeight[s] = plane.y;
}
if (plane.row == maxRow && plane.col == maxCol) {
lastX = plane.x;
lastY = plane.y;
}
}
// don't overwrite the dimensions if stitching already occurred
if (core.get(s).sizeX == x && core.get(s).sizeY == y) {
core.get(s).sizeX = (lastX + maxCol) - minCol;
core.get(s).sizeY = (lastY + maxRow) - minRow;
}
}
boolean keepMissingPyramid = false;
for (int r = 0; r < core.get(s).resolutionCount; r++) {
boolean hasValidPlane = false;
for (SubBlock plane : planes) {
if (plane.coreIndex == s + r) {
hasValidPlane = true;
break;
}
}
if (!hasValidPlane && r > 0 && !keepMissingPyramid) {
core.remove(s + r);
core.get(s).resolutionCount--;
// adjust the core indexes of any subsequent planes
for (SubBlock plane : planes) {
if (plane.coreIndex > s + r) {
plane.coreIndex--;
}
}
r--;
} else {
int div = (int) Math.pow(scaleFactor, r);
if (r == 0 && s > 0 && core.get(s).sizeX == 1) {
core.get(s).sizeX = core.get(s - maxResolution).sizeX;
core.get(s).sizeY = core.get(s - maxResolution).sizeY;
} else {
core.get(s + r).sizeX = core.get(s).sizeX / div;
core.get(s + r).sizeY = core.get(s).sizeY / div;
}
tileWidth[s + r] = tileWidth[s] / div;
tileHeight[s + r] = tileHeight[s] / div;
}
if (r == 0 && !hasValidPlane) {
keepMissingPyramid = true;
}
}
s += core.get(s).resolutionCount;
}
}
// check for PALM data; requires planes to split into separate series
String firstXML = null;
boolean canSkipXML = true;
String currentPath = new Location(currentId).getAbsolutePath();
boolean isPALM = false;
if (planes.size() <= 2 && getImageCount() <= 2) {
for (Segment segment : segments) {
String path = new Location(segment.filename).getAbsolutePath();
if (currentPath.equals(path) && segment instanceof Metadata) {
segment.fillInData();
String xml = ((Metadata) segment).xml;
xml = XMLTools.sanitizeXML(xml);
if (firstXML == null && canSkipXML) {
firstXML = xml;
}
if (canSkipXML && firstXML.equals(xml)) {
isPALM = checkPALM(xml);
} else if (!firstXML.equals(xml)) {
canSkipXML = false;
}
((Metadata) segment).clearXML();
}
}
}
if (isPALM) {
LOGGER.debug("Detected PALM data");
core.get(0).sizeC = 1;
core.get(0).imageCount = core.get(0).sizeZ * core.get(0).sizeT;
for (int i = 0; i < planes.size(); i++) {
SubBlock p = planes.get(i);
int storedX = p.directoryEntry.dimensionEntries[0].storedSize;
int storedY = p.directoryEntry.dimensionEntries[1].storedSize;
if (p.planeIndex >= getImageCount()) {
if (core.size() == 1) {
CoreMetadata second = new CoreMetadata(core.get(0));
core.add(second);
}
p.coreIndex = 1;
p.planeIndex -= (planes.size() / 2);
core.get(1).sizeX = storedX;
core.get(1).sizeY = storedY;
} else {
core.get(0).sizeX = storedX;
core.get(0).sizeY = storedY;
}
}
if (core.size() == 2) {
// prevent misidentification of PALM data; each plane should be a different size
if (core.get(0).sizeX == core.get(1).sizeX && core.get(0).sizeY == core.get(1).sizeY) {
isPALM = false;
core.remove(1);
core.get(0).sizeC = 2;
core.get(0).imageCount *= getSizeC();
for (int i = 0; i < planes.size(); i++) {
SubBlock p = planes.get(i);
if (p.coreIndex == 1) {
p.coreIndex = 0;
p.planeIndex += (planes.size() / 2);
}
}
}
}
}
// find and add attached label/overview images
readAttachments();
// populate the OME metadata
store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
firstXML = null;
canSkipXML = true;
for (Segment segment : segments) {
String path = new Location(segment.filename).getAbsolutePath();
if (currentPath.equals(path) && segment instanceof Metadata) {
segment.fillInData();
String xml = ((Metadata) segment).xml;
xml = XMLTools.sanitizeXML(xml);
if (firstXML == null && canSkipXML) {
firstXML = xml;
}
if (canSkipXML && firstXML.equals(xml)) {
translateMetadata(xml);
} else if (!firstXML.equals(xml)) {
canSkipXML = false;
}
((Metadata) segment).clearXML();
} else if (segment instanceof Attachment) {
AttachmentEntry entry = ((Attachment) segment).attachment;
String name = entry.name.trim();
if (name.equals("TimeStamps")) {
segment.fillInData();
RandomAccessInputStream s = new RandomAccessInputStream(((Attachment) segment).attachmentData);
try {
s.order(isLittleEndian());
s.seek(8);
while (s.getFilePointer() + 8 <= s.length()) {
timestamps.add(s.readDouble());
}
} finally {
s.close();
}
}
}
segment.close();
}
if (rotationLabels != null) {
ms0.moduloZ.labels = rotationLabels;
ms0.moduloZ.end = ms0.moduloZ.start;
}
if (illuminationLabels != null) {
ms0.moduloC.labels = illuminationLabels;
ms0.moduloC.end = ms0.moduloC.start;
}
if (phaseLabels != null) {
ms0.moduloT.labels = phaseLabels;
ms0.moduloT.end = ms0.moduloT.start;
}
for (int i = 0; i < planes.size(); i++) {
SubBlock p = planes.get(i);
Coordinate c = new Coordinate(p.coreIndex, p.planeIndex, getImageCount());
ArrayList<Integer> indices = new ArrayList<Integer>();
if (indexIntoPlanes.containsKey(c)) {
indices = indexIntoPlanes.get(c);
}
indices.add(i);
indexIntoPlanes.put(c, indices);
// Add series metadata : populate position list
int nameWidth = String.valueOf(getSeriesCount()).length();
for (DimensionEntry dimension : p.directoryEntry.dimensionEntries) {
if (dimension == null) {
continue;
}
switch(dimension.dimension.charAt(0)) {
case 'S':
setCoreIndex(p.coreIndex);
int seriesId = p.coreIndex + 1;
// add padding to make sure the original metadata table is organized properly in ImageJ
String sIndex = String.format("Positions|Series %0" + nameWidth + "d|", seriesId);
addSeriesMetaList(sIndex, dimension.start);
break;
}
}
setCoreIndex(0);
}
if (channels.size() > 0 && channels.get(0).color != null && !isRGB()) {
for (int i = 0; i < seriesCount; i++) {
core.get(i).indexed = true;
}
}
String experimenterID = MetadataTools.createLSID("Experimenter", 0);
store.setExperimenterID(experimenterID, 0);
store.setExperimenterEmail(userEmail, 0);
store.setExperimenterFirstName(userFirstName, 0);
store.setExperimenterInstitution(userInstitution, 0);
store.setExperimenterLastName(userLastName, 0);
store.setExperimenterMiddleName(userMiddleName, 0);
store.setExperimenterUserName(userName, 0);
String name = new Location(getCurrentFile()).getName();
if (imageName != null && imageName.trim().length() > 0) {
name = imageName;
}
store.setInstrumentID(MetadataTools.createLSID("Instrument", 0), 0);
int indexLength = String.valueOf(getSeriesCount()).length();
for (int i = 0; i < getSeriesCount(); i++) {
store.setImageInstrumentRef(MetadataTools.createLSID("Instrument", 0), i);
if (acquiredDate != null) {
store.setImageAcquisitionDate(new Timestamp(acquiredDate), i);
} else if (planes.get(0).timestamp != null) {
long timestamp = (long) (planes.get(0).timestamp * 1000);
String date = DateTools.convertDate(timestamp, DateTools.UNIX);
store.setImageAcquisitionDate(new Timestamp(date), i);
}
if (experimenterID != null) {
store.setImageExperimenterRef(experimenterID, i);
}
if (timeIncrement != null) {
store.setPixelsTimeIncrement(timeIncrement, i);
}
String imageIndex = String.valueOf(i + 1);
while (imageIndex.length() < indexLength) {
imageIndex = "0" + imageIndex;
}
int extraIndex = i - (getSeriesCount() - extraImages.size());
if (extraIndex < 0) {
if (hasFlattenedResolutions()) {
store.setImageName(name + " #" + imageIndex, i);
} else if (positions == 1) {
store.setImageName("", i);
} else {
store.setImageName("Scene #" + i, i);
}
} else if (extraIndex == 0) {
store.setImageName("label image", i);
} else if (extraIndex == 1) {
store.setImageName("macro image", i);
} else {
store.setImageName("thumbnail image", i);
}
// label and macro images
if (extraIndex >= 0) {
continue;
}
if (description != null && description.length() > 0) {
store.setImageDescription(description, i);
}
if (airPressure != null) {
store.setImagingEnvironmentAirPressure(new Pressure(new Double(airPressure), UNITS.MILLIBAR), i);
}
if (co2Percent != null) {
store.setImagingEnvironmentCO2Percent(PercentFraction.valueOf(co2Percent), i);
}
if (humidity != null) {
store.setImagingEnvironmentHumidity(PercentFraction.valueOf(humidity), i);
}
if (temperature != null) {
store.setImagingEnvironmentTemperature(new Temperature(new Double(temperature), UNITS.CELSIUS), i);
}
if (objectiveSettingsID != null) {
store.setObjectiveSettingsID(objectiveSettingsID, i);
if (correctionCollar != null) {
store.setObjectiveSettingsCorrectionCollar(new Double(correctionCollar), i);
}
if (medium != null) {
store.setObjectiveSettingsMedium(getMedium(medium), i);
}
if (refractiveIndex != null) {
store.setObjectiveSettingsRefractiveIndex(new Double(refractiveIndex), i);
}
}
Double startTime = null;
if (acquiredDate != null) {
Timestamp t = Timestamp.valueOf(acquiredDate);
if (t != null)
startTime = t.asInstant().getMillis() / 1000d;
}
for (int plane = 0; plane < getImageCount(); plane++) {
Coordinate coordinate = new Coordinate(i, plane, getImageCount());
ArrayList<Integer> index = indexIntoPlanes.get(coordinate);
if (index == null) {
continue;
}
SubBlock p = planes.get(index.get(0));
if (startTime == null) {
startTime = p.timestamp;
}
if (p.stageX != null) {
store.setPlanePositionX(p.stageX, i, plane);
} else if (positionsX != null && i < positionsX.length && positionsX[i] != null) {
store.setPlanePositionX(positionsX[i], i, plane);
} else {
store.setPlanePositionX(new Length(p.col, UNITS.REFERENCEFRAME), i, plane);
}
if (p.stageY != null) {
store.setPlanePositionY(p.stageY, i, plane);
} else if (positionsY != null && i < positionsY.length && positionsY[i] != null) {
store.setPlanePositionY(positionsY[i], i, plane);
} else {
store.setPlanePositionY(new Length(p.row, UNITS.REFERENCEFRAME), i, plane);
}
if (p.stageZ != null) {
store.setPlanePositionZ(p.stageZ, i, plane);
} else if (positionsZ != null && i < positionsZ.length) {
int zIndex = getZCTCoords(plane)[0];
if (positionsZ[i] != null) {
if (zStep != null) {
double value = positionsZ[i].value(zStep.unit()).doubleValue();
if (zStep != null) {
value += zIndex * zStep.value().doubleValue();
}
Length pos = new Length(value, zStep.unit());
store.setPlanePositionZ(pos, i, plane);
} else {
store.setPlanePositionZ(positionsZ[i], i, plane);
}
}
}
if (p.timestamp != null) {
store.setPlaneDeltaT(new Time(p.timestamp - startTime, UNITS.SECOND), i, plane);
} else if (plane < timestamps.size() && timestamps.size() == getImageCount()) {
// only use the plane index if there is one timestamp per plane
if (timestamps.get(plane) != null) {
store.setPlaneDeltaT(new Time(timestamps.get(plane), UNITS.SECOND), i, plane);
}
} else if (getZCTCoords(plane)[2] < timestamps.size()) {
// otherwise use the timepoint index, to prevent incorrect timestamping of channels
int t = getZCTCoords(plane)[2];
if (timestamps.get(t) != null) {
store.setPlaneDeltaT(new Time(timestamps.get(t), UNITS.S), i, plane);
}
}
if (p.exposureTime != null) {
store.setPlaneExposureTime(new Time(p.exposureTime, UNITS.SECOND), i, plane);
} else {
int channel = getZCTCoords(plane)[1];
if (channel < channels.size() && channels.get(channel).exposure != null) {
store.setPlaneExposureTime(new Time(channels.get(channel).exposure, UNITS.SECOND), i, plane);
}
}
}
for (int c = 0; c < getEffectiveSizeC(); c++) {
if (c < channels.size()) {
if (isPALM && i < channels.size()) {
store.setChannelName(channels.get(i).name, i, c);
} else {
store.setChannelName(channels.get(c).name, i, c);
}
store.setChannelFluor(channels.get(c).fluor, i, c);
if (channels.get(c).filterSetRef != null) {
store.setChannelFilterSetRef(channels.get(c).filterSetRef, i, c);
}
String color = channels.get(c).color;
if (color != null && !isRGB()) {
color = color.replaceAll("#", "");
if (color.length() > 6) {
color = color.substring(2, color.length());
}
try {
// shift by 8 to allow alpha in the final byte
store.setChannelColor(new Color((Integer.parseInt(color, 16) << 8) | 0xff), i, c);
} catch (NumberFormatException e) {
LOGGER.warn("", e);
}
}
String emWave = channels.get(c).emission;
if (emWave != null) {
Double wave = new Double(emWave);
Length em = FormatTools.getEmissionWavelength(wave);
if (em != null) {
store.setChannelEmissionWavelength(em, i, c);
}
}
String exWave = channels.get(c).excitation;
if (exWave != null) {
Double wave = new Double(exWave);
Length ex = FormatTools.getExcitationWavelength(wave);
if (ex != null) {
store.setChannelExcitationWavelength(ex, i, c);
}
}
if (channels.get(c).illumination != null) {
store.setChannelIlluminationType(channels.get(c).illumination, i, c);
}
if (channels.get(c).pinhole != null) {
store.setChannelPinholeSize(new Length(new Double(channels.get(c).pinhole), UNITS.MICROMETER), i, c);
}
if (channels.get(c).acquisitionMode != null) {
store.setChannelAcquisitionMode(channels.get(c).acquisitionMode, i, c);
}
}
if (c < detectorRefs.size()) {
String detector = detectorRefs.get(c);
store.setDetectorSettingsID(detector, i, c);
if (c < binnings.size()) {
store.setDetectorSettingsBinning(getBinning(binnings.get(c)), i, c);
}
if (c < channels.size()) {
store.setDetectorSettingsGain(channels.get(c).gain, i, c);
}
}
if (c < channels.size()) {
if (hasDetectorSettings) {
store.setDetectorSettingsGain(channels.get(c).gain, i, c);
}
}
}
}
// not needed by further calls on the reader
segments = null;
}
use of ome.units.quantity.Temperature in project bioformats by openmicroscopy.
the class FluoviewReader method initAlternateMetadataStore.
private void initAlternateMetadataStore() throws FormatException {
MetadataStore store = makeFilterMetadata();
store.setImagingEnvironmentTemperature(new Temperature(new Double(temperature.floatValue()), UNITS.CELSIUS), 0);
String instrumentID = MetadataTools.createLSID("Instrument", 0);
String detectorID = MetadataTools.createLSID("Detector", 0, 0);
store.setInstrumentID(instrumentID, 0);
store.setDetectorID(detectorID, 0, 0);
store.setDetectorModel(model, 0, 0);
store.setImageInstrumentRef(instrumentID, 0);
if (exposureTime != null) {
for (int i = 0; i < getImageCount(); i++) {
store.setPlaneExposureTime(new Time(new Double(exposureTime.floatValue()), UNITS.SECOND), 0, i);
}
}
for (int i = 0; i < getEffectiveSizeC(); i++) {
store.setDetectorSettingsID(detectorID, 0, i);
store.setDetectorSettingsReadOutRate(new Frequency(new Double(readoutTime.floatValue()), UNITS.HERTZ), 0, i);
}
}
Aggregations