Search in sources :

Example 76 with Length

use of ome.units.quantity.Length in project bioformats by openmicroscopy.

the class OMEXMLServiceImpl method convertMetadata.

/**
 * @see OMEXMLService#convertMetadata(java.lang.String, loci.formats.meta.MetadataStore)
 */
@Override
public void convertMetadata(String xml, MetadataStore dest) throws ServiceException {
    OMEXMLMetadataRoot ome = createRoot(transformToLatestVersion(xml));
    String rootVersion = getOMEXMLVersion(ome);
    String storeVersion = getOMEXMLVersion(dest);
    if (rootVersion.equals(storeVersion)) {
        // correct schema version; populate OME-XML string directly
        if (!(dest instanceof OMEXMLMetadata)) {
            throw new IllegalArgumentException("Expecting OMEXMLMetadata instance.");
        }
        dest.setRoot(ome);
    } else {
        // metadata store is incompatible; create an OME-XML
        // metadata object and copy it into the destination
        IMetadata src = createOMEXMLMetadata(xml);
        convertMetadata(src, dest);
        // make sure that physical sizes are corrected
        for (int image = 0; image < src.getImageCount(); image++) {
            Length physicalSizeX = src.getPixelsPhysicalSizeX(image);
            if (physicalSizeX != null && physicalSizeX.value() != null) {
                physicalSizeX = FormatTools.getPhysicalSize(physicalSizeX.value().doubleValue(), physicalSizeX.unit().getSymbol());
                dest.setPixelsPhysicalSizeX(physicalSizeX, image);
            }
            Length physicalSizeY = src.getPixelsPhysicalSizeY(image);
            if (physicalSizeY != null && physicalSizeY.value() != null) {
                physicalSizeY = FormatTools.getPhysicalSize(physicalSizeY.value().doubleValue(), physicalSizeY.unit().getSymbol());
                dest.setPixelsPhysicalSizeY(physicalSizeY, image);
            }
            Length physicalSizeZ = src.getPixelsPhysicalSizeZ(image);
            if (physicalSizeZ != null && physicalSizeZ.value() != null) {
                physicalSizeZ = FormatTools.getPhysicalSize(physicalSizeZ.value().doubleValue(), physicalSizeZ.unit().getSymbol());
                dest.setPixelsPhysicalSizeZ(physicalSizeZ, image);
            }
        }
    }
}
Also used : IMetadata(loci.formats.meta.IMetadata) Length(ome.units.quantity.Length) OMEXMLMetadata(loci.formats.ome.OMEXMLMetadata) OMEXMLMetadataRoot(ome.xml.meta.OMEXMLMetadataRoot)

Example 77 with Length

use of ome.units.quantity.Length in project bioformats by openmicroscopy.

the class BaseTiffReader method initMetadataStore.

