use of loci.common.Location in project bioformats by openmicroscopy.
the class MetadataTools method populatePixels.
/**
* Populates the Pixels element of the given metadata store, using core
* metadata from the given reader. If the {@code doPlane} flag is set,
* then the Plane elements will be populated as well. If the
* {@code doImageName} flag is set, then the image name will be populated as
* well.
*
* @param store The metadata store whose Pixels should be populated
* @param r The format reader whose core metadata should be used
* @param doPlane Specifies whether Plane elements should be populated
* @param doImageName Specifies whether the Image name should be populated
*/
public static void populatePixels(MetadataStore store, IFormatReader r, boolean doPlane, boolean doImageName) {
if (store == null || r == null)
return;
int oldSeries = r.getSeries();
for (int i = 0; i < r.getSeriesCount(); i++) {
r.setSeries(i);
String imageName = null;
if (doImageName) {
Location f = new Location(r.getCurrentFile());
imageName = f.getName();
if (r.getSeriesCount() > 1) {
imageName += " #" + (i + 1);
}
}
String pixelType = FormatTools.getPixelTypeString(r.getPixelType());
populateMetadata(store, r.getCurrentFile(), i, imageName, r.isLittleEndian(), r.getDimensionOrder(), pixelType, r.getSizeX(), r.getSizeY(), r.getSizeZ(), r.getSizeC(), r.getSizeT(), r.getRGBChannelCount());
store.setPixelsInterleaved(r.isInterleaved(), i);
store.setPixelsSignificantBits(new PositiveInteger(r.getBitsPerPixel()), i);
try {
OMEXMLService service = new ServiceFactory().getInstance(OMEXMLService.class);
if (service.isOMEXMLRoot(store.getRoot())) {
MetadataStore baseStore = r.getMetadataStore();
if (service.isOMEXMLMetadata(baseStore)) {
OMEXMLMetadata omeMeta;
try {
omeMeta = service.getOMEMetadata(service.asRetrieve(baseStore));
if (omeMeta.getTiffDataCount(i) == 0 && omeMeta.getPixelsBinDataCount(i) == 0) {
service.addMetadataOnly(omeMeta, i, i == 0);
}
} catch (ServiceException e) {
LOGGER.warn("Failed to add MetadataOnly", e);
}
}
}
} catch (DependencyException exc) {
LOGGER.warn("Failed to add MetadataOnly", exc);
}
if (doPlane) {
for (int q = 0; q < r.getImageCount(); q++) {
int[] coords = r.getZCTCoords(q);
store.setPlaneTheZ(new NonNegativeInteger(coords[0]), i, q);
store.setPlaneTheC(new NonNegativeInteger(coords[1]), i, q);
store.setPlaneTheT(new NonNegativeInteger(coords[2]), i, q);
}
}
}
r.setSeries(oldSeries);
}
use of loci.common.Location in project bioformats by openmicroscopy.
the class ICSReader method initFile.
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
LOGGER.info("Finding companion file");
String icsId = id, idsId = id;
int dot = id.lastIndexOf(".");
String ext = dot < 0 ? "" : id.substring(dot + 1).toLowerCase();
if (ext.equals("ics")) {
// convert C to D regardless of case
char[] c = idsId.toCharArray();
c[c.length - 2]++;
idsId = new String(c);
} else if (ext.equals("ids")) {
// convert D to C regardless of case
char[] c = icsId.toCharArray();
c[c.length - 2]--;
icsId = new String(c);
}
if (icsId == null)
throw new FormatException("No ICS file found.");
Location icsFile = new Location(icsId);
if (!icsFile.exists())
throw new FormatException("ICS file not found.");
LOGGER.info("Checking file version");
// check if we have a v2 ICS file - means there is no companion IDS file
RandomAccessInputStream f = new RandomAccessInputStream(icsId);
if (f.readString(17).trim().equals("ics_version\t2.0")) {
in = new RandomAccessInputStream(icsId);
versionTwo = true;
} else {
if (idsId == null) {
f.close();
throw new FormatException("No IDS file found.");
}
Location idsFile = new Location(idsId);
if (!idsFile.exists()) {
f.close();
throw new FormatException("IDS file not found.");
}
currentIdsId = idsId;
in = new RandomAccessInputStream(currentIdsId);
}
f.close();
currentIcsId = icsId;
LOGGER.info("Reading metadata");
CoreMetadata m = core.get(0);
Double[] scales = null;
Double[] timestamps = null;
String[] units = null;
String[] axes = null;
int[] axisLengths = null;
String byteOrder = null, rFormat = null, compression = null;
// parse key/value pairs from beginning of ICS file
RandomAccessInputStream reader = new RandomAccessInputStream(icsId);
reader.seek(0);
reader.readString(NL);
String line = reader.readString(NL);
boolean signed = false;
final StringBuilder textBlock = new StringBuilder();
double[] sizes = null;
Double[] emWaves = null, exWaves = null;
Length[] stagePos = null;
String imageName = null, date = null, description = null;
Double magnification = null, lensNA = null, workingDistance = null;
String objectiveModel = null, immersion = null, lastName = null;
Hashtable<Integer, Double> gains = new Hashtable<Integer, Double>();
Hashtable<Integer, Double> pinholes = new Hashtable<Integer, Double>();
Hashtable<Integer, Double> wavelengths = new Hashtable<Integer, Double>();
Hashtable<Integer, String> channelNames = new Hashtable<Integer, String>();
String laserModel = null;
String laserManufacturer = null;
Double laserPower = null;
Double laserRepetitionRate = null;
String detectorManufacturer = null;
String detectorModel = null;
String microscopeModel = null;
String microscopeManufacturer = null;
String experimentType = null;
Time exposureTime = null;
String filterSetModel = null;
String dichroicModel = null;
String excitationModel = null;
String emissionModel = null;
while (line != null && !line.trim().equals("end") && reader.getFilePointer() < reader.length() - 1) {
line = line.trim();
if (line.length() > 0) {
// split the line into tokens
String[] tokens = tokenize(line);
String token0 = tokens[0].toLowerCase();
String[] keyValue = null;
// version category
if (token0.equals("ics_version")) {
String value = concatenateTokens(tokens, 1, tokens.length);
addGlobalMeta(token0, value);
} else // filename category
if (token0.equals("filename")) {
imageName = concatenateTokens(tokens, 1, tokens.length);
addGlobalMeta(token0, imageName);
} else // layout category
if (token0.equals("layout")) {
keyValue = findKeyValue(tokens, LAYOUT_KEYS);
String key = keyValue[0];
String value = keyValue[1];
addGlobalMeta(key, value);
if (key.equalsIgnoreCase("layout sizes")) {
StringTokenizer t = new StringTokenizer(value);
axisLengths = new int[t.countTokens()];
for (int n = 0; n < axisLengths.length; n++) {
try {
axisLengths[n] = Integer.parseInt(t.nextToken().trim());
} catch (NumberFormatException e) {
LOGGER.debug("Could not parse axis length", e);
}
}
} else if (key.equalsIgnoreCase("layout order")) {
StringTokenizer t = new StringTokenizer(value);
axes = new String[t.countTokens()];
for (int n = 0; n < axes.length; n++) {
axes[n] = t.nextToken().trim();
}
} else if (key.equalsIgnoreCase("layout significant_bits")) {
m.bitsPerPixel = Integer.parseInt(value);
}
} else // representation category
if (token0.equals("representation")) {
keyValue = findKeyValue(tokens, REPRESENTATION_KEYS);
String key = keyValue[0];
String value = keyValue[1];
addGlobalMeta(key, value);
if (key.equalsIgnoreCase("representation byte_order")) {
byteOrder = value;
} else if (key.equalsIgnoreCase("representation format")) {
rFormat = value;
} else if (key.equalsIgnoreCase("representation compression")) {
compression = value;
} else if (key.equalsIgnoreCase("representation sign")) {
signed = value.equals("signed");
}
} else // parameter category
if (token0.equals("parameter")) {
keyValue = findKeyValue(tokens, PARAMETER_KEYS);
String key = keyValue[0];
String value = keyValue[1];
addGlobalMeta(key, value);
if (key.equalsIgnoreCase("parameter scale")) {
// parse physical pixel sizes and time increment
scales = splitDoubles(value);
} else if (key.equalsIgnoreCase("parameter t")) {
// parse explicit timestamps
timestamps = splitDoubles(value);
} else if (key.equalsIgnoreCase("parameter units")) {
// parse units for scale
units = value.split("\\s+");
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
if (key.equalsIgnoreCase("parameter ch")) {
String[] names = value.split(" ");
for (int n = 0; n < names.length; n++) {
channelNames.put(new Integer(n), names[n].trim());
}
}
}
} else // history category
if (token0.equals("history")) {
keyValue = findKeyValue(tokens, HISTORY_KEYS);
String key = keyValue[0];
String value = keyValue[1];
addGlobalMeta(key, value);
Double doubleValue = null;
try {
doubleValue = new Double(value);
} catch (NumberFormatException e) {
// ARG this happens a lot; spurious error in most cases
LOGGER.debug("Could not parse double value '{}'", value, e);
}
if (key.equalsIgnoreCase("history software") && value.indexOf("SVI") != -1) {
// ICS files written by SVI Huygens are inverted on the Y axis
invertY = true;
} else if (key.equalsIgnoreCase("history date") || key.equalsIgnoreCase("history created on")) {
if (value.indexOf(' ') > 0) {
date = value.substring(0, value.lastIndexOf(" "));
date = DateTools.formatDate(date, DATE_FORMATS);
}
} else if (key.equalsIgnoreCase("history creation date")) {
date = DateTools.formatDate(value, DATE_FORMATS);
} else if (key.equalsIgnoreCase("history type")) {
// HACK - support for Gray Institute at Oxford's ICS lifetime data
if (value.equalsIgnoreCase("time resolved") || value.equalsIgnoreCase("FluorescenceLifetime")) {
lifetime = true;
}
experimentType = value;
} else if (key.equalsIgnoreCase("history labels")) {
// HACK - support for Gray Institute at Oxford's ICS lifetime data
labels = value;
} else if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
if (key.equalsIgnoreCase("history") || key.equalsIgnoreCase("history text")) {
textBlock.append(value);
textBlock.append("\n");
metadata.remove(key);
} else if (key.startsWith("history gain")) {
Integer n = 0;
try {
n = new Integer(key.substring(12).trim());
n = new Integer(n.intValue() - 1);
} catch (NumberFormatException e) {
}
if (doubleValue != null) {
gains.put(n, doubleValue);
}
} else if (key.startsWith("history laser") && key.endsWith("wavelength")) {
int laser = Integer.parseInt(key.substring(13, key.indexOf(" ", 13))) - 1;
value = value.replaceAll("nm", "").trim();
try {
wavelengths.put(new Integer(laser), new Double(value));
} catch (NumberFormatException e) {
LOGGER.debug("Could not parse wavelength", e);
}
} else if (key.equalsIgnoreCase("history Wavelength*")) {
String[] waves = value.split(" ");
for (int i = 0; i < waves.length; i++) {
wavelengths.put(new Integer(i), new Double(waves[i]));
}
} else if (key.equalsIgnoreCase("history laser manufacturer")) {
laserManufacturer = value;
} else if (key.equalsIgnoreCase("history laser model")) {
laserModel = value;
} else if (key.equalsIgnoreCase("history laser power")) {
try {
// TODO ARG i.e. doubleValue
laserPower = new Double(value);
} catch (NumberFormatException e) {
}
} else if (key.equalsIgnoreCase("history laser rep rate")) {
String repRate = value;
if (repRate.indexOf(' ') != -1) {
repRate = repRate.substring(0, repRate.lastIndexOf(" "));
}
laserRepetitionRate = new Double(repRate);
} else if (key.equalsIgnoreCase("history objective type") || key.equalsIgnoreCase("history objective")) {
objectiveModel = value;
} else if (key.equalsIgnoreCase("history objective immersion")) {
immersion = value;
} else if (key.equalsIgnoreCase("history objective NA")) {
lensNA = doubleValue;
} else if (key.equalsIgnoreCase("history objective WorkingDistance")) {
workingDistance = doubleValue;
} else if (key.equalsIgnoreCase("history objective magnification") || key.equalsIgnoreCase("history objective mag")) {
magnification = doubleValue;
} else if (key.equalsIgnoreCase("history camera manufacturer")) {
detectorManufacturer = value;
} else if (key.equalsIgnoreCase("history camera model")) {
detectorModel = value;
} else if (key.equalsIgnoreCase("history author") || key.equalsIgnoreCase("history experimenter")) {
lastName = value;
} else if (key.equalsIgnoreCase("history extents")) {
String[] lengths = value.split(" ");
sizes = new double[lengths.length];
for (int n = 0; n < sizes.length; n++) {
try {
sizes[n] = Double.parseDouble(lengths[n].trim());
} catch (NumberFormatException e) {
LOGGER.debug("Could not parse axis length", e);
}
}
} else if (key.equalsIgnoreCase("history stage_xyzum")) {
String[] positions = value.split(" ");
stagePos = new Length[positions.length];
for (int n = 0; n < stagePos.length; n++) {
try {
final Double number = Double.valueOf(positions[n]);
stagePos[n] = new Length(number, UNITS.REFERENCEFRAME);
} catch (NumberFormatException e) {
LOGGER.debug("Could not parse stage position", e);
}
}
} else if (key.equalsIgnoreCase("history stage positionx")) {
if (stagePos == null) {
stagePos = new Length[3];
}
final Double number = Double.valueOf(value);
stagePos[0] = new Length(number, UNITS.REFERENCEFRAME);
} else if (key.equalsIgnoreCase("history stage positiony")) {
if (stagePos == null) {
stagePos = new Length[3];
}
final Double number = Double.valueOf(value);
stagePos[1] = new Length(number, UNITS.REFERENCEFRAME);
} else if (key.equalsIgnoreCase("history stage positionz")) {
if (stagePos == null) {
stagePos = new Length[3];
}
final Double number = Double.valueOf(value);
stagePos[2] = new Length(number, UNITS.REFERENCEFRAME);
} else if (key.equalsIgnoreCase("history other text")) {
description = value;
} else if (key.startsWith("history step") && key.endsWith("name")) {
Integer n = new Integer(key.substring(12, key.indexOf(" ", 12)));
channelNames.put(n, value);
} else if (key.equalsIgnoreCase("history cube")) {
channelNames.put(new Integer(channelNames.size()), value);
} else if (key.equalsIgnoreCase("history cube emm nm")) {
if (emWaves == null) {
emWaves = new Double[1];
}
emWaves[0] = new Double(value.split(" ")[1].trim());
} else if (key.equalsIgnoreCase("history cube exc nm")) {
if (exWaves == null) {
exWaves = new Double[1];
}
exWaves[0] = new Double(value.split(" ")[1].trim());
} else if (key.equalsIgnoreCase("history microscope")) {
microscopeModel = value;
} else if (key.equalsIgnoreCase("history manufacturer")) {
microscopeManufacturer = value;
} else if (key.equalsIgnoreCase("history Exposure")) {
String expTime = value;
if (expTime.indexOf(' ') != -1) {
expTime = expTime.substring(0, expTime.indexOf(' '));
}
Double expDouble = new Double(expTime);
if (expDouble != null) {
exposureTime = new Time(expDouble, UNITS.SECOND);
}
} else if (key.equalsIgnoreCase("history filterset")) {
filterSetModel = value;
} else if (key.equalsIgnoreCase("history filterset dichroic name")) {
dichroicModel = value;
} else if (key.equalsIgnoreCase("history filterset exc name")) {
excitationModel = value;
} else if (key.equalsIgnoreCase("history filterset emm name")) {
emissionModel = value;
}
}
} else // document category
if (token0.equals("document")) {
keyValue = findKeyValue(tokens, DOCUMENT_KEYS);
String key = keyValue[0];
String value = keyValue[1];
addGlobalMeta(key, value);
} else // sensor category
if (token0.equals("sensor")) {
keyValue = findKeyValue(tokens, SENSOR_KEYS);
String key = keyValue[0];
String value = keyValue[1];
addGlobalMeta(key, value);
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
if (key.equalsIgnoreCase("sensor s_params LambdaEm")) {
String[] waves = value.split(" ");
emWaves = new Double[waves.length];
for (int n = 0; n < emWaves.length; n++) {
try {
emWaves[n] = new Double(Double.parseDouble(waves[n]));
} catch (NumberFormatException e) {
LOGGER.debug("Could not parse emission wavelength", e);
}
}
} else if (key.equalsIgnoreCase("sensor s_params LambdaEx")) {
String[] waves = value.split(" ");
exWaves = new Double[waves.length];
for (int n = 0; n < exWaves.length; n++) {
try {
exWaves[n] = new Double(Double.parseDouble(waves[n]));
} catch (NumberFormatException e) {
LOGGER.debug("Could not parse excitation wavelength", e);
}
}
} else if (key.equalsIgnoreCase("sensor s_params PinholeRadius")) {
String[] pins = value.split(" ");
int channel = 0;
for (int n = 0; n < pins.length; n++) {
if (pins[n].trim().equals(""))
continue;
try {
pinholes.put(new Integer(channel++), new Double(pins[n]));
} catch (NumberFormatException e) {
LOGGER.debug("Could not parse pinhole", e);
}
}
}
}
} else // view category
if (token0.equals("view")) {
keyValue = findKeyValue(tokens, VIEW_KEYS);
String key = keyValue[0];
String value = keyValue[1];
// handle "view view color lib lut Green Fire green", etc.
if (key.equalsIgnoreCase("view view color lib lut")) {
int index;
int redIndex = value.toLowerCase().lastIndexOf("red");
int greenIndex = value.toLowerCase().lastIndexOf("green");
int blueIndex = value.toLowerCase().lastIndexOf("blue");
if (redIndex > 0 && redIndex > greenIndex && redIndex > blueIndex) {
index = redIndex + "red".length();
} else if (greenIndex > 0 && greenIndex > redIndex && greenIndex > blueIndex) {
index = greenIndex + "green".length();
} else if (blueIndex > 0 && blueIndex > redIndex && blueIndex > greenIndex) {
index = blueIndex + "blue".length();
} else {
index = value.indexOf(' ');
}
if (index > 0) {
key = key + ' ' + value.substring(0, index);
value = value.substring(index + 1);
}
} else // "view view color mode rgb set blue-green-red", etc.
if (key.equalsIgnoreCase("view view color mode rgb set")) {
int index = value.toLowerCase().lastIndexOf("colors");
if (index > 0) {
index += "colors".length();
} else {
index = value.indexOf(' ');
}
if (index > 0) {
key = key + ' ' + value.substring(0, index);
value = value.substring(index + 1);
}
}
addGlobalMeta(key, value);
} else {
LOGGER.debug("Unknown category " + token0);
}
}
line = reader.readString(NL);
}
reader.close();
hasInstrumentData = emWaves != null || exWaves != null || lensNA != null || stagePos != null || magnification != null || workingDistance != null || objectiveModel != null || immersion != null;
addGlobalMeta("history text", textBlock.toString());
LOGGER.info("Populating core metadata");
m.rgb = false;
m.dimensionOrder = "XY";
// find axis sizes
channelLengths = new Vector<Integer>();
channelTypes = new Vector<String>();
int bitsPerPixel = 0;
for (int i = 0; i < axes.length; i++) {
if (i >= axisLengths.length)
break;
if (axes[i].equals("bits")) {
bitsPerPixel = axisLengths[i];
while (bitsPerPixel % 8 != 0) bitsPerPixel++;
if (bitsPerPixel == 24 || bitsPerPixel == 48)
bitsPerPixel /= 3;
} else if (axes[i].equals("x")) {
m.sizeX = axisLengths[i];
} else if (axes[i].equals("y")) {
m.sizeY = axisLengths[i];
} else if (axes[i].equals("z")) {
m.sizeZ = axisLengths[i];
if (getDimensionOrder().indexOf('Z') == -1) {
m.dimensionOrder += 'Z';
}
} else if (axes[i].equals("t")) {
if (getSizeT() == 0)
m.sizeT = axisLengths[i];
else
m.sizeT *= axisLengths[i];
if (getDimensionOrder().indexOf('T') == -1) {
m.dimensionOrder += 'T';
}
} else {
if (m.sizeC == 0)
m.sizeC = axisLengths[i];
else
m.sizeC *= axisLengths[i];
channelLengths.add(new Integer(axisLengths[i]));
storedRGB = getSizeX() == 0;
m.rgb = getSizeX() == 0 && getSizeC() <= 4 && getSizeC() > 1;
if (getDimensionOrder().indexOf('C') == -1) {
m.dimensionOrder += 'C';
}
if (axes[i].startsWith("c")) {
channelTypes.add(FormatTools.CHANNEL);
} else if (axes[i].equals("p")) {
channelTypes.add(FormatTools.PHASE);
} else if (axes[i].equals("f")) {
channelTypes.add(FormatTools.FREQUENCY);
} else
channelTypes.add("");
}
}
if (channelLengths.isEmpty()) {
channelLengths.add(1);
channelTypes.add(FormatTools.CHANNEL);
}
if (isRGB() && emWaves != null && emWaves.length == getSizeC()) {
m.rgb = false;
storedRGB = true;
}
m.dimensionOrder = MetadataTools.makeSaneDimensionOrder(getDimensionOrder());
if (getSizeZ() == 0)
m.sizeZ = 1;
if (getSizeC() == 0)
m.sizeC = 1;
if (getSizeT() == 0)
m.sizeT = 1;
// length and type.
if (channelLengths.size() > 0) {
int clen0 = channelLengths.get(0);
String ctype0 = channelTypes.get(0);
boolean same = true;
for (Integer len : channelLengths) {
if (clen0 != len)
same = false;
}
for (String type : channelTypes) {
if (!ctype0.equals(type))
same = false;
}
if (same) {
m.moduloC.type = ctype0;
if (FormatTools.LIFETIME.equals(ctype0)) {
m.moduloC.parentType = FormatTools.SPECTRA;
}
m.moduloC.typeDescription = "TCSPC";
m.moduloC.start = 0;
m.moduloC.step = 1;
m.moduloC.end = clen0 - 1;
}
}
m.interleaved = isRGB();
m.indexed = false;
m.falseColor = false;
m.metadataComplete = true;
m.littleEndian = true;
// HACK - support for Gray Institute at Oxford's ICS lifetime data
if (lifetime && labels != null) {
int binCount = 0;
String newOrder = null;
if (labels.equalsIgnoreCase("t x y")) {
// nominal X Y Z is actually C X Y (which is X Y C interleaved)
newOrder = "XYCZT";
m.interleaved = true;
binCount = m.sizeX;
m.sizeX = m.sizeY;
m.sizeY = m.sizeZ;
m.sizeZ = 1;
} else if (labels.equalsIgnoreCase("x y t")) {
// nominal X Y Z is actually X Y C
newOrder = "XYCZT";
binCount = m.sizeZ;
m.sizeZ = 1;
} else {
LOGGER.debug("Lifetime data, unexpected 'history labels' " + labels);
}
if (newOrder != null) {
m.dimensionOrder = newOrder;
m.sizeC = binCount;
m.moduloC.parentType = FormatTools.LIFETIME;
}
}
// do not modify the Z, T, or channel counts after this point
m.imageCount = getSizeZ() * getSizeT();
if (!isRGB())
m.imageCount *= getSizeC();
if (byteOrder != null) {
String firstByte = byteOrder.split(" ")[0];
int first = Integer.parseInt(firstByte);
m.littleEndian = rFormat.equals("real") ? first == 1 : first != 1;
}
gzip = (compression == null) ? false : compression.equals("gzip");
if (versionTwo) {
String s = in.readString(NL);
while (!s.trim().equals("end")) s = in.readString(NL);
}
offset = in.getFilePointer();
int bytes = bitsPerPixel / 8;
if (bitsPerPixel < 32)
m.littleEndian = !isLittleEndian();
boolean fp = rFormat.equals("real");
m.pixelType = FormatTools.pixelTypeFromBytes(bytes, signed, fp);
LOGGER.info("Populating OME metadata");
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
// populate Image data
store.setImageName(imageName, 0);
if (date != null)
store.setImageAcquisitionDate(new Timestamp(date), 0);
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
store.setImageDescription(description, 0);
// link Instrument and Image
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
store.setMicroscopeModel(microscopeModel, 0);
store.setMicroscopeManufacturer(microscopeManufacturer, 0);
store.setImageInstrumentRef(instrumentID, 0);
store.setExperimentID(MetadataTools.createLSID("Experiment", 0), 0);
store.setExperimentType(getExperimentType(experimentType), 0);
if (scales != null) {
if (units != null && units.length == scales.length - 1) {
// correct for missing units
// sometimes, the units for the C axis are missing entirely
ArrayList<String> realUnits = new ArrayList<String>();
int unitIndex = 0;
for (int i = 0; i < axes.length; i++) {
if (axes[i].toLowerCase().equals("ch")) {
realUnits.add("nm");
} else {
realUnits.add(units[unitIndex++]);
}
}
units = realUnits.toArray(new String[realUnits.size()]);
}
for (int i = 0; i < scales.length; i++) {
Double scale = scales[i];
if (scale == null) {
continue;
}
String axis = axes != null && axes.length > i ? axes[i] : "";
String unit = units != null && units.length > i ? units[i] : "";
if (axis.equals("x")) {
if (checkUnit(unit, "um", "microns", "micrometers")) {
Length x = FormatTools.getPhysicalSizeX(scale);
if (x != null) {
store.setPixelsPhysicalSizeX(x, 0);
}
}
} else if (axis.equals("y")) {
if (checkUnit(unit, "um", "microns", "micrometers")) {
Length y = FormatTools.getPhysicalSizeY(scale);
if (y != null) {
store.setPixelsPhysicalSizeY(y, 0);
}
}
} else if (axis.equals("z")) {
if (checkUnit(unit, "um", "microns", "micrometers")) {
Length z = FormatTools.getPhysicalSizeZ(scale);
if (z != null) {
store.setPixelsPhysicalSizeZ(z, 0);
}
}
} else if (axis.equals("t") && scale != null) {
if (checkUnit(unit, "ms")) {
store.setPixelsTimeIncrement(new Time(scale, UNITS.MILLISECOND), 0);
} else if (checkUnit(unit, "seconds") || checkUnit(unit, "s")) {
store.setPixelsTimeIncrement(new Time(scale, UNITS.SECOND), 0);
}
}
}
} else if (sizes != null) {
if (sizes.length > 0) {
Length x = FormatTools.getPhysicalSizeX(sizes[0]);
if (x != null) {
store.setPixelsPhysicalSizeX(x, 0);
}
}
if (sizes.length > 1) {
sizes[1] /= getSizeY();
Length y = FormatTools.getPhysicalSizeY(sizes[1]);
if (y != null) {
store.setPixelsPhysicalSizeY(y, 0);
}
}
}
if (timestamps != null) {
for (int t = 0; t < timestamps.length; t++) {
// ignore superfluous timestamps
if (t >= getSizeT())
break;
// ignore missing timestamp
if (timestamps[t] == null)
continue;
Time deltaT = new Time(timestamps[t], UNITS.SECOND);
// ignore invalid timestamp
if (Double.isNaN(deltaT.value().doubleValue()))
continue;
// assign timestamp to all relevant planes
for (int z = 0; z < getSizeZ(); z++) {
for (int c = 0; c < getEffectiveSizeC(); c++) {
int index = getIndex(z, c, t);
store.setPlaneDeltaT(deltaT, 0, index);
}
}
}
}
for (int i = 0; i < getEffectiveSizeC(); i++) {
if (channelNames.containsKey(i)) {
store.setChannelName(channelNames.get(i), 0, i);
}
if (pinholes.containsKey(i)) {
store.setChannelPinholeSize(new Length(pinholes.get(i), UNITS.MICROMETER), 0, i);
}
if (emWaves != null && i < emWaves.length) {
Length em = FormatTools.getEmissionWavelength(emWaves[i]);
if (em != null) {
store.setChannelEmissionWavelength(em, 0, i);
}
}
if (exWaves != null && i < exWaves.length) {
Length ex = FormatTools.getExcitationWavelength(exWaves[i]);
if (ex != null) {
store.setChannelExcitationWavelength(ex, 0, i);
}
}
}
// populate Laser data
Integer[] lasers = wavelengths.keySet().toArray(new Integer[0]);
Arrays.sort(lasers);
for (int i = 0; i < lasers.length; i++) {
store.setLaserID(MetadataTools.createLSID("LightSource", 0, i), 0, i);
Length wave = FormatTools.getWavelength(wavelengths.get(lasers[i]));
if (wave != null) {
store.setLaserWavelength(wave, 0, i);
}
store.setLaserType(getLaserType("Other"), 0, i);
store.setLaserLaserMedium(getLaserMedium("Other"), 0, i);
store.setLaserManufacturer(laserManufacturer, 0, i);
store.setLaserModel(laserModel, 0, i);
Power theLaserPower = FormatTools.createPower(laserPower, UNITS.MILLIWATT);
if (theLaserPower != null) {
store.setLaserPower(theLaserPower, 0, i);
}
Frequency theLaserRepetitionRate = FormatTools.createFrequency(laserRepetitionRate, UNITS.HERTZ);
if (theLaserRepetitionRate != null) {
store.setLaserRepetitionRate(theLaserRepetitionRate, 0, i);
}
}
if (lasers.length == 0 && laserManufacturer != null) {
store.setLaserID(MetadataTools.createLSID("LightSource", 0, 0), 0, 0);
store.setLaserType(getLaserType("Other"), 0, 0);
store.setLaserLaserMedium(getLaserMedium("Other"), 0, 0);
store.setLaserManufacturer(laserManufacturer, 0, 0);
store.setLaserModel(laserModel, 0, 0);
Power theLaserPower = FormatTools.createPower(laserPower, UNITS.MILLIWATT);
if (theLaserPower != null) {
store.setLaserPower(theLaserPower, 0, 0);
}
Frequency theLaserRepetitionRate = FormatTools.createFrequency(laserRepetitionRate, UNITS.HERTZ);
if (theLaserRepetitionRate != null) {
store.setLaserRepetitionRate(theLaserRepetitionRate, 0, 0);
}
}
if (filterSetModel != null) {
store.setFilterSetID(MetadataTools.createLSID("FilterSet", 0, 0), 0, 0);
store.setFilterSetModel(filterSetModel, 0, 0);
String dichroicID = MetadataTools.createLSID("Dichroic", 0, 0);
String emFilterID = MetadataTools.createLSID("Filter", 0, 0);
String exFilterID = MetadataTools.createLSID("Filter", 0, 1);
store.setDichroicID(dichroicID, 0, 0);
store.setDichroicModel(dichroicModel, 0, 0);
store.setFilterSetDichroicRef(dichroicID, 0, 0);
store.setFilterID(emFilterID, 0, 0);
store.setFilterModel(emissionModel, 0, 0);
store.setFilterSetEmissionFilterRef(emFilterID, 0, 0, 0);
store.setFilterID(exFilterID, 0, 1);
store.setFilterModel(excitationModel, 0, 1);
store.setFilterSetExcitationFilterRef(exFilterID, 0, 0, 0);
}
if (objectiveModel != null)
store.setObjectiveModel(objectiveModel, 0, 0);
if (immersion == null)
immersion = "Other";
store.setObjectiveImmersion(getImmersion(immersion), 0, 0);
if (lensNA != null)
store.setObjectiveLensNA(lensNA, 0, 0);
if (workingDistance != null) {
store.setObjectiveWorkingDistance(new Length(workingDistance, UNITS.MICROMETER), 0, 0);
}
if (magnification != null) {
store.setObjectiveCalibratedMagnification(magnification, 0, 0);
}
store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
// link Objective to Image
String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
store.setObjectiveID(objectiveID, 0, 0);
store.setObjectiveSettingsID(objectiveID, 0);
// populate Detector data
String detectorID = MetadataTools.createLSID("Detector", 0, 0);
store.setDetectorID(detectorID, 0, 0);
store.setDetectorManufacturer(detectorManufacturer, 0, 0);
store.setDetectorModel(detectorModel, 0, 0);
store.setDetectorType(getDetectorType("Other"), 0, 0);
for (Integer key : gains.keySet()) {
int index = key.intValue();
if (index < getEffectiveSizeC()) {
store.setDetectorSettingsGain(gains.get(key), 0, index);
store.setDetectorSettingsID(detectorID, 0, index);
}
}
if (lastName != null) {
String experimenterID = MetadataTools.createLSID("Experimenter", 0);
store.setExperimenterID(experimenterID, 0);
store.setExperimenterLastName(lastName, 0);
}
if (stagePos != null) {
for (int i = 0; i < getImageCount(); i++) {
if (stagePos.length > 0) {
store.setPlanePositionX(stagePos[0], 0, i);
addGlobalMeta("X position for position #1", stagePos[0]);
}
if (stagePos.length > 1) {
store.setPlanePositionY(stagePos[1], 0, i);
addGlobalMeta("Y position for position #1", stagePos[1]);
}
if (stagePos.length > 2) {
store.setPlanePositionZ(stagePos[2], 0, i);
addGlobalMeta("Z position for position #1", stagePos[2]);
}
}
}
if (exposureTime != null) {
for (int i = 0; i < getImageCount(); i++) {
store.setPlaneExposureTime(exposureTime, 0, i);
}
}
}
}
use of loci.common.Location in project bioformats by openmicroscopy.
the class LegacyQTReader method initFile.
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
LOGGER.info("Checking for QuickTime Java");
if (tools == null) {
tools = new LegacyQTTools();
r = tools.getUniverse();
}
tools.checkQTLibrary();
super.initFile(id);
LOGGER.info("Reading movie dimensions");
try {
r.exec("QTSession.open()");
// open movie file
Location file = new Location(id);
r.setVar("path", file.getAbsolutePath());
r.exec("qtf = new QTFile(path)");
r.exec("openMovieFile = OpenMovieFile.asRead(qtf)");
r.exec("m = Movie.fromFile(openMovieFile)");
int numTracks = ((Integer) r.exec("m.getTrackCount()")).intValue();
int trackMostLikely = 0;
int trackNum = 0;
while (++trackNum <= numTracks && trackMostLikely == 0) {
r.setVar("trackNum", trackNum);
r.exec("imageTrack = m.getTrack(trackNum)");
r.exec("d = imageTrack.getSize()");
Integer w = (Integer) r.exec("d.getWidth()");
if (w.intValue() > 0)
trackMostLikely = trackNum;
}
r.setVar("trackMostLikely", trackMostLikely);
r.exec("imageTrack = m.getTrack(trackMostLikely)");
r.exec("d = imageTrack.getSize()");
Integer w = (Integer) r.exec("d.getWidth()");
Integer h = (Integer) r.exec("d.getHeight()");
r.exec("moviePlayer = new MoviePlayer(m)");
r.setVar("dim", new Dimension(w.intValue(), h.intValue()));
ImageProducer qtip = (ImageProducer) r.exec("qtip = new QTImageProducer(moviePlayer, dim)");
image = Toolkit.getDefaultToolkit().createImage(qtip);
r.setVar("zero", 0);
r.setVar("one", 1f);
r.exec("timeInfo = new TimeInfo(zero, zero)");
r.exec("moviePlayer.setTime(zero)");
Vector<Integer> v = new Vector<Integer>();
int time = 0;
Integer q = new Integer(time);
do {
v.add(q);
r.exec("timeInfo = imageTrack.getNextInterestingTime(" + "StdQTConstants.nextTimeMediaSample, timeInfo.time, one)");
q = (Integer) r.getVar("timeInfo.time");
time = q.intValue();
} while (time >= 0);
CoreMetadata m = core.get(0);
m.imageCount = v.size();
times = new int[getImageCount()];
for (int i = 0; i < times.length; i++) {
q = v.elementAt(i);
times[i] = q.intValue();
}
LOGGER.info("Populating metadata");
BufferedImage img = AWTImageTools.makeBuffered(image);
m.sizeX = img.getWidth();
m.sizeY = img.getHeight();
m.sizeZ = 1;
m.sizeC = img.getRaster().getNumBands();
m.sizeT = getImageCount();
m.pixelType = AWTImageTools.getPixelType(img);
m.dimensionOrder = "XYCTZ";
m.rgb = true;
m.interleaved = false;
m.littleEndian = false;
m.indexed = false;
m.falseColor = false;
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
} catch (ReflectException e) {
throw new FormatException("Open movie failed", e);
}
}
use of loci.common.Location in project bioformats by openmicroscopy.
the class MicromanagerReader method parsePosition.
private void parsePosition(String jsonData, int posIndex) throws IOException, FormatException {
Position p = positions.get(posIndex);
CoreMetadata ms = core.get(posIndex);
String parent = new Location(p.metadataFile).getParent();
// now parse the rest of the metadata
// metadata.txt looks something like this:
//
// {
// "Section Name": {
// "Key": "Value",
// "Array key": [
// first array value, second array value
// ]
// }
//
// }
LOGGER.info("Populating metadata");
Vector<Double> stamps = new Vector<Double>();
p.voltage = new Vector<Double>();
StringTokenizer st = new StringTokenizer(jsonData, "\n");
int[] slice = new int[3];
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
boolean open = token.indexOf('[') != -1;
boolean closed = token.indexOf(']') != -1;
if (open || (!open && !closed && !token.equals("{") && !token.startsWith("}"))) {
int quote = token.indexOf("\"") + 1;
String key = token.substring(quote, token.indexOf("\"", quote));
String value = null;
if (open == closed) {
value = token.substring(token.indexOf(':') + 1);
} else if (!closed) {
final StringBuilder valueBuffer = new StringBuilder();
while (!closed) {
token = st.nextToken();
closed = token.indexOf(']') != -1;
valueBuffer.append(token);
}
value = valueBuffer.toString();
value = value.replaceAll("\n", "");
}
if (value == null)
continue;
int startIndex = value.indexOf('[');
int endIndex = value.indexOf(']');
if (endIndex == -1)
endIndex = value.length();
value = value.substring(startIndex + 1, endIndex).trim();
if (value.length() == 0) {
continue;
}
value = value.substring(0, value.length() - 1);
value = value.replaceAll("\"", "");
if (value.endsWith(","))
value = value.substring(0, value.length() - 1);
addSeriesMeta(key, value);
if (key.equals("Channels")) {
ms.sizeC = Integer.parseInt(value);
} else if (key.equals("ChNames")) {
p.channels = value.split(",");
for (int q = 0; q < p.channels.length; q++) {
p.channels[q] = p.channels[q].replaceAll("\"", "").trim();
}
} else if (key.equals("Frames")) {
ms.sizeT = Integer.parseInt(value);
} else if (key.equals("Slices")) {
ms.sizeZ = Integer.parseInt(value);
} else if (key.equals("SlicesFirst")) {
if (value.equals("false")) {
ms.dimensionOrder = "XYCZT";
} else {
ms.dimensionOrder = "XYZCT";
}
} else if (key.equals("PixelSize_um")) {
p.pixelSize = new Double(value);
} else if (key.equals("z-step_um")) {
p.sliceThickness = new Double(value);
} else if (key.equals("Time")) {
p.time = value;
} else if (key.equals("Comment")) {
p.comment = value;
} else if (key.equals("FileName")) {
p.fileNameMap.put(new Index(slice), value);
if (p.baseTiff == null) {
p.baseTiff = value;
}
} else if (key.equals("Width")) {
ms.sizeX = Integer.parseInt(value);
} else if (key.equals("Height")) {
ms.sizeY = Integer.parseInt(value);
} else if (key.equals("IJType")) {
int type = Integer.parseInt(value);
switch(type) {
case 0:
ms.pixelType = FormatTools.UINT8;
break;
case 1:
ms.pixelType = FormatTools.UINT16;
break;
default:
throw new FormatException("Unknown type: " + type);
}
}
}
if (token.startsWith("\"FrameKey")) {
int dash = token.indexOf('-') + 1;
int nextDash = token.indexOf("-", dash);
slice[2] = Integer.parseInt(token.substring(dash, nextDash));
dash = nextDash + 1;
nextDash = token.indexOf("-", dash);
slice[1] = Integer.parseInt(token.substring(dash, nextDash));
dash = nextDash + 1;
slice[0] = Integer.parseInt(token.substring(dash, token.indexOf("\"", dash)));
token = st.nextToken().trim();
String key = "";
StringBuilder valueBuffer = new StringBuilder();
boolean valueArray = false;
int nestedCount = 0;
while (!token.startsWith("}") || nestedCount > 0) {
if (token.trim().endsWith("{")) {
nestedCount++;
token = st.nextToken().trim();
continue;
} else if (token.trim().startsWith("}")) {
nestedCount--;
token = st.nextToken().trim();
continue;
}
if (valueArray || token.trim().equals("],")) {
if (token.trim().equals("],")) {
valueArray = false;
} else {
valueBuffer.append(token.trim().replaceAll("\"", ""));
token = st.nextToken().trim();
continue;
}
} else {
int colon = token.indexOf(':');
key = token.substring(1, colon).trim();
valueBuffer.setLength(0);
valueBuffer.append(token.substring(colon + 1, token.length() - 1).trim().replaceAll("\"", ""));
key = key.replaceAll("\"", "");
if (token.trim().endsWith("[")) {
valueArray = true;
token = st.nextToken().trim();
continue;
}
}
String value = valueBuffer.toString();
addSeriesMeta(key, value);
if (key.equals("Exposure-ms")) {
p.exposureTime = new Time(Double.valueOf(value), UNITS.MILLISECOND);
} else if (key.equals("ElapsedTime-ms")) {
stamps.add(Double.valueOf(value));
} else if (key.equals("Core-Camera"))
p.cameraRef = value;
else if (key.equals(p.cameraRef + "-Binning")) {
if (value.indexOf('x') != -1)
p.binning = value;
else
p.binning = value + "x" + value;
} else if (key.equals(p.cameraRef + "-CameraID"))
p.detectorID = value;
else if (key.equals(p.cameraRef + "-CameraName")) {
p.detectorModel = value;
} else if (key.equals(p.cameraRef + "-Gain")) {
p.gain = (int) Double.parseDouble(value);
} else if (key.equals(p.cameraRef + "-Name")) {
p.detectorManufacturer = value;
} else if (key.equals(p.cameraRef + "-Temperature")) {
p.temperature = Double.parseDouble(value);
} else if (key.equals(p.cameraRef + "-CCDMode")) {
p.cameraMode = value;
} else if (key.startsWith("DAC-") && key.endsWith("-Volts")) {
p.voltage.add(new Double(value));
} else if (key.equals("FileName")) {
p.fileNameMap.put(new Index(slice), value);
Location realFile = new Location(parent, value);
if (realFile.exists()) {
if (p.tiffs == null) {
p.tiffs = new Vector<String>();
}
p.tiffs.add(realFile.getAbsolutePath());
}
if (p.baseTiff == null) {
p.baseTiff = value;
}
}
token = st.nextToken().trim();
}
} else if (token.startsWith("\"Coords-")) {
String path = token.substring(token.indexOf('-') + 1, token.lastIndexOf("\""));
int[] zct = new int[3];
int position = 0;
while (!token.startsWith("}")) {
int sep = token.indexOf(':');
if (sep > 0) {
String key = token.substring(0, sep);
String value = token.substring(sep + 1);
key = key.replaceAll("\"", "").trim();
value = value.replaceAll(",", "").trim();
if (key.equals("position")) {
position = Integer.parseInt(value);
} else if (key.equals("time")) {
zct[2] = Integer.parseInt(value);
} else if (key.equals("z")) {
zct[0] = Integer.parseInt(value);
} else if (key.equals("channel")) {
zct[1] = Integer.parseInt(value);
}
}
token = st.nextToken().trim();
}
Index idx = new Index(zct);
idx.position = position;
p.fileNameMap.put(idx, path);
}
}
p.timestamps = stamps.toArray(new Double[stamps.size()]);
Arrays.sort(p.timestamps);
if (new Location(parent, XML).exists()) {
p.xmlFile = new Location(parent, XML).getAbsolutePath();
parseXMLFile();
}
if (getSizeZ() == 0)
ms.sizeZ = 1;
if (getSizeT() == 0)
ms.sizeT = 1;
if (ms.dimensionOrder == null)
ms.dimensionOrder = "XYZCT";
ms.interleaved = false;
ms.rgb = false;
ms.littleEndian = false;
ms.imageCount = getSizeZ() * getSizeC() * getSizeT();
ms.indexed = false;
ms.falseColor = false;
ms.metadataComplete = true;
}
use of loci.common.Location in project bioformats by openmicroscopy.
the class MicromanagerReader method parsePosition.
// -- Helper methods --
private void parsePosition(int posIndex) throws IOException, FormatException {
Position p = positions.get(posIndex);
String s = DataTools.readFile(p.metadataFile);
parsePosition(s, posIndex);
buildTIFFList(posIndex);
// parse original metadata from each TIFF's JSON
p.positions = new Double[p.tiffs.size()][3];
int digits = String.valueOf(p.tiffs.size() - 1).length();
boolean parseMMJSONTag = true;
for (int plane = 0; plane < p.tiffs.size(); ) {
String path = p.tiffs.get(plane);
// file ordering is correct
if (p.tiffs.size() == p.fileNameMap.size() && plane < getImageCount()) {
path = p.getFile(plane);
}
if (path == null || !new Location(path).exists()) {
plane++;
continue;
}
try {
TiffParser parser = new TiffParser(path);
int nIFDs = parser.getIFDs().size();
IFD firstIFD = parser.getFirstIFD();
parser.fillInIFD(firstIFD);
// ensure that the plane dimensions and pixel type are correct
CoreMetadata ms = core.get(posIndex);
ms.sizeX = (int) firstIFD.getImageWidth();
ms.sizeY = (int) firstIFD.getImageLength();
ms.pixelType = firstIFD.getPixelType();
ms.littleEndian = firstIFD.isLittleEndian();
String json = firstIFD.getIFDTextValue(JSON_TAG);
if (json != null) {
String[] lines = json.split("\n");
for (String line : lines) {
String toSplit = line.trim();
if (toSplit.length() == 0) {
continue;
}
toSplit = toSplit.substring(0, toSplit.length() - 1);
String[] values = toSplit.split("\": ");
if (values.length < 2) {
continue;
}
String key = values[0].replaceAll("\"", "");
String value = values[1].replaceAll("\"", "");
if (key.length() > 0 && value.length() > 0) {
parseKeyAndValue(key, value, digits, plane * nIFDs, nIFDs);
}
}
}
IFDList ifds = parser.getIFDs();
for (int i = 0; i < ifds.size(); i++) {
if (!parseMMJSONTag) {
break;
}
IFD ifd = ifds.get(i);
parser.fillInIFD(ifd);
json = ifd.getIFDTextValue(MM_JSON_TAG);
LOGGER.trace("JSON for IFD #{} = {}", i, json);
if (json == null) {
// if one of the files is missing the per-plane JSON tag,
// assume all files are missing it (for performance)
parseMMJSONTag = false;
break;
}
String[] tokens = json.split("[\\{\\}:,\"]");
String key = null, value = null, propType = null;
int nEmptyTokens = 0;
for (int q = 0; q < tokens.length; q++) {
String token = tokens[q];
if (token.length() == 0) {
nEmptyTokens++;
continue;
}
if (nEmptyTokens == 5 && value == null) {
key = null;
}
if (key == null && value == null && propType == null) {
// don't use completeCoords as a key, defer to child attributes
if (!token.equals("completeCoords")) {
key = token;
}
nEmptyTokens = 0;
} else if (token.equals("PropVal") || token.equals("[")) {
value = token;
} else if (token.equals("PropType")) {
propType = token;
} else if (value != null && value.equals("PropVal") && propType == null) {
value = token;
} else if (value != null && propType == null && value.startsWith("[") && !token.startsWith("]")) {
value += token;
value += ", ";
} else if (((propType != null && propType.equals("PropType")) || token.equals("]")) || (key != null && value == null)) {
if (value == null && (propType == null || !propType.equals("PropType"))) {
StringBuilder sb = new StringBuilder(token);
while (q + 1 < tokens.length && tokens[q + 1].trim().length() > 0) {
sb.append(':');
sb.append(tokens[q + 1]);
q++;
}
value = sb.toString();
}
if (!value.equals("PropVal")) {
parseKeyAndValue(key, value, digits, plane + i, 1);
}
propType = null;
key = null;
value = null;
nEmptyTokens = 0;
}
}
}
plane += ifds.size();
parser.getStream().close();
} catch (IOException e) {
LOGGER.debug("Failed to read metadata from " + path, e);
}
}
}
Aggregations