Search in sources :

Example 41 with Timestamp

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

the class ColumbusReader method parseImageXML.

// -- Helper methods --
private void parseImageXML(String filename, int externalTime) throws FormatException, IOException {
    LOGGER.info("Parsing image data from {} with timepoint {}", filename, externalTime);
    String xml = DataTools.readFile(filename);
    Location parent = new Location(filename).getParentFile();
    Element root = null;
    try {
        ByteArrayInputStream s = new ByteArrayInputStream(xml.getBytes(Constants.ENCODING));
        root = XMLTools.parseDOM(s).getDocumentElement();
        s.close();
    } catch (ParserConfigurationException e) {
        throw new FormatException(e);
    } catch (SAXException e) {
        throw new FormatException(e);
    }
    NodeList plates = root.getElementsByTagName("Plates");
    if (plates == null) {
        LOGGER.debug("Plates node not found");
        return;
    }
    plates = ((Element) plates.item(0)).getElementsByTagName("Plate");
    if (plates == null) {
        LOGGER.debug("Plate nodes not found");
        return;
    }
    NodeList timestamps = ((Element) plates.item(0)).getElementsByTagName("MeasurementStartTime");
    if (externalTime <= 0) {
        acquisitionDate = ((Element) timestamps.item(0)).getTextContent();
    }
    NodeList images = root.getElementsByTagName("Images");
    if (images == null) {
        LOGGER.debug("Images node not found");
        return;
    }
    images = ((Element) images.item(0)).getElementsByTagName("Image");
    if (images == null) {
        LOGGER.debug("Image nodes not found");
        return;
    }
    LOGGER.debug("Found {} image definitions", images.getLength());
    for (int i = 0; i < images.getLength(); i++) {
        Element image = (Element) images.item(i);
        Plane p = new Plane();
        NodeList children = image.getChildNodes();
        for (int q = 0; q < children.getLength(); q++) {
            Node child = children.item(q);
            String name = child.getNodeName();
            String value = child.getTextContent();
            NamedNodeMap attrs = child.getAttributes();
            if (name.equals("URL")) {
                p.file = new Location(parent, value).getAbsolutePath();
                String buffer = attrs.getNamedItem("BufferNo").getNodeValue();
                p.fileIndex = Integer.parseInt(buffer);
            } else if (name.equals("Row")) {
                p.row = Integer.parseInt(value) - 1;
            } else if (name.equals("Col")) {
                p.col = Integer.parseInt(value) - 1;
            } else if (name.equals("FieldID")) {
                p.field = Integer.parseInt(value) - 1;
            } else if (name.equals("TimepointID")) {
                p.timepoint = Integer.parseInt(value) - 1;
                if (p.timepoint == 0) {
                    p.timepoint = externalTime;
                }
            } else if (name.equals("ChannelID")) {
                p.channel = Integer.parseInt(value) - 1;
            } else if (name.equals("ChannelName")) {
                p.channelName = value;
            } else if (name.equals("ChannelColor")) {
                Long color = new Long(value);
                int blue = (int) ((color >> 24) & 0xff);
                int green = (int) ((color >> 16) & 0xff);
                int red = (int) ((color >> 8) & 0xff);
                int alpha = (int) (color & 0xff);
            // not setting this yet, and deferring to the
            // emission wavelength to set the color
            // neither BGRA nor ARGB seems to make sense for all channels
            // p.channelColor = new Color(red, green, blue, alpha);
            } else if (name.equals("MeasurementTimeOffset")) {
                p.deltaT = new Double(value);
            } else if (name.equals("AbsTime")) {
                p.deltaT = new Timestamp(value).asInstant().getMillis() / 1000d;
            } else if (name.equals("MainEmissionWavelength")) {
                p.emWavelength = new Double(value);
            } else if (name.equals("MainExcitationWavelength")) {
                p.exWavelength = new Double(value);
            } else if (name.equals("ImageResolutionX")) {
                String unit = attrs.getNamedItem("Unit").getNodeValue();
                p.sizeX = correctUnits(new Double(value), unit);
            } else if (name.equals("ImageResolutionY")) {
                String unit = attrs.getNamedItem("Unit").getNodeValue();
                p.sizeY = correctUnits(new Double(value), unit);
            } else if (name.equals("PositionX")) {
                String unit = attrs.getNamedItem("Unit").getNodeValue();
                p.positionX = correctUnits(new Double(value), unit);
            } else if (name.equals("PositionY")) {
                String unit = attrs.getNamedItem("Unit").getNodeValue();
                p.positionY = correctUnits(new Double(value), unit);
            } else if (name.equals("PositionZ")) {
                String unit = attrs.getNamedItem("Unit").getNodeValue();
                p.positionZ = correctUnits(new Double(value), unit);
            }
        }
        planes.add(p);
    }
}
Also used : NamedNodeMap(org.w3c.dom.NamedNodeMap) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Timestamp(ome.xml.model.primitives.Timestamp) FormatException(loci.formats.FormatException) SAXException(org.xml.sax.SAXException) ByteArrayInputStream(java.io.ByteArrayInputStream) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Location(loci.common.Location)