/**
 * Populates the metadata store using the data parsed in
 * {@link #initStandardMetadata()} along with some further parsing done in
 * the method itself.
 *
 * 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;
    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();
        String unit = getResolutionUnitFromComment(firstIFD);
        Length sizeX = FormatTools.getPhysicalSizeX(pixX, unit);
        Length sizeY = FormatTools.getPhysicalSizeY(pixY, unit);
        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) {
                    Time exposure = new Time(((TiffRational) exp).doubleValue(), UNITS.SECOND);
                    for (int i = 0; i < getImageCount(); i++) {
                        store.setPlaneExposureTime(exposure, 0, i);
                    }
                }
            }
        }
    }
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) IFD(loci.formats.tiff.IFD) IFDList(loci.formats.tiff.IFDList) TiffRational(loci.formats.tiff.TiffRational) Time(ome.units.quantity.Time) IOException(java.io.IOException) Timestamp(ome.xml.model.primitives.Timestamp)

Example 78 with Length

use of ome.units.quantity.Length in project bioformats by openmicroscopy.

the class CellVoyagerReader method readInfo.

private void readInfo(final Document msDocument, final Document omeDocument) throws FormatException {
    /*
     * Magnification.
     *
     * We need it early, because the file format reports only un-magnified
     * sizes. So if we are to put proper metadata, we need to make the
     * conversion to size measured at the sample level ourselves. I feel
     * like this is fragile and most likely to change in a future version of
     * the file format.
     */
    final Element msRoot = msDocument.getDocumentElement();
    final double objectiveMagnification = Double.parseDouble(getChildText(msRoot, new String[] { "ObjectiveLens", "Magnification" }));
    // final double zoomLensMagnification = Double.parseDouble(
    // getChildText( msRoot, new String[] { "ZoomLens", "Magnification",
    // "Value" } ) );
    // *
    final double magnification = objectiveMagnification;
    // zoomLensMagnification;
    /*
     * Read the ome.xml file. Since it is malformed, we need to parse all
     * nodes, and add an "ID" attribute to those who do not have it.
     */
    final NodeList nodeList = omeDocument.getElementsByTagName("*");
    for (int i = 0; i < nodeList.getLength(); i++) {
        final Node node = nodeList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            final NamedNodeMap atts = node.getAttributes();
            final Node namedItem = atts.getNamedItem("ID");
            if (namedItem == null) {
                final String name = node.getNodeName();
                final String id = name + ":" + i;
                if (!node.getParentNode().getNodeName().equals("LightSource")) {
                    ((Element) node).setAttribute("ID", id);
                }
            }
        }
    }
    /*
     * For single-slice image, the PhysicalSizeZ can be 0, which will make
     * the metadata read fail. Correct that.
     */
    final Element pszEl = getChild(omeDocument.getDocumentElement(), new String[] { "Image", "Pixels" });
    final double physicalSizeZ = Double.parseDouble(pszEl.getAttribute("PhysicalSizeZ"));
    if (physicalSizeZ <= 0) {
        // default to 1 whatever
        pszEl.setAttribute("PhysicalSizeZ", "" + 1);
    }
    /*
     * Now that the XML document is properly formed, we can build a metadata
     * object from it.
     */
    OMEXMLService service = null;
    String xml = null;
    try {
        xml = XMLTools.getXML(omeDocument);
    } catch (final TransformerConfigurationException e2) {
        LOGGER.debug("", e2);
    } catch (final TransformerException e2) {
        LOGGER.debug("", e2);
    }
    try {
        service = new ServiceFactory().getInstance(OMEXMLService.class);
    } catch (final DependencyException e1) {
        LOGGER.debug("", e1);
    }
    OMEXMLMetadata omeMD = null;
    try {
        omeMD = service.createOMEXMLMetadata(xml);
    } catch (final ServiceException e) {
        LOGGER.debug("", e);
    } catch (final NullPointerException npe) {
        LOGGER.debug("", npe);
        throw npe;
    }
    // Correct pixel size for magnification
    omeMD.setPixelsPhysicalSizeX(FormatTools.createLength(omeMD.getPixelsPhysicalSizeX(0).value().doubleValue() / magnification, omeMD.getPixelsPhysicalSizeX(0).unit()), 0);
    omeMD.setPixelsPhysicalSizeY(FormatTools.createLength(omeMD.getPixelsPhysicalSizeY(0).value().doubleValue() / magnification, omeMD.getPixelsPhysicalSizeY(0).unit()), 0);
    // Time interval
    if (Double.valueOf(readFrameInterval(msDocument)) != null) {
        omeMD.setPixelsTimeIncrement(new Time(Double.valueOf(readFrameInterval(msDocument)), UNITS.SECOND), 0);
    }
    /*
     * Channels
     */
    final Element channelsEl = getChild(msRoot, "Channels");
    final List<Element> channelEls = getChildren(channelsEl, "Channel");
    channelInfos = new ArrayList<ChannelInfo>();
    for (final Element channelEl : channelEls) {
        final boolean isEnabled = Boolean.parseBoolean(getChildText(channelEl, "IsEnabled"));
        if (!isEnabled) {
            continue;
        }
        final ChannelInfo ci = readChannel(channelEl);
        channelInfos.add(ci);
    }
    /*
     * Fix missing IDs.
     *
     * Some IDs are missing in the malformed OME.XML file. We must put them
     * back manually. Some are fixed here
     */
    omeMD.setProjectID(MetadataTools.createLSID("Project", 0), 0);
    omeMD.setScreenID(MetadataTools.createLSID("Screen", 0), 0);
    omeMD.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
    omeMD.setInstrumentID(MetadataTools.createLSID("Instrument", 0), 0);
    // Read pixel sizes from OME metadata.
    final double pixelWidth = omeMD.getPixelsPhysicalSizeX(0).value().doubleValue();
    final double pixelHeight = omeMD.getPixelsPhysicalSizeY(0).value().doubleValue();
    /*
     * Read tile size from channel info. This is weird, but it's like that.
     * Since we build a multi-C image, we have to assume that all channels
     * have the same dimension, even if the file format allows for changing
     * the size, binning, etc. from channel to channel. Failure to load
     * datasets that have this exoticity is to be sought here.
     */
    final int tileWidth = channelInfos.get(0).tileWidth;
    final int tileHeight = channelInfos.get(0).tileHeight;
    /*
     * Handle multiple wells.
     *
     * The same kind of remark apply: We assume that a channel setting can
     * be applied to ALL wells. So this file reader will fail for dataset
     * that have one well that has a different dimension that of others.
     */
    /*
     * First remark: there can be two modes to store Areas in the xml file:
     * Either we define different areas for each well, and in that case, the
     * areas are found as a child element of the well element. Either the
     * definition of areas is common to all wells, and in that case they
     * area defined in a separate element.
     */
    final boolean sameAreaPerWell = Boolean.parseBoolean(getChildText(msRoot, "UsesSameAreaParWell"));
    List<AreaInfo> areas = null;
    if (sameAreaPerWell) {
        final Element areasEl = getChild(msRoot, new String[] { "SameAreaUsingWell", "Areas" });
        final List<Element> areaEls = getChildren(areasEl, "Area");
        int areaIndex = 0;
        areas = new ArrayList<AreaInfo>(areaEls.size());
        int fieldIndex = 1;
        for (final Element areaEl : areaEls) {
            final AreaInfo area = readArea(areaEl, fieldIndex, pixelWidth, pixelHeight, tileWidth, tileHeight);
            area.index = areaIndex++;
            areas.add(area);
            // Continue incrementing field index across areas.
            fieldIndex = area.fields.get(area.fields.size() - 1).index + 1;
        }
    }
    final Element wellsEl = getChild(msRoot, "Wells");
    final List<Element> wellEls = getChildren(wellsEl, "Well");
    wells = new ArrayList<WellInfo>();
    for (final Element wellEl : wellEls) {
        final boolean isWellEnabled = Boolean.parseBoolean(getChild(wellEl, "IsEnabled").getTextContent());
        if (isWellEnabled) {
            final WellInfo wi = readWellInfo(wellEl, pixelWidth, pixelHeight, tileWidth, tileHeight);
            if (sameAreaPerWell) {
                wi.areas = areas;
            }
            wells.add(wi);
        }
    }
    /*
     * Z range.
     *
     * In this file format, the Z range appears to be general: it applies to
     * all fields of all wells.
     */
    final int nZSlices = Integer.parseInt(getChildText(msRoot, new String[] { "ZStackConditions", "NumberOfSlices" }));
    /*
     * Time points. They are general as well. Which just makes sense.
     */
    timePoints = readTimePoints(msDocument);
    /*
     * Populate CORE metadata for each area.
     *
     * This reader takes to convention that state that 1 area = 1 series. So
     * if you have 10 wells with 2 areas in each well, and each area is made
     * of 20 fields, you will get 20 series, and each series will be
     * stitched from 20 fields.
     */
    OMEXMLMetadataRoot root = (OMEXMLMetadataRoot) omeMD.getRoot();
    Image firstImage = root.getImage(0);
    core.clear();
    for (final WellInfo well : wells) {
        for (final AreaInfo area : well.areas) {
            final CoreMetadata ms = new CoreMetadata();
            core.add(ms);
            if (core.size() > 1) {
                root.addImage(firstImage);
            }
            ms.sizeX = area.width;
            ms.sizeY = area.height;
            ms.sizeZ = nZSlices;
            ms.sizeC = channelInfos.size();
            ms.sizeT = timePoints.size();
            ms.dimensionOrder = "XYCZT";
            ms.rgb = false;
            ms.imageCount = nZSlices * channelInfos.size() * timePoints.size();
            // Bit depth.
            switch(omeMD.getPixelsType(0)) {
                case UINT8:
                    ms.pixelType = FormatTools.UINT8;
                    ms.bitsPerPixel = 8;
                    break;
                case UINT16:
                    ms.pixelType = FormatTools.UINT16;
                    ms.bitsPerPixel = 16;
                    break;
                case UINT32:
                    ms.pixelType = FormatTools.UINT32;
                    ms.bitsPerPixel = 32;
                    break;
                default:
                    throw new FormatException("Cannot read image with pixel type = " + omeMD.getPixelsType(0));
            }
            // Determined manually on sample data. Check here is the image
            // you get is weird.
            ms.littleEndian = true;
        }
    }
    omeMD.setRoot(root);
    /*
     * Populate the MetadataStore.
     */
    final MetadataStore store = makeFilterMetadata();
    MetadataConverter.convertMetadata(omeMD, store);
    MetadataTools.populatePixels(store, this, true);
    /*
     * Pinhole disk
     */
    final double pinholeSize = Double.parseDouble(getChildText(msRoot, new String[] { "PinholeDisk", "PinholeSize_um" }));
    /*
     * MicroPlate specific stuff
     */
    final Element containerEl = getChild(msRoot, new String[] { "Attachment", "HolderInfoList", "HolderInfo", "MountedSampleContainer" });
    final String type = containerEl.getAttribute("xsi:type");
    boolean plateMetadata = false;
    if (type.equals("WellPlate")) {
        plateMetadata = true;
        final int nrows = Integer.parseInt(getChildText(containerEl, "RowCount"));
        final int ncols = Integer.parseInt(getChildText(containerEl, "ColumnCount"));
        store.setPlateRows(new PositiveInteger(nrows), 0);
        store.setPlateColumns(new PositiveInteger(ncols), 0);
        final String plateAcqID = MetadataTools.createLSID("PlateAcquisition", 0, 0);
        store.setPlateAcquisitionID(plateAcqID, 0, 0);
        final Element dimInfoEl = getChild(msRoot, "DimensionsInfo");
        final int maxNFields = Integer.parseInt(getChild(dimInfoEl, "F").getAttribute("Max"));
        final PositiveInteger fieldCount = FormatTools.getMaxFieldCount(maxNFields);
        if (fieldCount != null) {
            store.setPlateAcquisitionMaximumFieldCount(fieldCount, 0, 0);
        }
        // Plate acquisition time
        final String beginTime = getChildText(msRoot, "BeginTime");
        final String endTime = getChildText(msRoot, "EndTime");
        store.setPlateAcquisitionStartTime(new Timestamp(beginTime), 0, 0);
        store.setPlateAcquisitionEndTime(new Timestamp(endTime), 0, 0);
        store.setPlateName(beginTime, 0);
    } else if (!type.equals("PreparedSlide")) {
        LOGGER.warn("Unexpected acquisition type: {}", type);
    }
    // Wells position on the plate
    int seriesIndex = -1;
    int wellIndex = -1;
    for (final WellInfo well : wells) {
        wellIndex++;
        final int wellNumber = well.number;
        if (plateMetadata) {
            store.setWellID(MetadataTools.createLSID("Well", 0, wellIndex), 0, wellIndex);
            store.setWellRow(new NonNegativeInteger(well.row), 0, wellIndex);
            store.setWellColumn(new NonNegativeInteger(well.col), 0, wellIndex);
        }
        int areaIndex = -1;
        for (final AreaInfo area : well.areas) {
            seriesIndex++;
            areaIndex++;
            String imageID = MetadataTools.createLSID("Image", seriesIndex);
            store.setImageID(imageID, seriesIndex);
            final String imageName = "Well " + wellNumber + " (UID=" + well.UID + ", r=" + well.row + ", c=" + well.col + ") - Area " + areaIndex;
            store.setImageName(imageName, seriesIndex);
            if (plateMetadata) {
                Length posX = new Length(Double.valueOf(well.centerX), UNITS.REFERENCEFRAME);
                Length posY = new Length(Double.valueOf(well.centerY), UNITS.REFERENCEFRAME);
                String wellSample = MetadataTools.createLSID("WellSample", 0, wellIndex, areaIndex);
                store.setWellSampleID(wellSample, 0, wellIndex, areaIndex);
                store.setWellSampleImageRef(imageID, 0, wellIndex, areaIndex);
                store.setWellSampleIndex(new NonNegativeInteger(area.index), 0, wellIndex, areaIndex);
                store.setWellSamplePositionX(posX, 0, wellIndex, areaIndex);
                store.setWellSamplePositionY(posY, 0, wellIndex, areaIndex);
                store.setPlateAcquisitionWellSampleRef(wellSample, 0, 0, seriesIndex);
            }
            store.setImageInstrumentRef(MetadataTools.createLSID("Instrument", 0), seriesIndex);
            for (int i = 0; i < channelInfos.size(); i++) {
                store.setChannelPinholeSize(new Length(pinholeSize, UNITS.MICROMETER), seriesIndex, i);
                store.setChannelName(channelInfos.get(i).name, seriesIndex, i);
                store.setChannelColor(channelInfos.get(i).color, seriesIndex, i);
            }
        }
    }
}
Also used : TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) ServiceFactory(loci.common.services.ServiceFactory) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) Time(ome.units.quantity.Time) Image(ome.xml.model.Image) Timestamp(ome.xml.model.primitives.Timestamp) OMEXMLService(loci.formats.services.OMEXMLService) TransformerException(javax.xml.transform.TransformerException) PositiveInteger(ome.xml.model.primitives.PositiveInteger) NamedNodeMap(org.w3c.dom.NamedNodeMap) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) NodeList(org.w3c.dom.NodeList) DependencyException(loci.common.services.DependencyException) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) ServiceException(loci.common.services.ServiceException) Length(ome.units.quantity.Length) OMEXMLMetadata(loci.formats.ome.OMEXMLMetadata) OMEXMLMetadataRoot(ome.xml.meta.OMEXMLMetadataRoot)

