Search in sources :

Example 6 with OMEXMLMetadataRoot

use of ome.xml.meta.OMEXMLMetadataRoot in project bioformats by openmicroscopy.

the class OMEXMLServiceImpl method addMetadataOnly.

/**
 * @see OMEXMLService#addMetadataOnly(OMEXMLMetadata, int, boolean)
 */
public void addMetadataOnly(OMEXMLMetadata omexmlMeta, int image, boolean resolve) {
    if (resolve) {
        omexmlMeta.resolveReferences();
    }
    MetadataOnly meta = new MetadataOnly();
    OMEXMLMetadataRoot root = (OMEXMLMetadataRoot) omexmlMeta.getRoot();
    Pixels pix = root.getImage(image).getPixels();
    pix.setMetadataOnly(meta);
}
Also used : MetadataOnly(ome.xml.model.MetadataOnly) OMEXMLMetadataRoot(ome.xml.meta.OMEXMLMetadataRoot) Pixels(ome.xml.model.Pixels)

Example 7 with OMEXMLMetadataRoot

use of ome.xml.meta.OMEXMLMetadataRoot in project bioformats by openmicroscopy.

the class OMEXMLServiceImpl method addModuloAlong.

@Override
public void addModuloAlong(OMEXMLMetadata meta, CoreMetadata core, int imageIdx) {
    meta.resolveReferences();
    if (core.moduloZ.length() == 1 && core.moduloC.length() == 1 && core.moduloT.length() == 1) {
        // nothing to populate
        return;
    }
    OMEXMLMetadataRoot root = (OMEXMLMetadataRoot) meta.getRoot();
    Image image;
    try {
        image = root.getImage(imageIdx);
    } catch (IndexOutOfBoundsException ieeb) {
        // and exiting without doing anything.
        return;
    }
    StructuredAnnotations annotations = root.getStructuredAnnotations();
    if (annotations == null)
        annotations = new StructuredAnnotations();
    int annotationIndex = annotations.sizeOfXMLAnnotationList();
    final Set<String> knownModulos = new HashSet<String>();
    if (annotationIndex > 0) {
        // Check which modulo annotations are already present.
        for (int idx = 0; idx < annotationIndex; idx++) {
            if (ModuloAnnotation.MODULO_NS.equals(meta.getXMLAnnotationNamespace(idx))) {
                // ignore this annotation if it is not linked to the current Image
                boolean ignore = true;
                String xmlID = meta.getXMLAnnotationID(idx);
                for (int link = 0; link < image.sizeOfLinkedAnnotationList(); link++) {
                    if (xmlID.equals(image.getLinkedAnnotation(link).getID())) {
                        ignore = false;
                        break;
                    }
                }
                if (ignore) {
                    continue;
                }
                String value = meta.getXMLAnnotationValue(idx);
                try {
                    Document doc = XMLTools.parseDOM(value);
                    NodeList modulos = doc.getElementsByTagName("Modulo");
                    for (int m = 0; m < modulos.getLength(); m++) {
                        Node modulo = modulos.item(m);
                        NodeList children = modulo.getChildNodes();
                        for (int c = 0; c < children.getLength(); c++) {
                            Node child = children.item(c);
                            String name = child.getNodeName();
                            knownModulos.add(name);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.warn("Could not parse XML from annotation: {}", value, e);
                }
            }
        }
        // Calculate the next annotation ID that should be used.
        String lastAnnotationID = meta.getXMLAnnotationID(annotationIndex - 1);
        String lastIndex = lastAnnotationID.substring(lastAnnotationID.lastIndexOf(":") + 1);
        try {
            int index = Integer.parseInt(lastIndex);
            while (index >= annotationIndex) {
                annotationIndex++;
            }
        } catch (NumberFormatException e) {
        }
    }
    int imageAnnotation = 0;
    if (core.moduloZ.length() > 1 && !knownModulos.contains("ModuloAlongZ")) {
        createModulo(meta, core.moduloZ, annotations, image, imageIdx, annotationIndex, imageAnnotation);
        annotationIndex++;
        imageAnnotation++;
    }
    if (core.moduloC.length() > 1 && !knownModulos.contains("ModuloAlongC")) {
        createModulo(meta, core.moduloC, annotations, image, imageIdx, annotationIndex, imageAnnotation);
        annotationIndex++;
        imageAnnotation++;
    }
    if (core.moduloT.length() > 1 && !knownModulos.contains("ModuloAlongT")) {
        createModulo(meta, core.moduloT, annotations, image, imageIdx, annotationIndex, imageAnnotation);
        annotationIndex++;
        imageAnnotation++;
    }
    root.setStructuredAnnotations(annotations);
    meta.setRoot(root);
}
Also used : NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) StructuredAnnotations(ome.xml.model.StructuredAnnotations) Image(ome.xml.model.Image) Document(org.w3c.dom.Document) ServiceException(loci.common.services.ServiceException) SAXException(org.xml.sax.SAXException) TransformerException(javax.xml.transform.TransformerException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) OMEXMLMetadataRoot(ome.xml.meta.OMEXMLMetadataRoot) HashSet(java.util.HashSet)

Example 8 with OMEXMLMetadataRoot

use of ome.xml.meta.OMEXMLMetadataRoot in project bioformats by openmicroscopy.

the class OMEXMLServiceImpl method removeBinData.

/**
 * @see OMEXMLService#removeBinData(OMEXMLMetadata)
 */
@Override
public void removeBinData(OMEXMLMetadata omexmlMeta) {
    omexmlMeta.resolveReferences();
    OMEXMLMetadataRoot root = (OMEXMLMetadataRoot) omexmlMeta.getRoot();
    List<Image> images = root.copyImageList();
    for (Image img : images) {
        Pixels pix = img.getPixels();
        List<BinData> binData = pix.copyBinDataList();
        for (BinData bin : binData) {
            pix.removeBinData(bin);
        }
        pix.setMetadataOnly(null);
    }
    omexmlMeta.setRoot(root);
}
Also used : OMEXMLMetadataRoot(ome.xml.meta.OMEXMLMetadataRoot) BinData(ome.xml.model.BinData) Image(ome.xml.model.Image) Pixels(ome.xml.model.Pixels)

Example 9 with OMEXMLMetadataRoot

use of ome.xml.meta.OMEXMLMetadataRoot in project bioformats by openmicroscopy.

the class FileWriteSPW method cleanup.

/**
 * Close the file writer.
 */
public void cleanup() {
    // No of planes expected for each image = 1 if not FLIM
    int validPlanes = 1;
    if (delays != null) {
        validPlanes = sizet;
    }
    OMEXMLMetadataRoot root = (OMEXMLMetadataRoot) omexml.getRoot();
    Plate plate = root.getPlate(0);
    StructuredAnnotations anns = root.getStructuredAnnotations();
    ArrayList<Image> invalidImages = new ArrayList<>();
    // if not record those images as being invalid
    for (int i = 0; i < expectedImages.length; i++) {
        if (expectedImages[i] < validPlanes) {
            Image im = root.getImage(i);
            invalidImages.add(im);
            // remove modulo Annotation if FLIM
            if (delays != null) {
                XMLAnnotation ann = (XMLAnnotation) im.getLinkedAnnotation(0);
                anns.removeXMLAnnotation(ann);
            }
        }
    }
    // Now remove all limked wellSnmples and then invalid images
    for (int i = 0; i < invalidImages.size(); i++) {
        Image im = invalidImages.get(i);
        List<WellSample> list = im.copyLinkedWellSampleList();
        if (!list.isEmpty()) {
            WellSample wellSample = im.getLinkedWellSample(0);
            Well well = wellSample.getWell();
            well.removeWellSample(wellSample);
        }
        root.removeImage(im);
    }
    if (writer != null) {
        try {
            writer.close();
        } catch (IOException e) {
            System.err.println("Failed to close file writer.");
        }
    }
}
Also used : OMEXMLMetadataRoot(ome.xml.meta.OMEXMLMetadataRoot) Well(ome.xml.model.Well) ArrayList(java.util.ArrayList) StructuredAnnotations(ome.xml.model.StructuredAnnotations) XMLAnnotation(ome.xml.model.XMLAnnotation) WellSample(ome.xml.model.WellSample) IOException(java.io.IOException) Image(ome.xml.model.Image) Plate(ome.xml.model.Plate)

Example 10 with OMEXMLMetadataRoot

use of ome.xml.meta.OMEXMLMetadataRoot in project bioformats by openmicroscopy.

the class ImageConverter method testConvert.

// -- Utility methods --
/**
 * A utility method for converting a file from the command line.
 */
public boolean testConvert(IFormatWriter writer, String[] args) throws FormatException, IOException {
    nextOutputIndex.clear();
    options.setValidate(validate);
    writer.setMetadataOptions(options);
    firstTile = true;
    boolean success = parseArgs(args);
    if (!success) {
        return false;
    }
    if (printVersion) {
        CommandLineTools.printVersion();
        return true;
    }
    CommandLineTools.runUpgradeCheck(args);
    if (in == null || out == null) {
        printUsage();
        return false;
    }
    if (new Location(out).exists()) {
        if (overwrite == null) {
            LOGGER.warn("Output file {} exists.", out);
            LOGGER.warn("Do you want to overwrite it? ([y]/n)");
            BufferedReader r = new BufferedReader(new InputStreamReader(System.in, Constants.ENCODING));
            String choice = r.readLine().trim().toLowerCase();
            overwrite = !choice.startsWith("n");
        }
        if (!overwrite) {
            LOGGER.warn("Exiting; next time, please specify an output file that " + "does not exist.");
            return false;
        } else {
            new Location(out).delete();
        }
    }
    if (map != null)
        Location.mapId(in, map);
    long start = System.currentTimeMillis();
    LOGGER.info(in);
    reader = new ImageReader();
    if (stitch) {
        reader = new FileStitcher(reader);
        Location f = new Location(in);
        String pat = null;
        if (!f.exists()) {
            pat = in;
        } else {
            pat = FilePattern.findPattern(f);
        }
        if (pat != null)
            in = pat;
    }
    if (separate)
        reader = new ChannelSeparator(reader);
    if (merge)
        reader = new ChannelMerger(reader);
    if (fill)
        reader = new ChannelFiller(reader);
    minMax = null;
    if (autoscale) {
        reader = new MinMaxCalculator(reader);
        minMax = (MinMaxCalculator) reader;
    }
    reader.setMetadataOptions(options);
    reader.setGroupFiles(group);
    reader.setMetadataFiltered(true);
    reader.setOriginalMetadataPopulated(true);
    OMEXMLService service = null;
    try {
        ServiceFactory factory = new ServiceFactory();
        service = factory.getInstance(OMEXMLService.class);
        reader.setMetadataStore(service.createOMEXMLMetadata());
    } catch (DependencyException de) {
        throw new MissingLibraryException(OMEXMLServiceImpl.NO_OME_XML_MSG, de);
    } catch (ServiceException se) {
        throw new FormatException(se);
    }
    reader.setId(in);
    MetadataStore store = reader.getMetadataStore();
    MetadataTools.populatePixels(store, reader, false, false);
    boolean dimensionsSet = true;
    if (width == 0 || height == 0) {
        // otherwise default to series 0
        if (series >= 0) {
            reader.setSeries(series);
        }
        width = reader.getSizeX();
        height = reader.getSizeY();
        dimensionsSet = false;
    }
    if (channel >= reader.getEffectiveSizeC()) {
        throw new FormatException("Invalid channel '" + channel + "' (" + reader.getEffectiveSizeC() + " channels in source file)");
    }
    if (timepoint >= reader.getSizeT()) {
        throw new FormatException("Invalid timepoint '" + timepoint + "' (" + reader.getSizeT() + " timepoints in source file)");
    }
    if (zSection >= reader.getSizeZ()) {
        throw new FormatException("Invalid Z section '" + zSection + "' (" + reader.getSizeZ() + " Z sections in source file)");
    }
    if (store instanceof MetadataRetrieve) {
        try {
            String xml = service.getOMEXML(service.asRetrieve(store));
            OMEXMLMetadataRoot root = (OMEXMLMetadataRoot) store.getRoot();
            IMetadata meta = service.createOMEXMLMetadata(xml);
            if (series >= 0) {
                Image exportImage = new Image(root.getImage(series));
                Pixels exportPixels = new Pixels(root.getImage(series).getPixels());
                exportImage.setPixels(exportPixels);
                OMEXMLMetadataRoot newRoot = (OMEXMLMetadataRoot) meta.getRoot();
                while (newRoot.sizeOfImageList() > 0) {
                    newRoot.removeImage(newRoot.getImage(0));
                }
                newRoot.addImage(exportImage);
                meta.setRoot(newRoot);
                meta.setPixelsSizeX(new PositiveInteger(width), 0);
                meta.setPixelsSizeY(new PositiveInteger(height), 0);
                if (autoscale) {
                    store.setPixelsType(PixelType.UINT8, 0);
                }
                if (channel >= 0) {
                    meta.setPixelsSizeC(new PositiveInteger(1), 0);
                }
                if (zSection >= 0) {
                    meta.setPixelsSizeZ(new PositiveInteger(1), 0);
                }
                if (timepoint >= 0) {
                    meta.setPixelsSizeT(new PositiveInteger(1), 0);
                }
                writer.setMetadataRetrieve((MetadataRetrieve) meta);
            } else {
                for (int i = 0; i < reader.getSeriesCount(); i++) {
                    meta.setPixelsSizeX(new PositiveInteger(width), 0);
                    meta.setPixelsSizeY(new PositiveInteger(height), 0);
                    if (autoscale) {
                        store.setPixelsType(PixelType.UINT8, i);
                    }
                    if (channel >= 0) {
                        meta.setPixelsSizeC(new PositiveInteger(1), 0);
                    }
                    if (zSection >= 0) {
                        meta.setPixelsSizeZ(new PositiveInteger(1), 0);
                    }
                    if (timepoint >= 0) {
                        meta.setPixelsSizeT(new PositiveInteger(1), 0);
                    }
                }
                writer.setMetadataRetrieve((MetadataRetrieve) meta);
            }
        } catch (ServiceException e) {
            throw new FormatException(e);
        }
    }
    writer.setWriteSequentially(true);
    if (writer instanceof TiffWriter) {
        ((TiffWriter) writer).setBigTiff(bigtiff);
    } else if (writer instanceof ImageWriter) {
        IFormatWriter w = ((ImageWriter) writer).getWriter(out);
        if (w instanceof TiffWriter) {
            ((TiffWriter) w).setBigTiff(bigtiff);
        }
    }
    String format = writer.getFormat();
    LOGGER.info("[{}] -> {} [{}]", new Object[] { reader.getFormat(), out, format });
    long mid = System.currentTimeMillis();
    int total = 0;
    int num = writer.canDoStacks() ? reader.getSeriesCount() : 1;
    long read = 0, write = 0;
    int first = series == -1 ? 0 : series;
    int last = series == -1 ? num : series + 1;
    long timeLastLogged = System.currentTimeMillis();
    for (int q = first; q < last; q++) {
        reader.setSeries(q);
        firstTile = true;
        if (!dimensionsSet) {
            width = reader.getSizeX();
            height = reader.getSizeY();
        }
        int writerSeries = series == -1 ? q : 0;
        writer.setSeries(writerSeries);
        writer.setInterleaved(reader.isInterleaved() && !autoscale);
        writer.setValidBitsPerPixel(reader.getBitsPerPixel());
        int numImages = writer.canDoStacks() ? reader.getImageCount() : 1;
        int startPlane = (int) Math.max(0, firstPlane);
        int endPlane = (int) Math.min(numImages, lastPlane);
        numImages = endPlane - startPlane;
        if (channel >= 0) {
            numImages /= reader.getEffectiveSizeC();
        }
        if (zSection >= 0) {
            numImages /= reader.getSizeZ();
        }
        if (timepoint >= 0) {
            numImages /= reader.getSizeT();
        }
        total += numImages;
        int count = 0;
        for (int i = startPlane; i < endPlane; i++) {
            int[] coords = reader.getZCTCoords(i);
            if ((zSection >= 0 && coords[0] != zSection) || (channel >= 0 && coords[1] != channel) || (timepoint >= 0 && coords[2] != timepoint)) {
                continue;
            }
            String outputName = FormatTools.getFilename(q, i, reader, out, zeroPadding);
            if (outputName.equals(FormatTools.getTileFilename(0, 0, 0, outputName))) {
                writer.setId(outputName);
                if (compression != null)
                    writer.setCompression(compression);
            } else {
                int tileNum = outputName.indexOf(FormatTools.TILE_NUM);
                int tileX = outputName.indexOf(FormatTools.TILE_X);
                int tileY = outputName.indexOf(FormatTools.TILE_Y);
                if (tileNum < 0 && (tileX < 0 || tileY < 0)) {
                    throw new FormatException("Invalid file name pattern; " + FormatTools.TILE_NUM + " or both of " + FormatTools.TILE_X + " and " + FormatTools.TILE_Y + " must be specified.");
                }
            }
            int outputIndex = 0;
            if (nextOutputIndex.containsKey(outputName)) {
                outputIndex = nextOutputIndex.get(outputName);
            }
            long s = System.currentTimeMillis();
            long m = convertPlane(writer, i, outputIndex, outputName);
            long e = System.currentTimeMillis();
            read += m - s;
            write += e - m;
            nextOutputIndex.put(outputName, outputIndex + 1);
            if (i == endPlane - 1) {
                nextOutputIndex.remove(outputName);
            }
            // log number of planes processed every second or so
            if (count == numImages - 1 || (e - timeLastLogged) / 1000 > 0) {
                int current = (count - startPlane) + 1;
                int percent = 100 * current / numImages;
                StringBuilder sb = new StringBuilder();
                sb.append("\t");
                int numSeries = last - first;
                if (numSeries > 1) {
                    sb.append("Series ");
                    sb.append(q);
                    sb.append(": converted ");
                } else
                    sb.append("Converted ");
                LOGGER.info(sb.toString() + "{}/{} planes ({}%)", new Object[] { current, numImages, percent });
                timeLastLogged = e;
            }
            count++;
        }
    }
    writer.close();
    long end = System.currentTimeMillis();
    LOGGER.info("[done]");
    // output timing results
    float sec = (end - start) / 1000f;
    long initial = mid - start;
    float readAvg = (float) read / total;
    float writeAvg = (float) write / total;
    LOGGER.info("{}s elapsed ({}+{}ms per plane, {}ms overhead)", new Object[] { sec, readAvg, writeAvg, initial });
    return true;
}
Also used : ServiceFactory(loci.common.services.ServiceFactory) ChannelMerger(loci.formats.ChannelMerger) ImageWriter(loci.formats.ImageWriter) ChannelFiller(loci.formats.ChannelFiller) Image(ome.xml.model.Image) OMEXMLService(loci.formats.services.OMEXMLService) Pixels(ome.xml.model.Pixels) IMetadata(loci.formats.meta.IMetadata) ImageReader(loci.formats.ImageReader) MetadataRetrieve(loci.formats.meta.MetadataRetrieve) PositiveInteger(ome.xml.model.primitives.PositiveInteger) TiffWriter(loci.formats.out.TiffWriter) InputStreamReader(java.io.InputStreamReader) DependencyException(loci.common.services.DependencyException) ChannelSeparator(loci.formats.ChannelSeparator) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) IFormatWriter(loci.formats.IFormatWriter) FileStitcher(loci.formats.FileStitcher) ServiceException(loci.common.services.ServiceException) OMEXMLMetadataRoot(ome.xml.meta.OMEXMLMetadataRoot) BufferedReader(java.io.BufferedReader) MinMaxCalculator(loci.formats.MinMaxCalculator) MissingLibraryException(loci.formats.MissingLibraryException) Location(loci.common.Location)

Aggregations

OMEXMLMetadataRoot (ome.xml.meta.OMEXMLMetadataRoot)27 ServiceException (loci.common.services.ServiceException)11 Image (ome.xml.model.Image)11 IOException (java.io.IOException)8 FormatException (loci.formats.FormatException)8 OMEXMLMetadata (loci.formats.ome.OMEXMLMetadata)7 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)6 DependencyException (loci.common.services.DependencyException)6 ServiceFactory (loci.common.services.ServiceFactory)6 OMEXMLService (loci.formats.services.OMEXMLService)6 Pixels (ome.xml.model.Pixels)6 Location (loci.common.Location)5 OriginalMetadataAnnotation (loci.formats.meta.OriginalMetadataAnnotation)5 Document (org.w3c.dom.Document)5 Node (org.w3c.dom.Node)5 NodeList (org.w3c.dom.NodeList)5 SAXException (org.xml.sax.SAXException)5 StructuredAnnotations (ome.xml.model.StructuredAnnotations)4 XMLAnnotation (ome.xml.model.XMLAnnotation)4 PositiveInteger (ome.xml.model.primitives.PositiveInteger)4