Search in sources :

Example 16 with Image

use of ome.xml.model.Image in project bioformats by openmicroscopy.

the class OMEXMLServiceImpl method getModuloAlong.

/**
 * Create a {@link loci.formats.Modulo} corresponding to the given ModuloAlong* tag.
 * @param omexml the OMEXMLMetadata from which to retrieve the ModuloAlong* tag
 * @param tag the tag name (e.g. "ModuloAlongC")
 * @param image the Image index within the OMEXMLMetadata
 * @return the corresponding Modulo object
 */
private Modulo getModuloAlong(OMEXMLMetadata omexml, String tag, int image) {
    OMEXMLMetadataRoot root = (OMEXMLMetadataRoot) omexml.getRoot();
    Image img = root.getImage(image);
    if (img == null) {
        return null;
    }
    for (int i = 0; i < img.sizeOfLinkedAnnotationList(); i++) {
        Annotation annotation = img.getLinkedAnnotation(i);
        if (!(annotation instanceof XMLAnnotation)) {
            continue;
        }
        String xml = ((XMLAnnotation) annotation).getValue();
        try {
            Document annotationRoot = XMLTools.parseDOM(xml);
            NodeList nodes = annotationRoot.getElementsByTagName(tag);
            if (nodes.getLength() > 0) {
                Element modulo = (Element) nodes.item(0);
                NamedNodeMap attrs = modulo.getAttributes();
                Modulo m = new Modulo(tag.substring(tag.length() - 1));
                Node start = attrs.getNamedItem("Start");
                Node end = attrs.getNamedItem("End");
                Node step = attrs.getNamedItem("Step");
                Node type = attrs.getNamedItem("Type");
                Node typeDescription = attrs.getNamedItem("TypeDescription");
                Node unit = attrs.getNamedItem("Unit");
                if (start != null) {
                    m.start = Double.parseDouble(start.getNodeValue());
                }
                if (end != null) {
                    m.end = Double.parseDouble(end.getNodeValue());
                }
                if (step != null) {
                    m.step = Double.parseDouble(step.getNodeValue());
                }
                if (type != null) {
                    m.type = type.getNodeValue();
                }
                if (typeDescription != null) {
                    m.typeDescription = typeDescription.getNodeValue();
                }
                if (unit != null) {
                    m.unit = unit.getNodeValue();
                }
                NodeList labels = modulo.getElementsByTagName("Label");
                if (labels != null && labels.getLength() > 0) {
                    m.labels = new String[labels.getLength()];
                    for (int q = 0; q < labels.getLength(); q++) {
                        m.labels[q] = labels.item(q).getTextContent();
                    }
                }
                return m;
            }
        } catch (ParserConfigurationException e) {
            LOGGER.debug("Failed to parse ModuloAlong", e);
        } catch (SAXException e) {
            LOGGER.debug("Failed to parse ModuloAlong", e);
        } catch (IOException e) {
            LOGGER.debug("Failed to parse ModuloAlong", e);
        }
    }
    return null;
}
Also used : NamedNodeMap(org.w3c.dom.NamedNodeMap) Modulo(loci.formats.Modulo) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) IOException(java.io.IOException) Image(ome.xml.model.Image) Document(org.w3c.dom.Document) Annotation(ome.xml.model.Annotation) ModuloAnnotation(loci.formats.meta.ModuloAnnotation) OriginalMetadataAnnotation(loci.formats.meta.OriginalMetadataAnnotation) XMLAnnotation(ome.xml.model.XMLAnnotation) SAXException(org.xml.sax.SAXException) OMEXMLMetadataRoot(ome.xml.meta.OMEXMLMetadataRoot) XMLAnnotation(ome.xml.model.XMLAnnotation) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 17 with Image

use of ome.xml.model.Image 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 18 with Image

use of ome.xml.model.Image in project bioformats by openmicroscopy.