Example 42 with Timestamp

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

the class BaseZeissReader method parseMainTags.

// -- Internal FormatReader API methods --
void parseMainTags(int image, MetadataStore store, ArrayList<Tag> tags) throws FormatException, IOException {
    int effectiveSizeC = 0;
    try {
        effectiveSizeC = getEffectiveSizeC();
    } catch (ArithmeticException e) {
    }
    for (Tag t : tags) {
        String key = t.getKey();
        String value = t.getValue();
        try {
            if (key.equals("Image Channel Index")) {
                cIndex = Integer.parseInt(value);
                addGlobalMetaList(key, cIndex);
                continue;
            } else if (key.equals("ImageWidth")) {
                int v = Integer.parseInt(value);
                if (getSizeX() == 0 || v < getSizeX()) {
                    core.get(0).sizeX = v;
                }
                if (realWidth == 0 && v > realWidth)
                    realWidth = v;
            } else if (key.equals("ImageHeight")) {
                int v = Integer.parseInt(value);
                if (getSizeY() == 0 || v < getSizeY())
                    core.get(0).sizeY = v;
                if (realHeight == 0 || v > realHeight)
                    realHeight = v;
            }
            if (cIndex != -1)
                key += " " + cIndex;
            if (!key.startsWith("Camera Acquisition Time") && !key.startsWith("ImageRelativeTime")) {
                String metavalue = value;
                if (key.endsWith("Date")) {
                    try {
                        metavalue = DateTools.convertDate(parseTimestamp(value), DateTools.UNIX, DateTools.ISO8601_FORMAT_MS);
                    } catch (Exception e) {
                    }
                }
                addGlobalMeta(key, metavalue);
            }
            if (key.startsWith("ImageTile") && !(store instanceof DummyMetadata)) {
                if (!tiles.containsKey(new Integer(value))) {
                    tiles.put(Integer.valueOf(value), 1);
                } else {
                    int v = tiles.get(new Integer(value)).intValue() + 1;
                    tiles.put(new Integer(value), new Integer(v));
                }
            }
            if (key.startsWith("MultiChannel Color")) {
                if (cIndex >= 0 && cIndex < effectiveSizeC) {
                    if (channelColors == null || effectiveSizeC > channelColors.length) {
                        channelColors = new int[effectiveSizeC];
                    }
                    if (channelColors[cIndex] == 0) {
                        channelColors[cIndex] = Integer.parseInt(value);
                    }
                } else if (cIndex == effectiveSizeC && channelColors != null && channelColors[0] == 0) {
                    System.arraycopy(channelColors, 1, channelColors, 0, channelColors.length - 1);
                    channelColors[cIndex - 1] = Integer.parseInt(value);
                } else if (channelColors != null && channelColors[0] > 0 && channelColors.length > 1) {
                    int c = 1;
                    while (c < channelColors.length - 1 && channelColors[c] != 0) {
                        c++;
                    }
                    if (channelColors[c] == 0) {
                        channelColors[c] = Integer.parseInt(value);
                    }
                }
            } else if (key.startsWith("Scale Factor for X") && physicalSizeX == null) {
                physicalSizeX = Double.parseDouble(value);
            } else if (key.startsWith("Scale Factor for Y") && physicalSizeY == null) {
                physicalSizeY = Double.parseDouble(value);
            } else if (key.startsWith("Scale Factor for Z") && physicalSizeZ == null) {
                physicalSizeZ = Double.parseDouble(value);
            } else if (key.startsWith("Number Rows") && rowCount == 0) {
                rowCount = parseInt(value);
            } else if (key.startsWith("Number Columns") && colCount == 0) {
                colCount = parseInt(value);
            } else if (key.startsWith("NumberOfRawImages") && rawCount == 0) {
                rawCount = parseInt(value);
            } else if (key.startsWith("Emission Wavelength")) {
                if (cIndex != -1) {
                    Double wave = new Double(value);
                    Length emission = FormatTools.getEmissionWavelength(wave);
                    if (emission != null) {
                        emWavelength.put(cIndex, emission);
                    }
                }
            } else if (key.startsWith("Excitation Wavelength")) {
                if (cIndex != -1) {
                    Double wave = new Double(Double.parseDouble(value));
                    Length excitation = FormatTools.getExcitationWavelength(wave);
                    if (excitation != null) {
                        exWavelength.put(cIndex, excitation);
                    }
                }
            } else if (key.startsWith("Channel Name")) {
                if (cIndex != -1) {
                    channelName.put(cIndex, value);
                }
            } else if (key.startsWith("Exposure Time [ms]")) {
                if (exposureTime.get(new Integer(cIndex)) == null) {
                    double exp = Double.parseDouble(value) / 1000;
                    exposureTime.put(new Integer(cIndex), String.valueOf(exp));
                }
            } else if (key.startsWith("User Name")) {
                String[] username = value.split(" ");
                if (username.length >= 2) {
                    String id = MetadataTools.createLSID("Experimenter", 0);
                    store.setExperimenterID(id, 0);
                    store.setExperimenterFirstName(username[0], 0);
                    store.setExperimenterLastName(username[username.length - 1], 0);
                }
            } else if (key.equals("User company")) {
                String id = MetadataTools.createLSID("Experimenter", 0);
                store.setExperimenterID(id, 0);
                store.setExperimenterInstitution(value, 0);
            } else if (key.startsWith("Objective Magnification")) {
                Double magnification = Double.parseDouble(value);
                store.setObjectiveNominalMagnification(magnification, 0, 0);
            } else if (key.startsWith("Objective ID")) {
                store.setObjectiveID("Objective:" + value, 0, 0);
                store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
                store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
            } else if (key.startsWith("Objective N.A.")) {
                store.setObjectiveLensNA(new Double(value), 0, 0);
            } else if (key.startsWith("Objective Name")) {
                String[] tokens = value.split(" ");
                for (int q = 0; q < tokens.length; q++) {
                    int slash = tokens[q].indexOf('/');
                    if (slash != -1 && slash - q > 0) {
                        Double mag = Double.parseDouble(tokens[q].substring(0, slash - q));
                        String na = tokens[q].substring(slash + 1);
                        store.setObjectiveNominalMagnification(mag, 0, 0);
                        store.setObjectiveLensNA(new Double(na), 0, 0);
                        store.setObjectiveCorrection(getCorrection(tokens[q - 1]), 0, 0);
                        break;
                    }
                }
            } else if (key.startsWith("Objective Working Distance")) {
                store.setObjectiveWorkingDistance(new Length(new Double(value), UNITS.MICROMETER), 0, 0);
            } else if (key.startsWith("Objective Immersion Type")) {
                String immersion = "Other";
                switch(Integer.parseInt(value)) {
                    // case 1: no immersion
                    case 2:
                        immersion = "Oil";
                        break;
                    case 3:
                        immersion = "Water";
                        break;
                }
                store.setObjectiveImmersion(getImmersion(immersion), 0, 0);
            } else if (key.startsWith("Stage Position X")) {
                final Double number = Double.valueOf(value);
                stageX.put(image, new Length(number, UNITS.REFERENCEFRAME));
                addGlobalMetaList("X position for position", value);
            } else if (key.startsWith("Stage Position Y")) {
                final Double number = Double.valueOf(value);
                stageY.put(image, new Length(number, UNITS.REFERENCEFRAME));
                addGlobalMetaList("Y position for position", value);
            } else if (key.startsWith("Orca Analog Gain")) {
                detectorGain.put(cIndex, new Double(value));
            } else if (key.startsWith("Orca Analog Offset")) {
                detectorOffset.put(cIndex, new Double(value));
            } else if (key.startsWith("Comments")) {
                imageDescription = value;
            } else if (key.startsWith("Acquisition Date")) {
                acquisitionDate = new Timestamp(DateTools.convertDate(parseTimestamp(value), DateTools.UNIX, DateTools.ISO8601_FORMAT_MS));
            } else if (image >= 0 && key.startsWith("Camera Acquisition Time")) {
                // Note Double variant for TIFF XML.
                String date = DateTools.convertDate(parseTimestamp(value), DateTools.UNIX, DateTools.ISO8601_FORMAT_MS);
                addSeriesMetaList(key, date);
                if (timepoint != 0) {
                    // First timepoint is duplicated for some reason.
                    timestamps.put(timepoint - 1, date);
                } else {
                    timestamps.put(timepoint, date);
                }
                timepoint++;
            } else if (image >= 0 && key.startsWith("ImageRelativeTime")) {
                Time time = new Time(Double.parseDouble(value), UNITS.DAY);
                String timestr = time.value().toString() + " " + time.unit().getSymbol();
                addSeriesMetaList(key, timestr);
            }
        } catch (NumberFormatException e) {
        }
    }
}
Also used : DateTime(org.joda.time.DateTime) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp) FormatException(loci.formats.FormatException) IOException(java.io.IOException) DummyMetadata(loci.formats.meta.DummyMetadata) Length(ome.units.quantity.Length)

