Search in sources :

Example 21 with NonNegativeInteger

use of ome.xml.model.primitives.NonNegativeInteger in project bioformats by openmicroscopy.

the class FileWriteSPW method initializeMetadata.

/**
 * Populate the minimum amount of metadata required to export a Plate.
 */
private IMetadata initializeMetadata(int[][] nFovs) {
    Exception exception = null;
    try {
        // create the OME-XML metadata storage object
        ServiceFactory factory = new ServiceFactory();
        service = factory.getInstance(OMEXMLService.class);
        OMEXMLMetadata meta = service.createOMEXMLMetadata();
        // IMetadata meta = service.createOMEXMLMetadata();
        meta.createRoot();
        int plateIndex = 0;
        // count of images
        int series = 0;
        int well = 0;
        meta.setPlateDescription(plateDescription, 0);
        meta.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
        meta.setPlateRowNamingConvention(NamingConvention.LETTER, 0);
        meta.setPlateColumnNamingConvention(NamingConvention.NUMBER, 0);
        meta.setPlateRows(new PositiveInteger(rows), 0);
        meta.setPlateColumns(new PositiveInteger(cols), 0);
        meta.setPlateName("First test Plate", 0);
        PositiveInteger pwidth = new PositiveInteger(width);
        PositiveInteger pheight = new PositiveInteger(height);
        char rowChar = 'A';
        for (int row = 0; row < rows; row++) {
            for (int column = 0; column < cols; column++) {
                // set up well
                String wellID = MetadataTools.createLSID("Well", well);
                meta.setWellID(wellID, plateIndex, well);
                meta.setWellRow(new NonNegativeInteger(row), plateIndex, well);
                meta.setWellColumn(new NonNegativeInteger(column), plateIndex, well);
                int nFOV = nFovs[row][column];
                for (int fov = 0; fov < nFOV; fov++) {
                    // Create Image NB numberng in the Name goes from 1->n not 0-> n-1
                    String imageName = rowChar + ":" + Integer.toString(column + 1) + ":FOV:" + Integer.toString(fov + 1);
                    String imageID = MetadataTools.createLSID("Image", well, fov);
                    meta.setImageID(imageID, series);
                    meta.setImageName(imageName, series);
                    String pixelsID = MetadataTools.createLSID("Pixels", well, fov);
                    meta.setPixelsID(pixelsID, series);
                    // specify that the pixel data is stored in big-endian format
                    // change 'TRUE' to 'FALSE' to specify little-endian format
                    meta.setPixelsBigEndian(Boolean.TRUE, series);
                    // specify that the image is stored in ZCT order
                    meta.setPixelsDimensionOrder(DimensionOrder.XYZCT, series);
                    // specify the pixel type of the image
                    meta.setPixelsType(PixelType.fromString(FormatTools.getPixelTypeString(pixelType)), series);
                    // specify the dimensions of the image
                    meta.setPixelsSizeX(pwidth, series);
                    meta.setPixelsSizeY(pheight, series);
                    meta.setPixelsSizeZ(new PositiveInteger(1), series);
                    meta.setPixelsSizeC(new PositiveInteger(1), series);
                    meta.setPixelsSizeT(new PositiveInteger(sizet), series);
                    // define each channel and specify the number of samples in the channel
                    // the number of samples is 3 for RGB images and 1 otherwise
                    String channelID = MetadataTools.createLSID("Channel", well, fov);
                    meta.setChannelID(channelID, series, 0);
                    meta.setChannelSamplesPerPixel(new PositiveInteger(1), series, 0);
                    // set sample
                    String wellSampleID = MetadataTools.createLSID("WellSample", well, fov);
                    meta.setWellSampleID(wellSampleID, 0, well, fov);
                    // NB sampleIndex here == series ie the image No
                    meta.setWellSampleIndex(new NonNegativeInteger(series), 0, well, fov);
                    meta.setWellSampleImageRef(imageID, 0, well, fov);
                    if (exposureTimes != null && exposureTimes.length == sizet) {
                        for (int t = 0; t < sizet; t++) {
                            meta.setPlaneTheT(new NonNegativeInteger(t), series, t);
                            meta.setPlaneTheC(new NonNegativeInteger(0), series, t);
                            meta.setPlaneTheZ(new NonNegativeInteger(0), series, t);
                            meta.setPlaneExposureTime(new Time(exposureTimes[t], ome.units.UNITS.SECOND), series, t);
                        }
                    }
                    // add FLIM ModuloAlongT annotation if required
                    if (delays != null) {
                        CoreMetadata modlo = createModuloAnn(meta);
                        service.addModuloAlong(meta, modlo, series);
                    }
                    series++;
                }
                // end of samples
                well++;
            }
            rowChar++;
        }
        expectedImages = new int[series];
        // System.out.println(dump);
        return meta;
    } catch (DependencyException | ServiceException | EnumerationException e) {
        exception = e;
    }
    System.err.println("Failed to populate OME-XML metadata object.");
    return null;
}
Also used : PositiveInteger(ome.xml.model.primitives.PositiveInteger) ServiceFactory(loci.common.services.ServiceFactory) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) Time(ome.units.quantity.Time) DependencyException(loci.common.services.DependencyException) CoreMetadata(loci.formats.CoreMetadata) EnumerationException(ome.xml.model.enums.EnumerationException) ServiceException(loci.common.services.ServiceException) DependencyException(loci.common.services.DependencyException) FormatException(loci.formats.FormatException) IOException(java.io.IOException) OMEXMLService(loci.formats.services.OMEXMLService) ServiceException(loci.common.services.ServiceException) OMEXMLMetadata(loci.formats.ome.OMEXMLMetadata) EnumerationException(ome.xml.model.enums.EnumerationException)

Example 22 with NonNegativeInteger

use of ome.xml.model.primitives.NonNegativeInteger in project bioformats by openmicroscopy.