Example 79 with Length

use of ome.units.quantity.Length in project bioformats by openmicroscopy.

the class CellWorxReader method parseWellLogFile.

/**
 * Parse metadata from a well log file.
 */
private void parseWellLogFile(int wellIndex, MetadataStore store) throws IOException {
    int seriesIndex = wellIndex * fieldCount;
    int row = getWellRow(seriesIndex);
    int col = getWellColumn(seriesIndex);
    int well = row * wellFiles[0].length + col;
    String logFile = logFiles[row][col];
    if (!new Location(logFile).exists()) {
        return;
    }
    LOGGER.debug("Parsing log file for well {}{}", (char) (row + 'A'), col + 1);
    int oldSeries = getSeries();
    setSeries(seriesIndex);
    String data = DataTools.readFile(logFile);
    String[] lines = data.split("\n");
    for (String line : lines) {
        line = line.trim();
        int separator = line.indexOf(':');
        if (separator < 0)
            continue;
        String key = line.substring(0, separator).trim();
        String value = line.substring(separator + 1).trim();
        addSeriesMeta(key, value);
        if (key.equals("Date")) {
            String date = DateTools.formatDate(value, DATE_FORMAT);
            for (int field = 0; field < fieldCount; field++) {
                if (date != null) {
                    int imageIndex = seriesIndex + field;
                    timestamps.put(imageIndex, new Timestamp(date));
                    store.setImageAcquisitionDate(timestamps.get(imageIndex), imageIndex);
                }
            }
        } else if (key.equals("Scan Origin")) {
            String[] axes = value.split(",");
            Double posX = new Double(axes[0]);
            Double posY = new Double(axes[1]);
            for (int fieldRow = 0; fieldRow < fieldMap.length; fieldRow++) {
                for (int fieldCol = 0; fieldCol < fieldMap[fieldRow].length; fieldCol++) {
                    if (fieldMap[fieldRow][fieldCol] && wellFiles[row][col] != null) {
                        int field = fieldRow * fieldMap[fieldRow].length + fieldCol;
                        Length px = new Length(posX, UNITS.REFERENCEFRAME);
                        Length py = new Length(posY, UNITS.REFERENCEFRAME);
                        store.setWellSamplePositionX(px, 0, well, field);
                        store.setWellSamplePositionY(py, 0, well, field);
                        addGlobalMetaList("X position for position", axes[0]);
                        addGlobalMetaList("Y position for position", axes[1]);
                    }
                }
            }
        } else if (key.equals("Scan Area")) {
            int s = value.indexOf('x');
            if (s > 0) {
                int end = value.indexOf(" ", s + 2);
                Double xSize = new Double(value.substring(0, s).trim());
                Double ySize = new Double(value.substring(s + 1, end).trim());
                Length x = FormatTools.getPhysicalSizeX(xSize / getSizeX());
                Length y = FormatTools.getPhysicalSizeY(ySize / getSizeY());
                for (int field = 0; field < fieldCount; field++) {
                    int index = seriesIndex + field;
                    if (x != null) {
                        store.setPixelsPhysicalSizeX(x, index);
                    }
                    if (y != null) {
                        store.setPixelsPhysicalSizeY(y, index);
                    }
                }
            }
        } else if (key.startsWith("Channel")) {
            int start = key.indexOf(' ') + 1;
            int end = key.indexOf(" ", start);
            if (end < 0)
                end = key.length();
            int index = Integer.parseInt(key.substring(start, end)) - 1;
            String[] tokens = value.split(",");
            for (String token : tokens) {
                token = token.trim();
                if (token.startsWith("gain")) {
                    String instrumentID = MetadataTools.createLSID("Instrument", 0);
                    Double gain = new Double(token.replaceAll("gain ", ""));
                    String detectorID = MetadataTools.createLSID("Detector", 0, 0);
                    store.setInstrumentID(instrumentID, 0);
                    store.setDetectorID(detectorID, 0, 0);
                    for (int field = 0; field < fieldCount; field++) {
                        store.setImageInstrumentRef(instrumentID, seriesIndex + field);
                        store.setDetectorSettingsGain(gain, seriesIndex + field, index);
                        store.setDetectorSettingsID(detectorID, seriesIndex + field, index);
                    }
                } else if (token.startsWith("EX")) {
                    int slash = token.indexOf('/');
                    if (slash > 0) {
                        String ex = token.substring(0, slash).trim();
                        String em = token.substring(slash + 1).trim();
                        if (ex.indexOf(' ') > 0)
                            ex = ex.substring(ex.indexOf(' ') + 1);
                        if (em.indexOf(' ') > 0) {
                            em = em.substring(em.indexOf(' ') + 1);
                            if (em.indexOf(' ') > 0) {
                                em = em.substring(0, em.indexOf(' '));
                            }
                        }
                        Double emission = new Double(em);
                        Double excitation = new Double(ex);
                        Length exWave = FormatTools.getExcitationWavelength(excitation);
                        Length emWave = FormatTools.getEmissionWavelength(emission);
                        for (int field = 0; field < fieldCount; field++) {
                            if (exWave != null) {
                                store.setChannelExcitationWavelength(exWave, seriesIndex + field, index);
                            }
                            if (emWave != null) {
                                store.setChannelEmissionWavelength(emWave, seriesIndex + field, index);
                            }
                        }
                    }
                }
            }
        }
    }
    setSeries(oldSeries);
}
Also used : Length(ome.units.quantity.Length) Timestamp(ome.xml.model.primitives.Timestamp) Location(loci.common.Location)