Example 43 with Timestamp

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

the class BrukerReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    Location originalFile = new Location(id).getAbsoluteFile();
    Location parent = originalFile.getParentFile().getParentFile();
    String[] acquisitionDirs = parent.list(true);
    Comparator<String> comparator = new Comparator<String>() {

        @Override
        public int compare(String s1, String s2) {
            Integer i1 = 0;
            try {
                i1 = new Integer(s1);
            } catch (NumberFormatException e) {
            }
            Integer i2 = 0;
            try {
                i2 = new Integer(s2);
            } catch (NumberFormatException e) {
            }
            return i1.compareTo(i2);
        }
    };
    Arrays.sort(acquisitionDirs, comparator);
    ArrayList<String> acqpFiles = new ArrayList<String>();
    ArrayList<String> recoFiles = new ArrayList<String>();
    for (String f : acquisitionDirs) {
        Location dir = new Location(parent, f);
        if (dir.isDirectory()) {
            String[] files = dir.list(true);
            for (String file : files) {
                Location child = new Location(dir, file);
                if (!child.isDirectory()) {
                    allFiles.add(child.getAbsolutePath());
                    if (file.equals("acqp")) {
                        acqpFiles.add(child.getAbsolutePath());
                    }
                } else {
                    Location grandchild = new Location(child, "1");
                    if (grandchild.exists()) {
                        String[] moreFiles = grandchild.list(true);
                        for (String m : moreFiles) {
                            Location ggc = new Location(grandchild, m);
                            if (!ggc.isDirectory()) {
                                allFiles.add(ggc.getAbsolutePath());
                                if (m.equals("2dseq")) {
                                    pixelsFiles.add(ggc.getAbsolutePath());
                                } else if (m.equals("reco")) {
                                    recoFiles.add(ggc.getAbsolutePath());
                                }
                            }
                        }
                    }
                }
            }
            if (acqpFiles.size() > pixelsFiles.size()) {
                acqpFiles.remove(acqpFiles.size() - 1);
            }
            if (recoFiles.size() > pixelsFiles.size()) {
                recoFiles.remove(recoFiles.size() - 1);
            }
        }
    }
    String[] imageNames = new String[pixelsFiles.size()];
    String[] timestamps = new String[pixelsFiles.size()];
    String[] institutions = new String[pixelsFiles.size()];
    String[] users = new String[pixelsFiles.size()];
    core.clear();
    for (int series = 0; series < pixelsFiles.size(); series++) {
        CoreMetadata ms = new CoreMetadata();
        core.add(ms);
        setSeries(series);
        String acqData = DataTools.readFile(acqpFiles.get(series));
        String[] lines = acqData.split("\n");
        String[] sizes = null;
        String[] ordering = null;
        int ni = 0, nr = 0, ns = 0;
        int bits = 0;
        boolean signed = false;
        boolean isFloat = false;
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            int index = line.indexOf('=');
            if (index >= 0) {
                String key = line.substring(0, index);
                String value = line.substring(index + 1);
                if (value.startsWith("(")) {
                    value = lines[i + 1].trim();
                    if (value.startsWith("<")) {
                        value = value.substring(1, value.length() - 1);
                    }
                }
                if (key.length() < 4) {
                    continue;
                }
                addSeriesMeta(key.substring(3), value);
                if (key.equals("##$NI")) {
                    ni = Integer.parseInt(value);
                } else if (key.equals("##$NR")) {
                    nr = Integer.parseInt(value);
                } else if (key.equals("##$ACQ_word_size")) {
                    bits = Integer.parseInt(value.substring(1, value.lastIndexOf("_")));
                } else if (key.equals("##$BYTORDA")) {
                    ms.littleEndian = value.toLowerCase().equals("little");
                } else if (key.equals("##$ACQ_size")) {
                    sizes = value.split(" ");
                } else if (key.equals("##$ACQ_obj_order")) {
                    ordering = value.split(" ");
                } else if (key.equals("##$ACQ_time")) {
                    timestamps[series] = value;
                } else if (key.equals("##$ACQ_institution")) {
                    institutions[series] = value;
                } else if (key.equals("##$ACQ_operator")) {
                    users[series] = value;
                } else if (key.equals("##$ACQ_scan_name")) {
                    imageNames[series] = value;
                } else if (key.equals("##$ACQ_ns_list_size")) {
                    ns = Integer.parseInt(value);
                }
            }
        }
        String recoData = DataTools.readFile(recoFiles.get(series));
        lines = recoData.split("\n");
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            int index = line.indexOf('=');
            if (index >= 0) {
                String key = line.substring(0, index);
                String value = line.substring(index + 1);
                if (value.startsWith("(")) {
                    value = lines[i + 1].trim();
                    if (value.startsWith("<")) {
                        value = value.substring(1, value.length() - 1);
                    }
                }
                if (key.length() < 4) {
                    continue;
                }
                addSeriesMeta(key.substring(3), value);
                if (key.equals("##$RECO_size")) {
                    sizes = value.split(" ");
                } else if (key.equals("##$RECO_wordtype")) {
                    bits = Integer.parseInt(value.substring(1, value.indexOf("BIT")));
                    signed = value.indexOf("_SGN_") >= 0;
                    isFloat = !value.endsWith("_INT");
                }
            }
        }
        int td = Integer.parseInt(sizes[0]);
        int ys = sizes.length > 1 ? Integer.parseInt(sizes[1]) : 0;
        int zs = sizes.length > 2 ? Integer.parseInt(sizes[2]) : 0;
        if (sizes.length == 2) {
            if (ni == 1) {
                ms.sizeY = ys;
                ms.sizeZ = nr;
            } else {
                ms.sizeY = ys;
                ms.sizeZ = ni;
            }
        } else if (sizes.length == 3) {
            ms.sizeY = ni * ys;
            ms.sizeZ = nr * zs;
        }
        ms.sizeX = td;
        ms.sizeZ /= ns;
        ms.sizeT = ns * nr;
        ms.sizeC = 1;
        ms.imageCount = getSizeZ() * getSizeC() * getSizeT();
        ms.dimensionOrder = "XYCTZ";
        ms.rgb = false;
        ms.interleaved = false;
        ms.pixelType = FormatTools.pixelTypeFromBytes(bits / 8, signed, isFloat);
    }
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
    for (int series = 0; series < getSeriesCount(); series++) {
        store.setImageName(imageNames[series] + " #" + (series + 1), series);
        String date = DateTools.formatDate(timestamps[series], DATE_FORMAT);
        if (date != null) {
            store.setImageAcquisitionDate(new Timestamp(date), series);
        }
        String expID = MetadataTools.createLSID("Experimenter", series);
        store.setExperimenterID(expID, series);
        store.setExperimenterLastName(users[series], series);
        store.setExperimenterInstitution(institutions[series], series);
        store.setImageExperimenterRef(expID, series);
    }
}
Also used : ArrayList(java.util.ArrayList) CoreMetadata(loci.formats.CoreMetadata) Timestamp(ome.xml.model.primitives.Timestamp) Comparator(java.util.Comparator) MetadataStore(loci.formats.meta.MetadataStore) Location(loci.common.Location)