the class OMETiffReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    // normalize file name
    super.initFile(normalizeFilename(null, id));
    id = currentId;
    String dir = new File(id).getParent();
    // parse and populate OME-XML metadata
    String fileName = new Location(id).getAbsoluteFile().getAbsolutePath();
    if (!new File(fileName).exists()) {
        fileName = currentId;
    }
    String xml;
    IFD firstIFD = null;
    boolean companion = false;
    if (checkSuffix(fileName, "companion.ome")) {
        xml = DataTools.readFile(fileName);
        companion = true;
    } else {
        RandomAccessInputStream ras = new RandomAccessInputStream(fileName, 16);
        try {
            TiffParser tp = new TiffParser(ras);
            firstIFD = tp.getFirstIFD();
            xml = firstIFD.getComment();
        } finally {
            ras.close();
        }
    }
    if (service == null)
        setupService();
    try {
        if (meta == null || !metaFile.equals(currentId)) {
            meta = service.createOMEXMLMetadata(xml);
            metaFile = currentId;
        }
        if (companion) {
            String firstTIFF = meta.getUUIDFileName(0, 0);
            initFile(new Location(dir, firstTIFF).getAbsolutePath());
            return;
        }
    } catch (ServiceException se) {
        throw new FormatException(se);
    }
    String metadataPath = null;
    try {
        metadataPath = meta.getBinaryOnlyMetadataFile();
    } catch (NullPointerException e) {
    }
    if (metadataPath != null) {
        // this is a binary-only file
        // overwrite XML with what is in the companion OME-XML file
        Location path = new Location(dir, metadataPath);
        if (path.exists()) {
            metadataFile = path.getAbsolutePath();
            xml = readMetadataFile();
            try {
                meta = service.createOMEXMLMetadata(xml);
            } catch (ServiceException se) {
                throw new FormatException(se);
            } catch (NullPointerException e) {
                metadataFile = null;
                metadataPath = null;
            }
        }
    }
    hasSPW = meta.getPlateCount() > 0;
    for (int i = 0; i < meta.getImageCount(); i++) {
        int sizeC = meta.getPixelsSizeC(i).getValue().intValue();
        service.removeChannels(meta, i, sizeC);
    }
    Hashtable originalMetadata = service.getOriginalMetadata(meta);
    if (originalMetadata != null)
        metadata = originalMetadata;
    LOGGER.trace(xml);
    if (meta.getRoot() == null) {
        throw new FormatException("Could not parse OME-XML from TIFF comment");
    }
    String[] acquiredDates = new String[meta.getImageCount()];
    for (int i = 0; i < acquiredDates.length; i++) {
        Timestamp acquisitionDate = meta.getImageAcquisitionDate(i);
        if (acquisitionDate != null) {
            acquiredDates[i] = acquisitionDate.getValue();
        }
    }
    String currentUUID = meta.getUUID();
    if (!isGroupFiles() && !isSingleFile(currentId)) {
        IFormatReader reader = new MinimalTiffReader();
        reader.setId(currentId);
        core.set(0, reader.getCoreMetadataList().get(0));
        int ifdCount = reader.getImageCount();
        reader.close();
        int maxSeries = 0;
        info = new OMETiffPlane[meta.getImageCount()][];
        ArrayList<Integer> imagesToRemove = new ArrayList<Integer>();
        ArrayList<int[]> cBounds = new ArrayList<int[]>();
        for (int i = 0; i < meta.getImageCount(); i++) {
            int maxZ = 0;
            int maxC = 0;
            int maxT = 0;
            int minZ = Integer.MAX_VALUE;
            int minC = Integer.MAX_VALUE;
            int minT = Integer.MAX_VALUE;
            int sizeZ = meta.getPixelsSizeZ(i).getValue();
            int sizeC = meta.getChannelCount(i);
            int sizeT = meta.getPixelsSizeT(i).getValue();
            String order = meta.getPixelsDimensionOrder(i).getValue();
            int num = sizeZ * sizeC * sizeT;
            CoreMetadata m = i < core.size() ? core.get(i) : new CoreMetadata(core.get(0));
            m.dimensionOrder = order;
            info[i] = new OMETiffPlane[meta.getTiffDataCount(i)];
            int next = 0;
            for (int td = 0; td < meta.getTiffDataCount(i); td++) {
                String uuid = null;
                try {
                    uuid = meta.getUUIDValue(i, td);
                } catch (NullPointerException e) {
                }
                String filename = null;
                try {
                    filename = meta.getUUIDFileName(i, td);
                } catch (NullPointerException e) {
                }
                if ((uuid == null || !uuid.equals(currentUUID)) && (filename == null || !currentId.endsWith(filename))) {
                    // this plane doesn't appear to be in the current file
                    continue;
                }
                if (i > maxSeries) {
                    maxSeries = i;
                }
                NonNegativeInteger ifd = meta.getTiffDataIFD(i, td);
                NonNegativeInteger count = meta.getTiffDataPlaneCount(i, td);
                NonNegativeInteger firstZ = meta.getTiffDataFirstZ(i, td);
                NonNegativeInteger firstC = meta.getTiffDataFirstC(i, td);
                NonNegativeInteger firstT = meta.getTiffDataFirstT(i, td);
                int realCount = count == null ? 1 : count.getValue();
                if (ifd == null && count == null) {
                    realCount = ifdCount;
                }
                for (int q = 0; q < realCount; q++) {
                    OMETiffPlane p = new OMETiffPlane();
                    p.id = currentId;
                    p.ifd = q;
                    if (ifd != null) {
                        p.ifd += ifd.getValue();
                    }
                    p.reader = reader;
                    info[i][next++] = p;
                    int z = firstZ == null ? 0 : firstZ.getValue();
                    int c = firstC == null ? 0 : firstC.getValue();
                    int t = firstT == null ? 0 : firstT.getValue();
                    if (q > 0) {
                        int index = FormatTools.getIndex(order, sizeZ, sizeC, sizeT, num, z, c, t);
                        int[] add = FormatTools.getZCTCoords(order, sizeZ, sizeC, sizeT, num, q);
                        z += add[0];
                        c += add[1];
                        t += add[2];
                    }
                    if (z > maxZ) {
                        maxZ = z;
                    }
                    if (c > maxC) {
                        maxC = c;
                    }
                    if (t > maxT) {
                        maxT = t;
                    }
                    if (z < minZ) {
                        minZ = z;
                    }
                    if (c < minC) {
                        minC = c;
                    }
                    if (t < minT) {
                        minT = t;
                    }
                }
            }
            if (i <= maxSeries) {
                m.sizeZ = (maxZ - minZ) + 1;
                m.sizeC = (maxC - minC) + 1;
                m.sizeT = (maxT - minT) + 1;
                m.imageCount = m.sizeZ * m.sizeC * m.sizeT;
                m.sizeC *= meta.getChannelSamplesPerPixel(i, 0).getValue();
                if (i >= core.size()) {
                    core.add(m);
                }
                cBounds.add(new int[] { minC, maxC });
            } else {
                imagesToRemove.add(i);
            }
        }
        // remove extra Images, Channels, and Planes
        meta.resolveReferences();
        OMEXMLMetadataRoot root = (OMEXMLMetadataRoot) meta.getRoot();
        List<Image> images = root.copyImageList();
        for (int i = imagesToRemove.size() - 1; i >= 0; i--) {
            images.remove(imagesToRemove.get(i));
        }
        for (int i = 0; i < images.size(); i++) {
            Image img = images.get(i);
            Pixels pix = img.getPixels();
            List<Plane> planes = pix.copyPlaneList();
            for (int p = 0; p < planes.size(); p++) {
                Plane plane = planes.get(p);
                if (plane.getTheZ().getValue() >= core.get(i).sizeZ || plane.getTheC().getValue() >= core.get(i).sizeC || plane.getTheT().getValue() >= core.get(i).sizeT) {
                    pix.removePlane(planes.get(p));
                }
            }
            pix.setMetadataOnly(null);
            List<Channel> channels = pix.copyChannelList();
            for (int c = 0; c < channels.size(); c++) {
                if (c < cBounds.get(i)[0] || c > cBounds.get(i)[1]) {
                    pix.removeChannel(channels.get(c));
                }
            }
        }
        meta.setRoot(root);
        service.convertMetadata(meta, metadataStore);
        MetadataTools.populatePixels(metadataStore, this);
        return;
    }
    service.convertMetadata(meta, metadataStore);
    // determine series count from Image and Pixels elements
    int seriesCount = meta.getImageCount();
    core.clear();
    for (int i = 0; i < seriesCount; i++) {
        core.add(new CoreMetadata());
    }
    info = new OMETiffPlane[seriesCount][];
    tileWidth = new int[seriesCount];
    tileHeight = new int[seriesCount];
    // compile list of file/UUID mappings
    Hashtable<String, String> files = new Hashtable<String, String>();
    boolean needSearch = false;
    for (int i = 0; i < seriesCount; i++) {
        int tiffDataCount = meta.getTiffDataCount(i);
        for (int td = 0; td < tiffDataCount; td++) {
            String uuid = null;
            try {
                uuid = meta.getUUIDValue(i, td);
            } catch (NullPointerException e) {
            }
            String filename = null;
            if (uuid == null) {
                // no UUID means that TiffData element refers to this file
                uuid = "";
                filename = id;
            } else {
                filename = meta.getUUIDFileName(i, td);
                if (!new Location(dir, filename).exists())
                    filename = null;
                if (filename == null) {
                    if (uuid.equals(currentUUID) || currentUUID == null) {
                        // UUID references this file
                        filename = id;
                    } else {
                        // will need to search for this UUID
                        filename = "";
                        needSearch = true;
                    }
                } else
                    filename = normalizeFilename(dir, filename);
            }
            String existing = files.get(uuid);
            if (existing == null)
                files.put(uuid, filename);
            else if (!existing.equals(filename)) {
                throw new FormatException("Inconsistent UUID filenames");
            }
        }
    }
    // search for missing filenames
    if (needSearch) {
        Enumeration en = files.keys();
        while (en.hasMoreElements()) {
            String uuid = (String) en.nextElement();
            String filename = files.get(uuid);
            if (filename.equals("")) {
                // to make this work with OME server may be a little tricky?
                throw new FormatException("Unmatched UUID: " + uuid);
            }
        }
    }
    // build list of used files
    Enumeration en = files.keys();
    int numUUIDs = files.size();
    // ensure no duplicate filenames
    HashSet fileSet = new HashSet();
    for (int i = 0; i < numUUIDs; i++) {
        String uuid = (String) en.nextElement();
        String filename = files.get(uuid);
        fileSet.add(filename);
    }
    used = new String[fileSet.size()];
    Iterator iter = fileSet.iterator();
    for (int i = 0; i < used.length; i++) used[i] = (String) iter.next();
    // process TiffData elements
    Hashtable<String, IFormatReader> readers = new Hashtable<String, IFormatReader>();
    boolean adjustedSamples = false;
    for (int i = 0; i < seriesCount; i++) {
        int s = i;
        LOGGER.debug("Image[{}] {", i);
        LOGGER.debug("  id = {}", meta.getImageID(i));
        String order = meta.getPixelsDimensionOrder(i).toString();
        PositiveInteger samplesPerPixel = null;
        if (meta.getChannelCount(i) > 0) {
            samplesPerPixel = meta.getChannelSamplesPerPixel(i, 0);
        }
        int samples = samplesPerPixel == null ? -1 : samplesPerPixel.getValue();
        int tiffSamples = firstIFD.getSamplesPerPixel();
        if (adjustedSamples || (samples != tiffSamples && (i == 0 || samples < 0))) {
            LOGGER.warn("SamplesPerPixel mismatch: OME={}, TIFF={}", samples, tiffSamples);
            samples = tiffSamples;
            adjustedSamples = true;
        } else {
            adjustedSamples = false;
        }
        if (adjustedSamples && meta.getChannelCount(i) <= 1) {
            adjustedSamples = false;
        }
        int effSizeC = meta.getPixelsSizeC(i).getValue().intValue();
        if (!adjustedSamples) {
            effSizeC /= samples;
        }
        if (effSizeC == 0)
            effSizeC = 1;
        if (effSizeC * samples != meta.getPixelsSizeC(i).getValue().intValue()) {
            effSizeC = meta.getPixelsSizeC(i).getValue().intValue();
        }
        int sizeT = meta.getPixelsSizeT(i).getValue().intValue();
        int sizeZ = meta.getPixelsSizeZ(i).getValue().intValue();
        int num = effSizeC * sizeT * sizeZ;
        OMETiffPlane[] planes = new OMETiffPlane[num];
        for (int no = 0; no < num; no++) planes[no] = new OMETiffPlane();
        int tiffDataCount = meta.getTiffDataCount(i);
        Boolean zOneIndexed = null;
        Boolean cOneIndexed = null;
        Boolean tOneIndexed = null;
        for (int td = 0; td < tiffDataCount; td++) {
            NonNegativeInteger firstC = meta.getTiffDataFirstC(i, td);
            NonNegativeInteger firstT = meta.getTiffDataFirstT(i, td);
            NonNegativeInteger firstZ = meta.getTiffDataFirstZ(i, td);
            int c = firstC == null ? 0 : firstC.getValue();
            int t = firstT == null ? 0 : firstT.getValue();
            int z = firstZ == null ? 0 : firstZ.getValue();
            if (c >= effSizeC && cOneIndexed == null) {
                cOneIndexed = true;
            } else if (c == 0) {
                cOneIndexed = false;
            }
            if (z >= sizeZ && zOneIndexed == null) {
                zOneIndexed = true;
            } else if (z == 0) {
                zOneIndexed = false;
            }
            if (t >= sizeT && tOneIndexed == null) {
                tOneIndexed = true;
            } else if (t == 0) {
                tOneIndexed = false;
            }
        }
        for (int td = 0; td < tiffDataCount; td++) {
            LOGGER.debug("    TiffData[{}] {", td);
            // extract TiffData parameters
            String filename = null;
            String uuid = null;
            try {
                filename = meta.getUUIDFileName(i, td);
            } catch (NullPointerException e) {
                LOGGER.debug("Ignoring null UUID object when retrieving filename.");
            }
            try {
                uuid = meta.getUUIDValue(i, td);
            } catch (NullPointerException e) {
                LOGGER.debug("Ignoring null UUID object when retrieving value.");
            }
            NonNegativeInteger tdIFD = meta.getTiffDataIFD(i, td);
            int ifd = tdIFD == null ? 0 : tdIFD.getValue();
            NonNegativeInteger numPlanes = meta.getTiffDataPlaneCount(i, td);
            NonNegativeInteger firstC = meta.getTiffDataFirstC(i, td);
            NonNegativeInteger firstT = meta.getTiffDataFirstT(i, td);
            NonNegativeInteger firstZ = meta.getTiffDataFirstZ(i, td);
            int c = firstC == null ? 0 : firstC.getValue();
            int t = firstT == null ? 0 : firstT.getValue();
            int z = firstZ == null ? 0 : firstZ.getValue();
            // NB: some writers index FirstC, FirstZ and FirstT from 1
            if (cOneIndexed != null && cOneIndexed)
                c--;
            if (zOneIndexed != null && zOneIndexed)
                z--;
            if (tOneIndexed != null && tOneIndexed)
                t--;
            if (z >= sizeZ || c >= effSizeC || t >= sizeT) {
                LOGGER.warn("Found invalid TiffData: Z={}, C={}, T={}", new Object[] { z, c, t });
                break;
            }
            int index = FormatTools.getIndex(order, sizeZ, effSizeC, sizeT, num, z, c, t);
            int count = numPlanes == null ? 1 : numPlanes.getValue();
            if (count == 0) {
                core.set(s, null);
                break;
            }
            // get reader object for this filename
            if (filename == null) {
                if (uuid == null)
                    filename = id;
                else
                    filename = files.get(uuid);
            } else
                filename = normalizeFilename(dir, filename);
            IFormatReader r = readers.get(filename);
            if (r == null) {
                r = new MinimalTiffReader();
                readers.put(filename, r);
            }
            Location file = new Location(filename);
            boolean exists = true;
            if (!file.exists()) {
                // if this is an absolute file name, try using a relative name
                // old versions of OMETiffWriter wrote an absolute path to
                // UUID.FileName, which causes problems if the file is moved to
                // a different directory
                filename = filename.substring(filename.lastIndexOf(File.separator) + 1);
                filename = dir + File.separator + filename;
                if (!new Location(filename).exists()) {
                    filename = currentId;
                    // if only one file is defined, we have to assume that it
                    // corresponds to the current file
                    exists = fileSet.size() == 1;
                }
            }
            // populate plane index -> IFD mapping
            for (int q = 0; q < count; q++) {
                int no = index + q;
                planes[no].reader = r;
                planes[no].id = filename;
                planes[no].ifd = ifd + q;
                planes[no].certain = true;
                planes[no].exists = exists;
                LOGGER.debug("      Plane[{}]: file={}, IFD={}", new Object[] { no, planes[no].id, planes[no].ifd });
            }
            if (numPlanes == null) {
                // unknown number of planes; fill down
                for (int no = index + 1; no < num; no++) {
                    if (planes[no].certain)
                        break;
                    planes[no].reader = r;
                    planes[no].id = filename;
                    planes[no].ifd = planes[no - 1].ifd + 1;
                    planes[no].exists = exists;
                    LOGGER.debug("      Plane[{}]: FILLED", no);
                }
            } else {
                // known number of planes; clear anything subsequently filled
                for (int no = index + count; no < num; no++) {
                    if (planes[no].certain)
                        break;
                    planes[no].reader = null;
                    planes[no].id = null;
                    planes[no].ifd = -1;
                    LOGGER.debug("      Plane[{}]: CLEARED", no);
                }
            }
            LOGGER.debug("    }");
        }
        if (core.get(s) == null)
            continue;
        // verify that all planes are available
        LOGGER.debug("    --------------------------------");
        for (int no = 0; no < num; no++) {
            LOGGER.debug("    Plane[{}]: file={}, IFD={}", new Object[] { no, planes[no].id, planes[no].ifd });
            if (planes[no].reader == null) {
                LOGGER.warn("Image ID '{}': missing plane #{}.  " + "Using TiffReader to determine the number of planes.", meta.getImageID(i), no);
                TiffReader r = new TiffReader();
                r.setId(currentId);
                try {
                    planes = new OMETiffPlane[r.getImageCount()];
                    for (int plane = 0; plane < planes.length; plane++) {
                        planes[plane] = new OMETiffPlane();
                        planes[plane].id = currentId;
                        planes[plane].reader = r;
                        planes[plane].ifd = plane;
                    }
                    num = planes.length;
                } finally {
                    r.close();
                }
            }
        }
        LOGGER.debug("  }");
        // populate core metadata
        CoreMetadata m = core.get(s);
        info[s] = planes;
        try {
            RandomAccessInputStream testFile = new RandomAccessInputStream(info[s][0].id, 16);
            String firstFile = info[s][0].id;
            if (!info[s][0].reader.isThisType(testFile)) {
                LOGGER.warn("{} is not a valid OME-TIFF", info[s][0].id);
                info[s][0].id = currentId;
                info[s][0].exists = false;
            }
            testFile.close();
            for (int plane = 1; plane < info[s].length; plane++) {
                if (info[s][plane].id.equals(firstFile)) {
                    // don't repeat slow type checking if the files are the same
                    if (!info[s][0].exists) {
                        info[s][plane].id = info[s][0].id;
                        info[s][plane].exists = false;
                    }
                    continue;
                }
                testFile = new RandomAccessInputStream(info[s][plane].id, 16);
                if (!info[s][plane].reader.isThisType(testFile)) {
                    LOGGER.warn("{} is not a valid OME-TIFF", info[s][plane].id);
                    info[s][plane].id = info[s][0].id;
                    info[s][plane].exists = false;
                }
                testFile.close();
            }
            info[s][0].reader.setId(info[s][0].id);
            tileWidth[s] = info[s][0].reader.getOptimalTileWidth();
            tileHeight[s] = info[s][0].reader.getOptimalTileHeight();
            m.sizeX = meta.getPixelsSizeX(i).getValue().intValue();
            int tiffWidth = (int) firstIFD.getImageWidth();
            if (m.sizeX != tiffWidth && s == 0) {
                LOGGER.warn("SizeX mismatch: OME={}, TIFF={}", m.sizeX, tiffWidth);
            }
            m.sizeY = meta.getPixelsSizeY(i).getValue().intValue();
            int tiffHeight = (int) firstIFD.getImageLength();
            if (m.sizeY != tiffHeight && s == 0) {
                LOGGER.warn("SizeY mismatch: OME={}, TIFF={}", m.sizeY, tiffHeight);
            }
            m.sizeZ = meta.getPixelsSizeZ(i).getValue().intValue();
            m.sizeC = meta.getPixelsSizeC(i).getValue().intValue();
            m.sizeT = meta.getPixelsSizeT(i).getValue().intValue();
            m.pixelType = FormatTools.pixelTypeFromString(meta.getPixelsType(i).toString());
            int tiffPixelType = firstIFD.getPixelType();
            if (m.pixelType != tiffPixelType && (s == 0 || adjustedSamples)) {
                LOGGER.warn("PixelType mismatch: OME={}, TIFF={}", m.pixelType, tiffPixelType);
                m.pixelType = tiffPixelType;
            }
            m.imageCount = num;
            m.dimensionOrder = meta.getPixelsDimensionOrder(i).toString();
            // hackish workaround for files exported by OMERO that have an
            // incorrect dimension order
            String uuidFileName = "";
            try {
                if (meta.getTiffDataCount(i) > 0) {
                    uuidFileName = meta.getUUIDFileName(i, 0);
                }
            } catch (NullPointerException e) {
            }
            if (meta.getChannelCount(i) > 0 && meta.getChannelName(i, 0) == null && meta.getTiffDataCount(i) > 0 && uuidFileName.indexOf("__omero_export") != -1) {
                m.dimensionOrder = "XYZCT";
            }
            m.orderCertain = true;
            PhotoInterp photo = firstIFD.getPhotometricInterpretation();
            m.rgb = samples > 1 || photo == PhotoInterp.RGB;
            if ((samples != m.sizeC && (samples % m.sizeC) != 0 && (m.sizeC % samples) != 0) || m.sizeC == 1 || adjustedSamples) {
                m.sizeC *= samples;
            }
            if (m.sizeZ * m.sizeT * m.sizeC > m.imageCount && !m.rgb) {
                if (m.sizeZ == m.imageCount) {
                    m.sizeT = 1;
                    m.sizeC = 1;
                } else if (m.sizeT == m.imageCount) {
                    m.sizeZ = 1;
                    m.sizeC = 1;
                } else if (m.sizeC == m.imageCount) {
                    m.sizeT = 1;
                    m.sizeZ = 1;
                }
            }
            if (meta.getPixelsBinDataCount(i) > 1) {
                LOGGER.warn("OME-TIFF Pixels element contains BinData elements! " + "Ignoring.");
            }
            m.littleEndian = firstIFD.isLittleEndian();
            m.interleaved = false;
            m.indexed = photo == PhotoInterp.RGB_PALETTE && firstIFD.getIFDValue(IFD.COLOR_MAP) != null;
            if (m.indexed) {
                m.rgb = false;
            }
            m.falseColor = true;
            m.metadataComplete = true;
            if (meta.getPixelsSignificantBits(i) != null) {
                m.bitsPerPixel = meta.getPixelsSignificantBits(i).getValue();
            }
        } catch (NullPointerException exc) {
            throw new FormatException("Incomplete Pixels metadata", exc);
        }
    }
    // remove null CoreMetadata entries
    ArrayList<CoreMetadata> series = new ArrayList<CoreMetadata>();
    final List<OMETiffPlane[]> planeInfo = new ArrayList<OMETiffPlane[]>();
    for (int i = 0; i < core.size(); i++) {
        if (core.get(i) != null) {
            series.add(core.get(i));
            planeInfo.add(info[i]);
        }
    }
    core = series;
    info = planeInfo.toArray(new OMETiffPlane[0][0]);
    if (getImageCount() == 1) {
        CoreMetadata ms0 = core.get(0);
        ms0.sizeZ = 1;
        if (!ms0.rgb) {
            ms0.sizeC = 1;
        }
        ms0.sizeT = 1;
    }
    for (int i = 0; i < core.size(); i++) {
        CoreMetadata m = core.get(i);
        Modulo z = service.getModuloAlongZ(meta, i);
        if (z != null) {
            m.moduloZ = z;
        }
        Modulo c = service.getModuloAlongC(meta, i);
        if (c != null) {
            m.moduloC = c;
        }
        Modulo t = service.getModuloAlongT(meta, i);
        if (t != null) {
            m.moduloT = t;
        }
    }
    MetadataTools.populatePixels(metadataStore, this, false, false);
    for (int i = 0; i < meta.getImageCount(); i++) {
        // TheT values are not changed
        for (int p = 0; p < meta.getPlaneCount(i); p++) {
            NonNegativeInteger z = meta.getPlaneTheZ(i, p);
            NonNegativeInteger c = meta.getPlaneTheC(i, p);
            NonNegativeInteger t = meta.getPlaneTheT(i, p);
            if (z == null) {
                z = new NonNegativeInteger(0);
                metadataStore.setPlaneTheZ(z, i, p);
            }
            if (c == null) {
                c = new NonNegativeInteger(0);
                metadataStore.setPlaneTheC(c, i, p);
            }
            if (t == null) {
                t = new NonNegativeInteger(0);
                metadataStore.setPlaneTheT(t, i, p);
            }
        }
    }
    for (int i = 0; i < acquiredDates.length; i++) {
        if (acquiredDates[i] != null) {
            metadataStore.setImageAcquisitionDate(new Timestamp(acquiredDates[i]), i);
        }
    }
}
Also used : IFormatReader(loci.formats.IFormatReader) IFD(loci.formats.tiff.IFD) ArrayList(java.util.ArrayList) Image(ome.xml.model.Image) Timestamp(ome.xml.model.primitives.Timestamp) Pixels(ome.xml.model.Pixels) Iterator(java.util.Iterator) HashSet(java.util.HashSet) PositiveInteger(ome.xml.model.primitives.PositiveInteger) Enumeration(java.util.Enumeration) Plane(ome.xml.model.Plane) Hashtable(java.util.Hashtable) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) Modulo(loci.formats.Modulo) Channel(ome.xml.model.Channel) PhotoInterp(loci.formats.tiff.PhotoInterp) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) PositiveInteger(ome.xml.model.primitives.PositiveInteger) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) ServiceException(loci.common.services.ServiceException) OMEXMLMetadataRoot(ome.xml.meta.OMEXMLMetadataRoot) TiffParser(loci.formats.tiff.TiffParser) RandomAccessInputStream(loci.common.RandomAccessInputStream) File(java.io.File) Location(loci.common.Location)

