use of ome.xml.model.primitives.PositiveInteger in project bioformats by openmicroscopy.
the class Calibrator method computeVariableTimeInterval.
private double computeVariableTimeInterval(IMetadata meta, int series) {
// collect variable time interval values
final PositiveInteger sizeT = meta.getPixelsSizeT(series);
final int tSize = sizeT == null ? 1 : sizeT.getValue();
final int planeCount = meta.getPlaneCount(series);
final Time[] deltas = new Time[tSize];
Arrays.fill(deltas, new Time(Double.NaN, UNITS.SECOND));
for (int p = 0; p < planeCount; p++) {
final NonNegativeInteger theZ = meta.getPlaneTheZ(series, p);
final NonNegativeInteger theC = meta.getPlaneTheC(series, p);
final NonNegativeInteger theT = meta.getPlaneTheT(series, p);
if (theZ == null || theC == null || theT == null)
continue;
if (theZ.getValue() != 0 || theC.getValue() != 0)
continue;
// store delta T value at appropriate index
final int t = theT.getValue();
if (t >= tSize)
continue;
final Time deltaT = meta.getPlaneDeltaT(series, p);
if (deltaT == null)
continue;
deltas[t] = deltaT;
}
// average delta T differences
double tiTotal = 0;
int tiCount = 0;
for (int t = 1; t < tSize; t++) {
double delta1 = deltas[t - 1].value(UNITS.SECOND).doubleValue();
;
double delta2 = deltas[t].value(UNITS.SECOND).doubleValue();
;
if (Double.isNaN(delta1) || Double.isNaN(delta2))
continue;
tiTotal += delta2 - delta1;
tiCount++;
}
if (tiCount == 0)
return Double.NaN;
// DeltaT is stored in seconds, and the expected units are seconds
return (float) (tiTotal / tiCount);
}
use of ome.xml.model.primitives.PositiveInteger 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.xml.model.primitives.PositiveInteger in project bioformats by openmicroscopy.
the class MIASReader method initFile.
// -- 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, "txt")) {
// first need to find a relevant TIFF file
Location base = new Location(id).getAbsoluteFile();
Location plate = null;
if (base.getParentFile().getName().equals("Batchresults")) {
Location experiment = base.getParentFile().getParentFile();
String[] plates = experiment.list(true);
Arrays.sort(plates);
plate = new Location(experiment, plates[0]);
} else {
plate = base.getParentFile();
if (plate.getName().equals("results"))
plate = plate.getParentFile();
}
String[] list = plate.list(true);
for (String f : list) {
if (f.startsWith("Well")) {
Location well = new Location(plate, f);
String[] wellList = well.list(true);
for (String file : wellList) {
String path = new Location(well, file).getAbsolutePath();
if (isThisType(path) && checkSuffix(path, new String[] { "tif", "tiff" })) {
initFile(path);
return;
}
}
}
}
throw new FormatException("Could not locate an appropriate TIFF file.");
}
if (!isGroupFiles()) {
tiffs = new String[][] { { id } };
readers = new MinimalTiffReader[1][1];
readers[0][0] = new MinimalTiffReader();
TiffReader r = new TiffReader();
r.setMetadataStore(getMetadataStore());
r.setId(tiffs[0][0]);
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();
tileRows = 1;
tileCols = 1;
return;
}
analysisFiles = new ArrayList<AnalysisFile>();
// MIAS is a high content screening format which supports multiple plates,
// wells and fields.
// Most of the metadata comes from the directory hierarchy, as very little
// metadata is present in the actual files.
//
// The directory hierarchy is either:
//
// <experiment name> top level experiment directory
// Batchresults analysis results for experiment
// <plate number>_<plate barcode> one directory for each plate
// results analysis results for plate
// Well<xxxx> one directory for each well
// mode<x>_z<xxx>_t<xxx>_im<x>_<x>.tif
//
// or:
//
// <experiment name> top level experiment directory
// <plate number> plate directory (3 digits)
// <well number> well directory (4 digits)
// <channel number> channel directory (1 digit)
// <tile row>_<tile col>_<Z>_<T>.tif
//
// Each TIFF file contains a single grayscale plane. The "mode" block
// refers to the channel number; the "z" and "t" blocks refer to the
// Z section and timepoint, respectively. The "im<x>_<x>" block gives
// the row and column coordinates of the image within a mosaic.
//
// We are initially given one of these TIFF files; from there, we need
// to find the top level experiment directory and work our way down to
// determine how many plates and wells are present.
LOGGER.info("Building list of TIFF files");
Location baseFile = new Location(id).getAbsoluteFile();
Location plate = baseFile.getParentFile().getParentFile();
String plateName = plate.getName();
if (!(plateName.length() == 3 || (plateName.length() > 3 && plateName.replaceAll("\\d", "").startsWith("-")))) {
plate = plate.getParentFile();
plateName = plate.getName();
}
int plateNumber = Integer.parseInt(plateName.substring(0, 3));
Location experiment = plate.getParentFile();
String[] directories = experiment.list(true);
Arrays.sort(directories);
for (String dir : directories) {
Location f = new Location(experiment, dir);
if (dir.equals("Batchresults")) {
String[] results = f.list(true);
for (String result : results) {
Location file = new Location(f, result);
if (result.startsWith("NEO_Results")) {
resultFile = file.getAbsolutePath();
AnalysisFile af = new AnalysisFile();
af.filename = resultFile;
analysisFiles.add(af);
} else if (result.startsWith("NEO_PlateOutput_")) {
int plateIndex = Integer.parseInt(result.substring(16, 19));
if (plateIndex == plateNumber) {
AnalysisFile af = new AnalysisFile();
af.filename = file.getAbsolutePath();
af.plate = 0;
analysisFiles.add(af);
}
}
}
}
}
String[] list = plate.list(true);
Arrays.sort(list);
final List<String> wellDirectories = new ArrayList<String>();
for (String dir : list) {
Location f = new Location(plate, dir);
if (f.getName().startsWith("Well") || f.getName().length() == 4) {
// directory name is valid, but we need to make sure that the
// directory contains a TIFF or a subdirectory
String[] wellList = f.list(true);
if (wellList != null) {
boolean validWell = false;
for (String potentialTIFF : wellList) {
if (potentialTIFF.toLowerCase().endsWith(".tif") || new Location(f, potentialTIFF).isDirectory()) {
validWell = true;
break;
}
}
if (validWell)
wellDirectories.add(f.getAbsolutePath());
}
} else if (f.getName().equals("results")) {
String[] resultsList = f.list(true);
for (String result : resultsList) {
// exclude proprietary program state files
if (!result.endsWith(".sav") && !result.endsWith(".dsv") && !result.endsWith(".dat")) {
Location r = new Location(f, result);
AnalysisFile af = new AnalysisFile();
af.filename = r.getAbsolutePath();
af.plate = 0;
if (result.toLowerCase().startsWith("well")) {
af.well = Integer.parseInt(result.substring(4, 8)) - 1;
}
analysisFiles.add(af);
}
}
} else if (f.getName().equals("Nugenesistemplate.txt")) {
templateFile = f.getAbsolutePath();
}
}
int nWells = wellDirectories.size();
LOGGER.debug("Found {} wells.", nWells);
readers = new MinimalTiffReader[nWells][];
tiffs = new String[nWells][];
int[] zCount = new int[nWells];
int[] cCount = new int[nWells];
int[] tCount = new int[nWells];
String[] order = new String[nWells];
wellNumber = new int[nWells];
String[] wells = wellDirectories.toArray(new String[nWells]);
Arrays.sort(wells);
for (int j = 0; j < nWells; j++) {
Location well = new Location(wells[j]);
String wellName = well.getName().replaceAll("Well", "");
wellNumber[j] = Integer.parseInt(wellName) - 1;
String[] tiffFiles = well.list(true);
final List<String> tmpFiles = new ArrayList<String>();
for (String tiff : tiffFiles) {
String name = tiff.toLowerCase();
if (name.endsWith(".tif") || name.endsWith(".tiff")) {
tmpFiles.add(new Location(well, tiff).getAbsolutePath());
}
}
if (tmpFiles.size() == 0) {
LOGGER.debug("No TIFFs in well directory {}", wells[j]);
// directories which contain the TIFFs
for (String dir : tiffFiles) {
Location file = new Location(well, dir);
if (dir.length() == 1 && file.isDirectory()) {
cCount[j]++;
String[] tiffs = file.list(true);
for (String tiff : tiffs) {
String name = tiff.toLowerCase();
if (name.endsWith(".tif") || name.endsWith(".tiff")) {
tmpFiles.add(new Location(file, tiff).getAbsolutePath());
}
}
}
}
}
tiffFiles = tmpFiles.toArray(new String[0]);
if (ArrayUtils.isEmpty(tiffFiles)) {
throw new FormatException("Empty dataset - No tiff files were found.");
}
Location firstTiff = new Location(tiffFiles[0]);
List<String> names = new ArrayList<String>();
for (Location f : firstTiff.getParentFile().listFiles()) {
names.add(f.getName());
}
FilePattern fp = new FilePattern(FilePattern.findPattern(firstTiff.getName(), null, names.toArray(new String[names.size()])));
String[] blocks = fp.getPrefixes();
order[j] = "XY";
int[] count = fp.getCount();
for (int block = blocks.length - 1; block >= 0; block--) {
blocks[block] = blocks[block].toLowerCase();
blocks[block] = blocks[block].substring(blocks[block].lastIndexOf("_") + 1);
if (blocks[block].equals("z")) {
zCount[j] = count[block];
order[j] += 'Z';
} else if (blocks[block].equals("t")) {
tCount[j] = count[block];
order[j] += 'T';
} else if (blocks[block].equals("mode")) {
cCount[j] = count[block];
order[j] += 'C';
} else if (blocks[block].equals("im"))
tileRows = count[block];
else if (blocks[block].equals(""))
tileCols = count[block];
else if (blocks[block].replaceAll("\\d", "").length() == 0) {
if (block == 3)
tileRows = count[block];
else if (block == 2)
tileCols = count[block];
else if (block == 0) {
zCount[j] = count[block];
order[j] += 'Z';
} else if (block == 1) {
tCount[j] = count[block];
order[j] += 'T';
}
} else {
throw new FormatException("Unsupported block '" + blocks[block]);
}
}
Arrays.sort(tiffFiles);
tiffs[j] = tiffFiles;
LOGGER.debug("Well {} has {} files.", j, tiffFiles.length);
readers[j] = new MinimalTiffReader[tiffFiles.length];
for (int k = 0; k < tiffFiles.length; k++) {
readers[j][k] = new MinimalTiffReader();
}
}
// Populate core metadata
LOGGER.info("Populating core metadata");
int nSeries = tiffs.length;
bpp = new int[nSeries];
if (readers.length == 0) {
throw new FormatException("No wells were found.");
}
// assume that all wells have the same width, height, and pixel type
readers[0][0].setId(tiffs[0][0]);
tileWidth = readers[0][0].getSizeX();
tileHeight = readers[0][0].getSizeY();
if (tileCols == 0)
tileCols = 1;
if (tileRows == 0)
tileRows = 1;
core.clear();
for (int i = 0; i < nSeries; i++) {
CoreMetadata ms = new CoreMetadata();
core.add(ms);
ms.sizeZ = zCount[i];
ms.sizeC = cCount[i];
ms.sizeT = tCount[i];
if (ms.sizeZ == 0)
ms.sizeZ = 1;
if (ms.sizeC == 0)
ms.sizeC = 1;
if (ms.sizeT == 0)
ms.sizeT = 1;
ms.sizeX = tileWidth * tileCols;
ms.sizeY = tileHeight * tileRows;
ms.pixelType = readers[0][0].getPixelType();
ms.sizeC *= readers[0][0].getSizeC();
ms.rgb = readers[0][0].isRGB();
ms.littleEndian = readers[0][0].isLittleEndian();
ms.interleaved = readers[0][0].isInterleaved();
ms.indexed = readers[0][0].isIndexed();
ms.falseColor = readers[0][0].isFalseColor();
ms.dimensionOrder = order[i];
if (ms.dimensionOrder.indexOf('Z') == -1) {
ms.dimensionOrder += 'Z';
}
if (ms.dimensionOrder.indexOf('C') == -1) {
ms.dimensionOrder += 'C';
}
if (ms.dimensionOrder.indexOf('T') == -1) {
ms.dimensionOrder += 'T';
}
ms.imageCount = ms.sizeZ * ms.sizeT * cCount[i];
if (ms.imageCount == 0) {
ms.imageCount = 1;
}
bpp[i] = FormatTools.getBytesPerPixel(ms.pixelType);
}
// Populate metadata hashtable
LOGGER.info("Populating metadata hashtable");
if (resultFile != null && getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
String[] cols = null;
final List<String> rows = new ArrayList<String>();
boolean doKeyValue = true;
int nStarLines = 0;
String analysisResults = DataTools.readFile(resultFile);
String[] lines = analysisResults.split("\n");
for (String line : lines) {
line = line.trim();
if (line.length() == 0)
continue;
if (line.startsWith("******") && line.endsWith("******"))
nStarLines++;
if (doKeyValue) {
String[] n = line.split("\t");
if (n[0].endsWith(":"))
n[0] = n[0].substring(0, n[0].length() - 1);
if (n.length >= 2)
addGlobalMeta(n[0], n[1]);
} else {
if (cols == null)
cols = line.split("\t");
else
rows.add(line);
}
if (nStarLines == 2)
doKeyValue = false;
}
for (String row : rows) {
String[] d = row.split("\t");
for (int col = 3; col < cols.length; col++) {
addGlobalMeta("Plate " + d[0] + ", Well " + d[2] + " " + cols[col], d[col]);
if (cols[col].equals("AreaCode")) {
String wellID = d[col].replaceAll("\\D", "");
wellColumns = Integer.parseInt(wellID);
}
}
}
}
// Populate MetadataStore
LOGGER.info("Populating MetadataStore");
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
// assume that a 96 well plate is 8x12, and a 384 well plate is 16x24
if (wellColumns == 0) {
if (nWells == 96) {
wellColumns = 12;
} else if (nWells == 384) {
wellColumns = 24;
} else {
LOGGER.warn("Could not determine the plate dimensions.");
wellColumns = 24;
}
}
store.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
String plateAcqId = MetadataTools.createLSID("PlateAcquisition", 0, 0);
store.setPlateAcquisitionID(plateAcqId, 0, 0);
store.setPlateAcquisitionMaximumFieldCount(new PositiveInteger(1), 0, 0);
for (int well = 0; well < nWells; well++) {
int wellIndex = wellNumber[well];
int row = wellIndex / wellColumns;
int wellCol = (wellIndex % wellColumns) + 1;
char wellRow = (char) ('A' + row);
store.setWellID(MetadataTools.createLSID("Well", 0, well), 0, well);
store.setWellRow(new NonNegativeInteger(row), 0, well);
store.setWellColumn(new NonNegativeInteger(wellCol - 1), 0, well);
String imageID = MetadataTools.createLSID("Image", well);
String wellSampleID = MetadataTools.createLSID("WellSample", 0, well, 0);
store.setWellSampleID(wellSampleID, 0, well, 0);
store.setWellSampleIndex(new NonNegativeInteger(well), 0, well, 0);
store.setImageID(imageID, well);
store.setImageName("Well " + wellRow + wellCol, well);
store.setWellSampleImageRef(imageID, 0, well, 0);
store.setPlateAcquisitionWellSampleRef(wellSampleID, 0, 0, well);
}
MetadataLevel level = getMetadataOptions().getMetadataLevel();
if (level != MetadataLevel.MINIMUM) {
String experimentID = MetadataTools.createLSID("Experiment", 0);
store.setExperimentID(experimentID, 0);
store.setExperimentType(getExperimentType("Other"), 0);
store.setExperimentDescription(experiment.getName(), 0);
// populate SPW metadata
store.setPlateColumnNamingConvention(getNamingConvention("Number"), 0);
store.setPlateRowNamingConvention(getNamingConvention("Letter"), 0);
parseTemplateFile(store);
plateName = plateName.substring(plateName.indexOf('-') + 1);
store.setPlateName(plateName, 0);
store.setPlateExternalIdentifier(plateName, 0);
for (int well = 0; well < nWells; well++) {
// populate Image/Pixels metadata
store.setImageExperimentRef(experimentID, well);
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
store.setImageInstrumentRef(instrumentID, well);
}
roiFiles = new ArrayList<AnalysisFile>();
for (AnalysisFile af : analysisFiles) {
String file = af.filename;
String name = new Location(file).getName();
if (!name.startsWith("Well"))
continue;
if (name.endsWith("AllModesOverlay.tif")) {
roiFiles.add(af);
} else if (name.endsWith("overlay.tif")) {
roiFiles.add(af);
}
}
if (level != MetadataLevel.NO_OVERLAYS) {
// populate image-level ROIs
Color[] colors = new Color[getSizeC()];
int nextROI = 0;
for (AnalysisFile af : analysisFiles) {
String file = af.filename;
String name = new Location(file).getName();
if (!name.startsWith("Well"))
continue;
int[] position = getPositionFromFile(file);
int well = position[0];
if (name.endsWith("detail.txt")) {
String data = DataTools.readFile(file);
String[] lines = data.split("\n");
int start = 0;
while (start < lines.length && !lines[start].startsWith("Label")) {
start++;
}
if (start >= lines.length)
continue;
String[] columns = lines[start].split("\t");
List<String> columnNames = Arrays.asList(columns);
for (int j = start + 1; j < lines.length; j++) {
populateROI(columnNames, lines[j].split("\t"), well, nextROI++, position[1], position[2], store);
}
} else if (name.endsWith("AllModesOverlay.tif")) {
// results/Well<nnnn>_mode<n>_z<nnn>_t<nnn>_AllModesOverlay.tif
if (colors[position[3]] != null)
continue;
try {
colors[position[3]] = getChannelColorFromFile(file);
} catch (IOException e) {
}
if (colors[position[3]] == null)
continue;
for (int s = 0; s < getSeriesCount(); s++) {
store.setChannelColor(colors[position[3]], s, position[3]);
}
if (position[3] == 0) {
nextROI += parseMasks(store, well, nextROI, file);
}
} else if (name.endsWith("overlay.tif")) {
nextROI += parseMasks(store, well, nextROI, file);
}
}
}
}
}
use of ome.xml.model.primitives.PositiveInteger in project bioformats by openmicroscopy.
the class FlexReader method populateMetadataStore.
private void populateMetadataStore(MetadataStore store) throws FormatException {
LOGGER.info("Populating MetadataStore");
MetadataTools.populatePixels(store, this, true);
Location currentFile = new Location(getCurrentFile()).getAbsoluteFile();
int[] lengths = new int[] { fieldCount, wellCount, plateCount };
store.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
String plateAcqID = MetadataTools.createLSID("PlateAcquisition", 0, 0);
store.setPlateAcquisitionID(plateAcqID, 0, 0);
PositiveInteger maxFieldCount = FormatTools.getMaxFieldCount(fieldCount);
if (maxFieldCount != null) {
store.setPlateAcquisitionMaximumFieldCount(maxFieldCount, 0, 0);
}
plateAcqStartTime = DateTools.formatDate(plateAcqStartTime, "dd.MM.yyyy HH:mm:ss");
if (plateAcqStartTime != null) {
store.setPlateAcquisitionStartTime(new Timestamp(plateAcqStartTime), 0, 0);
}
for (int row = 0; row < wellRows; row++) {
for (int col = 0; col < wellColumns; col++) {
int well = row * wellColumns + col;
store.setWellID(MetadataTools.createLSID("Well", 0, well), 0, well);
store.setWellRow(new NonNegativeInteger(row), 0, well);
store.setWellColumn(new NonNegativeInteger(col), 0, well);
}
}
for (int i = 0; i < getSeriesCount(); i++) {
int[] pos = FormatTools.rasterToPosition(lengths, i);
String imageID = MetadataTools.createLSID("Image", i);
store.setImageID(imageID, i);
int well = wellNumber[pos[1]][0] * wellColumns + wellNumber[pos[1]][1];
char wellRow = (char) ('A' + wellNumber[pos[1]][0]);
store.setImageName("Well " + wellRow + "-" + (wellNumber[pos[1]][1] + 1) + "; Field #" + (pos[0] + 1), i);
if (acquisitionDates.get(i) != null) {
store.setImageAcquisitionDate(acquisitionDates.get(i), i);
}
if (wellRows == 0 && wellColumns == 0) {
well = pos[1];
NonNegativeInteger row = new NonNegativeInteger(wellNumber[pos[1]][0]);
NonNegativeInteger col = new NonNegativeInteger(wellNumber[pos[1]][1]);
String wellID = MetadataTools.createLSID("Well", pos[2], well);
store.setWellID(wellID, pos[2], well);
store.setWellRow(row, pos[2], pos[1]);
store.setWellColumn(col, pos[2], pos[1]);
}
String wellSample = MetadataTools.createLSID("WellSample", pos[2], well, pos[0]);
store.setWellSampleID(wellSample, pos[2], well, pos[0]);
store.setWellSampleIndex(new NonNegativeInteger(i), pos[2], well, pos[0]);
store.setWellSampleImageRef(imageID, pos[2], well, pos[0]);
store.setPlateAcquisitionWellSampleRef(wellSample, 0, 0, i);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
if (plateName == null)
plateName = currentFile.getParentFile().getName();
if (plateBarcode != null)
plateName = plateBarcode + " " + plateName;
store.setPlateName(plateName, 0);
store.setPlateRowNamingConvention(getNamingConvention("Letter"), 0);
store.setPlateColumnNamingConvention(getNamingConvention("Number"), 0);
for (int i = 0; i < getSeriesCount(); i++) {
int[] pos = FormatTools.rasterToPosition(lengths, i);
store.setImageInstrumentRef(instrumentID, i);
int seriesIndex = i * getImageCount();
if (seriesIndex < objectiveRefs.size()) {
store.setObjectiveSettingsID(objectiveRefs.get(seriesIndex), i);
}
for (int c = 0; c < getEffectiveSizeC(); c++) {
int channelIndex = seriesIndex + c;
if (seriesIndex > 0 && channelNames.length == getEffectiveSizeC() * getSeriesCount()) {
channelIndex = i * getEffectiveSizeC() + c;
}
if (channelNames != null && channelIndex >= channelNames.length) {
channelIndex = c;
}
if (channelNames != null && channelIndex < channelNames.length) {
store.setChannelName(channelNames[channelIndex], i, c);
}
}
if (seriesIndex < lightSourceCombinationRefs.size()) {
String lightSourceCombo = lightSourceCombinationRefs.get(seriesIndex);
List<String> lightSources = lightSourceCombinationIDs.get(lightSourceCombo);
for (int c = 0; c < getEffectiveSizeC(); c++) {
int index = seriesIndex + c;
if (index < cameraRefs.size()) {
store.setDetectorSettingsID(cameraRefs.get(index), i, c);
if (index < binnings.size()) {
store.setDetectorSettingsBinning(getBinning(binnings.get(index)), i, c);
}
}
if (lightSources != null && c < lightSources.size()) {
store.setChannelLightSourceSettingsID(lightSources.get(c), i, c);
} else if (c > 0 && lightSources != null && lightSources.size() == 1) {
lightSourceCombo = lightSourceCombinationRefs.get(seriesIndex + c);
lightSources = lightSourceCombinationIDs.get(lightSourceCombo);
store.setChannelLightSourceSettingsID(lightSources.get(0), i, c);
}
if (index < filterSets.size()) {
FilterGroup group = filterSetMap.get(filterSets.get(index));
if (group != null) {
if (group.emission != null) {
store.setLightPathEmissionFilterRef(group.emission, i, c, 0);
}
if (group.excitation != null) {
store.setLightPathExcitationFilterRef(group.excitation, i, c, 0);
}
if (group.dichroic != null) {
store.setLightPathDichroicRef(group.dichroic, i, c);
}
}
}
}
}
if (seriesIndex < xSizes.size()) {
Length size = FormatTools.getPhysicalSizeX(xSizes.get(seriesIndex));
if (size != null) {
store.setPixelsPhysicalSizeX(size, i);
}
}
if (seriesIndex < ySizes.size()) {
Length size = FormatTools.getPhysicalSizeY(ySizes.get(seriesIndex));
if (size != null) {
store.setPixelsPhysicalSizeY(size, i);
}
}
int well = wellNumber[pos[1]][0] * wellColumns + wellNumber[pos[1]][1];
if (wellRows == 0 && wellColumns == 0) {
well = pos[1];
}
if (pos[0] < xPositions.size()) {
Length l = new Length(xPositions.get(pos[0]), UNITS.REFERENCEFRAME);
store.setWellSamplePositionX(l, pos[2], well, pos[0]);
}
if (pos[0] < yPositions.size()) {
Length l = new Length(yPositions.get(pos[0]), UNITS.REFERENCEFRAME);
store.setWellSamplePositionY(l, pos[2], well, pos[0]);
}
for (int image = 0; image < getImageCount(); image++) {
int plane = i * getImageCount() + image;
int c = getZCTCoords(image)[1];
if (plane < planePositionX.size()) {
store.setPlanePositionX(planePositionX.get(plane), i, image);
}
if (plane < planePositionY.size()) {
store.setPlanePositionY(planePositionY.get(plane), i, image);
}
if (plane < planePositionZ.size()) {
store.setPlanePositionZ(planePositionZ.get(plane), i, image);
}
if (plane - image + c < planeExposureTime.size()) {
if (planeExposureTime.get(plane - image + c) != null) {
store.setPlaneExposureTime(new Time(planeExposureTime.get(plane - image + c), UNITS.SECOND), i, image);
}
}
if (plane < planeDeltaT.size() && planeDeltaT.get(plane) != null) {
store.setPlaneDeltaT(new Time(planeDeltaT.get(plane), UNITS.SECOND), i, image);
}
}
}
}
}
use of ome.xml.model.primitives.PositiveInteger in project bioformats by openmicroscopy.
the class ScanrReader method initFile.
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
if (metadataFiles.size() > 0) {
// this dataset has already been initialized
return;
}
// make sure we have the .xml file
if (!checkSuffix(id, "xml") && isGroupFiles()) {
Location parent = new Location(id).getAbsoluteFile().getParentFile();
if (checkSuffix(id, "tif") && parent.getName().equalsIgnoreCase("Data")) {
parent = parent.getParentFile();
}
String[] list = parent.list();
for (String file : list) {
if (file.equals(XML_FILE)) {
id = new Location(parent, file).getAbsolutePath();
super.initFile(id);
break;
}
}
if (!checkSuffix(id, "xml")) {
throw new FormatException("Could not find " + XML_FILE + " in " + parent.getAbsolutePath());
}
} else if (!isGroupFiles() && checkSuffix(id, "tif")) {
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();
tiffs = new String[] { id };
reader = new MinimalTiffReader();
return;
}
Location dir = new Location(id).getAbsoluteFile().getParentFile();
String[] list = dir.list(true);
for (String file : list) {
Location f = new Location(dir, file);
if (checkSuffix(file, METADATA_SUFFIXES) && !f.isDirectory()) {
metadataFiles.add(f.getAbsolutePath());
}
}
// parse XML metadata
String xml = DataTools.readFile(id).trim();
if (xml.startsWith("<?")) {
xml = xml.substring(xml.indexOf("?>") + 2);
}
xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + xml;
XMLTools.parseXML(xml, new ScanrHandler());
final List<String> uniqueRows = new ArrayList<String>();
final List<String> uniqueColumns = new ArrayList<String>();
if (wellRows == 0 || wellColumns == 0) {
for (String well : wellLabels.keySet()) {
if (!Character.isLetter(well.charAt(0)))
continue;
String row = well.substring(0, 1).trim();
String column = well.substring(1).trim();
if (!uniqueRows.contains(row) && row.length() > 0)
uniqueRows.add(row);
if (!uniqueColumns.contains(column) && column.length() > 0) {
uniqueColumns.add(column);
}
}
wellRows = uniqueRows.size();
wellColumns = uniqueColumns.size();
if (wellRows * wellColumns != wellCount) {
adjustWellDimensions();
}
}
int nChannels = getSizeC() == 0 ? channelNames.size() : (int) Math.min(channelNames.size(), getSizeC());
if (nChannels == 0)
nChannels = 1;
int nSlices = getSizeZ() == 0 ? 1 : getSizeZ();
int nTimepoints = getSizeT();
int nWells = wellCount;
int nPos = 0;
if (foundPositions)
nPos = fieldPositionX.length;
else
nPos = fieldRows * fieldColumns;
if (nPos == 0)
nPos = 1;
// get list of TIFF files
Location dataDir = new Location(dir, "data");
list = dataDir.list(true);
if (list == null) {
// try to find the TIFFs in the current directory
list = dir.list(true);
} else
dir = dataDir;
if (nTimepoints == 0 || list.length < nTimepoints * nChannels * nSlices * nWells * nPos) {
nTimepoints = list.length / (nChannels * nWells * nPos * nSlices);
if (nTimepoints == 0)
nTimepoints = 1;
}
tiffs = new String[nChannels * nWells * nPos * nTimepoints * nSlices];
Arrays.sort(list, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
int lastSeparator1 = s1.lastIndexOf(File.separator) + 1;
int lastSeparator2 = s2.lastIndexOf(File.separator) + 1;
String dir1 = s1.substring(0, lastSeparator1);
String dir2 = s2.substring(0, lastSeparator2);
if (!dir1.equals(dir2)) {
return dir1.compareTo(dir2);
}
int dash1 = s1.indexOf("-", lastSeparator1);
int dash2 = s2.indexOf("-", lastSeparator2);
String label1 = dash1 < 0 ? "" : s1.substring(lastSeparator1, dash1);
String label2 = dash2 < 0 ? "" : s2.substring(lastSeparator2, dash2);
if (label1.equals(label2)) {
String remainder1 = dash1 < 0 ? s1 : s1.substring(dash1);
String remainder2 = dash2 < 0 ? s2 : s2.substring(dash2);
return remainder1.compareTo(remainder2);
}
Integer index1 = wellLabels.get(label1);
Integer index2 = wellLabels.get(label2);
if (index1 == null && index2 != null) {
return 1;
} else if (index1 != null && index2 == null) {
return -1;
}
return index1.compareTo(index2);
}
});
int lastListIndex = 0;
int next = 0;
String[] keys = wellLabels.keySet().toArray(new String[wellLabels.size()]);
Arrays.sort(keys, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
char row1 = s1.charAt(0);
char row2 = s2.charAt(0);
final Integer col1 = new Integer(s1.substring(1));
final Integer col2 = new Integer(s2.substring(1));
if (row1 < row2) {
return -1;
} else if (row1 > row2) {
return 1;
}
return col1.compareTo(col2);
}
});
int realPosCount = 0;
for (int well = 0; well < nWells; well++) {
int missingWellFiles = 0;
int wellIndex = wellNumbers.get(well);
String wellPos = getBlock(wellIndex, "W");
int originalIndex = next;
for (int pos = 0; pos < nPos; pos++) {
String posPos = getBlock(pos + 1, "P");
int posIndex = next;
for (int z = 0; z < nSlices; z++) {
String zPos = getBlock(z, "Z");
for (int t = 0; t < nTimepoints; t++) {
String tPos = getBlock(t, "T");
for (int c = 0; c < nChannels; c++) {
for (int i = lastListIndex; i < list.length; i++) {
String file = list[i];
if (file.indexOf(wellPos) != -1 && file.indexOf(zPos) != -1 && file.indexOf(posPos) != -1 && file.indexOf(tPos) != -1 && file.indexOf(channelNames.get(c)) != -1) {
tiffs[next++] = new Location(dir, file).getAbsolutePath();
if (c == nChannels - 1) {
lastListIndex = i;
}
break;
}
}
if (next == originalIndex) {
missingWellFiles++;
}
}
}
}
if (posIndex != next)
realPosCount++;
}
if (next == originalIndex && well < keys.length) {
wellLabels.remove(keys[well]);
}
if (next == originalIndex && missingWellFiles == nSlices * nTimepoints * nChannels * nPos) {
wellNumbers.remove(well);
}
}
nWells = wellNumbers.size();
if (wellLabels.size() > 0 && wellLabels.size() != nWells) {
uniqueRows.clear();
uniqueColumns.clear();
for (String well : wellLabels.keySet()) {
if (!Character.isLetter(well.charAt(0)))
continue;
String row = well.substring(0, 1).trim();
String column = well.substring(1).trim();
if (!uniqueRows.contains(row) && row.length() > 0)
uniqueRows.add(row);
if (!uniqueColumns.contains(column) && column.length() > 0) {
uniqueColumns.add(column);
}
}
nWells = uniqueRows.size() * uniqueColumns.size();
adjustWellDimensions();
}
if (realPosCount < nPos) {
nPos = realPosCount;
}
reader = new MinimalTiffReader();
reader.setId(tiffs[0]);
int sizeX = reader.getSizeX();
int sizeY = reader.getSizeY();
int pixelType = reader.getPixelType();
tileWidth = reader.getOptimalTileWidth();
tileHeight = reader.getOptimalTileHeight();
switch(pixelType) {
case FormatTools.INT8:
pixelType = FormatTools.UINT8;
break;
case FormatTools.INT16:
pixelType = FormatTools.UINT16;
break;
}
boolean rgb = reader.isRGB();
boolean interleaved = reader.isInterleaved();
boolean indexed = reader.isIndexed();
boolean littleEndian = reader.isLittleEndian();
reader.close();
int seriesCount = nWells * nPos;
core.clear();
for (int i = 0; i < seriesCount; i++) {
CoreMetadata ms = new CoreMetadata();
core.add(ms);
ms.sizeC = nChannels;
ms.sizeZ = nSlices;
ms.sizeT = nTimepoints;
ms.sizeX = sizeX;
ms.sizeY = sizeY;
ms.pixelType = pixelType;
ms.rgb = rgb;
ms.interleaved = interleaved;
ms.indexed = indexed;
ms.littleEndian = littleEndian;
ms.dimensionOrder = "XYCTZ";
ms.imageCount = nSlices * nTimepoints * nChannels;
ms.bitsPerPixel = 12;
}
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
store.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
store.setPlateColumns(new PositiveInteger(wellColumns), 0);
store.setPlateRows(new PositiveInteger(wellRows), 0);
String plateAcqID = MetadataTools.createLSID("PlateAcquisition", 0, 0);
store.setPlateAcquisitionID(plateAcqID, 0, 0);
int nFields = 0;
if (foundPositions) {
nFields = fieldPositionX.length;
} else {
nFields = fieldRows * fieldColumns;
}
PositiveInteger fieldCount = FormatTools.getMaxFieldCount(nFields);
if (fieldCount != null) {
store.setPlateAcquisitionMaximumFieldCount(fieldCount, 0, 0);
}
for (int i = 0; i < getSeriesCount(); i++) {
int field = i % nFields;
int well = i / nFields;
int index = well;
while (wellNumbers.get(index) == null && index < wellNumbers.size()) {
index++;
}
int wellIndex = wellNumbers.get(index) == null ? index : wellNumbers.get(index) - 1;
int wellRow = wellIndex / wellColumns;
int wellCol = wellIndex % wellColumns;
if (field == 0) {
store.setWellID(MetadataTools.createLSID("Well", 0, well), 0, well);
store.setWellColumn(new NonNegativeInteger(wellCol), 0, well);
store.setWellRow(new NonNegativeInteger(wellRow), 0, well);
}
String wellSample = MetadataTools.createLSID("WellSample", 0, well, field);
store.setWellSampleID(wellSample, 0, well, field);
store.setWellSampleIndex(new NonNegativeInteger(i), 0, well, field);
String imageID = MetadataTools.createLSID("Image", i);
store.setWellSampleImageRef(imageID, 0, well, field);
store.setImageID(imageID, i);
String name = "Well " + (well + 1) + ", Field " + (field + 1) + " (Spot " + (i + 1) + ")";
store.setImageName(name, i);
store.setPlateAcquisitionWellSampleRef(wellSample, 0, 0, i);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
for (int i = 0; i < getSeriesCount(); i++) {
for (int c = 0; c < getSizeC(); c++) {
store.setChannelName(channelNames.get(c), i, c);
}
Length x = FormatTools.getPhysicalSizeX(pixelSize);
Length y = FormatTools.getPhysicalSizeY(pixelSize);
if (x != null) {
store.setPixelsPhysicalSizeX(x, i);
}
if (y != null) {
store.setPixelsPhysicalSizeY(y, i);
}
if (fieldPositionX != null && fieldPositionY != null) {
int field = i % nFields;
int well = i / nFields;
final Length posX = fieldPositionX[field];
final Length posY = fieldPositionY[field];
store.setWellSamplePositionX(posX, 0, well, field);
store.setWellSamplePositionY(posY, 0, well, field);
for (int c = 0; c < getSizeC(); c++) {
int image = getIndex(0, c, 0);
store.setPlaneTheZ(new NonNegativeInteger(0), i, image);
store.setPlaneTheC(new NonNegativeInteger(c), i, image);
store.setPlaneTheT(new NonNegativeInteger(0), i, image);
store.setPlanePositionX(fieldPositionX[field], i, image);
store.setPlanePositionY(fieldPositionY[field], i, image);
// exposure time is stored in milliseconds
// convert to seconds before populating MetadataStore
Double time = exposures.get(c);
if (time != null) {
time /= 1000;
store.setPlaneExposureTime(new Time(time, UNITS.SECOND), i, image);
}
if (deltaT != null) {
store.setPlaneDeltaT(new Time(deltaT, UNITS.SECOND), i, image);
}
}
}
}
String row = wellRows > 26 ? "Number" : "Letter";
String col = wellRows > 26 ? "Letter" : "Number";
store.setPlateRowNamingConvention(getNamingConvention(row), 0);
store.setPlateColumnNamingConvention(getNamingConvention(col), 0);
store.setPlateName(plateName, 0);
}
}
Aggregations