private void parseROIs(MetadataStore store) throws IOException { if (roiFile == null) return; String roiData = DataTools.readFile(roiFile); String[] lines = roiData.split("\r\n"); int firstRow = 0; while (firstRow < lines.length && !lines[firstRow].startsWith("ROI")) { firstRow++; } firstRow += 2; if (firstRow >= lines.length) return; for (int i = firstRow; i < lines.length; i++) { String[] cols = lines[i].split("\t"); if (cols.length < 6) break; if (cols[2].trim().length() > 0) { String rectangleID = MetadataTools.createLSID("Shape", i - firstRow, 0); store.setRectangleID(rectangleID, i - firstRow, 0); store.setRectangleX(new Double(cols[2]), i - firstRow, 0); store.setRectangleY(new Double(cols[3]), i - firstRow, 0); store.setRectangleWidth(new Double(cols[4]), i - firstRow, 0); store.setRectangleHeight(new Double(cols[5]), i - firstRow, 0); String roiID = MetadataTools.createLSID("ROI", i - firstRow); store.setROIID(roiID, i - firstRow); for (int s = 0; s < getSeriesCount(); s++) { store.setImageROIRef(roiID, s, i - firstRow); } } } }
/* @see BaseTiffReader#initMetadataStore() */ protected void initMetadataStore() throws FormatException { super.initMetadataStore(); MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this, true); if (date != null) { date = DateTools.formatDate(date, DATE_FORMAT); if (date != null) { store.setImageAcquisitionDate(new Timestamp(date), 0); } } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { store.setImageDescription(MAGIC_STRING, 0); if (scaling > 0) { store.setPixelsPhysicalSizeX(new PositiveFloat(scaling), 0); store.setPixelsPhysicalSizeY(new PositiveFloat(scaling), 0); } else { LOGGER.warn("Expected positive value for PhysicalSize; got {}", scaling); } String instrument = MetadataTools.createLSID("Instrument", 0); store.setInstrumentID(instrument, 0); store.setImageInstrumentRef(instrument, 0); store.setObjectiveID(MetadataTools.createLSID("Objective", 0, 0), 0, 0); if (magnification > 0) { store.setObjectiveNominalMagnification(new PositiveInteger(magnification), 0, 0); } else { LOGGER.warn("Expected positive value for NominalMagnification; got {}", magnification); } store.setObjectiveImmersion(getImmersion(immersion), 0, 0); String detector = MetadataTools.createLSID("Detector", 0, 0); store.setDetectorID(detector, 0, 0); store.setDetectorModel(cameraType + " " + cameraName, 0, 0); store.setDetectorType(getDetectorType("CCD"), 0, 0); for (int i = 0; i < getSizeC(); i++) { store.setDetectorSettingsID(detector, 0, i); store.setDetectorSettingsBinning(getBinning(binning), 0, i); } for (int i = 0; i < getImageCount(); i++) { int[] zct = getZCTCoords(i); store.setPlaneExposureTime(exposureTimes.get(zct[1]) / 1000000, 0, i); } } }
private void parseROIs(MetadataStore store) throws FormatException, IOException { if (MetadataTools.isOMEXMLMetadata(store) || MetadataTools.isOMEXMLRoot(store.getRoot())) { return; } String roiID = MetadataTools.createLSID("ROI", 0, 0); String maskID = MetadataTools.createLSID("Shape", 0, 0); store.setROIID(roiID, 0); store.setMaskID(maskID, 0, 0); String positionData = DataTools.readFile(roiDrawFile); String[] coordinates = positionData.split("[ ,]"); double x1 = Double.parseDouble(coordinates[1]); double y1 = Double.parseDouble(coordinates[2]); double x2 = Double.parseDouble(coordinates[3]); double y2 = Double.parseDouble(coordinates[5]); store.setMaskX(x1, 0, 0); store.setMaskY(y1, 0, 0); store.setMaskWidth(x2 - x1, 0, 0); store.setMaskHeight(y2 - y1, 0, 0); store.setImageROIRef(roiID, 0, 0); ImageReader roiReader = new ImageReader(); roiReader.setId(roiFile); byte[] roiPixels = roiReader.openBytes(0); roiReader.close(); BitWriter bits = new BitWriter(roiPixels.length / 8); for (int i = 0; i < roiPixels.length; i++) { bits.write(roiPixels[i] == 0 ? 0 : 1, 1); } store.setMaskBinData(bits.toByteArray(), 0, 0); }
/* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); in = new RandomAccessInputStream(id); CoreMetadata m = core.get(0); m.littleEndian = true; in.order(isLittleEndian()); while (in.getFilePointer() < MAX_HEADER_SIZE) { readVariable(); } in.seek(pixelsOffset); m.sizeX = in.readShort(); pixelsOffset += 2; m.sizeY = getSizeX(); m.pixelType = FormatTools.UINT16; m.sizeZ = 1; m.sizeC = 1; m.sizeT = 1; m.imageCount = 1; m.dimensionOrder = "XYZCT"; MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); if (date != null) { date = DateTools.formatDate(date, "MMM dd yyyy HH:mm:ssSSS"); if (date != null) { store.setImageAcquisitionDate(new Timestamp(date), 0); } } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { store.setImageDescription(comment, 0); PositiveFloat sizeX = FormatTools.getPhysicalSizeX((double) xSize / getSizeX()); PositiveFloat sizeY = FormatTools.getPhysicalSizeY((double) xSize / getSizeY()); if (sizeX != null) { store.setPixelsPhysicalSizeX(sizeX, 0); } if (sizeY != null) { store.setPixelsPhysicalSizeY(sizeY, 0); } } }
/* @see BaseTiffReader#initMetadataStore() */ protected void initMetadataStore() throws FormatException { super.initMetadataStore(); MetadataStore store = makeFilterMetadata(); if (creationDate != null) { creationDate = DateTools.formatDate(creationDate, "yyyyMMdd HHmmSSZ"); } for (int i = 0; i < getSeriesCount(); i++) { String name = imageName; if (imageName.length() == 0) { name = "#" + (i + 1); } else { name += " #" + (i + 1); } store.setImageName(name, i); if (creationDate != null) { store.setImageAcquisitionDate(new Timestamp(creationDate), i); } } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { if (experimenterName == null) experimenterName = ""; int nameSpace = experimenterName.indexOf(" "); String firstName = nameSpace == -1 ? "" : experimenterName.substring(0, nameSpace); String lastName = nameSpace == -1 ? experimenterName : experimenterName.substring(nameSpace + 1); String experimenter = MetadataTools.createLSID("Experimenter", 0); store.setExperimenterID(experimenter, 0); store.setExperimenterFirstName(firstName, 0); store.setExperimenterLastName(lastName, 0); for (int i = 0; i < getSeriesCount(); i++) { store.setImageExperimenterRef(experimenter, i); } } }
/* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); Location parent = new Location(id).getAbsoluteFile().getParentFile(); String[] lines = DataTools.readFile(currentId).split("\r\n"); for (String line : lines) { int eq = line.indexOf("="); if (eq < 0) { continue; } String key = line.substring(0, eq).trim(); String value = line.substring(eq + 1).trim(); if (key.equals("NoImages")) { ndpiFiles = new String[Integer.parseInt(value)]; readers = new ChannelSeparator[ndpiFiles.length]; } else if (key.startsWith("Image")) { int index = Integer.parseInt(key.replaceAll("Image", "")); ndpiFiles[index] = new Location(parent, value).getAbsolutePath(); readers[index] = new ChannelSeparator(new NDPIReader()); } } readers[0].setMetadataStore(getMetadataStore()); readers[0].setId(ndpiFiles[0]); core = readers[0].getCoreMetadata(); for (int i = 0; i < getSeriesCount(); i++) { core[i].sizeC = readers.length; core[i].rgb = false; core[i].imageCount = core[i].sizeC * core[i].sizeZ * core[i].sizeT; core[i].cLengths = new int[] {getSizeC()}; } MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); }
public static double[] readImageInfo(String id) { try { reader.setId(id); } catch (FormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // ORDERING: 0 little, 1 seriesCount, 2 pixelType, 3 bpp, 4 itkComponentType, 5 sizeX, // 6 sizeY, 7 sizeZ, 8 sizeT, 9 sizeC, 10 effSizeC, 11 rgbChannelCount, 12 imageCount // 13 physX, 14 physY, 15 physZ, 16 timeIncrement double[] returnValues = new double[17]; // return this and use SetByteOrderToLittleEndian or SetByteOrderToBigEndian in C++ land boolean little = reader.isLittleEndian(); if (little) { returnValues[0] = 1; } else { returnValues[0] = 0; } returnValues[1] = reader.getSeriesCount(); // return bpp and set an IOComponent based on it int pixelType = reader.getPixelType(); returnValues[2] = (double) pixelType; returnValues[3] = (double) FormatTools.getBytesPerPixel((int) returnValues[2]); // 0 UCHAR, 1 CHAR, 2 USHORT, 3 SHORT, 4 UINT, 5 INT, 6 FLOAT, 7 DOUBLE, 8 UNKNOWN if (pixelType == FormatTools.UINT8) returnValues[4] = (double) 0; else if (pixelType == FormatTools.INT8) returnValues[4] = (double) 1; else if (pixelType == FormatTools.UINT16) returnValues[4] = (double) 2; else if (pixelType == FormatTools.INT16) returnValues[4] = (double) 3; else if (pixelType == FormatTools.UINT32) returnValues[4] = (double) 4; else if (pixelType == FormatTools.INT32) returnValues[4] = (double) 5; else if (pixelType == FormatTools.FLOAT) returnValues[4] = (double) 6; else if (pixelType == FormatTools.DOUBLE) returnValues[4] = (double) 7; else returnValues[4] = (double) 8; // return these returnValues[5] = (double) reader.getSizeX(); returnValues[6] = (double) reader.getSizeY(); returnValues[7] = (double) reader.getSizeZ(); returnValues[8] = (double) reader.getSizeT(); returnValues[9] = (double) reader.getSizeC(); returnValues[10] = (double) reader.getEffectiveSizeC(); returnValues[11] = (double) reader.getRGBChannelCount(); returnValues[12] = (double) reader.getImageCount(); MetadataRetrieve retrieve = MetadataTools.asRetrieve(reader.getMetadataStore()); Double d = retrieve.getPixelsPhysicalSizeX(0).getValue(); double d2 = d == null ? 1.0 : d.doubleValue(); returnValues[13] = d2; d = retrieve.getPixelsPhysicalSizeY(0).getValue(); d2 = d == null ? 1.0 : d.doubleValue(); returnValues[14] = d2; d = retrieve.getPixelsPhysicalSizeZ(0).getValue(); d2 = d == null ? 1.0 : d.doubleValue(); returnValues[15] = d2; d = retrieve.getPixelsTimeIncrement(0); d2 = d == null ? 1.0 : d.doubleValue(); returnValues[16] = d2; return returnValues; }
/* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); if (!checkSuffix(id, "vsi")) { Location current = new Location(id).getAbsoluteFile(); Location parent = current.getParentFile(); parent = parent.getParentFile(); Location grandparent = parent.getParentFile(); String vsi = parent.getName(); vsi = vsi.substring(1, vsi.length() - 1) + ".vsi"; Location vsiFile = new Location(grandparent, vsi); if (!vsiFile.exists()) { throw new FormatException("Could not find .vsi file."); } else { id = vsiFile.getAbsolutePath(); } } parser = new TiffParser(id); ifds = parser.getIFDs(); RandomAccessInputStream vsi = new RandomAccessInputStream(id); vsi.order(parser.getStream().isLittleEndian()); vsi.seek(8); readTags(vsi); vsi.seek(parser.getStream().getFilePointer()); vsi.skipBytes(273); ArrayList<String> files = new ArrayList<String>(); Location file = new Location(id).getAbsoluteFile(); Location dir = file.getParentFile(); String name = file.getName(); name = name.substring(0, name.lastIndexOf(".")); Location pixelsDir = new Location(dir, "_" + name + "_"); String[] stackDirs = pixelsDir.list(true); if (stackDirs != null) { for (String f : stackDirs) { Location stackDir = new Location(pixelsDir, f); String[] pixelsFiles = stackDir.list(true); if (pixelsFiles != null) { for (String pixelsFile : pixelsFiles) { if (checkSuffix(pixelsFile, "ets")) { files.add(new Location(stackDir, pixelsFile).getAbsolutePath()); } } } } } files.add(file.getAbsolutePath()); usedFiles = files.toArray(new String[files.size()]); core = new CoreMetadata[files.size() - 1 + ifds.size()]; tileOffsets = new Long[files.size() - 1][]; rows = new int[files.size() - 1]; cols = new int[files.size() - 1]; nDimensions = new int[core.length]; IFDList exifs = parser.getExifIFDs(); compressionType = new int[core.length]; tileX = new int[core.length]; tileY = new int[core.length]; tileMap = new HashMap[core.length]; for (int s = 0; s < core.length; s++) { core[s] = new CoreMetadata(); } for (int s = 0; s < core.length; s++) { tileMap[s] = new HashMap<TileCoordinate, Integer>(); if (s == 0 && !hasFlattenedResolutions()) { core[s].resolutionCount = ifds.size() + (files.size() == 1 ? 0 : 1); } if (s < files.size() - 1) { setSeries(s); parseETSFile(files.get(s), s); core[s].littleEndian = compressionType[s] == RAW; core[s].interleaved = core[s].rgb; if (s == 0 && exifs.size() > 0) { IFD exif = exifs.get(0); int newX = exif.getIFDIntValue(IFD.PIXEL_X_DIMENSION); int newY = exif.getIFDIntValue(IFD.PIXEL_Y_DIMENSION); if (getSizeX() > newX || getSizeY() > newY) { core[s].sizeX = newX; core[s].sizeY = newY; } } setSeries(0); } else { IFD ifd = ifds.get(s - files.size() + 1); PhotoInterp p = ifd.getPhotometricInterpretation(); int samples = ifd.getSamplesPerPixel(); core[s].rgb = samples > 1 || p == PhotoInterp.RGB; core[s].sizeX = (int) ifd.getImageWidth(); core[s].sizeY = (int) ifd.getImageLength(); core[s].sizeZ = 1; core[s].sizeT = 1; core[s].sizeC = core[s].rgb ? samples : 1; core[s].littleEndian = ifd.isLittleEndian(); core[s].indexed = p == PhotoInterp.RGB_PALETTE && (get8BitLookupTable() != null || get16BitLookupTable() != null); core[s].imageCount = 1; core[s].pixelType = ifd.getPixelType(); core[s].interleaved = false; core[s].falseColor = false; core[s].thumbnail = s != 0; } core[s].metadataComplete = true; core[s].dimensionOrder = "XYCZT"; } vsi.close(); MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); }
/* @see loci.formats.FormatReader#initFile(String) */ public void initFile(String id) throws FormatException, IOException { super.initFile(id); in = new RandomAccessInputStream(id); MetadataLevel level = getMetadataOptions().getMetadataLevel(); LOGGER.info("Reading header"); // check endianness in.seek(ENDIANNESS_OFFSET); core[0].littleEndian = in.read() == 68; // read dimension information from 1024 byte header in.seek(0); in.order(isLittleEndian()); core[0].sizeX = in.readInt(); core[0].sizeY = in.readInt(); core[0].sizeZ = in.readInt(); // We are using BigInteger here because of the very real possiblity // of not just an int overflow but also a long overflow when multiplying // sizeX * sizeY * sizeZ. BigInteger v = BigInteger.valueOf(getSizeX()); v = v.multiply(BigInteger.valueOf(getSizeY())); v = v.multiply(BigInteger.valueOf(getSizeZ())); if (getSizeX() < 0 || getSizeY() < 0 || getSizeZ() < 0 || (v.compareTo(BigInteger.valueOf(in.length())) > 0)) { LOGGER.debug("Detected endianness is wrong, swapping"); core[0].littleEndian = !isLittleEndian(); in.seek(0); in.order(isLittleEndian()); core[0].sizeX = in.readInt(); core[0].sizeY = in.readInt(); core[0].sizeZ = in.readInt(); } core[0].sizeC = 1; int mode = in.readInt(); switch (mode) { case 0: core[0].pixelType = FormatTools.UINT8; break; case 1: core[0].pixelType = FormatTools.INT16; break; case 6: core[0].pixelType = FormatTools.UINT16; break; case 2: core[0].pixelType = FormatTools.FLOAT; break; case 3: core[0].pixelType = FormatTools.UINT32; break; case 4: core[0].pixelType = FormatTools.DOUBLE; break; case 16: core[0].sizeC = 3; core[0].pixelType = FormatTools.UINT16; break; } in.skipBytes(12); // pixel size = xlen / mx double xSize = 0d, ySize = 0d, zSize = 0d; if (level != MetadataLevel.MINIMUM) { int mx = in.readInt(); int my = in.readInt(); int mz = in.readInt(); // physical sizes are stored in ångströms, we want them in µm xSize = (in.readFloat() / mx) / 10000.0; ySize = (in.readFloat() / my) / 10000.0; zSize = (in.readFloat() / mz) / 10000.0; addGlobalMeta("Pixel size (X)", xSize); addGlobalMeta("Pixel size (Y)", ySize); addGlobalMeta("Pixel size (Z)", zSize); addGlobalMeta("Alpha angle", in.readFloat()); addGlobalMeta("Beta angle", in.readFloat()); addGlobalMeta("Gamma angle", in.readFloat()); in.skipBytes(12); // min, max and mean pixel values } else in.skipBytes(48); double minValue = in.readFloat(); double maxValue = in.readFloat(); addGlobalMeta("Minimum pixel value", minValue); addGlobalMeta("Maximum pixel value", maxValue); addGlobalMeta("Mean pixel value", in.readFloat()); int bytes = FormatTools.getBytesPerPixel(getPixelType()); double range = Math.pow(2, bytes * 8) - 1; double pixelTypeMin = 0; boolean signed = FormatTools.isSigned(getPixelType()); if (signed) { pixelTypeMin -= (range / 2); } double pixelTypeMax = pixelTypeMin + range; if (pixelTypeMax < maxValue || pixelTypeMin > minValue && signed) { // make the pixel type unsigned switch (getPixelType()) { case FormatTools.INT8: core[0].pixelType = FormatTools.UINT8; break; case FormatTools.INT16: core[0].pixelType = FormatTools.UINT16; break; case FormatTools.INT32: core[0].pixelType = FormatTools.UINT32; break; } } in.skipBytes(4); extHeaderSize = in.readInt(); if (level != MetadataLevel.MINIMUM) { in.skipBytes(64); int idtype = in.readShort(); String type = "unknown"; if (idtype >= 0 && idtype < TYPES.length) type = TYPES[idtype]; addGlobalMeta("Series type", type); addGlobalMeta("Lens", in.readShort()); addGlobalMeta("ND1", in.readShort()); addGlobalMeta("ND2", in.readShort()); addGlobalMeta("VD1", in.readShort()); addGlobalMeta("VD2", in.readShort()); for (int i = 0; i < 6; i++) { addGlobalMeta("Angle " + (i + 1), in.readFloat()); } in.skipBytes(24); addGlobalMeta("Number of useful labels", in.readInt()); for (int i = 0; i < 10; i++) { addGlobalMeta("Label " + (i + 1), in.readString(80)); } } LOGGER.info("Populating metadata"); core[0].sizeT = 1; core[0].dimensionOrder = "XYZTC"; core[0].imageCount = getSizeZ(); core[0].rgb = false; core[0].interleaved = true; core[0].indexed = false; core[0].falseColor = false; core[0].metadataComplete = true; MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); if (level != MetadataLevel.MINIMUM) { if (xSize - Constants.EPSILON > 0) { store.setPixelsPhysicalSizeX(new PositiveFloat(xSize), 0); } else { LOGGER.warn("xSize {} not a positive float skipping", xSize); } if (ySize - Constants.EPSILON > 0) { store.setPixelsPhysicalSizeY(new PositiveFloat(ySize), 0); } else { LOGGER.warn("ySize {} not a positive float skipping", ySize); } if (zSize - Constants.EPSILON > 0) { store.setPixelsPhysicalSizeZ(new PositiveFloat(zSize), 0); } else { LOGGER.warn("zSize {} not a positive float skipping", zSize); } } }
@Override protected void initFile(String id) throws FormatException, IOException { LOGGER.debug("OmeroReader.initFile({})", id); super.initFile(id); if (!id.startsWith("omero:")) { throw new IllegalArgumentException("Not an OMERO id: " + id); } // parse credentials from id string LOGGER.info("Parsing credentials"); String address = server, user = username, pass = password; int port = thePort; long iid = -1; final String[] tokens = id.substring(6).split("\n"); for (String token : tokens) { final int equals = token.indexOf("="); if (equals < 0) continue; final String key = token.substring(0, equals); final String val = token.substring(equals + 1); if (key.equals("server")) address = val; else if (key.equals("user")) user = val; else if (key.equals("pass")) pass = val; else if (key.equals("port")) { try { port = Integer.parseInt(val); } catch (NumberFormatException exc) { } } else if (key.equals("session")) { sessionID = val; } else if (key.equals("groupName")) { group = val; } else if (key.equals("groupID")) { groupID = new Long(val); } else if (key.equals("iid")) { try { iid = Long.parseLong(val); } catch (NumberFormatException exc) { } } } if (address == null) { throw new FormatException("Invalid server address"); } if (user == null && sessionID == null) { throw new FormatException("Invalid username"); } if (pass == null && sessionID == null) { throw new FormatException("Invalid password"); } if (iid < 0) { throw new FormatException("Invalid image ID"); } try { // authenticate with OMERO server LOGGER.info("Logging in"); client = new omero.client(address, port); ServiceFactoryPrx serviceFactory = null; if (user != null && pass != null) { serviceFactory = client.createSession(user, pass); } else { serviceFactory = client.createSession(sessionID, sessionID); } if (!encrypted) { client = client.createClient(false); serviceFactory = client.getSession(); } if (group != null || groupID != null) { IAdminPrx iAdmin = serviceFactory.getAdminService(); IQueryPrx iQuery = serviceFactory.getQueryService(); EventContext eventContext = iAdmin.getEventContext(); ExperimenterGroup defaultGroup = iAdmin.getDefaultGroup(eventContext.userId); if (!defaultGroup.getName().getValue().equals(group) && !new Long(defaultGroup.getId().getValue()).equals(groupID)) { Experimenter exp = iAdmin.getExperimenter(eventContext.userId); ParametersI p = new ParametersI(); p.addId(eventContext.userId); List<IObject> groupList = iQuery.findAllByQuery( "select distinct g from ExperimenterGroup as g " + "join fetch g.groupExperimenterMap as map " + "join fetch map.parent e " + "left outer join fetch map.child u " + "left outer join fetch u.groupExperimenterMap m2 " + "left outer join fetch m2.parent p " + "where g.id in " + " (select m.parent from GroupExperimenterMap m " + " where m.child.id = :id )", p); Iterator<IObject> i = groupList.iterator(); ExperimenterGroup g = null; boolean in = false; while (i.hasNext()) { g = (ExperimenterGroup) i.next(); if (g.getName().getValue().equals(group) || new Long(g.getId().getValue()).equals(groupID)) { in = true; groupID = g.getId().getValue(); break; } } if (in) { iAdmin.setDefaultGroup(exp, iAdmin.getGroup(groupID)); serviceFactory.setSecurityContext(new ExperimenterGroupI(groupID, false)); } } } // get raw pixels store and pixels store = serviceFactory.createRawPixelsStore(); final GatewayPrx gateway = serviceFactory.createGateway(); img = gateway.getImage(iid); if (img == null) { throw new FormatException( "Could not find Image with ID=" + iid + " in group '" + group + "'."); } long pixelsId = img.getPixels(0).getId().getValue(); store.setPixelsId(pixelsId, false); pix = gateway.getPixels(pixelsId); final int sizeX = pix.getSizeX().getValue(); final int sizeY = pix.getSizeY().getValue(); final int sizeZ = pix.getSizeZ().getValue(); final int sizeC = pix.getSizeC().getValue(); final int sizeT = pix.getSizeT().getValue(); final String pixelType = pix.getPixelsType().getValue().getValue(); // populate metadata LOGGER.info("Populating metadata"); core[0].sizeX = sizeX; core[0].sizeY = sizeY; core[0].sizeZ = sizeZ; core[0].sizeC = sizeC; core[0].sizeT = sizeT; core[0].rgb = false; core[0].littleEndian = false; core[0].dimensionOrder = "XYZCT"; core[0].imageCount = sizeZ * sizeC * sizeT; core[0].pixelType = FormatTools.pixelTypeFromString(pixelType); RDouble x = pix.getPhysicalSizeX(); Double px = x == null ? null : x.getValue(); RDouble y = pix.getPhysicalSizeY(); Double py = y == null ? null : y.getValue(); RDouble z = pix.getPhysicalSizeZ(); Double pz = z == null ? null : z.getValue(); RDouble t = pix.getTimeIncrement(); Double time = t == null ? null : t.getValue(); RString imageName = img.getName(); String name = imageName == null ? null : imageName.getValue(); if (name != null) { currentId = name; } else { currentId = "Image ID " + iid; } RString imgDescription = img.getDescription(); String description = imgDescription == null ? null : imgDescription.getValue(); RTime date = img.getAcquisitionDate(); MetadataStore store = getMetadataStore(); MetadataTools.populatePixels(store, this); store.setImageName(name, 0); store.setImageDescription(description, 0); if (date != null) { store.setImageAcquisitionDate( new Timestamp(DateTools.convertDate(date.getValue(), (int) DateTools.UNIX_EPOCH)), 0); } if (px != null && px > 0) { store.setPixelsPhysicalSizeX(new PositiveFloat(px), 0); } if (py != null && py > 0) { store.setPixelsPhysicalSizeY(new PositiveFloat(py), 0); } if (pz != null && pz > 0) { store.setPixelsPhysicalSizeZ(new PositiveFloat(pz), 0); } if (time != null) { store.setPixelsTimeIncrement(time, 0); } List<Channel> channels = pix.copyChannels(); for (int c = 0; c < channels.size(); c++) { LogicalChannel channel = channels.get(c).getLogicalChannel(); RInt emWave = channel.getEmissionWave(); RInt exWave = channel.getExcitationWave(); RDouble pinholeSize = channel.getPinHoleSize(); RString cname = channel.getName(); Integer emission = emWave == null ? null : emWave.getValue(); Integer excitation = exWave == null ? null : exWave.getValue(); String channelName = cname == null ? null : cname.getValue(); Double pinhole = pinholeSize == null ? null : pinholeSize.getValue(); if (channelName != null) { store.setChannelName(channelName, 0, c); } if (pinhole != null) { store.setChannelPinholeSize(pinhole, 0, c); } if (emission != null && emission > 0) { store.setChannelEmissionWavelength(new PositiveInteger(emission), 0, c); } if (excitation != null && excitation > 0) { store.setChannelExcitationWavelength(new PositiveInteger(excitation), 0, c); } } } catch (CannotCreateSessionException e) { throw new FormatException(e); } catch (PermissionDeniedException e) { throw new FormatException(e); } catch (ServerError e) { throw new FormatException(e); } }
private void populateMetadata() throws FormatException, IOException { MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this, true); String instrumentID = MetadataTools.createLSID("Instrument", 0); store.setInstrumentID(instrumentID, 0); for (int i = 0; i < positions.size(); i++) { Position p = positions.get(i); if (p.time != null) { String date = DateTools.formatDate(p.time, DATE_FORMAT); if (date != null) { store.setImageAcquisitionDate(new Timestamp(date), i); } } if (positions.size() > 1) { Location parent = new Location(p.metadataFile).getParentFile(); store.setImageName(parent.getName(), i); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { store.setImageDescription(p.comment, i); // link Instrument and Image store.setImageInstrumentRef(instrumentID, i); for (int c = 0; c < p.channels.length; c++) { store.setChannelName(p.channels[c], i, c); } if (p.pixelSize != null && p.pixelSize > 0) { store.setPixelsPhysicalSizeX(new PositiveFloat(p.pixelSize), i); store.setPixelsPhysicalSizeY(new PositiveFloat(p.pixelSize), i); } else { LOGGER.warn("Expected positive value for PhysicalSizeX; got {}", p.pixelSize); } if (p.sliceThickness != null && p.sliceThickness > 0) { store.setPixelsPhysicalSizeZ(new PositiveFloat(p.sliceThickness), i); } else { LOGGER.warn("Expected positive value for PhysicalSizeZ; got {}", p.sliceThickness); } int nextStamp = 0; for (int q = 0; q < getImageCount(); q++) { store.setPlaneExposureTime(p.exposureTime, i, q); String tiff = positions.get(getSeries()).getFile(q); if (tiff != null && new Location(tiff).exists() && nextStamp < p.timestamps.length) { store.setPlaneDeltaT(p.timestamps[nextStamp++], i, q); } } String serialNumber = p.detectorID; p.detectorID = MetadataTools.createLSID("Detector", 0, i); for (int c = 0; c < p.channels.length; c++) { store.setDetectorSettingsBinning(getBinning(p.binning), i, c); store.setDetectorSettingsGain(new Double(p.gain), i, c); if (c < p.voltage.size()) { store.setDetectorSettingsVoltage(p.voltage.get(c), i, c); } store.setDetectorSettingsID(p.detectorID, i, c); } store.setDetectorID(p.detectorID, 0, i); if (p.detectorModel != null) { store.setDetectorModel(p.detectorModel, 0, i); } if (serialNumber != null) { store.setDetectorSerialNumber(serialNumber, 0, i); } if (p.detectorManufacturer != null) { store.setDetectorManufacturer(p.detectorManufacturer, 0, i); } if (p.cameraMode == null) p.cameraMode = "Other"; store.setDetectorType(getDetectorType(p.cameraMode), 0, i); store.setImagingEnvironmentTemperature(p.temperature, i); } } }
/* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); in = new RandomAccessInputStream(id); core[0].littleEndian = true; in.order(isLittleEndian()); String comment = null; MetadataLevel level = getMetadataOptions().getMetadataLevel(); if (level != MetadataLevel.MINIMUM) { in.seek(49); comment = in.readString(33); } in.seek(211); int year = in.readInt(); int month = in.readInt(); int day = in.readInt(); int hour = in.readInt(); int min = in.readInt(); String date = year + "-" + month + "-" + day + "T" + hour + ":" + min; date = DateTools.formatDate(date, "yyyy-MM-dd'T'HH:mm"); in.skipBytes(8); double xSize = in.readInt() / 100d; double ySize = in.readInt() / 100d; double zSize = in.readInt() / 100d; core[0].sizeX = in.readInt(); core[0].sizeY = in.readInt(); if (level != MetadataLevel.MINIMUM) { double tunnelCurrent = in.readInt() / 1000d; double sampleVolts = in.readInt() / 1000d; in.skipBytes(180); int originalZMax = in.readInt(); int originalZMin = in.readInt(); int zMax = in.readInt(); int zMin = in.readInt(); addGlobalMeta("Comment", comment); addGlobalMeta("X size (in um)", xSize); addGlobalMeta("Y size (in um)", ySize); addGlobalMeta("Z size (in um)", zSize); addGlobalMeta("Tunnel current (in amps)", tunnelCurrent); addGlobalMeta("Sample volts", sampleVolts); addGlobalMeta("Acquisition date", date); } core[0].pixelType = FormatTools.INT16; core[0].sizeC = 1; core[0].sizeZ = 1; core[0].sizeT = 1; core[0].imageCount = 1; core[0].dimensionOrder = "XYZCT"; core[0].rgb = false; MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); if (date != null) { store.setImageAcquisitionDate(new Timestamp(date), 0); } if (level != MetadataLevel.MINIMUM) { store.setImageDescription(comment, 0); if (xSize > 0) { store.setPixelsPhysicalSizeX(new PositiveFloat((double) xSize / getSizeX()), 0); } else { LOGGER.warn( "Expected positive value for PhysicalSizeX; got {}", (double) xSize / getSizeX()); } if (ySize > 0) { store.setPixelsPhysicalSizeY(new PositiveFloat((double) ySize / getSizeY()), 0); } else { LOGGER.warn( "Expected positive value for PhysicalSizeY; got {}", (double) ySize / getSizeY()); } } }
/* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { // make sure we have the experiment file id = locateExperimentFile(id); super.initFile(id); Location dir = new Location(id).getAbsoluteFile().getParentFile(); for (String file : dir.list(true)) { Location f = new Location(dir, file); if (!f.isDirectory()) { if (checkSuffix(file, META_EXT)) { metadataFiles.add(f.getAbsolutePath()); } } } // parse Experiment metadata IniList experiment = readMetaData(id); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { objective = experiment.getTable("Geometry").get("Name"); IniTable camera = experiment.getTable("Camera"); binning = camera.get("BinX") + "x" + camera.get("BinY"); parseChannelData(dir); addGlobalMeta("Objective", objective); addGlobalMeta("Camera binning", binning); } Vector<String> uniqueRows = new Vector<String>(); Vector<String> uniqueColumns = new Vector<String>(); for (String well : wellLabels) { 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); } } int nSlices = getSizeZ() == 0 ? 1 : getSizeZ(); int nTimepoints = getSizeT(); int nWells = wellLabels.size(); int nChannels = getSizeC() == 0 ? channelNames.size() : getSizeC(); if (nChannels == 0) nChannels = 1; tiffs = getTiffs(dir.getAbsolutePath()); reader = new MinimalTiffReader(); reader.setId(tiffs[0][0]); int sizeX = reader.getSizeX(); int sizeY = reader.getSizeY(); int pixelType = reader.getPixelType(); boolean rgb = reader.isRGB(); boolean interleaved = reader.isInterleaved(); boolean indexed = reader.isIndexed(); boolean littleEndian = reader.isLittleEndian(); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { IniParser parser = new IniParser(); for (String metadataFile : metadataFiles) { String filename = new Location(metadataFile).getName(); if (!checkSuffix(metadataFile, "txt")) { String data = DataTools.readFile(metadataFile); IniList ini = parser.parseINI(new BufferedReader(new StringReader(data))); HashMap<String, String> h = ini.flattenIntoHashMap(); for (String key : h.keySet()) { addGlobalMeta(filename + " " + key, h.get(key)); } } } } for (int i = 0; i < getSeriesCount(); i++) { core[i] = new CoreMetadata(); core[i].sizeC = nChannels; core[i].sizeZ = nSlices; core[i].sizeT = nTimepoints; core[i].sizeX = sizeX / fieldCols; core[i].sizeY = sizeY / fieldRows; core[i].pixelType = pixelType; core[i].rgb = rgb; core[i].interleaved = interleaved; core[i].indexed = indexed; core[i].littleEndian = littleEndian; core[i].dimensionOrder = "XYZTC"; core[i].imageCount = nSlices * nTimepoints * nChannels; } MetadataStore store = makeFilterMetadata(); boolean populatePlanes = getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM; MetadataTools.populatePixels(store, this, populatePlanes); String plateAcqID = MetadataTools.createLSID("PlateAcquisition", 0, 0); store.setPlateAcquisitionID(plateAcqID, 0, 0); if (fieldRows * fieldCols > 0) { store.setPlateAcquisitionMaximumFieldCount(new PositiveInteger(fieldRows * fieldCols), 0, 0); } else { LOGGER.warn("Expected positive value for MaximumFieldCount; got {}", fieldRows * fieldCols); } for (int row = 0; row < wellRows; row++) { for (int col = 0; col < wellCols; col++) { int index = row * wellCols + col; store.setWellID(MetadataTools.createLSID("Well", 0, index), 0, index); store.setWellRow(new NonNegativeInteger(row), 0, index); store.setWellColumn(new NonNegativeInteger(col), 0, index); } } for (int i = 0; i < getSeriesCount(); i++) { int well = i / (fieldRows * fieldCols); int field = i % (fieldRows * fieldCols); MetadataTools.setDefaultCreationDate(store, tiffs[well][0], i); String name = wellLabels.get(well); String row = name.substring(0, 1); Integer col = Integer.parseInt(name.substring(1)); int index = (row.charAt(0) - 'A') * wellCols + col - 1; String wellSampleID = MetadataTools.createLSID("WellSample", 0, index, field); store.setWellSampleID(wellSampleID, 0, index, field); store.setWellSampleIndex(new NonNegativeInteger(i), 0, index, field); String imageID = MetadataTools.createLSID("Image", i); store.setWellSampleImageRef(imageID, 0, index, field); store.setImageID(imageID, i); store.setImageName(name + " Field #" + (field + 1), i); store.setPlateAcquisitionWellSampleRef(wellSampleID, 0, 0, i); } MetadataLevel level = getMetadataOptions().getMetadataLevel(); if (level != MetadataLevel.MINIMUM) { String instrumentID = MetadataTools.createLSID("Instrument", 0); store.setInstrumentID(instrumentID, 0); String objectiveID = MetadataTools.createLSID("Objective", 0, 0); store.setObjectiveID(objectiveID, 0, 0); if (objective != null) { String[] tokens = objective.split(" "); String mag = tokens[0].replaceAll("[xX]", ""); String na = null; int naIndex = 0; for (int i = 0; i < tokens.length; i++) { if (tokens[i].equals("NA")) { naIndex = i + 1; na = tokens[naIndex]; break; } } Integer magnification = new Integer(mag); if (magnification > 0) { store.setObjectiveNominalMagnification(new PositiveInteger(magnification), 0, 0); } else { LOGGER.warn("Expected positive value for NominalMagnification; got {}", magnification); } if (na != null) { na = na.substring(0, 1) + "." + na.substring(1); store.setObjectiveLensNA(new Double(na), 0, 0); } if (naIndex + 1 < tokens.length) { store.setObjectiveManufacturer(tokens[naIndex + 1], 0, 0); } } // populate LogicalChannel data for (int i = 0; i < getSeriesCount(); i++) { store.setImageInstrumentRef(instrumentID, i); store.setObjectiveSettingsID(objectiveID, i); for (int c = 0; c < getSizeC(); c++) { store.setChannelName(channelNames.get(c), i, c); if (emWave[c] > 0) { store.setChannelEmissionWavelength(new PositiveInteger(emWave[c]), i, c); } else { LOGGER.warn("Expected positive value for EmissionWavelength; got {}", emWave[c]); } if (exWave[c] > 0) { store.setChannelExcitationWavelength(new PositiveInteger(exWave[c]), i, c); } else { LOGGER.warn("Expected positive value for ExcitationWavelength; got {}", exWave[c]); } String detectorID = MetadataTools.createLSID("Detector", 0, c); store.setDetectorID(detectorID, 0, c); store.setDetectorSettingsID(detectorID, i, c); store.setDetectorSettingsGain(gain[c], i, c); store.setDetectorSettingsOffset(offset[c], i, c); store.setDetectorSettingsBinning(getBinning(binning), i, c); } long firstPlane = 0; for (int p = 0; p < getImageCount(); p++) { int[] zct = getZCTCoords(p); store.setPlaneExposureTime(exposure[zct[1]], i, p); String file = getFilename(i, p); if (file != null) { long plane = getTimestamp(file); if (p == 0) { firstPlane = plane; } double timestamp = (plane - firstPlane) / 1000.0; store.setPlaneDeltaT(timestamp, i, p); } } } store.setPlateID(MetadataTools.createLSID("Plate", 0), 0); store.setPlateRowNamingConvention(getNamingConvention("Letter"), 0); store.setPlateColumnNamingConvention(getNamingConvention("Number"), 0); store.setPlateName(plateName, 0); store.setPlateDescription(plateDescription, 0); if (level != MetadataLevel.NO_OVERLAYS) { parseROIs(store); } } }
/* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { if (noOME) { throw new MissingLibraryException(OMEXMLServiceImpl.NO_OME_XML_MSG); } super.initFile(id); in = new RandomAccessInputStream(id); binData = new Vector<BinData>(); binDataOffsets = new Vector<Long>(); compression = new Vector<String>(); DefaultHandler handler = new OMEXMLHandler(); try { RandomAccessInputStream s = new RandomAccessInputStream(id); XMLTools.parseXML(s, handler); s.close(); } catch (IOException e) { throw new FormatException("Malformed OME-XML", e); } int lineNumber = 1; for (BinData bin : binData) { int line = bin.getRow(); int col = bin.getColumn(); while (lineNumber < line) { in.readLine(); lineNumber++; } binDataOffsets.add(in.getFilePointer() + col - 1); } if (binDataOffsets.size() == 0) { throw new FormatException("Pixel data not found"); } LOGGER.info("Populating metadata"); OMEXMLMetadata omexmlMeta; OMEXMLService service; try { ServiceFactory factory = new ServiceFactory(); service = factory.getInstance(OMEXMLService.class); omexmlMeta = service.createOMEXMLMetadata(omexml); } catch (DependencyException de) { throw new MissingLibraryException(OMEXMLServiceImpl.NO_OME_XML_MSG, de); } catch (ServiceException se) { throw new FormatException(se); } hasSPW = omexmlMeta.getPlateCount() > 0; addGlobalMeta("Is SPW file", hasSPW); // TODO // Hashtable originalMetadata = omexmlMeta.getOriginalMetadata(); // if (originalMetadata != null) metadata = originalMetadata; int numDatasets = omexmlMeta.getImageCount(); core = new CoreMetadata[numDatasets]; int oldSeries = getSeries(); for (int i = 0; i < numDatasets; i++) { setSeries(i); core[i] = new CoreMetadata(); Integer w = omexmlMeta.getPixelsSizeX(i).getValue(); Integer h = omexmlMeta.getPixelsSizeY(i).getValue(); Integer t = omexmlMeta.getPixelsSizeT(i).getValue(); Integer z = omexmlMeta.getPixelsSizeZ(i).getValue(); Integer c = omexmlMeta.getPixelsSizeC(i).getValue(); if (w == null || h == null || t == null || z == null | c == null) { throw new FormatException("Image dimensions not found"); } Boolean endian = omexmlMeta.getPixelsBinDataBigEndian(i, 0); String pixType = omexmlMeta.getPixelsType(i).toString(); core[i].dimensionOrder = omexmlMeta.getPixelsDimensionOrder(i).toString(); core[i].sizeX = w.intValue(); core[i].sizeY = h.intValue(); core[i].sizeT = t.intValue(); core[i].sizeZ = z.intValue(); core[i].sizeC = c.intValue(); core[i].imageCount = getSizeZ() * getSizeC() * getSizeT(); core[i].littleEndian = endian == null ? false : !endian.booleanValue(); core[i].rgb = false; core[i].interleaved = false; core[i].indexed = false; core[i].falseColor = true; core[i].pixelType = FormatTools.pixelTypeFromString(pixType); core[i].orderCertain = true; } setSeries(oldSeries); // populate assigned metadata store with the // contents of the internal OME-XML metadata object MetadataStore store = getMetadataStore(); MetadataTools.populatePixels(store, this); service.convertMetadata(omexmlMeta, store); }
/** * Populates the metadata store using the data parsed in {@link #initStandardMetadata()} along * with some further parsing done in the method itself. * * <p>All calls to the active <code>MetadataStore</code> should be made in this method and * <b>only</b> in this method. This is especially important for sub-classes that override the * getters for pixel set array size, etc. */ protected void initMetadataStore() throws FormatException { LOGGER.info("Populating OME metadata"); // the metadata store we're working with MetadataStore store = makeFilterMetadata(); IFD firstIFD = ifds.get(0); IFD exif = null; if (ifds.get(0).containsKey(IFD.EXIF)) { try { IFDList exifIFDs = tiffParser.getExifIFDs(); if (exifIFDs.size() > 0) { exif = exifIFDs.get(0); } tiffParser.fillInIFD(exif); } catch (IOException e) { LOGGER.debug("Could not read EXIF IFDs", e); } } MetadataTools.populatePixels(store, this, exif != null); // format the creation date to ISO 8601 String creationDate = getImageCreationDate(); String date = DateTools.formatDate(creationDate, DATE_FORMATS); if (creationDate != null && date == null) { LOGGER.warn("unknown creation date format: {}", creationDate); } creationDate = date; // populate Image if (creationDate != null) { store.setImageAcquisitionDate(new Timestamp(creationDate), 0); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { // populate Experimenter String artist = firstIFD.getIFDTextValue(IFD.ARTIST); if (artist != null) { String firstName = null, lastName = null; int ndx = artist.indexOf(" "); if (ndx < 0) lastName = artist; else { firstName = artist.substring(0, ndx); lastName = artist.substring(ndx + 1); } String email = firstIFD.getIFDStringValue(IFD.HOST_COMPUTER); store.setExperimenterFirstName(firstName, 0); store.setExperimenterLastName(lastName, 0); store.setExperimenterEmail(email, 0); store.setExperimenterID(MetadataTools.createLSID("Experimenter", 0), 0); } store.setImageDescription(firstIFD.getComment(), 0); // set the X and Y pixel dimensions double pixX = firstIFD.getXResolution(); double pixY = firstIFD.getYResolution(); PositiveFloat sizeX = FormatTools.getPhysicalSizeX(pixX); PositiveFloat sizeY = FormatTools.getPhysicalSizeY(pixY); if (sizeX != null) { store.setPixelsPhysicalSizeX(sizeX, 0); } if (sizeY != null) { store.setPixelsPhysicalSizeY(sizeY, 0); } store.setPixelsPhysicalSizeZ(null, 0); if (exif != null) { if (exif.containsKey(IFD.EXPOSURE_TIME)) { Object exp = exif.get(IFD.EXPOSURE_TIME); if (exp instanceof TiffRational) { Double exposure = ((TiffRational) exp).doubleValue(); for (int i = 0; i < getImageCount(); i++) { store.setPlaneExposureTime(exposure, 0, i); } } } } } }
/* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); Vector<String> uniqueChannels = new Vector<String>(); Vector<Double> uniqueZs = new Vector<Double>(); Vector<Double> stageX = new Vector<Double>(); Vector<Double> stageY = new Vector<Double>(); String filename = id.substring(id.lastIndexOf(File.separator) + 1); filename = filename.substring(0, filename.indexOf(".")); boolean integerFilename = true; try { Integer.parseInt(filename); } catch (NumberFormatException e) { integerFilename = false; } if (integerFilename && ifds.size() == 1 && ifds.get(0).getIFDIntValue(IFD.NEW_SUBFILE_TYPE) == 2) { // look for other files in the dataset findTIFFs(); String stageLabel = null; for (String tiff : files) { MetamorphHandler handler = new MetamorphHandler(); parseFile(tiff, handler); String label = handler.getStageLabel(); if (stageLabel == null) { stageLabel = label; } else if (!label.equals(stageLabel)) { break; } if (!uniqueChannels.contains(handler.getChannelName())) { uniqueChannels.add(handler.getChannelName()); } Vector<Double> zPositions = handler.getZPositions(); Double pos = Math.rint(zPositions.get(0)); if (!uniqueZs.contains(pos)) { uniqueZs.add(pos); } } MetamorphHandler handler = new MetamorphHandler(); parseFile(files[files.length - 1], handler); String lastStageLabel = handler.getStageLabel(); int lastField = getField(lastStageLabel); int lastWellRow = getWellRow(lastStageLabel); int lastWellColumn = getWellColumn(lastStageLabel); int field = getField(stageLabel); int fieldRow = getWellRow(stageLabel); int fieldColumn = getWellColumn(stageLabel); wellCount = lastField - field + 1; fieldRowCount = lastWellRow - fieldRow + 1; fieldColumnCount = lastWellColumn - fieldColumn + 1; core[0].sizeC = uniqueChannels.size(); core[0].sizeZ = uniqueZs.size(); } else { files = new String[] {id}; wellCount = 1; fieldRowCount = 1; fieldColumnCount = 1; core[0].sizeC = 0; } // parse XML comment MetamorphHandler handler = new MetamorphHandler(getGlobalMetadata()); Vector<Double> xPositions = new Vector<Double>(); Vector<Double> yPositions = new Vector<Double>(); for (IFD ifd : ifds) { String xml = XMLTools.sanitizeXML(ifd.getComment()); XMLTools.parseXML(xml, handler); double x = handler.getStagePositionX(); double y = handler.getStagePositionY(); if (xPositions.size() == 0) { xPositions.add(x); yPositions.add(y); } else { double previousX = xPositions.get(xPositions.size() - 1); double previousY = yPositions.get(yPositions.size() - 1); if (Math.abs(previousX - x) > 0.21 || Math.abs(previousY - y) > 0.21) { xPositions.add(x); yPositions.add(y); } } } if (xPositions.size() > 1) { fieldRowCount = xPositions.size(); } Vector<Integer> wavelengths = handler.getWavelengths(); Vector<Double> zPositions = handler.getZPositions(); // calculate axis sizes Vector<Integer> uniqueC = new Vector<Integer>(); for (Integer c : wavelengths) { if (!uniqueC.contains(c)) { uniqueC.add(c); } } int effectiveC = uniqueC.size(); if (effectiveC == 0) effectiveC = 1; if (getSizeC() == 0) core[0].sizeC = 1; int samples = ifds.get(0).getSamplesPerPixel(); core[0].sizeC *= effectiveC * samples; Vector<Double> uniqueZ = new Vector<Double>(); for (Double z : zPositions) { if (!uniqueZ.contains(z)) uniqueZ.add(z); } if (getSizeZ() == 0) core[0].sizeZ = 1; core[0].sizeZ *= uniqueZ.size(); int totalPlanes = files.length * ifds.size(); effectiveC = getSizeC() / samples; core[0].sizeT = totalPlanes / (wellCount * fieldRowCount * fieldColumnCount * getSizeZ() * effectiveC); if (getSizeT() == 0) core[0].sizeT = 1; int seriesCount = wellCount * fieldRowCount * fieldColumnCount; if (seriesCount > 1 && getSizeZ() > totalPlanes / seriesCount) { core[0].sizeZ = 1; core[0].sizeT = totalPlanes / (seriesCount * getSizeT() * effectiveC); } core[0].imageCount = getSizeZ() * getSizeT() * effectiveC; if (seriesCount > 1) { CoreMetadata oldCore = core[0]; core = new CoreMetadata[seriesCount]; for (int i = 0; i < seriesCount; i++) { core[i] = oldCore; } } for (int s = 0; s < wellCount * fieldRowCount * fieldColumnCount; s++) { if (files.length > 1) { int[] lengths = new int[] { getSizeZ(), getEffectiveSizeC(), fieldColumnCount, fieldRowCount, wellCount, getSizeT() }; Well well = getWell(s); int[] position = new int[] {0, 0, well.fieldCol, well.fieldRow, well.well, 0}; int fileIndex = FormatTools.positionToRaster(lengths, position); parseFile(files[fileIndex], handler); stageX.add(handler.getStagePositionX()); stageY.add(handler.getStagePositionY()); } else { stageX.add(xPositions.get(s)); stageY.add(yPositions.get(s)); } } MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); store.setPlateID(MetadataTools.createLSID("Plate", 0), 0); store.setPlateRowNamingConvention(NamingConvention.LETTER, 0); store.setPlateColumnNamingConvention(NamingConvention.NUMBER, 0); for (int well = 0; well < wellCount; well++) { store.setWellID(MetadataTools.createLSID("Well", 0, well), 0, well); store.setWellRow(new NonNegativeInteger(0), 0, well); store.setWellColumn(new NonNegativeInteger(well), 0, well); for (int row = 0; row < fieldRowCount; row++) { for (int col = 0; col < fieldColumnCount; col++) { int field = row * fieldColumnCount + col; String wellSampleID = MetadataTools.createLSID("WellSample", 0, well, field); store.setWellSampleID(wellSampleID, 0, well, field); int seriesIndex = getSeriesIndex(row, col, well); String imageID = MetadataTools.createLSID("Image", seriesIndex); store.setImageID(imageID, seriesIndex); store.setWellSampleImageRef(imageID, 0, well, field); store.setWellSampleIndex(new NonNegativeInteger(seriesIndex), 0, well, field); } } } for (int s = 0; s < seriesCount; s++) { setSeries(s); Well well = getWell(s); String name = handler.getImageName(); if (seriesCount > 1) { name = "Field " + (char) (well.fieldRow + 'A') + (well.fieldCol + 1) + ", Well " + (well.well + 1) + ": " + name; } store.setImageName(name, s); String date = DateTools.formatDate(handler.getDate(), DateTools.ISO8601_FORMAT); store.setImageAcquiredDate(date, s); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { Vector<String> timestamps = handler.getTimestamps(); Vector<Double> exposures = handler.getExposures(); for (int i = 0; i < timestamps.size(); i++) { long timestamp = DateTools.getTime(timestamps.get(i), DATE_FORMAT); addSeriesMeta("timestamp " + i, timestamp); } for (int i = 0; i < exposures.size(); i++) { addSeriesMeta("exposure time " + i + " (ms)", exposures.get(i).floatValue() * 1000); } long startDate = 0; if (timestamps.size() > 0) { startDate = DateTools.getTime(timestamps.get(0), DATE_FORMAT); } store.setImageDescription("", s); int image = 0; for (int c = 0; c < getEffectiveSizeC(); c++) { for (int t = 0; t < getSizeT(); t++) { store.setPlaneTheZ(new NonNegativeInteger(0), s, image); store.setPlaneTheC(new NonNegativeInteger(c), s, image); store.setPlaneTheT(new NonNegativeInteger(t), s, image); if (t < timestamps.size()) { String stamp = timestamps.get(t); long ms = DateTools.getTime(stamp, DATE_FORMAT); store.setPlaneDeltaT((ms - startDate) / 1000.0, s, image); } if (image < exposures.size()) { store.setPlaneExposureTime(exposures.get(image), s, image); } if (s < stageX.size()) { store.setPlanePositionX(stageX.get(s), s, image); } if (s < stageY.size()) { store.setPlanePositionY(stageY.get(s), s, image); } image++; } } store.setImagingEnvironmentTemperature(handler.getTemperature(), s); store.setPixelsPhysicalSizeX(new PositiveFloat(handler.getPixelSizeX()), s); store.setPixelsPhysicalSizeY(new PositiveFloat(handler.getPixelSizeY()), s); for (int c = 0; c < getEffectiveSizeC(); c++) { if (uniqueChannels.size() > c) { store.setChannelName(uniqueChannels.get(c), s, c); } else store.setChannelName(handler.getChannelName(), s, c); } } } }
/* @see BaseTiffReader#initMetadataStore() */ @Override protected void initMetadataStore() throws FormatException { super.initMetadataStore(); MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); if (date != null) { date = DateTools.formatDate(date, DATE_FORMAT); if (date != null) { store.setImageAcquisitionDate(new Timestamp(date), 0); } } if (imageName != null) { store.setImageName(imageName, 0); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { if (imageDescription != null) { store.setImageDescription(imageDescription, 0); } if (userName != null) { store.setExperimenterID(MetadataTools.createLSID("Experimenter", 0), 0); store.setExperimenterLastName(userName, 0); } if (microscopeModel != null) { String instrument = MetadataTools.createLSID("Instrument", 0); store.setInstrumentID(instrument, 0); store.setImageInstrumentRef(instrument, 0); store.setMicroscopeModel(microscopeModel, 0); } if (detectors != null && detectors.size() > 0) { String instrument = MetadataTools.createLSID("Instrument", 0); store.setInstrumentID(instrument, 0); store.setImageInstrumentRef(instrument, 0); for (int i = 0; i < detectors.size(); i++) { String detectorID = MetadataTools.createLSID("Detector", 0, i); store.setDetectorID(detectorID, 0, i); store.setDetectorModel(detectors.get(i), 0, i); store.setDetectorType(getDetectorType("Other"), 0, i); } } if (magnification != null) { store.setObjectiveID(MetadataTools.createLSID("Objective", 0, 0), 0, 0); store.setObjectiveNominalMagnification(magnification, 0, 0); store.setObjectiveCorrection(getCorrection("Other"), 0, 0); store.setObjectiveImmersion(getImmersion("Other"), 0, 0); } store.setStageLabelX(stageX, 0); store.setStageLabelY(stageY, 0); store.setStageLabelZ(stageZ, 0); store.setStageLabelName("", 0); Length physicalSizeX = FormatTools.getPhysicalSizeX(sizeX); Length physicalSizeY = FormatTools.getPhysicalSizeY(sizeY); if (physicalSizeX != null) { store.setPixelsPhysicalSizeX(physicalSizeX, 0); } if (physicalSizeY != null) { store.setPixelsPhysicalSizeY(physicalSizeY, 0); } if (timeIncrement != null) { store.setPixelsTimeIncrement(new Time(timeIncrement, UNITS.S), 0); } } }