Example 23 with NonNegativeInteger

use of ome.xml.model.primitives.NonNegativeInteger in project bioformats by openmicroscopy.

the class OMETiffWriter method populateTiffData.

private void populateTiffData(OMEXMLMetadata omeMeta, int[] zct, int ifd, int series, int plane) {
    omeMeta.setTiffDataFirstZ(new NonNegativeInteger(zct[0]), series, plane);
    omeMeta.setTiffDataFirstC(new NonNegativeInteger(zct[1]), series, plane);
    omeMeta.setTiffDataFirstT(new NonNegativeInteger(zct[2]), series, plane);
    omeMeta.setTiffDataIFD(new NonNegativeInteger(ifd), series, plane);
    omeMeta.setTiffDataPlaneCount(new NonNegativeInteger(1), series, plane);
}
Also used : NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger)

Example 24 with NonNegativeInteger

use of ome.xml.model.primitives.NonNegativeInteger in project bioformats by openmicroscopy.

the class IMODReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    in = new RandomAccessInputStream(id);
    String check = in.readString(8);
    if (!check.equals(MAGIC_STRING)) {
        throw new FormatException("Invalid file ID: " + check);
    }
    CoreMetadata m = core.get(0);
    String filename = in.readString(128);
    m.sizeX = in.readInt();
    m.sizeY = in.readInt();
    m.sizeZ = in.readInt();
    int nObjects = in.readInt();
    points = new float[nObjects][][][];
    colors = new byte[nObjects][3];
    int flags = in.readInt();
    int drawMode = in.readInt();
    int mouseMode = in.readInt();
    int blackLevel = in.readInt();
    int whiteLevel = in.readInt();
    float xOffset = in.readFloat();
    float yOffset = in.readFloat();
    float zOffset = in.readFloat();
    float xScale = in.readFloat();
    float yScale = in.readFloat();
    float zScale = in.readFloat();
    int currentObject = in.readInt();
    int currentContour = in.readInt();
    int currentPoint = in.readInt();
    int res = in.readInt();
    int thresh = in.readInt();
    float pixSize = in.readFloat();
    int pixSizeUnits = in.readInt();
    int checksum = in.readInt();
    float alpha = in.readFloat();
    float beta = in.readFloat();
    float gamma = in.readFloat();
    addGlobalMeta("Model name", filename);
    addGlobalMeta("Model flags", flags);
    addGlobalMeta("Model drawing mode", drawMode);
    addGlobalMeta("Mouse mode", mouseMode);
    addGlobalMeta("Black level", blackLevel);
    addGlobalMeta("White level", whiteLevel);
    addGlobalMeta("X offset", xOffset);
    addGlobalMeta("Y offset", yOffset);
    addGlobalMeta("Z offset", zOffset);
    addGlobalMeta("X scale", xScale);
    addGlobalMeta("Y scale", yScale);
    addGlobalMeta("Z scale", zScale);
    addGlobalMeta("Alpha", alpha);
    addGlobalMeta("Beta", beta);
    addGlobalMeta("Gamma", gamma);
    MetadataStore store = makeFilterMetadata();
    ArrayList<String> roiIDs = new ArrayList<String>();
    for (int obj = 0; obj < nObjects; obj++) {
        String objt = in.readString(4);
        while (!objt.equals("OBJT") && in.getFilePointer() < in.length()) {
            String prefix = "Object #" + obj + " ";
            if (objt.equals("IMAT")) {
                addGlobalMeta(prefix + "ambient", in.read());
                addGlobalMeta(prefix + "diffuse", in.read());
                addGlobalMeta(prefix + "specular", in.read());
                addGlobalMeta(prefix + "shininess", in.read());
                addGlobalMeta(prefix + "fill red", in.read());
                addGlobalMeta(prefix + "fill green", in.read());
                addGlobalMeta(prefix + "fill blue", in.read());
                addGlobalMeta(prefix + "sphere quality", in.read());
                in.skipBytes(4);
                addGlobalMeta(prefix + "black level", in.read());
                addGlobalMeta(prefix + "white level", in.read());
                in.skipBytes(2);
            }
            objt = in.readString(4);
        }
        if (!objt.equals("OBJT")) {
            break;
        }
        String objName = in.readString(64);
        // unused
        in.skipBytes(64);
        int nContours = in.readInt();
        points[obj] = new float[nContours][][];
        int objFlags = in.readInt();
        int axis = in.readInt();
        int objDrawMode = in.readInt();
        float red = in.readFloat();
        float green = in.readFloat();
        float blue = in.readFloat();
        colors[obj][0] = (byte) (red * 255);
        colors[obj][1] = (byte) (green * 255);
        colors[obj][2] = (byte) (blue * 255);
        int pixelRadius = in.readInt();
        int pixelSymbol = in.read();
        int symbolSize = in.read();
        int lineWidth2D = in.read();
        int lineWidth3D = in.read();
        int lineStyle = in.read();
        int symbolFlags = in.read();
        int symbolPadding = in.read();
        int transparency = in.read();
        int nMeshes = in.readInt();
        int nSurfaces = in.readInt();
        if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) {
            String roiID = MetadataTools.createLSID("ROI", obj);
            store.setROIID(roiID, obj);
            store.setROIName(objName, obj);
            roiIDs.add(roiID);
        }
        int nextShape = 0;
        for (int contour = 0; contour < nContours; contour++) {
            // CONT
            in.skipBytes(4);
            int nPoints = in.readInt();
            int contourFlags = in.readInt();
            int timeIndex = in.readInt();
            int surface = in.readInt();
            if (nPoints > in.length() || nPoints < 0) {
                while (!"CONT".equals(in.readString(4))) {
                    in.seek(in.getFilePointer() - 8);
                }
                nPoints = in.readInt();
                contourFlags = in.readInt();
                timeIndex = in.readInt();
                surface = in.readInt();
            }
            points[obj][contour] = new float[nPoints][3];
            for (int p = 0; p < nPoints; p++) {
                for (int i = 0; i < points[obj][contour][p].length; i++) {
                    points[obj][contour][p][i] = in.readFloat();
                }
            }
            if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) {
                boolean wild = (contourFlags & 0x10) == 0x10;
                Length l;
                if (wild) {
                    int r = colors[obj][0] & 0xff;
                    int g = colors[obj][1] & 0xff;
                    int b = colors[obj][2] & 0xff;
                    for (int i = 0; i < nPoints; i++) {
                        String shapeID = MetadataTools.createLSID("Shape", obj, nextShape);
                        store.setPointID(shapeID, obj, nextShape);
                        store.setPointStrokeColor(new Color(r, g, b, 0xff), obj, nextShape);
                        l = new Length(new Double(lineWidth2D), UNITS.PIXEL);
                        store.setPointStrokeWidth(l, obj, nextShape);
                        if (lineStyle == 1) {
                            store.setPointStrokeDashArray("5", obj, nextShape);
                        }
                        store.setPointX(new Double(points[obj][contour][i][0]), obj, nextShape);
                        store.setPointY(new Double(points[obj][contour][i][1]), obj, nextShape);
                        if (points[obj][contour][i][2] >= 0) {
                            store.setPointTheZ(new NonNegativeInteger((int) points[obj][contour][i][2]), obj, nextShape);
                        }
                        nextShape++;
                    }
                } else {
                    String shapeID = MetadataTools.createLSID("Shape", obj, nextShape);
                    boolean closed = (contourFlags & 0x8) == 0;
                    int r = colors[obj][0] & 0xff;
                    int g = colors[obj][1] & 0xff;
                    int b = colors[obj][2] & 0xff;
                    final StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < nPoints; i++) {
                        sb.append(points[obj][contour][i][0]);
                        sb.append(",");
                        sb.append(points[obj][contour][i][1]);
                        if (i < nPoints - 1) {
                            sb.append(" ");
                        }
                    }
                    if (closed) {
                        store.setPolygonID(shapeID, obj, nextShape);
                        store.setPolygonStrokeColor(new Color(r, g, b, 0xff), obj, nextShape);
                        l = new Length(new Double(lineWidth2D), UNITS.PIXEL);
                        store.setPolygonStrokeWidth(l, obj, nextShape);
                        if (lineStyle == 1) {
                            store.setPolygonStrokeDashArray("5", obj, nextShape);
                        }
                        if (nPoints > 0 && points[obj][contour][0][2] >= 0) {
                            store.setPolygonTheZ(new NonNegativeInteger((int) points[obj][contour][0][2]), obj, nextShape);
                        }
                        store.setPolygonPoints(sb.toString(), obj, nextShape);
                    } else {
                        store.setPolylineID(shapeID, obj, nextShape);
                        store.setPolylineStrokeColor(new Color(r, g, b, 0xff), obj, nextShape);
                        l = new Length(new Double(lineWidth2D), UNITS.PIXEL);
                        store.setPolylineStrokeWidth(l, obj, nextShape);
                        if (lineStyle == 1) {
                            store.setPolylineStrokeDashArray("5", obj, nextShape);
                        }
                        if (nPoints > 0 && points[obj][contour][0][2] >= 0) {
                            store.setPolylineTheZ(new NonNegativeInteger((int) points[obj][contour][0][2]), obj, nextShape);
                        }
                        store.setPolylinePoints(sb.toString(), obj, nextShape);
                    }
                    nextShape++;
                }
            }
        }
        for (int mesh = 0; mesh < nMeshes; mesh++) {
            // MESH
            in.skipBytes(4);
            int vsize = in.readInt();
            int lsize = in.readInt();
            int meshFlags = in.readInt();
            int timeIndex = in.readShort();
            int surface = in.readShort();
            // TODO
            in.skipBytes(12 * vsize + 4 * lsize);
        }
    }
    double physicalX = 0d, physicalY = 0d, physicalZ = 0d;
    while (in.getFilePointer() + 4 < in.length()) {
        // check if there is any extra metadata at the end of the file
        String chunkType = in.readString(4);
        if (chunkType.equals("IMAT")) {
            in.skipBytes(20);
        } else if (chunkType.equals("VIEW")) {
            in.skipBytes(4);
            if (in.readInt() != 1) {
                in.skipBytes(176);
                int bytesPerView = in.readInt();
                in.skipBytes(bytesPerView);
            }
        } else if (chunkType.equals("MINX")) {
            // skip old transformation values
            in.skipBytes(40);
            physicalX = in.readFloat();
            physicalY = in.readFloat();
            physicalZ = in.readFloat();
        }
    }
    m.sizeT = 1;
    m.sizeC = 3;
    m.rgb = true;
    m.interleaved = true;
    m.imageCount = getSizeT() * getSizeZ();
    m.littleEndian = false;
    m.dimensionOrder = "XYCZT";
    m.pixelType = FormatTools.UINT8;
    MetadataTools.populatePixels(store, this);
    if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) {
        for (int i = 0; i < roiIDs.size(); i++) {
            store.setROIID(roiIDs.get(i), i);
            store.setImageROIRef(roiIDs.get(i), 0, i);
        }
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        Unit<Length> physicalSizeUnit = convertUnits(pixSizeUnits);
        if (physicalX > 0) {
            Length x = FormatTools.getPhysicalSizeX(physicalX, physicalSizeUnit);
            if (x != null) {
                store.setPixelsPhysicalSizeX(x, 0);
            }
        }
        if (physicalY > 0) {
            Length y = FormatTools.getPhysicalSizeY(physicalY, physicalSizeUnit);
            if (y != null) {
                store.setPixelsPhysicalSizeY(y, 0);
            }
        }
        if (physicalZ > 0) {
            Length z = FormatTools.getPhysicalSizeZ(physicalZ, physicalSizeUnit);
            if (z != null) {
                store.setPixelsPhysicalSizeZ(z, 0);
            }
        }
    }
}
Also used : NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) Color(ome.xml.model.primitives.Color) ArrayList(java.util.ArrayList) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) RandomAccessInputStream(loci.common.RandomAccessInputStream)