Example 44 with Timestamp

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

the class CellSensReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    if (!checkSuffix(id, "vsi")) {
        Location current = new Location(id).getAbsoluteFile();
        Location parent = current.getParentFile();
        parent = parent.getParentFile();
        Location grandparent = parent.getParentFile();
        String vsi = parent.getName();
        vsi = vsi.substring(1, vsi.length() - 1) + ".vsi";
        Location vsiFile = new Location(grandparent, vsi);
        if (!vsiFile.exists()) {
            throw new FormatException("Could not find .vsi file.");
        } else {
            id = vsiFile.getAbsolutePath();
        }
    }
    parser = new TiffParser(id);
    ifds = parser.getIFDs();
    RandomAccessInputStream vsi = new RandomAccessInputStream(id);
    vsi.order(parser.getStream().isLittleEndian());
    vsi.seek(8);
    readTags(vsi, false, "");
    vsi.close();
    ArrayList<String> files = new ArrayList<String>();
    Location file = new Location(id).getAbsoluteFile();
    Location dir = file.getParentFile();
    String name = file.getName();
    name = name.substring(0, name.lastIndexOf("."));
    Location pixelsDir = new Location(dir, "_" + name + "_");
    String[] stackDirs = pixelsDir.list(true);
    if (stackDirs != null) {
        Arrays.sort(stackDirs);
        for (String f : stackDirs) {
            Location stackDir = new Location(pixelsDir, f);
            String[] pixelsFiles = stackDir.list(true);
            if (pixelsFiles != null) {
                Arrays.sort(pixelsFiles);
                for (String pixelsFile : pixelsFiles) {
                    if (checkSuffix(pixelsFile, "ets")) {
                        files.add(new Location(stackDir, pixelsFile).getAbsolutePath());
                    }
                }
            }
        }
    }
    files.add(file.getAbsolutePath());
    usedFiles = files.toArray(new String[files.size()]);
    if (expectETS && files.size() == 1) {
        String message = "Missing expected .ets files in " + pixelsDir.getAbsolutePath();
        if (failOnMissingETS()) {
            throw new FormatException(message);
        } else {
            LOGGER.warn(message);
        }
    } else if (!expectETS && files.size() > 1) {
        LOGGER.warn(".ets files present but not expected");
    }
    int seriesCount = files.size();
    core.clear();
    IFDList exifs = parser.getExifIFDs();
    int index = 0;
    for (int s = 0; s < seriesCount; s++) {
        CoreMetadata ms = new CoreMetadata();
        core.add(ms);
        if (s < files.size() - 1) {
            setCoreIndex(index);
            parseETSFile(files.get(s), s);
            ms.littleEndian = compressionType.get(index) == RAW;
            ms.interleaved = ms.rgb;
            for (int q = 1; q < ms.resolutionCount; q++) {
                int res = core.size() - ms.resolutionCount + q;
                core.get(res).littleEndian = ms.littleEndian;
                core.get(res).interleaved = ms.interleaved;
            }
            if (s == 0 && exifs.size() > 0) {
                IFD exif = exifs.get(0);
                int newX = exif.getIFDIntValue(IFD.PIXEL_X_DIMENSION);
                int newY = exif.getIFDIntValue(IFD.PIXEL_Y_DIMENSION);
                if (getSizeX() > newX || getSizeY() > newY) {
                    ms.sizeX = newX;
                    ms.sizeY = newY;
                }
            }
            index += ms.resolutionCount;
            if (s < pyramids.size()) {
                ms.seriesMetadata = pyramids.get(s).originalMetadata;
            }
            setCoreIndex(0);
        } else {
            IFD ifd = ifds.get(s - files.size() + 1);
            PhotoInterp p = ifd.getPhotometricInterpretation();
            int samples = ifd.getSamplesPerPixel();
            ms.rgb = samples > 1 || p == PhotoInterp.RGB;
            ms.sizeX = (int) ifd.getImageWidth();
            ms.sizeY = (int) ifd.getImageLength();
            ms.sizeZ = 1;
            ms.sizeT = 1;
            ms.sizeC = ms.rgb ? samples : 1;
            ms.littleEndian = ifd.isLittleEndian();
            ms.indexed = p == PhotoInterp.RGB_PALETTE && (get8BitLookupTable() != null || get16BitLookupTable() != null);
            ms.imageCount = 1;
            ms.pixelType = ifd.getPixelType();
            ms.interleaved = false;
            ms.falseColor = false;
            ms.thumbnail = s != 0;
            index++;
        }
        ms.metadataComplete = true;
        ms.dimensionOrder = "XYCZT";
    }
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);
    String instrument = MetadataTools.createLSID("Instrument", 0);
    store.setInstrumentID(instrument, 0);
    for (int i = 0; i < pyramids.size(); i++) {
        Pyramid pyramid = pyramids.get(i);
        store.setObjectiveID(MetadataTools.createLSID("Objective", 0, i), 0, i);
        store.setObjectiveNominalMagnification(pyramid.magnification, 0, i);
        store.setObjectiveWorkingDistance(FormatTools.createLength(pyramid.workingDistance, UNITS.MICROMETER), 0, i);
        for (int q = 0; q < pyramid.objectiveTypes.size(); q++) {
            if (pyramid.objectiveTypes.get(q) == 1) {
                store.setObjectiveModel(pyramid.objectiveNames.get(q), 0, i);
                break;
            }
        }
        store.setObjectiveLensNA(pyramid.numericalAperture, 0, i);
        store.setDetectorID(MetadataTools.createLSID("Detector", 0, i), 0, i);
        store.setDetectorOffset(pyramid.offset, 0, i);
        store.setDetectorGain(pyramid.gain, 0, i);
        for (int q = 0; q < pyramid.deviceTypes.size(); q++) {
            if (pyramid.deviceTypes.get(q).equals("Camera")) {
                if (q < pyramid.deviceNames.size()) {
                    store.setDetectorModel(pyramid.deviceNames.get(q), 0, i);
                }
                if (q < pyramid.deviceIDs.size()) {
                    store.setDetectorSerialNumber(pyramid.deviceIDs.get(q), 0, i);
                }
                if (q < pyramid.deviceManufacturers.size()) {
                    store.setDetectorManufacturer(pyramid.deviceManufacturers.get(q), 0, i);
                }
                store.setDetectorType(getDetectorType("CCD"), 0, i);
                break;
            }
        }
    }
    int nextPyramid = 0;
    for (int i = 0; i < core.size(); ) {
        setCoreIndex(i);
        Pyramid pyramid = null;
        if (nextPyramid < pyramids.size()) {
            pyramid = pyramids.get(nextPyramid++);
        }
        int ii = coreIndexToSeries(i);
        if (pyramid != null) {
            int nextPlane = 0;
            int effectiveSizeC = core.get(i).rgb ? 1 : core.get(i).sizeC;
            for (int c = 0; c < effectiveSizeC; c++) {
                store.setDetectorSettingsID(MetadataTools.createLSID("Detector", 0, nextPyramid - 1), ii, c);
                store.setDetectorSettingsBinning(getBinning(pyramid.binningX + "x" + pyramid.binningY), ii, c);
                if (c == 0) {
                    store.setDetectorSettingsGain(pyramid.redGain, ii, c);
                    store.setDetectorSettingsOffset(pyramid.redOffset, ii, c);
                } else if (c == 1) {
                    store.setDetectorSettingsGain(pyramid.greenGain, ii, c);
                    store.setDetectorSettingsOffset(pyramid.greenOffset, ii, c);
                } else if (c == 2) {
                    store.setDetectorSettingsGain(pyramid.blueGain, ii, c);
                    store.setDetectorSettingsOffset(pyramid.blueOffset, ii, c);
                }
                if (c < pyramid.channelNames.size()) {
                    store.setChannelName(pyramid.channelNames.get(c), ii, c);
                }
                if (c < pyramid.channelWavelengths.size()) {
                    int wave = pyramid.channelWavelengths.get(c).intValue();
                    if (wave > 0) {
                        store.setChannelEmissionWavelength(FormatTools.getEmissionWavelength((double) wave), ii, c);
                    }
                }
                for (int z = 0; z < core.get(i).sizeZ; z++) {
                    for (int t = 0; t < core.get(i).sizeT; t++) {
                        nextPlane = getIndex(z, c, t);
                        Long exp = pyramid.defaultExposureTime;
                        if (c < pyramid.exposureTimes.size()) {
                            exp = pyramid.exposureTimes.get(c);
                        }
                        if (exp != null) {
                            store.setPlaneExposureTime(FormatTools.createTime(exp / 1000000.0, UNITS.SECOND), ii, nextPlane);
                        }
                        store.setPlanePositionX(FormatTools.createLength(pyramid.originX, UNITS.MICROMETER), ii, nextPlane);
                        store.setPlanePositionY(FormatTools.createLength(pyramid.originY, UNITS.MICROMETER), ii, nextPlane);
                    }
                }
            }
        }
        store.setImageInstrumentRef(instrument, ii);
        if (pyramid != null) {
            String imageName = pyramid.name;
            boolean duplicate = false;
            for (int q = 0; q < pyramids.size(); q++) {
                if (q != (nextPyramid - 1) && imageName.equals(pyramids.get(q).name)) {
                    duplicate = true;
                    break;
                }
            }
            if (!imageName.equals("Overview") && !imageName.equals("Label") && duplicate) {
                imageName += " #" + ii;
            }
            if (imageName.equals("Overview") || imageName.equals("Label")) {
                imageName = imageName.toLowerCase();
            }
            store.setImageName(imageName, ii);
            store.setObjectiveSettingsID(MetadataTools.createLSID("Objective", 0, nextPyramid - 1), ii);
            store.setObjectiveSettingsRefractiveIndex(pyramid.refractiveIndex, ii);
            if (pyramid.physicalSizeX > 0) {
                store.setPixelsPhysicalSizeX(FormatTools.getPhysicalSizeX(pyramid.physicalSizeX), ii);
            }
            if (pyramid.physicalSizeY > 0) {
                store.setPixelsPhysicalSizeY(FormatTools.getPhysicalSizeY(pyramid.physicalSizeY), ii);
            }
            if (pyramid.acquisitionTime != null) {
                // acquisition time is stored in seconds
                store.setImageAcquisitionDate(new Timestamp(DateTools.convertDate(pyramid.acquisitionTime * 1000, DateTools.UNIX)), ii);
            }
        } else {
            store.setImageName("macro image", ii);
        }
        i += core.get(i).resolutionCount;
    }
    setCoreIndex(0);
}
Also used : IFD(loci.formats.tiff.IFD) ArrayList(java.util.ArrayList) PhotoInterp(loci.formats.tiff.PhotoInterp) CoreMetadata(loci.formats.CoreMetadata) Timestamp(ome.xml.model.primitives.Timestamp) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) IFDList(loci.formats.tiff.IFDList) TiffParser(loci.formats.tiff.TiffParser) RandomAccessInputStream(loci.common.RandomAccessInputStream) Location(loci.common.Location)

