Search in sources :

Example 56 with Timestamp

use of ome.xml.model.primitives.Timestamp 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 57 with Timestamp

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

the class LIFReader method initMetadata.

// -- Helper methods --
/**
 * Parses a string of XML and puts the values in a Hashtable.
 */
private void initMetadata(String xml) throws FormatException, IOException {
    try {
        ServiceFactory factory = new ServiceFactory();
        OMEXMLService service = factory.getInstance(OMEXMLService.class);
        service.createOMEXMLMetadata();
    } catch (DependencyException exc) {
        throw new FormatException("Could not create OME-XML store.", exc);
    } catch (ServiceException exc) {
        throw new FormatException("Could not create OME-XML store.", exc);
    }
    MetadataStore store = makeFilterMetadata();
    // the XML blocks stored in a LIF file are invalid,
    // because they don't have a root node
    xml = "<?xml version=\"1.0\" encoding=\"" + ENCODING + "\"?><LEICA>" + xml + "</LEICA>";
    xml = XMLTools.sanitizeXML(xml);
    LOGGER.trace(xml);
    translateMetadata(getMetadataRoot(xml));
    for (int i = 0; i < imageNames.length; i++) {
        setSeries(i);
        addSeriesMeta("Image name", imageNames[i]);
    }
    setSeries(0);
    // set up mapping to rearrange channels
    // for instance, the green channel may be #0, and the red channel may be #1
    realChannel = new int[tileCount.length][];
    int nextLut = 0;
    for (int i = 0; i < core.size(); i++) {
        int index = getTileIndex(i);
        if (realChannel[index] != null) {
            continue;
        }
        CoreMetadata ms = core.get(i);
        realChannel[index] = new int[ms.sizeC];
        for (int q = 0; q < ms.sizeC; q++) {
            String lut = "";
            if (nextLut < lutNames.size()) {
                lut = lutNames.get(nextLut++).toLowerCase();
            }
            if (!CHANNEL_PRIORITIES.containsKey(lut))
                lut = "";
            realChannel[index][q] = CHANNEL_PRIORITIES.get(lut).intValue();
        }
        int[] sorted = new int[ms.sizeC];
        Arrays.fill(sorted, -1);
        for (int q = 0; q < sorted.length; q++) {
            int min = Integer.MAX_VALUE;
            int minIndex = -1;
            for (int n = 0; n < ms.sizeC; n++) {
                if (realChannel[index][n] < min && !DataTools.containsValue(sorted, n)) {
                    min = realChannel[index][n];
                    minIndex = n;
                }
            }
            sorted[q] = minIndex;
        }
    }
    MetadataTools.populatePixels(store, this, true, false);
    int roiCount = 0;
    for (int i = 0; i < getSeriesCount(); i++) {
        setSeries(i);
        String instrumentID = MetadataTools.createLSID("Instrument", i);
        store.setInstrumentID(instrumentID, i);
        int index = getTileIndex(i);
        store.setMicroscopeModel(microscopeModels[index], i);
        store.setMicroscopeType(getMicroscopeType("Other"), i);
        String objectiveID = MetadataTools.createLSID("Objective", i, 0);
        store.setObjectiveID(objectiveID, i, 0);
        store.setObjectiveLensNA(lensNA[index], i, 0);
        store.setObjectiveSerialNumber(serialNumber[index], i, 0);
        if (magnification[index] != null) {
            store.setObjectiveNominalMagnification(magnification[index], i, 0);
        }
        store.setObjectiveImmersion(getImmersion(immersions[index]), i, 0);
        store.setObjectiveCorrection(getCorrection(corrections[index]), i, 0);
        store.setObjectiveModel(objectiveModels[index], i, 0);
        if (cutIns[index] != null && filterModels[index] != null) {
            int channel = 0;
            if (cutIns[index].size() >= filterModels[index].size() * 2) {
                int diff = cutIns[index].size() - filterModels[index].size();
                for (int q = 0; q < diff; q++) {
                    cutIns[index].remove(filterModels[index].size());
                }
            }
            for (int filter = 0; filter < cutIns[index].size(); filter++) {
                String filterID = MetadataTools.createLSID("Filter", i, filter);
                store.setFilterID(filterID, i, filter);
                if (filterModels[index] != null && filter < filterModels[index].size()) {
                    store.setFilterModel((String) filterModels[index].get(filter), i, filter);
                }
                store.setTransmittanceRangeCutIn((Length) cutIns[index].get(filter), i, filter);
                store.setTransmittanceRangeCutOut((Length) cutOuts[index].get(filter), i, filter);
            }
        }
        final List<Double> lasers = laserWavelength[index];
        final List<Double> laserIntensities = laserIntensity[index];
        final List<Boolean> active = laserActive[index];
        final List<Boolean> frap = laserFrap[index];
        int nextChannel = 0;
        if (lasers != null) {
            int laserIndex = 0;
            while (laserIndex < lasers.size()) {
                if ((Double) lasers.get(laserIndex) == 0) {
                    lasers.remove(laserIndex);
                } else {
                    laserIndex++;
                }
            }
            for (int laser = 0; laser < lasers.size(); laser++) {
                String id = MetadataTools.createLSID("LightSource", i, laser);
                store.setLaserID(id, i, laser);
                store.setLaserType(LaserType.OTHER, i, laser);
                store.setLaserLaserMedium(LaserMedium.OTHER, i, laser);
                Double wavelength = (Double) lasers.get(laser);
                Length wave = FormatTools.getWavelength(wavelength);
                if (wave != null) {
                    store.setLaserWavelength(wave, i, laser);
                }
            }
            Set<Integer> ignoredChannels = new HashSet<Integer>();
            final List<Integer> validIntensities = new ArrayList<Integer>();
            int size = lasers.size();
            int channel = 0;
            Set<Integer> channels = new HashSet<Integer>();
            for (int laser = 0; laser < laserIntensities.size(); laser++) {
                double intensity = (Double) laserIntensities.get(laser);
                channel = laser / size;
                if (intensity < 100) {
                    validIntensities.add(laser);
                    channels.add(channel);
                }
                ignoredChannels.add(channel);
            }
            // remove channels w/o valid intensities
            ignoredChannels.removeAll(channels);
            // remove entries if channel has 2 wavelengths
            // e.g. 30% 458 70% 633
            int s = validIntensities.size();
            int jj;
            Set<Integer> toRemove = new HashSet<Integer>();
            int as = active.size();
            for (int j = 0; j < s; j++) {
                if (j < as && !(Boolean) active.get(j)) {
                    toRemove.add(validIntensities.get(j));
                }
                jj = j + 1;
                if (jj < s) {
                    int v = validIntensities.get(j) / size;
                    int vv = validIntensities.get(jj) / size;
                    if (vv == v) {
                        // do not consider that channel.
                        toRemove.add(validIntensities.get(j));
                        toRemove.add(validIntensities.get(jj));
                        ignoredChannels.add(j);
                    }
                }
            }
            if (toRemove.size() > 0) {
                validIntensities.removeAll(toRemove);
            }
            boolean noNames = true;
            if (channelNames[index] != null) {
                for (String name : channelNames[index]) {
                    if (name != null && !name.equals("")) {
                        noNames = false;
                        break;
                    }
                }
            }
            if (!noNames && frap != null) {
                // only use name for frap.
                for (int k = 0; k < frap.size(); k++) {
                    if (!frap.get(k)) {
                        noNames = true;
                        break;
                    }
                }
            }
            int nextFilter = 0;
            // int nextFilter = cutIns[i].size() - getEffectiveSizeC();
            for (int k = 0; k < validIntensities.size(); k++, nextChannel++) {
                int laserArrayIndex = validIntensities.get(k);
                double intensity = (Double) laserIntensities.get(laserArrayIndex);
                int laser = laserArrayIndex % lasers.size();
                Double wavelength = (Double) lasers.get(laser);
                if (wavelength != 0) {
                    while (ignoredChannels.contains(nextChannel)) {
                        nextChannel++;
                    }
                    while (channelNames != null && nextChannel < getEffectiveSizeC() && channelNames[index] != null && ((channelNames[index][nextChannel] == null || channelNames[index][nextChannel].equals("")) && !noNames)) {
                        nextChannel++;
                    }
                    if (nextChannel < getEffectiveSizeC()) {
                        String id = MetadataTools.createLSID("LightSource", i, laser);
                        store.setChannelLightSourceSettingsID(id, i, nextChannel);
                        store.setChannelLightSourceSettingsAttenuation(new PercentFraction((float) intensity / 100f), i, nextChannel);
                        Length ex = FormatTools.getExcitationWavelength(wavelength);
                        if (ex != null) {
                            store.setChannelExcitationWavelength(ex, i, nextChannel);
                        }
                        if (wavelength > 0) {
                            if (cutIns[index] == null || nextFilter >= cutIns[index].size()) {
                                continue;
                            }
                            Double cutIn = ((Length) cutIns[index].get(nextFilter)).value(UNITS.NANOMETER).doubleValue();
                            while (cutIn - wavelength > 20) {
                                nextFilter++;
                                if (nextFilter < cutIns[index].size()) {
                                    cutIn = ((Length) cutIns[index].get(nextFilter)).value(UNITS.NANOMETER).doubleValue();
                                } else {
                                    break;
                                }
                            }
                            if (nextFilter < cutIns[index].size()) {
                                String fid = MetadataTools.createLSID("Filter", i, nextFilter);
                                // store.setLightPathEmissionFilterRef(fid, i, nextChannel, 0);
                                nextFilter++;
                            }
                        }
                    }
                }
            }
        }
        store.setImageInstrumentRef(instrumentID, i);
        store.setObjectiveSettingsID(objectiveID, i);
        store.setObjectiveSettingsRefractiveIndex(refractiveIndex[index], i);
        store.setImageDescription(descriptions[index], i);
        if (acquiredDate[index] > 0) {
            store.setImageAcquisitionDate(new Timestamp(DateTools.convertDate((long) (acquiredDate[index] * 1000), DateTools.COBOL, DateTools.ISO8601_FORMAT, false)), i);
        }
        store.setImageName(imageNames[index].trim(), i);
        Length sizeX = FormatTools.getPhysicalSizeX(physicalSizeXs.get(index));
        Length sizeY = FormatTools.getPhysicalSizeY(physicalSizeYs.get(index));
        Length sizeZ = FormatTools.getPhysicalSizeZ(zSteps[index]);
        if (sizeX != null) {
            store.setPixelsPhysicalSizeX(sizeX, i);
        }
        if (sizeY != null) {
            store.setPixelsPhysicalSizeY(sizeY, i);
        }
        if (sizeZ != null) {
            store.setPixelsPhysicalSizeZ(sizeZ, i);
        }
        if (tSteps[index] != null) {
            store.setPixelsTimeIncrement(new Time(tSteps[index], UNITS.SECOND), i);
        }
        final List<String> detectors = detectorModels[index];
        if (detectors != null) {
            nextChannel = 0;
            int start = detectors.size() - getEffectiveSizeC();
            if (start < 0) {
                start = 0;
            }
            for (int detector = start; detector < detectors.size(); detector++) {
                int dIndex = detector - start;
                String detectorID = MetadataTools.createLSID("Detector", i, dIndex);
                store.setDetectorID(detectorID, i, dIndex);
                store.setDetectorModel((String) detectors.get(detector), i, dIndex);
                store.setDetectorZoom(zooms[index], i, dIndex);
                store.setDetectorType(DetectorType.PMT, i, dIndex);
                if (activeDetector[index] != null) {
                    int detectorIndex = activeDetector[index].size() - getEffectiveSizeC() + dIndex;
                    if (detectorIndex >= 0 && detectorIndex < activeDetector[index].size() && (Boolean) activeDetector[index].get(detectorIndex) && detectorOffsets[index] != null && nextChannel < detectorOffsets[index].length) {
                        store.setDetectorOffset(detectorOffsets[index][nextChannel++], i, dIndex);
                    }
                }
            }
        }
        final List<Boolean> activeDetectors = activeDetector[index];
        int firstDetector = activeDetectors == null ? 0 : activeDetectors.size() - getEffectiveSizeC();
        int nextDetector = firstDetector;
        int nextFilter = 0;
        int nextFilterDetector = 0;
        if (activeDetectors != null && activeDetectors.size() > cutIns[index].size() && (Boolean) activeDetectors.get(activeDetectors.size() - 1) && (Boolean) activeDetectors.get(activeDetectors.size() - 2)) {
            nextFilterDetector = activeDetectors.size() - cutIns[index].size();
            if (cutIns[index].size() > filterModels[index].size()) {
                nextFilterDetector += filterModels[index].size();
                nextFilter += filterModels[index].size();
            }
        }
        for (int c = 0; c < getEffectiveSizeC(); c++) {
            if (activeDetectors != null) {
                while (nextDetector >= 0 && nextDetector < activeDetectors.size() && !(Boolean) activeDetectors.get(nextDetector)) {
                    nextDetector++;
                }
                if (nextDetector < activeDetectors.size() && detectors != null && nextDetector - firstDetector < detectors.size()) {
                    String detectorID = MetadataTools.createLSID("Detector", i, nextDetector - firstDetector);
                    store.setDetectorSettingsID(detectorID, i, c);
                    nextDetector++;
                    if (detectorOffsets[index] != null && c < detectorOffsets[index].length) {
                        store.setDetectorSettingsOffset(detectorOffsets[index][c], i, c);
                    }
                    if (gains[index] != null) {
                        store.setDetectorSettingsGain(gains[index][c], i, c);
                    }
                }
            }
            if (channelNames[index] != null) {
                store.setChannelName(channelNames[index][c], i, c);
            }
            if (pinholes[index] != null) {
                store.setChannelPinholeSize(new Length(pinholes[index], UNITS.MICROMETER), i, c);
            }
            if (exWaves[index] != null) {
                if (exWaves[index][c] != null && exWaves[index][c] > 1) {
                    Length ex = FormatTools.getExcitationWavelength(exWaves[index][c]);
                    if (ex != null) {
                        store.setChannelExcitationWavelength(ex, i, c);
                    }
                }
            }
            // channel coloring is implicit if the image is stored as RGB
            Color channelColor = getChannelColor(realChannel[index][c]);
            if (!isRGB()) {
                store.setChannelColor(channelColor, i, c);
            }
            if (channelColor.getValue() != -1 && nextFilter >= 0) {
                if (nextDetector - firstDetector != getSizeC() && cutIns[index] != null && nextDetector >= cutIns[index].size()) {
                    while (nextFilterDetector < firstDetector) {
                        String filterID = MetadataTools.createLSID("Filter", i, nextFilter);
                        store.setFilterID(filterID, i, nextFilter);
                        nextFilterDetector++;
                        nextFilter++;
                    }
                }
                while (activeDetectors != null && nextFilterDetector < activeDetectors.size() && !(Boolean) activeDetectors.get(nextFilterDetector)) {
                    String filterID = MetadataTools.createLSID("Filter", i, nextFilter);
                    store.setFilterID(filterID, i, nextFilter);
                    nextFilterDetector++;
                    nextFilter++;
                }
                String filterID = MetadataTools.createLSID("Filter", i, nextFilter);
                store.setFilterID(filterID, i, nextFilter);
                store.setLightPathEmissionFilterRef(filterID, i, c, 0);
                nextFilterDetector++;
                nextFilter++;
            }
        }
        for (int image = 0; image < getImageCount(); image++) {
            Length xPos = posX[index];
            Length yPos = posY[index];
            if (i < fieldPosX.size() && fieldPosX.get(i) != null) {
                xPos = fieldPosX.get(i);
            }
            if (i < fieldPosY.size() && fieldPosY.get(i) != null) {
                yPos = fieldPosY.get(i);
            }
            if (xPos != null) {
                store.setPlanePositionX(xPos, i, image);
            }
            if (yPos != null) {
                store.setPlanePositionY(yPos, i, image);
            }
            store.setPlanePositionZ(posZ[index], i, image);
            if (timestamps[index] != null) {
                if (timestamps[index][image] != null) {
                    double timestamp = timestamps[index][image];
                    if (timestamps[index][0] == acquiredDate[index]) {
                        timestamp -= acquiredDate[index];
                    } else if (timestamp == acquiredDate[index] && image > 0) {
                        timestamp = timestamps[index][0];
                    }
                    store.setPlaneDeltaT(new Time(timestamp, UNITS.SECOND), i, image);
                }
            }
            if (expTimes[index] != null) {
                int c = getZCTCoords(image)[1];
                if (expTimes[index][c] != null) {
                    store.setPlaneExposureTime(new Time(expTimes[index][c], UNITS.SECOND), i, image);
                }
            }
        }
        if (imageROIs[index] != null) {
            for (int roi = 0; roi < imageROIs[index].length; roi++) {
                if (imageROIs[index][roi] != null) {
                    imageROIs[index][roi].storeROI(store, i, roiCount++, roi);
                }
            }
        }
    }
}
Also used : ServiceFactory(loci.common.services.ServiceFactory) ArrayList(java.util.ArrayList) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp) OMEXMLService(loci.formats.services.OMEXMLService) HashSet(java.util.HashSet) Color(ome.xml.model.primitives.Color) 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) PercentFraction(ome.xml.model.primitives.PercentFraction)