the class CellWorxReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    if (!checkSuffix(id, "htd")) {
        LOGGER.info("Searching for .htd file");
        String base = new Location(id).getAbsolutePath();
        base = base.substring(0, base.lastIndexOf("_"));
        id = base + ".HTD";
        if (!new Location(id).exists()) {
            Location parent = new Location(id).getAbsoluteFile().getParentFile();
            directoryList = parent.list(true);
            for (String f : directoryList) {
                if (checkSuffix(f, "htd")) {
                    id = new Location(parent, f).getAbsolutePath();
                    LOGGER.info("Found .htd file {}", f);
                    break;
                }
            }
        }
    }
    super.initFile(id);
    try {
        ServiceFactory factory = new ServiceFactory();
        service = factory.getInstance(OMEXMLService.class);
    } catch (DependencyException exc) {
        throw new FormatException("Could not create OME-XML store.", exc);
    }
    String plateData = DataTools.readFile(id);
    String[] lines = plateData.split("\n");
    int xWells = 0, yWells = 0;
    int xFields = 0, yFields = 0;
    String[] wavelengths = null;
    int nTimepoints = 1;
    // determine dataset dimensions
    for (String line : lines) {
        int split = line.indexOf("\",");
        if (split < 1)
            continue;
        String key = line.substring(1, split).trim();
        String value = line.substring(split + 2).trim();
        if (key.equals("XWells")) {
            xWells = Integer.parseInt(value);
        } else if (key.equals("YWells")) {
            yWells = Integer.parseInt(value);
            wellFiles = new String[yWells][xWells][];
            logFiles = new String[yWells][xWells];
        } else if (key.startsWith("WellsSelection")) {
            int row = Integer.parseInt(key.substring(14)) - 1;
            String[] mapping = value.split(",");
            for (int col = 0; col < xWells; col++) {
                if (new Boolean(mapping[col].trim()).booleanValue()) {
                    wellFiles[row][col] = new String[1];
                }
            }
        } else if (key.equals("XSites")) {
            xFields = Integer.parseInt(value);
        } else if (key.equals("YSites")) {
            yFields = Integer.parseInt(value);
            fieldMap = new boolean[yFields][xFields];
        } else if (key.equals("TimePoints")) {
            nTimepoints = Integer.parseInt(value);
        } else if (key.startsWith("SiteSelection")) {
            int row = Integer.parseInt(key.substring(13)) - 1;
            String[] mapping = value.split(",");
            for (int col = 0; col < xFields; col++) {
                fieldMap[row][col] = new Boolean(mapping[col].trim()).booleanValue();
            }
        } else if (key.equals("Waves")) {
            doChannels = new Boolean(value.toLowerCase());
        } else if (key.equals("NWavelengths")) {
            wavelengths = new String[Integer.parseInt(value)];
        } else if (key.startsWith("WaveName")) {
            int index = Integer.parseInt(key.substring(8)) - 1;
            wavelengths[index] = value.replaceAll("\"", "");
        }
    }
    for (int row = 0; row < fieldMap.length; row++) {
        for (int col = 0; col < fieldMap[row].length; col++) {
            if (fieldMap[row][col])
                fieldCount++;
        }
    }
    // find pixels files
    String plateName = new Location(id).getAbsolutePath();
    plateName = plateName.substring(0, plateName.lastIndexOf(".")) + "_";
    int wellCount = 0;
    for (int row = 0; row < wellFiles.length; row++) {
        for (int col = 0; col < wellFiles[row].length; col++) {
            if (wellFiles[row][col] != null) {
                wellCount++;
                char rowLetter = (char) (row + 'A');
                String base = plateName + rowLetter + String.format("%02d", col + 1);
                wellFiles[row][col][0] = base + ".pnl";
                logFiles[row][col] = base + "_scan.log";
                if (!new Location(wellFiles[row][col][0]).exists()) {
                    // using TIFF files instead
                    wellFiles[row][col] = getTiffFiles(plateName, rowLetter, col, wavelengths.length, nTimepoints);
                }
            }
        }
    }
    plateLogFile = plateName + "scan.log";
    String serialNumber = null;
    if (new Location(plateLogFile).exists()) {
        String[] f = DataTools.readFile(plateLogFile).split("\n");
        for (String line : f) {
            if (line.trim().startsWith("Z Map File")) {
                String file = line.substring(line.indexOf(':') + 1);
                file = file.substring(file.lastIndexOf("/") + 1).trim();
                String parent = new Location(id).getAbsoluteFile().getParent();
                zMapFile = new Location(parent, file).getAbsolutePath();
            } else if (line.trim().startsWith("Scanner SN")) {
                serialNumber = line.substring(line.indexOf(':') + 1).trim();
            }
        }
    }
    int seriesCount = fieldCount * wellCount;
    int planeIndex = 0;
    int seriesIndex = 0;
    String file = getFile(seriesIndex, planeIndex);
    while (!new Location(file).exists()) {
        if (planeIndex < nTimepoints * wavelengths.length) {
            planeIndex++;
        } else if (seriesIndex < seriesCount - 1) {
            planeIndex = 0;
            seriesIndex++;
        } else {
            break;
        }
        file = getFile(seriesIndex, planeIndex);
    }
    IFormatReader pnl = getReader(file, true);
    core.clear();
    for (int i = 0; i < seriesCount; i++) {
        CoreMetadata ms = new CoreMetadata();
        core.add(ms);
        setSeries(i);
        ms.littleEndian = pnl.isLittleEndian();
        ms.sizeX = pnl.getSizeX();
        ms.sizeY = pnl.getSizeY();
        ms.pixelType = pnl.getPixelType();
        ms.sizeZ = 1;
        ms.sizeT = nTimepoints;
        ms.sizeC = wavelengths.length;
        ms.imageCount = getSizeZ() * getSizeC() * getSizeT();
        ms.dimensionOrder = "XYCZT";
        ms.rgb = false;
        ms.interleaved = pnl.isInterleaved();
    }
    OMEXMLMetadata readerMetadata = (OMEXMLMetadata) pnl.getMetadataStore();
    OMEXMLMetadataRoot root = (OMEXMLMetadataRoot) readerMetadata.getRoot();
    Instrument instrument = root.getInstrument(0);
    List<Image> images = root.copyImageList();
    OMEXMLMetadataRoot convertRoot = new OMEXMLMetadataRoot();
    convertRoot.addInstrument(instrument);
    for (int i = 0; i < core.size() / images.size(); i++) {
        for (Image img : images) {
            convertRoot.addImage(img);
        }
    }
    OMEXMLMetadata convertMetadata;
    try {
        convertMetadata = service.createOMEXMLMetadata();
    } catch (ServiceException exc) {
        throw new FormatException("Could not create OME-XML store.", exc);
    }
    convertMetadata.setRoot(convertRoot);
    pnl.close();
    MetadataStore store = makeFilterMetadata();
    MetadataConverter.convertMetadata(convertMetadata, store);
    MetadataTools.populatePixels(store, this);
    String plateID = MetadataTools.createLSID("Plate", 0);
    Location plate = new Location(id).getAbsoluteFile();
    store.setPlateID(plateID, 0);
    plateName = plate.getName();
    if (plateName.indexOf('.') > 0) {
        plateName = plateName.substring(0, plateName.lastIndexOf('.'));
    }
    store.setPlateName(plateName, 0);
    store.setPlateRows(new PositiveInteger(wellFiles.length), 0);
    store.setPlateColumns(new PositiveInteger(wellFiles[0].length), 0);
    for (int i = 0; i < core.size(); i++) {
        store.setImageID(MetadataTools.createLSID("Image", i), i);
    }
    String plateAcqID = MetadataTools.createLSID("PlateAcquisition", 0, 0);
    store.setPlateAcquisitionID(plateAcqID, 0, 0);
    PositiveInteger fieldCount = FormatTools.getMaxFieldCount(fieldMap.length * fieldMap[0].length);
    if (fieldCount != null) {
        store.setPlateAcquisitionMaximumFieldCount(fieldCount, 0, 0);
    }
    int nextImage = 0;
    for (int row = 0; row < wellFiles.length; row++) {
        for (int col = 0; col < wellFiles[row].length; col++) {
            int wellIndex = row * wellFiles[row].length + col;
            String wellID = MetadataTools.createLSID("Well", 0, wellIndex);
            store.setWellID(wellID, 0, wellIndex);
            store.setWellColumn(new NonNegativeInteger(col), 0, wellIndex);
            store.setWellRow(new NonNegativeInteger(row), 0, wellIndex);
            int fieldIndex = 0;
            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) {
                        String wellSampleID = MetadataTools.createLSID("WellSample", 0, wellIndex, fieldIndex);
                        store.setWellSampleID(wellSampleID, 0, wellIndex, fieldIndex);
                        String imageID = MetadataTools.createLSID("Image", nextImage);
                        store.setWellSampleImageRef(imageID, 0, wellIndex, fieldIndex);
                        store.setWellSampleIndex(new NonNegativeInteger(nextImage), 0, wellIndex, fieldIndex);
                        store.setPlateAcquisitionWellSampleRef(wellSampleID, 0, 0, nextImage);
                        String well = (char) (row + 'A') + String.format("%02d", col + 1);
                        store.setImageName("Well " + well + " Field #" + (fieldIndex + 1), nextImage);
                        nextImage++;
                        fieldIndex++;
                    }
                }
            }
        }
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        if (serialNumber != null) {
            store.setMicroscopeSerialNumber(serialNumber, 0);
        }
        for (int well = 0; well < wellCount; well++) {
            parseWellLogFile(well, store);
        }
        if (timestamps.size() > 0) {
            store.setPlateAcquisitionStartTime(timestamps.get(0), 0, 0);
            store.setPlateAcquisitionEndTime(timestamps.get(timestamps.size() - 1), 0, 0);
        }
        for (int i = 0; i < core.size(); i++) {
            for (int c = 0; c < getSizeC(); c++) {
                if (c < wavelengths.length && wavelengths[c] != null) {
                    store.setChannelName(wavelengths[c], i, c);
                }
            }
        }
    }
}
Also used : PositiveInteger(ome.xml.model.primitives.PositiveInteger) IFormatReader(loci.formats.IFormatReader) ServiceFactory(loci.common.services.ServiceFactory) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) DependencyException(loci.common.services.DependencyException) Image(ome.xml.model.Image) CoreMetadata(loci.formats.CoreMetadata) OMEXMLService(loci.formats.services.OMEXMLService) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) ServiceException(loci.common.services.ServiceException) OMEXMLMetadata(loci.formats.ome.OMEXMLMetadata) OMEXMLMetadataRoot(ome.xml.meta.OMEXMLMetadataRoot) Instrument(ome.xml.model.Instrument) Location(loci.common.Location)