Example 45 with Timestamp

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

the class AFIReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    // The AFI file is just simple XML that lists the .svs files from
    // which to read pixel data.  Each .svs corresponds to a single channel;
    // we assemble the channels in the order in which they are stored in
    // the XML.
    // 
    // Note that the last two series are identical across the .svs files,
    // so we just use the ones from the first listed file.
    String xml = DataTools.readFile(id);
    XMLTools.parseXML(xml, new AFIHandler());
    String parent = new Location(id).getAbsoluteFile().getParent();
    String[] channelNames = new String[pixels.size()];
    reader = new ChannelSeparator[pixels.size()];
    for (int i = 0; i < pixels.size(); i++) {
        String file = pixels.get(i);
        int underscore = file.indexOf('_');
        int fullStop = file.indexOf('.');
        if (underscore >= 0 && fullStop > underscore) {
            channelNames[i] = file.substring(underscore + 1, fullStop);
        }
        pixels.set(i, new Location(parent, file).getAbsolutePath());
        reader[i] = new ChannelSeparator(new SVSReader());
        reader[i].setFlattenedResolutions(hasFlattenedResolutions());
        reader[i].setId(pixels.get(i));
    }
    core = reader[0].getCoreMetadataList();
    for (int i = 0; i < core.size() - EXTRA_IMAGES; i++) {
        CoreMetadata c = core.get(i);
        c.sizeC = pixels.size();
        c.imageCount = c.sizeC * c.sizeZ * c.sizeT;
        c.rgb = false;
        if (i == 0) {
            c.resolutionCount = core.size() - EXTRA_IMAGES;
        }
    }
    MetadataStore store = makeFilterMetadata();
    boolean minimalMetadata = getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM;
    MetadataTools.populatePixels(store, this, !minimalMetadata);
    String fileID = currentId.substring(currentId.lastIndexOf(File.separator) + 1, currentId.lastIndexOf("."));
    for (int i = 0; i < getSeriesCount(); i++) {
        store.setImageName(fileID + " - image #" + (i + 1), i);
    }
    if (!minimalMetadata) {
        Length[] emission = new Length[pixels.size()];
        Length[] excitation = new Length[pixels.size()];
        Double[] exposure = new Double[pixels.size()];
        Timestamp[] datestamp = new Timestamp[pixels.size()];
        Length[] physicalSizes = null;
        double magnification = Double.NaN;
        for (int c = 0; c < pixels.size(); c++) {
            SVSReader baseReader = (SVSReader) reader[c].getReader();
            emission[c] = baseReader.getEmission();
            excitation[c] = baseReader.getExcitation();
            exposure[c] = baseReader.getExposureTime();
            datestamp[c] = baseReader.getDatestamp();
            physicalSizes = baseReader.getPhysicalSizes();
            if (c == 0) {
                magnification = baseReader.getMagnification();
            }
        }
        String instrument = MetadataTools.createLSID("Instrument", 0);
        String objective = MetadataTools.createLSID("Objective", 0, 0);
        store.setInstrumentID(instrument, 0);
        store.setObjectiveID(objective, 0, 0);
        store.setObjectiveNominalMagnification(magnification, 0, 0);
        for (int i = 0; i < getSeriesCount() - EXTRA_IMAGES; i++) {
            if (datestamp[0] != null) {
                store.setImageAcquisitionDate(datestamp[0], i);
            }
            store.setImageInstrumentRef(instrument, i);
            store.setObjectiveSettingsID(objective, i);
            if (i < physicalSizes.length && physicalSizes[i] != null && physicalSizes[i].value(UNITS.MICROMETER).doubleValue() - Constants.EPSILON > 0) {
                Length size = physicalSizes[i];
                store.setPixelsPhysicalSizeX(size, i);
                store.setPixelsPhysicalSizeY(size, i);
            }
            for (int c = 0; c < channelNames.length; c++) {
                store.setChannelName(channelNames[c], i, c);
                if (emission[c] != null) {
                    store.setChannelEmissionWavelength(emission[c], i, c);
                }
                if (excitation[c] != null) {
                    store.setChannelExcitationWavelength(excitation[c], i, c);
                }
                store.setPlaneExposureTime(FormatTools.createTime(exposure[c], UNITS.SECOND), i, c);
            }
        }
    }
}
Also used : CoreMetadata(loci.formats.CoreMetadata) Timestamp(ome.xml.model.primitives.Timestamp) ChannelSeparator(loci.formats.ChannelSeparator) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) Location(loci.common.Location)

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