Example 58 with Timestamp

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

the class LiFlimReader method initOMEMetadata.

private void initOMEMetadata() {
    int times = timestamps == null ? 0 : Integer.parseInt(timestamps);
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, times > 0);
    String path = new Location(getCurrentFile()).getName();
    store.setImageName(path + " Primary Image #1", 0);
    if (getSeriesCount() > 1) {
        store.setImageName(path + " Background Image #1", 1);
    }
    if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) {
        return;
    }
    // timestamps
    long firstStamp = 0;
    for (int t = 0; t < times; t++) {
        if (stampValues.get(t) == null)
            break;
        String[] stampWords = stampValues.get(t).split(" ");
        long stampHi = Long.parseLong(stampWords[0]);
        long stampLo = Long.parseLong(stampWords[1]);
        long stamp = DateTools.getMillisFromTicks(stampHi, stampLo);
        Double deltaT;
        if (t == 0) {
            String date = DateTools.convertDate(stamp, DateTools.COBOL);
            if (date != null) {
                store.setImageAcquisitionDate(new Timestamp(date), 0);
            }
            firstStamp = stamp;
            deltaT = Double.valueOf(0);
        } else {
            long ms = stamp - firstStamp;
            deltaT = new Double(ms / 1000.0);
        }
        for (int c = 0; c < getEffectiveSizeC(); c++) {
            for (int z = 0; z < getSizeZ(); z++) {
                int index = getIndex(z, c, t);
                if (deltaT != null) {
                    store.setPlaneDeltaT(new Time(deltaT, UNITS.SECOND), 0, index);
                }
                if (exposureTime != null) {
                    store.setPlaneExposureTime(new Time(exposureTime, exposureTimeUnit), 0, index);
                }
            }
        }
    }
    if (getMetadataOptions().getMetadataLevel() == MetadataLevel.NO_OVERLAYS) {
        return;
    }
    // regions of interest
    Integer[] roiIndices = rois.keySet().toArray(new Integer[rois.size()]);
    Arrays.sort(roiIndices);
    for (int roi = 0; roi < roiIndices.length; roi++) {
        ROI r = rois.get(roiIndices[roi]);
        String polylineID = MetadataTools.createLSID("Shape", roi, 0);
        store.setPolygonID(polylineID, roi, 0);
        store.setPolygonPoints(r.pointsToString(), roi, 0);
        String roiID = MetadataTools.createLSID("ROI", roi);
        store.setROIID(roiID, roi);
        for (int s = 0; s < getSeriesCount(); s++) {
            store.setImageROIRef(roiID, s, roi);
        }
    }
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp) Location(loci.common.Location)