Example 19 with Image

use of ome.xml.model.Image in project bioformats by openmicroscopy.

the class Schema2011_06_TO_2012_06_Test method testName.

@Test
public void testName() {
    Assert.assertNotNull(ome);
    Assert.assertEquals(1, ome.sizeOfImageList());
    Image image = ome.getImage(0);
    Assert.assertNotNull(image);
    Assert.assertEquals(IMAGE_NAME, image.getName());
}
Also used : Image(ome.xml.model.Image) Test(org.testng.annotations.Test)

Example 20 with Image

use of ome.xml.model.Image in project bioformats by openmicroscopy.

the class PumpWithLightSourceSettingsTest method setUp.

@BeforeClass
public void setUp() throws Exception {
    Instrument instrument = new Instrument();
    instrument.setID("Instrument:0");
    // Add a Laser with an Arc pump
    Laser laser = new Laser();
    laser.setID("Laser:0");
    Arc pump = new Arc();
    pump.setID("Arc:0");
    laser.linkPump(pump);
    instrument.addLightSource(laser);
    instrument.addLightSource(pump);
    ome.addInstrument(instrument);
    // Add an Image/Pixels with a LightSourceSettings reference to the Pump
    // on one of its channels.
    Image image = new Image();
    image.setID("Image:0");
    Pixels pixels = new Pixels();
    pixels.setID("Pixels:0");
    Channel channel = new Channel();
    channel.setID("Channel:0");
    LightSourceSettings settings = new LightSourceSettings();
    settings.setID("Arc:0");
    channel.setLightSourceSettings(settings);
    pixels.addChannel(channel);
    image.setPixels(pixels);
    ome.addImage(image);
}
Also used : LightSourceSettings(ome.xml.model.LightSourceSettings) Arc(ome.xml.model.Arc) Laser(ome.xml.model.Laser) Channel(ome.xml.model.Channel) Instrument(ome.xml.model.Instrument) Image(ome.xml.model.Image) Pixels(ome.xml.model.Pixels) BeforeClass(org.testng.annotations.BeforeClass)

Aggregations

Image (ome.xml.model.Image)29 Pixels (ome.xml.model.Pixels)15 OMEXMLMetadataRoot (ome.xml.meta.OMEXMLMetadataRoot)11 Test (org.testng.annotations.Test)10 Channel (ome.xml.model.Channel)8 PositiveInteger (ome.xml.model.primitives.PositiveInteger)8 ServiceException (loci.common.services.ServiceException)7 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)5 FormatException (loci.formats.FormatException)5 Instrument (ome.xml.model.Instrument)5 DependencyException (loci.common.services.DependencyException)4 XMLAnnotation (ome.xml.model.XMLAnnotation)4 BeforeClass (org.testng.annotations.BeforeClass)4 Node (org.w3c.dom.Node)4 NodeList (org.w3c.dom.NodeList)4 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)3 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)3 TransformerException (javax.xml.transform.TransformerException)3 Location (loci.common.Location)3