Example 80 with Length

use of ome.units.quantity.Length in project bioformats by openmicroscopy.

the class CellomicsReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    // look for files with similar names
    Location baseFile = new Location(id).getAbsoluteFile();
    Location parent = baseFile.getParentFile();
    ArrayList<String> pixelFiles = new ArrayList<String>();
    String plateName = getPlateName(baseFile.getName());
    if (plateName != null && isGroupFiles()) {
        String[] list = parent.list();
        for (String f : list) {
            if (plateName.equals(getPlateName(f)) && (checkSuffix(f, "c01") || checkSuffix(f, "dib"))) {
                Location loc = new Location(parent, f);
                if ((!f.startsWith(".") || !loc.isHidden()) && getChannel(f) >= 0) {
                    pixelFiles.add(loc.getAbsolutePath());
                }
            }
        }
    } else
        pixelFiles.add(id);
    files = pixelFiles.toArray(new String[pixelFiles.size()]);
    int wellRows = 0;
    int wellColumns = 0;
    int fields = 0;
    ArrayList<Integer> uniqueRows = new ArrayList<Integer>();
    ArrayList<Integer> uniqueCols = new ArrayList<Integer>();
    ArrayList<Integer> uniqueFields = new ArrayList<Integer>();
    ArrayList<Integer> uniqueChannels = new ArrayList<Integer>();
    for (String f : files) {
        int wellRow = getWellRow(f);
        int wellCol = getWellColumn(f);
        int field = getField(f);
        int channel = getChannel(f);
        if (!uniqueRows.contains(wellRow))
            uniqueRows.add(wellRow);
        if (!uniqueCols.contains(wellCol))
            uniqueCols.add(wellCol);
        if (!uniqueFields.contains(field))
            uniqueFields.add(field);
        if (!uniqueChannels.contains(channel))
            uniqueChannels.add(channel);
    }
    fields = uniqueFields.size();
    wellRows = uniqueRows.size();
    wellColumns = uniqueCols.size();
    if (fields * wellRows * wellColumns > files.length) {
        files = new String[] { id };
    }
    Arrays.sort(files, new Comparator<String>() {

        @Override
        public int compare(String f1, String f2) {
            int wellRow1 = getWellRow(f1);
            int wellCol1 = getWellColumn(f1);
            int field1 = getField(f1);
            int channel1 = getChannel(f1);
            int wellRow2 = getWellRow(f2);
            int wellCol2 = getWellColumn(f2);
            int field2 = getField(f2);
            int channel2 = getChannel(f2);
            if (wellRow1 < wellRow2) {
                return -1;
            } else if (wellRow1 > wellRow2) {
                return 1;
            }
            if (wellCol1 < wellCol2) {
                return -1;
            } else if (wellCol1 > wellCol2) {
                return 1;
            }
            if (field1 < field2) {
                return -1;
            } else if (field1 > field2) {
                return 1;
            }
            return channel1 - channel2;
        }
    });
    core.clear();
    int seriesCount = files.length;
    if (uniqueChannels.size() > 0) {
        seriesCount /= uniqueChannels.size();
    }
    for (int i = 0; i < seriesCount; i++) {
        core.add(new CoreMetadata());
    }
    in = getDecompressedStream(id);
    LOGGER.info("Reading header data");
    in.order(true);
    in.skipBytes(4);
    int x = in.readInt();
    int y = in.readInt();
    int nPlanes = in.readShort();
    int nBits = in.readShort();
    int compression = in.readInt();
    if (x * y * nPlanes * (nBits / 8) + 52 > in.length()) {
        throw new UnsupportedCompressionException("Compressed pixel data is not yet supported.");
    }
    in.skipBytes(4);
    int pixelWidth = 0, pixelHeight = 0;
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        pixelWidth = in.readInt();
        pixelHeight = in.readInt();
        int colorUsed = in.readInt();
        int colorImportant = in.readInt();
        LOGGER.info("Populating metadata hashtable");
        addGlobalMeta("Image width", x);
        addGlobalMeta("Image height", y);
        addGlobalMeta("Number of planes", nPlanes);
        addGlobalMeta("Bits per pixel", nBits);
        addGlobalMeta("Compression", compression);
        addGlobalMeta("Pixels per meter (X)", pixelWidth);
        addGlobalMeta("Pixels per meter (Y)", pixelHeight);
        addGlobalMeta("Color used", colorUsed);
        addGlobalMeta("Color important", colorImportant);
    }
    LOGGER.info("Populating core metadata");
    for (int i = 0; i < getSeriesCount(); i++) {
        CoreMetadata ms = core.get(i);
        ms.sizeX = x;
        ms.sizeY = y;
        ms.sizeZ = nPlanes;
        ms.sizeT = 1;
        ms.sizeC = uniqueChannels.size();
        ms.imageCount = getSizeZ() * getSizeT() * getSizeC();
        ms.littleEndian = true;
        ms.dimensionOrder = "XYCZT";
        ms.pixelType = FormatTools.pixelTypeFromBytes(nBits / 8, false, false);
    }
    LOGGER.info("Populating metadata store");
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
    store.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
    store.setPlateName(plateName, 0);
    store.setPlateRowNamingConvention(NamingConvention.LETTER, 0);
    store.setPlateColumnNamingConvention(NamingConvention.NUMBER, 0);
    int realRows = wellRows;
    int realCols = wellColumns;
    if (files.length == 1) {
        realRows = 1;
        realCols = 1;
    } else if (realRows <= 8 && realCols <= 12) {
        realRows = 8;
        realCols = 12;
    } else {
        realRows = 16;
        realCols = 24;
    }
    int fieldCntr = 0;
    int wellCntr = 0;
    int wellIndexPrev = 0;
    int wellIndex = 0;
    for (int i = 0; i < getSeriesCount(); i++) {
        String file = files[i * getSizeC()];
        int fieldIndex = getField(file);
        int row = getWellRow(file);
        int col = getWellColumn(file);
        store.setImageName(String.format("Well %s%02d, Field #%02d", new String(Character.toChars(row + 'A')), col, fieldIndex), i);
        if (files.length == 1) {
            row = 0;
            col = 0;
        }
        if (i > 0 && files.length != 1) {
            String prevFile = files[(i - 1) * getSizeC()];
            int prevRow = getWellRow(prevFile);
            int prevCol = getWellColumn(prevFile);
            if (prevRow < realRows && prevCol < realCols) {
                wellIndexPrev = prevRow * realCols + prevCol;
            }
        }
        String imageID = MetadataTools.createLSID("Image", i);
        store.setImageID(imageID, i);
        if (row < realRows && col < realCols) {
            wellIndex = row * realCols + col;
            if ((wellIndexPrev != wellIndex) || i == 0) {
                if (i > 0) {
                    wellCntr++;
                    fieldCntr = 0;
                } else {
                    wellIndexPrev = wellIndex;
                }
                store.setWellID(MetadataTools.createLSID("Well", 0, wellIndex), 0, wellCntr);
                store.setWellRow(new NonNegativeInteger(row), 0, wellCntr);
                store.setWellColumn(new NonNegativeInteger(col), 0, wellCntr);
            }
            if (files.length == 1) {
                fieldIndex = 0;
            }
            if (fieldIndex == 0) {
                fieldCntr = 0;
            }
            String wellSampleID = MetadataTools.createLSID("WellSample", 0, wellIndex, fieldIndex);
            store.setWellSampleID(wellSampleID, 0, wellCntr, fieldCntr);
            store.setWellSampleIndex(new NonNegativeInteger(i), 0, wellCntr, fieldCntr);
            store.setWellSampleImageRef(imageID, 0, wellCntr, fieldCntr);
            fieldCntr++;
        }
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        // physical dimensions are stored as pixels per meter - we want them
        // in microns per pixel
        double width = pixelWidth == 0 ? 0.0 : 1000000.0 / pixelWidth;
        double height = pixelHeight == 0 ? 0.0 : 1000000.0 / pixelHeight;
        Length sizeX = FormatTools.getPhysicalSizeX(width);
        Length sizeY = FormatTools.getPhysicalSizeY(height);
        for (int i = 0; i < getSeriesCount(); i++) {
            if (sizeX != null) {
                store.setPixelsPhysicalSizeX(sizeX, 0);
            }
            if (sizeY != null) {
                store.setPixelsPhysicalSizeY(sizeY, 0);
            }
        }
    }
}
Also used : NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) ArrayList(java.util.ArrayList) UnsupportedCompressionException(loci.formats.UnsupportedCompressionException) CoreMetadata(loci.formats.CoreMetadata) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) Location(loci.common.Location)

Aggregations

Length (ome.units.quantity.Length)154 MetadataStore (loci.formats.meta.MetadataStore)82 CoreMetadata (loci.formats.CoreMetadata)74 Timestamp (ome.xml.model.primitives.Timestamp)52 RandomAccessInputStream (loci.common.RandomAccessInputStream)48 Time (ome.units.quantity.Time)46 FormatException (loci.formats.FormatException)39 Location (loci.common.Location)34 ArrayList (java.util.ArrayList)29 IMetadata (loci.formats.meta.IMetadata)13 NonNegativeInteger (ome.xml.model.primitives.NonNegativeInteger)13 ServiceFactory (loci.common.services.ServiceFactory)12 IOException (java.io.IOException)11 DependencyException (loci.common.services.DependencyException)11 PositiveInteger (ome.xml.model.primitives.PositiveInteger)11 MetadataRetrieve (loci.formats.meta.MetadataRetrieve)10 ElectricPotential (ome.units.quantity.ElectricPotential)9 Test (org.testng.annotations.Test)9 Element (org.w3c.dom.Element)9 NodeList (org.w3c.dom.NodeList)9