Example 59 with Timestamp

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

the class FluoviewReader method initMetadataStore.

/* @see loci.formats.in.BaseTiffReader#initMetadataStore() */
@Override
protected void initMetadataStore() throws FormatException {
    super.initMetadataStore();
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);
    if (date != null) {
        store.setImageAcquisitionDate(new Timestamp(date), 0);
    }
    if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) {
        return;
    }
    if (ifds.get(0).get(MMHEADER) == null) {
        initAlternateMetadataStore();
        return;
    }
    store.setImageDescription(comment, 0);
    // link Instrument and Image
    String instrumentID = MetadataTools.createLSID("Instrument", 0);
    store.setInstrumentID(instrumentID, 0);
    store.setImageInstrumentRef(instrumentID, 0);
    // populate timing data
    if (timeIndex >= 0) {
        for (int s = 0; s < getSeriesCount(); s++) {
            setSeries(s);
            for (int i = 0; i < getImageCount(); i++) {
                int index = getImageIndex(i);
                store.setPlaneDeltaT(new Time(stamps[timeIndex][index], UNITS.SECOND), s, i);
            }
        }
        setSeries(0);
    }
    // populate Dimensions
    for (int i = 0; i < getSeriesCount(); i++) {
        Length sizeX = FormatTools.getPhysicalSizeX(voxelX);
        Length sizeY = FormatTools.getPhysicalSizeY(voxelY);
        Length sizeZ = FormatTools.getPhysicalSizeZ(voxelZ);
        if (sizeX != null) {
            store.setPixelsPhysicalSizeX(sizeX, i);
        }
        if (sizeY != null) {
            store.setPixelsPhysicalSizeY(sizeY, i);
        }
        if (sizeZ != null) {
            store.setPixelsPhysicalSizeZ(sizeZ, i);
        }
        store.setPixelsTimeIncrement(new Time(voxelT, UNITS.SECOND), i);
        int montage = getMontage(i);
        int field = getField(i);
        double posX = 0d, posY = 0d, posZ = 0d;
        if (montageOffsets != null && montage < montageOffsets.length) {
            if (montageOffsets[montage].length > 0) {
                posX += montageOffsets[montage][0];
            }
            if (montageOffsets[montage].length > 1) {
                posY += montageOffsets[montage][1];
            }
            if (montageOffsets[montage].length > 2) {
                posZ += montageOffsets[montage][2];
            }
        }
        if (fieldOffsets != null && field < fieldOffsets.length) {
            if (fieldOffsets[field].length > 0) {
                posX += fieldOffsets[field][0];
            }
            if (fieldOffsets[field].length > 1) {
                posY += fieldOffsets[field][1];
            }
            if (fieldOffsets[field].length > 2) {
                posZ += fieldOffsets[field][2];
            }
        }
        for (int image = 0; image < getImageCount(); image++) {
            final Length xl = new Length(posX, UNITS.REFERENCEFRAME);
            final Length yl = new Length(posY, UNITS.REFERENCEFRAME);
            Length zl = new Length(posZ, UNITS.REFERENCEFRAME);
            if (zPositions != null && zPositions.length > image) {
                zl = new Length(zPositions[image], UNITS.MICROMETER);
            }
            store.setPlanePositionX(xl, i, image);
            store.setPlanePositionY(yl, i, image);
            store.setPlanePositionZ(zl, i, image);
        }
    }
    if (channelNames != null) {
        for (int i = 0; i < getSizeC(); i++) {
            if (channelNames[i] != null) {
                store.setChannelName(channelNames[i].trim(), 0, i);
            }
        }
    }
    for (int i = 0; i < getSizeC(); i++) {
        if (voltages != null && voltages[i] != null) {
            store.setDetectorSettingsVoltage(new ElectricPotential(new Double(voltages[i]), UNITS.VOLT), 0, i);
        }
        if (gains != null && gains[i] != null) {
            store.setDetectorSettingsGain(new Double(gains[i]), 0, i);
        }
        if (offsets != null && offsets[i] != null) {
            store.setDetectorSettingsOffset(new Double(offsets[i]), 0, i);
        }
        store.setDetectorType(getDetectorType("Other"), 0, i);
        if (detectorManufacturer != null) {
            store.setDetectorManufacturer(detectorManufacturer, 0, i);
        }
        // link DetectorSettings to an actual Detector
        String detectorID = MetadataTools.createLSID("Detector", 0, i);
        store.setDetectorID(detectorID, 0, i);
        store.setDetectorSettingsID(detectorID, 0, i);
    }
    if (mag != null && mag.toLowerCase().endsWith("x")) {
        mag = mag.substring(0, mag.length() - 1);
    } else if (mag == null)
        mag = "1";
    store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
    store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
    if (objectiveManufacturer != null) {
        String[] objectiveData = objectiveManufacturer.split(" ");
        store.setObjectiveModel(objectiveData[0], 0, 0);
        if (objectiveData.length > 2) {
            store.setObjectiveImmersion(getImmersion(objectiveData[2]), 0, 0);
        }
    }
    if (mag != null) {
        store.setObjectiveCalibratedMagnification(new Double(mag), 0, 0);
    }
    if (lensNA != null) {
        for (int i = 0; i < getSizeC(); i++) {
            if (lensNA[i] != null) {
                store.setObjectiveLensNA(new Double(lensNA[i]), 0, i);
            }
        }
    }
    // link Objective to Image using ObjectiveSettings
    String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
    store.setObjectiveID(objectiveID, 0, 0);
    store.setObjectiveSettingsID(objectiveID, 0);
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp) ElectricPotential(ome.units.quantity.ElectricPotential)