Example 25 with NonNegativeInteger

use of ome.xml.model.primitives.NonNegativeInteger in project bioformats by openmicroscopy.

the class MetamorphTiffReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    List<String> uniqueChannels = new ArrayList<String>();
    final List<Double> uniqueZs = new ArrayList<Double>();
    final List<Length> stageX = new ArrayList<Length>();
    final List<Length> stageY = new ArrayList<Length>();
    CoreMetadata m = core.get(0);
    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());
            }
            final List<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;
        m.sizeC = uniqueChannels.size();
        m.sizeZ = uniqueZs.size();
    } else {
        files = new String[] { id };
        wellCount = 1;
        fieldRowCount = 1;
        fieldColumnCount = 1;
        m.sizeC = 0;
    }
    // parse XML comment
    MetamorphHandler handler = new MetamorphHandler(getGlobalMetadata());
    final List<Length> xPositions = new ArrayList<Length>();
    final List<Length> yPositions = new ArrayList<Length>();
    for (IFD ifd : ifds) {
        String xml = XMLTools.sanitizeXML(ifd.getComment());
        XMLTools.parseXML(xml, handler);
        final Length x = handler.getStagePositionX();
        final Length y = handler.getStagePositionY();
        if (xPositions.isEmpty()) {
            xPositions.add(x);
            yPositions.add(y);
        } else {
            final Length previousX = xPositions.get(xPositions.size() - 1);
            final Length previousY = yPositions.get(yPositions.size() - 1);
            final double x1 = x.value(UNITS.REFERENCEFRAME).doubleValue();
            final double x2 = previousX.value(UNITS.REFERENCEFRAME).doubleValue();
            final double y1 = y.value(UNITS.REFERENCEFRAME).doubleValue();
            final double y2 = previousY.value(UNITS.REFERENCEFRAME).doubleValue();
            if (Math.abs(x1 - x2) > 0.21 || Math.abs(y1 - y2) > 0.21) {
                xPositions.add(x);
                yPositions.add(y);
            }
        }
    }
    if (xPositions.size() > 1) {
        fieldRowCount = xPositions.size();
    }
    final List<Integer> wavelengths = handler.getWavelengths();
    final List<Double> zPositions = handler.getZPositions();
    dualCamera = handler.hasDualCamera();
    // calculate axis sizes
    final List<Integer> uniqueC = new ArrayList<Integer>();
    for (Integer c : wavelengths) {
        if (!uniqueC.contains(c)) {
            uniqueC.add(c);
        }
    }
    int effectiveC = uniqueC.size();
    if (effectiveC == 0)
        effectiveC = 1;
    if (getSizeC() == 0)
        m.sizeC = 1;
    int samples = ifds.get(0).getSamplesPerPixel();
    m.sizeC *= effectiveC * samples;
    final List<Double> uniqueZ = new ArrayList<Double>();
    for (Double z : zPositions) {
        if (!uniqueZ.contains(z))
            uniqueZ.add(z);
    }
    if (getSizeZ() == 0)
        m.sizeZ = 1;
    if (uniqueZ.size() > 1)
        m.sizeZ *= uniqueZ.size();
    Double physicalSizeZ = null;
    if (m.sizeZ > 1) {
        Double zRange = zPositions.get(zPositions.size() - 1) - zPositions.get(0);
        physicalSizeZ = Math.abs(zRange);
        physicalSizeZ /= (m.sizeZ - 1);
    }
    int totalPlanes = files.length * ifds.size();
    effectiveC = getSizeC() / samples;
    // account for the multiple actual Z sections
    if (effectiveC * getSizeZ() > totalPlanes && (effectiveC * (getSizeZ() / uniqueC.size()) == totalPlanes || effectiveC == totalPlanes)) {
        if (getSizeZ() >= uniqueC.size()) {
            m.sizeZ /= uniqueC.size();
        } else {
            m.sizeZ = 1;
        }
    }
    m.sizeT = totalPlanes / (wellCount * fieldRowCount * fieldColumnCount * getSizeZ() * effectiveC);
    if (getSizeT() == 0)
        m.sizeT = 1;
    int seriesCount = wellCount * fieldRowCount * fieldColumnCount;
    if (seriesCount > 1 && getSizeZ() > totalPlanes / seriesCount || totalPlanes > getSizeZ() * getSizeT() * effectiveC) {
        m.sizeZ = 1;
        m.sizeT = totalPlanes / (seriesCount * effectiveC);
    }
    m.imageCount = getSizeZ() * getSizeT() * effectiveC;
    if (dualCamera) {
        m.sizeX /= 2;
        m.sizeC *= 2;
        m.imageCount *= 2;
    }
    if (seriesCount > 1) {
        core.clear();
        for (int i = 0; i < seriesCount; i++) {
            core.add(m);
        }
    }
    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);
    // effectively useless).
    if (wellCount > 1) {
        store.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
        store.setPlateRows(new PositiveInteger(1), 0);
        store.setPlateColumns(new PositiveInteger(wellCount), 0);
        store.setPlateRowNamingConvention(NamingConvention.LETTER, 0);
        store.setPlateColumnNamingConvention(NamingConvention.NUMBER, 0);
        store.setPlateAcquisitionID(MetadataTools.createLSID("PlateAcquisition", 0, 0), 0, 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);
                    store.setPlateAcquisitionWellSampleRef(wellSampleID, 0, 0, seriesIndex);
                }
            }
        }
    }
    final List<String> timestamps = handler.getTimestamps();
    final List<Double> exposures = handler.getExposures();
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        for (int i = 0; i < timestamps.size(); i++) {
            long timestamp = DateTools.getTime(timestamps.get(i), DATE_FORMAT, ".");
            addGlobalMetaList("timestamp", timestamp);
        }
        for (int i = 0; i < exposures.size(); i++) {
            addGlobalMetaList("exposure time (ms)", exposures.get(i).floatValue() * 1000);
        }
    }
    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, ".");
        if (date != null) {
            store.setImageAcquisitionDate(new Timestamp(date), s);
        }
        if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
            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(new Time((ms - startDate) / 1000.0, UNITS.SECOND), s, image);
                    }
                    int exposureIndex = image;
                    if (dualCamera) {
                        exposureIndex /= getEffectiveSizeC();
                    }
                    if (exposures.size() == 1) {
                        exposureIndex = 0;
                    }
                    if (exposureIndex < exposures.size() && exposures.get(exposureIndex) != null) {
                        store.setPlaneExposureTime(new Time(exposures.get(exposureIndex), UNITS.SECOND), 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(new Temperature(handler.getTemperature(), UNITS.CELSIUS), s);
            Length sizeX = FormatTools.getPhysicalSizeX(handler.getPixelSizeX());
            Length sizeY = FormatTools.getPhysicalSizeY(handler.getPixelSizeY());
            Length sizeZ = physicalSizeZ == null ? null : FormatTools.getPhysicalSizeZ(physicalSizeZ);
            if (sizeX != null) {
                store.setPixelsPhysicalSizeX(sizeX, s);
            }
            if (sizeY != null) {
                store.setPixelsPhysicalSizeY(sizeY, s);
            }
            if (sizeZ != null) {
                store.setPixelsPhysicalSizeZ(sizeZ, s);
            }
            if (uniqueChannels.size() == 0) {
                uniqueChannels = handler.getChannelNames();
            }
            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);
                if (c < wavelengths.size()) {
                    store.setChannelEmissionWavelength(FormatTools.getEmissionWavelength(Double.valueOf(wavelengths.get(c))), s, c);
                }
            }
        }
    }
}
Also used : Temperature(ome.units.quantity.Temperature) IFD(loci.formats.tiff.IFD) ArrayList(java.util.ArrayList) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp) PositiveInteger(ome.xml.model.primitives.PositiveInteger) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) CoreMetadata(loci.formats.CoreMetadata) PositiveInteger(ome.xml.model.primitives.PositiveInteger) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length)

Aggregations

NonNegativeInteger (ome.xml.model.primitives.NonNegativeInteger)28 PositiveInteger (ome.xml.model.primitives.PositiveInteger)17 CoreMetadata (loci.formats.CoreMetadata)15 FormatException (loci.formats.FormatException)14 MetadataStore (loci.formats.meta.MetadataStore)14 Location (loci.common.Location)13 ArrayList (java.util.ArrayList)12 Length (ome.units.quantity.Length)11 Time (ome.units.quantity.Time)11 Timestamp (ome.xml.model.primitives.Timestamp)9 IOException (java.io.IOException)6 ServiceException (loci.common.services.ServiceException)6 RandomAccessInputStream (loci.common.RandomAccessInputStream)5 DependencyException (loci.common.services.DependencyException)5 ServiceFactory (loci.common.services.ServiceFactory)5 OMEXMLMetadata (loci.formats.ome.OMEXMLMetadata)5 OMEXMLService (loci.formats.services.OMEXMLService)5 IFD (loci.formats.tiff.IFD)5 HashMap (java.util.HashMap)3 Map (java.util.Map)3