Example 60 with Timestamp

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

the class GatanDM2Reader 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);
    in.setEncoding("ISO-8859-1");
    int magicBytes = in.readInt();
    if (magicBytes != DM2_MAGIC_BYTES) {
        throw new FormatException("Invalid DM2 file");
    }
    in.skipBytes(8);
    long footerOffset = in.readInt() + 16;
    CoreMetadata m = core.get(0);
    m.sizeX = in.readShort();
    m.sizeY = in.readShort();
    int bpp = in.readShort();
    boolean signed = in.readShort() == 1;
    m.pixelType = FormatTools.pixelTypeFromBytes(bpp, signed, true);
    m.sizeC = 1;
    m.sizeT = 1;
    m.sizeZ = 1;
    m.imageCount = 1;
    m.dimensionOrder = "XYZCT";
    m.littleEndian = false;
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
    String instrumentID = MetadataTools.createLSID("Instrument", 0);
    store.setInstrumentID(instrumentID, 0);
    store.setImageInstrumentRef(instrumentID, 0);
    String date = null, time = null, name = null;
    in.skipBytes(FormatTools.getPlaneSize(this) + 35);
    MetadataLevel level = getMetadataOptions().getMetadataLevel();
    while (in.getFilePointer() < in.length()) {
        if (level == MetadataLevel.MINIMUM && date != null && time != null && name != null) {
            break;
        }
        int strlen = in.readShort();
        if (strlen == 0 || strlen > 255) {
            in.skipBytes(35);
            strlen = in.readShort();
            if (strlen < 0 || strlen + in.getFilePointer() >= in.length()) {
                in.seek(in.getFilePointer() - 10);
                strlen = in.readShort();
            }
        }
        if (strlen < 0 || strlen + in.getFilePointer() >= in.length())
            break;
        String label = in.readString(strlen);
        final StringBuilder value = new StringBuilder();
        int block = in.readInt();
        if (block == 5) {
            in.skipBytes(33);
            if (in.readShort() == 0) {
                if (in.readShort() == 39) {
                    in.skipBytes(1);
                } else {
                    in.skipBytes(2);
                }
            } else {
                in.seek(in.getFilePointer() - 2);
                continue;
            }
        } else if (block == 0 || (block > 0xffff && block < 0x01000000)) {
            if (block != 0 && strlen > 0) {
                in.seek(in.getFilePointer() - 4);
                value.append(label);
                label = "Description";
                addGlobalMeta(label, value.toString());
            } else if (block != 0) {
                in.skipBytes(15);
            }
            parseExtraTags();
            continue;
        } else if (block >= 0x01000000) {
            in.skipBytes(34);
            strlen = in.readShort();
            if (strlen + in.getFilePointer() >= in.length()) {
                break;
            }
            label = in.readString(strlen);
            block = in.readInt();
            if (block == 5) {
                in.skipBytes(33);
                continue;
            }
        }
        int len = in.readInt();
        if (len + in.getFilePointer() >= in.length() || len < 0)
            break;
        String type = in.readString(len);
        int extra = in.readInt() - 2;
        int count = in.readInt();
        if (type.equals("TEXT")) {
            value.append(in.readString(count));
            if (block == 5) {
                in.skipBytes(22);
                if (in.readInt() == 4) {
                    if (in.readString(4).equals("TEXT")) {
                        in.skipBytes(4);
                        count = in.readInt();
                        value.append(", " + in.readString(count));
                        in.skipBytes(37);
                    } else {
                        in.skipBytes(7);
                    }
                } else {
                    in.skipBytes(11);
                }
            }
        } else if (type.equals("long")) {
            count /= 8;
            for (int i = 0; i < count; i++) {
                value.append(in.readLong());
                if (i < count - 1)
                    value.append(", ");
            }
            in.skipBytes(4);
        } else if (type.equals("bool")) {
            for (int i = 0; i < count; i++) {
                value.append(in.read() == 1);
                if (i < count - 1)
                    value.append(", ");
            }
        } else if (type.equals("shor")) {
            count /= 2;
            for (int i = 0; i < count; i++) {
                value.append(in.readShort());
                if (i < count - 1)
                    value.append(", ");
            }
        } else if (type.equals("sing")) {
            count /= 4;
            for (int i = 0; i < count; i++) {
                value.append(in.readFloat());
                if (i < count - 1)
                    value.append(", ");
            }
        } else {
            if (count < 0 || count + in.getFilePointer() > in.length()) {
                break;
            }
            in.skipBytes(count);
        }
        in.skipBytes(16);
        addGlobalMeta(label, value.toString());
        if (label.equals("Acquisition Date")) {
            date = value.toString();
            if (date != null && date.indexOf('/') != -1) {
                // if the year is stored as a single digit, then it will be parsed
                // literally, e.g. '7' -> '0007', when we want '7' -> '2007'
                String year = date.substring(date.lastIndexOf("/") + 1);
                if (year.length() < 2) {
                    year = "0" + year;
                }
                date = date.substring(0, date.lastIndexOf("/") + 1) + year;
            }
        } else if (label.equals("Acquisition Time")) {
            time = value.toString();
        } else if (label.equals("Binning")) {
            int bin = (int) Double.parseDouble(value.toString());
            store.setDetectorSettingsBinning(getBinning(bin + "x" + bin), 0, 0);
            String detectorID = MetadataTools.createLSID("Detector", 0, 0);
            store.setDetectorID(detectorID, 0, 0);
            store.setDetectorSettingsID(detectorID, 0, 0);
        } else if (label.equals("Name")) {
            name = value.toString();
        } else if (label.equals("Operator")) {
            String[] experimenterName = value.toString().split(" ");
            store.setExperimenterFirstName(experimenterName[0], 0);
            if (experimenterName.length > 1) {
                store.setExperimenterLastName(experimenterName[1], 0);
            }
            String expID = MetadataTools.createLSID("Experimenter", 0);
            store.setExperimenterID(expID, 0);
            store.setImageExperimenterRef(expID, 0);
        }
    }
    if (date != null && time != null) {
        String[] format = new String[] { "M/d/yy h:mm:ss a", "d/M/yy h:mm:ss a", "M/d/yy H:mm:ss", "d/M/yy H:mm:ss" };
        date += " " + time;
        date = DateTools.formatDate(date, format);
        if (date != null) {
            store.setImageAcquisitionDate(new Timestamp(date), 0);
        }
    }
    if (name != null) {
        store.setImageName(name, 0);
    }
    if (pixelSizeX != null) {
        store.setPixelsPhysicalSizeX(FormatTools.createLength(pixelSizeX, UNITS.MICROMETER), 0);
    }
    if (pixelSizeY != null) {
        store.setPixelsPhysicalSizeY(FormatTools.createLength(pixelSizeY, UNITS.MICROMETER), 0);
    }
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) RandomAccessInputStream(loci.common.RandomAccessInputStream) CoreMetadata(loci.formats.CoreMetadata) Timestamp(ome.xml.model.primitives.Timestamp) FormatException(loci.formats.FormatException)

Aggregations

Timestamp (ome.xml.model.primitives.Timestamp)76 MetadataStore (loci.formats.meta.MetadataStore)54 Length (ome.units.quantity.Length)52 CoreMetadata (loci.formats.CoreMetadata)44 Time (ome.units.quantity.Time)33 Location (loci.common.Location)28 RandomAccessInputStream (loci.common.RandomAccessInputStream)28 FormatException (loci.formats.FormatException)23 ArrayList (java.util.ArrayList)20 IFD (loci.formats.tiff.IFD)11 NonNegativeInteger (ome.xml.model.primitives.NonNegativeInteger)10 TiffParser (loci.formats.tiff.TiffParser)9 IOException (java.io.IOException)8 IFDList (loci.formats.tiff.IFDList)8 PositiveInteger (ome.xml.model.primitives.PositiveInteger)8 Temperature (ome.units.quantity.Temperature)7 Hashtable (java.util.Hashtable)4 StringTokenizer (java.util.StringTokenizer)4 Frequency (ome.units.quantity.Frequency)4 File (java.io.File)3