Search in sources :

Example 66 with Timestamp

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

the class PrairieReader method populateOMEMetadata.

/**
 * This step populates the OME {@link MetadataStore} by extracting relevant
 * values from the parsed {@link #meta} structure.
 */
private void populateOMEMetadata() throws FormatException {
    LOGGER.info("Populating OME metadata");
    // populate required Pixels metadata
    final boolean minimumMetadata = isMinimumMetadata();
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, !minimumMetadata);
    // populate required AcquisitionDate
    final String date = DateTools.formatDate(meta.getDate(), DATE_FORMAT);
    final Timestamp acquisitionDate = Timestamp.valueOf(date);
    final int seriesCount = getSeriesCount();
    for (int s = 0; s < seriesCount; s++) {
        setSeries(s);
        if (date != null)
            store.setImageAcquisitionDate(acquisitionDate, s);
    }
    if (minimumMetadata)
        return;
    // create an Instrument
    final String instrumentID = MetadataTools.createLSID("Instrument", 0);
    store.setInstrumentID(instrumentID, 0);
    // populate Laser Power, if available
    final Double laserPower = meta.getLaserPower();
    if (laserPower != null) {
        // create a Laser
        final String laserID = MetadataTools.createLSID("LightSource", 0, 0);
        store.setLaserID(laserID, 0, 0);
        store.setLaserPower(new Power(laserPower, UNITS.MILLIWATT), 0, 0);
    }
    String objectiveID = null;
    for (int s = 0; s < seriesCount; s++) {
        setSeries(s);
        final Sequence sequence = sequence(s);
        final Frame firstFrame = sequence.getFirstFrame();
        // link Instrument and Image
        store.setImageInstrumentRef(instrumentID, s);
        // populate PhysicalSizeX
        final PositiveFloat physicalSizeX = pf(firstFrame.getMicronsPerPixelX(), "PhysicalSizeX");
        if (physicalSizeX != null) {
            store.setPixelsPhysicalSizeX(FormatTools.createLength(physicalSizeX, UNITS.MICROMETER), s);
        }
        // populate PhysicalSizeY
        final PositiveFloat physicalSizeY = pf(firstFrame.getMicronsPerPixelY(), "PhysicalSizeY");
        if (physicalSizeY != null) {
            store.setPixelsPhysicalSizeY(FormatTools.createLength(physicalSizeY, UNITS.MICROMETER), s);
        }
        // populate TimeIncrement
        final Double waitTime = meta.getWaitTime();
        if (waitTime != null)
            store.setPixelsTimeIncrement(new Time(waitTime, UNITS.SECOND), s);
        final String[] detectorIDs = new String[channels.length];
        for (int c = 0; c < channels.length; c++) {
            final int channel = channels[c];
            final PFile file = firstFrame.getFile(channel);
            // populate channel name
            final String channelName = file == null ? null : file.getChannelName();
            if (channelName != null)
                store.setChannelName(channelName, s, c);
            // populate emission wavelength
            if (file != null) {
                final Double waveMin = file.getWavelengthMin();
                final Double waveMax = file.getWavelengthMax();
                if (waveMin != null && waveMax != null) {
                    final double waveAvg = (waveMin + waveMax) / 2;
                    final Length wavelength = FormatTools.getEmissionWavelength(waveAvg);
                    store.setChannelEmissionWavelength(wavelength, s, c);
                }
            }
            if (detectorIDs[c] == null) {
                // create a Detector for this channel
                detectorIDs[c] = MetadataTools.createLSID("Detector", 0, c);
                store.setDetectorID(detectorIDs[c], 0, c);
                store.setDetectorType(getDetectorType("Other"), 0, c);
                // NB: Ideally we would populate the detector zoom differently for
                // each Image, rather than globally for the Detector, but
                // unfortunately it is a property of Detector, not DetectorSettings.
                final Double zoom = firstFrame.getOpticalZoom();
                if (zoom != null)
                    store.setDetectorZoom(zoom, 0, c);
            }
            // link DetectorSettings and Detector
            store.setDetectorSettingsID(detectorIDs[c], s, c);
            // populate Offset
            final Double offset = firstFrame.getOffset(c);
            if (offset != null)
                store.setDetectorSettingsOffset(offset, s, c);
            // populate Gain
            final Double gain = firstFrame.getGain(c);
            if (gain != null)
                store.setDetectorSettingsGain(gain, s, c);
        }
        if (objectiveID == null) {
            // create an Objective
            objectiveID = MetadataTools.createLSID("Objective", 0, 0);
            store.setObjectiveID(objectiveID, 0, 0);
            store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
            // populate Objective NominalMagnification
            final Double magnification = firstFrame.getMagnification();
            if (magnification != null) {
                store.setObjectiveNominalMagnification(magnification, 0, 0);
            }
            // populate Objective Manufacturer
            final String objectiveManufacturer = firstFrame.getObjectiveManufacturer();
            store.setObjectiveManufacturer(objectiveManufacturer, 0, 0);
            // populate Objective Immersion
            final String immersion = firstFrame.getImmersion();
            store.setObjectiveImmersion(getImmersion(immersion), 0, 0);
            // populate Objective LensNA
            final Double lensNA = firstFrame.getObjectiveLensNA();
            if (lensNA != null)
                store.setObjectiveLensNA(lensNA, 0, 0);
            // populate Microscope Model
            final String microscopeModel = firstFrame.getImagingDevice();
            store.setMicroscopeModel(microscopeModel, 0);
        }
        // link ObjectiveSettings and Objective
        store.setObjectiveSettingsID(objectiveID, s);
        // populate stage position coordinates
        for (int t = 0; t < getSizeT(); t++) {
            final Sequence tSequence = sequence(t, s);
            for (int z = 0; z < getSizeZ(); z++) {
                final int index = frameIndex(tSequence, z, t, s);
                final Frame zFrame = tSequence.getFrame(index);
                if (zFrame == null) {
                    warnFrame(sequence, index);
                    continue;
                }
                final Length posX = zFrame.getPositionX();
                final Length posY = zFrame.getPositionY();
                final Length posZ = zFrame.getPositionZ();
                final Double deltaT = zFrame.getRelativeTime();
                for (int c = 0; c < getSizeC(); c++) {
                    final int i = getIndex(z, c, t);
                    if (posX != null)
                        store.setPlanePositionX(posX, s, i);
                    if (posY != null)
                        store.setPlanePositionY(posY, s, i);
                    if (posZ != null)
                        store.setPlanePositionZ(posZ, s, i);
                    if (deltaT != null)
                        store.setPlaneDeltaT(new Time(deltaT, UNITS.SECOND), s, i);
                }
            }
        }
    }
    setSeries(0);
}
Also used : Frame(loci.formats.in.PrairieMetadata.Frame) PFile(loci.formats.in.PrairieMetadata.PFile) Time(ome.units.quantity.Time) Sequence(loci.formats.in.PrairieMetadata.Sequence) Timestamp(ome.xml.model.primitives.Timestamp) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) PositiveFloat(ome.xml.model.primitives.PositiveFloat) Power(ome.units.quantity.Power)

Example 67 with Timestamp

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

the class KodakReader method readExtraMetadata.

private void readExtraMetadata(MetadataStore store) throws IOException {
    if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) {
        return;
    }
    in.seek(0);
    findString("Image Capture Source");
    String metadata = in.readCString();
    if (metadata == null) {
        return;
    }
    String[] lines = metadata.split("\n");
    for (String line : lines) {
        int index = line.indexOf(':');
        if (index < 0 || line.startsWith("#") || line.startsWith("-")) {
            continue;
        }
        String key = line.substring(0, index).trim();
        String value = line.substring(index + 1).trim();
        addGlobalMeta(key, value);
        if (key.equals("Image Capture Source")) {
            String instrument = MetadataTools.createLSID("Instrument", 0);
            store.setInstrumentID(instrument, 0);
            store.setImageInstrumentRef(instrument, 0);
            store.setMicroscopeModel(value, 0);
        } else if (key.equals("Capture Time/Date")) {
            String date = DateTools.formatDate(value, DATE_FORMAT);
            if (date != null) {
                store.setImageAcquisitionDate(new Timestamp(date), 0);
            }
        } else if (key.equals("Exposure Time")) {
            Double exposureTime = new Double(value.substring(0, value.indexOf(' ')));
            if (exposureTime != null) {
                store.setPlaneExposureTime(new Time(exposureTime, UNITS.SECOND), 0, 0);
            }
        } else if (key.equals("Vertical Resolution")) {
            // resolution stored in pixels per inch
            if (value.indexOf(' ') > 0) {
                value = value.substring(0, value.indexOf(' '));
            }
            Double size = new Double(value);
            size = 1.0 / (size * (1.0 / 25400));
            Length sizeY = FormatTools.getPhysicalSizeY(size);
            if (sizeY != null) {
                store.setPixelsPhysicalSizeY(sizeY, 0);
            }
        } else if (key.equals("Horizontal Resolution")) {
            // resolution stored in pixels per inch
            if (value.indexOf(' ') > 0) {
                value = value.substring(0, value.indexOf(' '));
            }
            Double size = new Double(value);
            size = 1.0 / (size * (1.0 / 25400));
            Length sizeX = FormatTools.getPhysicalSizeX(size);
            if (sizeX != null) {
                store.setPixelsPhysicalSizeX(sizeX, 0);
            }
        } else if (key.equals("CCD Temperature")) {
            Double temp;
            Matcher hexMatcher = Pattern.compile("0x([0-9A-F]+)").matcher(value);
            if (hexMatcher.matches()) {
                // CCD temperature stored as a hexadecimal string such as "0xEB".
                temp = new Double(Integer.parseInt(hexMatcher.group(1), 16));
                LOGGER.debug("CCD temperature detected as {}; assumed to be invalid", temp);
            } else {
                temp = new Double(value.substring(0, value.indexOf(' ')));
                store.setImagingEnvironmentTemperature(new Temperature(temp, UNITS.CELSIUS), 0);
            }
        }
    }
}
Also used : Temperature(ome.units.quantity.Temperature) Length(ome.units.quantity.Length) Matcher(java.util.regex.Matcher) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp)

Example 68 with Timestamp

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

the class LeicaHandler method startElement.

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) {
    if (attributes.getLength() > 0 && !qName.equals("Element") && !qName.equals("Attachment") && !qName.equals("LMSDataContainerHeader")) {
        nameStack.push(qName);
    }
    int oldSeriesCount = numDatasets;
    Hashtable h = getSeriesHashtable(numDatasets);
    if (qName.equals("LDM_Block_Sequential_Master")) {
        canParse = false;
    } else if (qName.startsWith("LDM")) {
        linkedInstruments = true;
    }
    if (!canParse)
        return;
    final StringBuilder key = new StringBuilder();
    final Iterator<String> nameStackIterator = nameStack.descendingIterator();
    while (nameStackIterator.hasNext()) {
        final String k = nameStackIterator.next();
        key.append(k);
        key.append("|");
    }
    String suffix = attributes.getValue("Identifier");
    String value = attributes.getValue("Variant");
    if (suffix == null)
        suffix = attributes.getValue("Description");
    if (level != MetadataLevel.MINIMUM) {
        if (suffix != null && value != null) {
            storeKeyValue(h, key.toString() + suffix, value);
        } else {
            for (int i = 0; i < attributes.getLength(); i++) {
                String name = attributes.getQName(i);
                storeKeyValue(h, key.toString() + name, attributes.getValue(i));
            }
        }
    }
    if (qName.equals("Element")) {
        elementName = attributes.getValue("Name");
    } else if (qName.equals("Collection")) {
        collection = elementName;
    } else if (qName.equals("Image")) {
        if (!linkedInstruments && level != MetadataLevel.MINIMUM) {
            int c = 0;
            for (Detector d : detectors) {
                String id = MetadataTools.createLSID("Detector", numDatasets, detectorChannel);
                store.setDetectorID(id, numDatasets, detectorChannel);
                try {
                    DetectorTypeEnumHandler handler = new DetectorTypeEnumHandler();
                    store.setDetectorType((DetectorType) handler.getEnumeration(d.type), numDatasets, detectorChannel);
                } catch (EnumerationException e) {
                }
                store.setDetectorModel(d.model, numDatasets, detectorChannel);
                store.setDetectorZoom(d.zoom, numDatasets, detectorChannel);
                store.setDetectorOffset(d.offset, numDatasets, detectorChannel);
                store.setDetectorVoltage(new ElectricPotential(d.voltage, UNITS.VOLT), numDatasets, detectorChannel);
                if (c < numChannels) {
                    if (d.active) {
                        store.setDetectorSettingsOffset(d.offset, numDatasets, c);
                        store.setDetectorSettingsID(id, numDatasets, c);
                        c++;
                    }
                }
                detectorChannel++;
            }
            int filter = 0;
            for (int i = 0; i < nextFilter; i++) {
                while (filter < detectors.size() && !detectors.get(filter).active) {
                    filter++;
                }
                if (filter >= detectors.size() || filter >= nextFilter)
                    break;
                String id = MetadataTools.createLSID("Filter", numDatasets, filter);
                if (i < numChannels && detectors.get(filter).active) {
                    String lsid = MetadataTools.createLSID("Channel", numDatasets, i);
                    store.setChannelID(lsid, numDatasets, i);
                    store.setLightPathEmissionFilterRef(id, numDatasets, i, 0);
                }
                filter++;
            }
        }
        core.add(new CoreMetadata());
        numDatasets++;
        laserCount = 0;
        linkedInstruments = false;
        detectorChannel = 0;
        detectors.clear();
        lasers.clear();
        nextFilter = 0;
        String name = elementName;
        if (collection != null)
            name = collection + "/" + name;
        store.setImageName(name, numDatasets);
        h = getSeriesHashtable(numDatasets);
        storeKeyValue(h, "Image name", name);
        storeSeriesHashtable(numDatasets, h);
        String instrumentID = MetadataTools.createLSID("Instrument", numDatasets);
        store.setInstrumentID(instrumentID, numDatasets);
        store.setImageInstrumentRef(instrumentID, numDatasets);
        numChannels = 0;
        extras = 1;
    } else if (qName.equals("Attachment") && level != MetadataLevel.MINIMUM) {
        if ("ContextDescription".equals(attributes.getValue("Name"))) {
            store.setImageDescription(attributes.getValue("Content"), numDatasets);
        }
    } else if (qName.equals("ChannelDescription")) {
        count++;
        numChannels++;
        lutNames.add(attributes.getValue("LUTName"));
        String bytesInc = attributes.getValue("BytesInc");
        int bytes = bytesInc == null ? 0 : Integer.parseInt(bytesInc);
        if (bytes > 0) {
            bytesPerAxis.put(new Integer(bytes), "C");
        }
    } else if (qName.equals("DimensionDescription")) {
        int len = Integer.parseInt(attributes.getValue("NumberOfElements"));
        int id = Integer.parseInt(attributes.getValue("DimID"));
        double physicalLen = Double.parseDouble(attributes.getValue("Length"));
        String unit = attributes.getValue("Unit");
        int nBytes = Integer.parseInt(attributes.getValue("BytesInc"));
        physicalLen /= len;
        if (unit.equals("Ks")) {
            physicalLen /= 1000;
        } else if (unit.equals("m")) {
            physicalLen *= 1000000;
        }
        Double physicalSize = new Double(physicalLen);
        CoreMetadata coreMeta = core.get(core.size() - 1);
        switch(id) {
            case // X axis
            1:
                coreMeta.sizeX = len;
                coreMeta.rgb = (nBytes % 3) == 0;
                if (coreMeta.rgb)
                    nBytes /= 3;
                switch(nBytes) {
                    case 1:
                        coreMeta.pixelType = FormatTools.UINT8;
                        break;
                    case 2:
                        coreMeta.pixelType = FormatTools.UINT16;
                        break;
                    case 4:
                        coreMeta.pixelType = FormatTools.FLOAT;
                        break;
                }
                physicalSizeX = physicalSize.doubleValue();
                Length sizeX = FormatTools.getPhysicalSizeX(physicalSize);
                if (sizeX != null) {
                    store.setPixelsPhysicalSizeX(sizeX, numDatasets);
                }
                break;
            case // Y axis
            2:
                if (coreMeta.sizeY != 0) {
                    if (coreMeta.sizeZ == 1) {
                        coreMeta.sizeZ = len;
                        bytesPerAxis.put(new Integer(nBytes), "Z");
                    } else if (coreMeta.sizeT == 1) {
                        coreMeta.sizeT = len;
                        bytesPerAxis.put(new Integer(nBytes), "T");
                    }
                } else {
                    coreMeta.sizeY = len;
                    physicalSizeY = physicalSize.doubleValue();
                    Length sizeY = FormatTools.getPhysicalSizeY(physicalSize);
                    if (sizeY != null) {
                        store.setPixelsPhysicalSizeY(sizeY, numDatasets);
                    }
                }
                break;
            case // Z axis
            3:
                if (coreMeta.sizeY == 0) {
                    // XZ scan - swap Y and Z
                    coreMeta.sizeY = len;
                    coreMeta.sizeZ = 1;
                    physicalSizeY = physicalSize.doubleValue();
                    Length sizeY = FormatTools.getPhysicalSizeY(physicalSize);
                    if (sizeY != null) {
                        store.setPixelsPhysicalSizeY(sizeY, numDatasets);
                    }
                    bytesPerAxis.put(new Integer(nBytes), "Y");
                } else {
                    coreMeta.sizeZ = len;
                    bytesPerAxis.put(new Integer(nBytes), "Z");
                }
                break;
            case // T axis
            4:
                if (coreMeta.sizeY == 0) {
                    // XT scan - swap Y and T
                    coreMeta.sizeY = len;
                    coreMeta.sizeT = 1;
                    physicalSizeY = physicalSize.doubleValue();
                    Length sizeY = FormatTools.getPhysicalSizeY(physicalSize);
                    if (sizeY != null) {
                        store.setPixelsPhysicalSizeY(sizeY, numDatasets);
                    }
                    bytesPerAxis.put(new Integer(nBytes), "Y");
                } else {
                    coreMeta.sizeT = len;
                    bytesPerAxis.put(new Integer(nBytes), "T");
                }
                break;
            default:
                extras *= len;
        }
        count++;
    } else if (qName.equals("ScannerSettingRecord") && level != MetadataLevel.MINIMUM) {
        String id = attributes.getValue("Identifier");
        if (id == null)
            id = "";
        if (id.equals("SystemType")) {
            store.setMicroscopeModel(value, numDatasets);
            store.setMicroscopeType(MicroscopeType.OTHER, numDatasets);
        } else if (id.equals("dblPinhole")) {
            pinhole = new Double(Double.parseDouble(value) * 1000000);
        } else if (id.equals("dblZoom")) {
            zoom = new Double(value);
        } else if (id.equals("dblStepSize")) {
            double zStep = Double.parseDouble(value) * 1000000;
            Length sizeZ = FormatTools.getPhysicalSizeZ(zStep);
            if (sizeZ != null) {
                store.setPixelsPhysicalSizeZ(sizeZ, numDatasets);
            }
        } else if (id.equals("nDelayTime_s")) {
            Double timeIncrement = new Double(value);
            if (timeIncrement != null) {
                store.setPixelsTimeIncrement(new Time(timeIncrement, UNITS.SECOND), numDatasets);
            }
        } else if (id.equals("CameraName")) {
            store.setDetectorModel(value, numDatasets, 0);
        } else if (id.indexOf("WFC") == 1) {
            int c = 0;
            try {
                c = Integer.parseInt(id.replaceAll("\\D", ""));
            } catch (NumberFormatException e) {
            }
            Channel channel = channels.get(numDatasets + "-" + c);
            if (channel == null)
                channel = new Channel();
            if (id.endsWith("ExposureTime") && c < numChannels) {
                try {
                    Double exposureTime = new Double(value);
                    if (exposureTime != null) {
                        store.setPlaneExposureTime(new Time(exposureTime, UNITS.SECOND), numDatasets, c);
                    }
                } catch (IndexOutOfBoundsException e) {
                }
            } else if (id.endsWith("Gain")) {
                channel.gain = new Double(value);
                String detectorID = MetadataTools.createLSID("Detector", numDatasets, 0);
                channel.detector = detectorID;
                store.setDetectorID(detectorID, numDatasets, 0);
                store.setDetectorType(DetectorType.CCD, numDatasets, 0);
            } else if (id.endsWith("WaveLength")) {
                Double exWave = new Double(value);
                Length ex = FormatTools.getExcitationWavelength(exWave);
                if (ex != null) {
                    channel.exWave = ex;
                }
            } else // NB: "UesrDefName" is not a typo.
            if (id.endsWith("UesrDefName") && !value.equals("None")) {
                channel.name = value;
            }
            channels.put(numDatasets + "-" + c, channel);
        }
    } else if (qName.equals("FilterSettingRecord") && level != MetadataLevel.MINIMUM) {
        String object = attributes.getValue("ObjectName");
        String attribute = attributes.getValue("Attribute");
        String objectClass = attributes.getValue("ClassName");
        String variant = attributes.getValue("Variant");
        CoreMetadata coreMeta = core.get(numDatasets);
        if (attribute.equals("NumericalAperture")) {
            store.setObjectiveLensNA(new Double(variant), numDatasets, 0);
        } else if (attribute.equals("OrderNumber")) {
            store.setObjectiveSerialNumber(variant, numDatasets, 0);
        } else if (objectClass.equals("CDetectionUnit")) {
            if (attribute.equals("State")) {
                Detector d = new Detector();
                String data = attributes.getValue("data");
                if (data == null)
                    data = attributes.getValue("Data");
                d.channel = data == null ? 0 : Integer.parseInt(data);
                d.type = "PMT";
                d.model = object;
                d.active = variant.equals("Active");
                d.zoom = zoom;
                detectors.add(d);
            } else if (attribute.equals("HighVoltage")) {
                Detector d = detectors.get(detectors.size() - 1);
                d.voltage = new Double(variant);
            } else if (attribute.equals("VideoOffset")) {
                Detector d = detectors.get(detectors.size() - 1);
                d.offset = new Double(variant);
            }
        } else if (attribute.equals("Objective")) {
            StringTokenizer tokens = new StringTokenizer(variant, " ");
            boolean foundMag = false;
            final StringBuilder model = new StringBuilder();
            while (!foundMag) {
                String token = tokens.nextToken();
                int x = token.indexOf('x');
                if (x != -1) {
                    foundMag = true;
                    Double mag = Double.parseDouble(token.substring(0, x));
                    String na = token.substring(x + 1);
                    store.setObjectiveNominalMagnification(mag, numDatasets, 0);
                    store.setObjectiveLensNA(new Double(na), numDatasets, 0);
                } else {
                    model.append(token);
                    model.append(" ");
                }
            }
            String immersion = "Other";
            if (tokens.hasMoreTokens()) {
                immersion = tokens.nextToken();
                if (immersion == null || immersion.trim().equals("")) {
                    immersion = "Other";
                }
            }
            try {
                ImmersionEnumHandler handler = new ImmersionEnumHandler();
                store.setObjectiveImmersion((Immersion) handler.getEnumeration(immersion), numDatasets, 0);
            } catch (EnumerationException e) {
            }
            String correction = "Other";
            if (tokens.hasMoreTokens()) {
                correction = tokens.nextToken();
                if (correction == null || correction.trim().equals("")) {
                    correction = "Other";
                }
            }
            try {
                CorrectionEnumHandler handler = new CorrectionEnumHandler();
                store.setObjectiveCorrection((Correction) handler.getEnumeration(correction), numDatasets, 0);
            } catch (EnumerationException e) {
            }
            store.setObjectiveModel(model.toString().trim(), numDatasets, 0);
        } else if (attribute.equals("RefractionIndex")) {
            String id = MetadataTools.createLSID("Objective", numDatasets, 0);
            store.setObjectiveID(id, numDatasets, 0);
            store.setObjectiveSettingsID(id, numDatasets);
            store.setObjectiveSettingsRefractiveIndex(new Double(variant), numDatasets);
        } else if (attribute.equals("XPos")) {
            int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
            int nPlanes = coreMeta.imageCount;
            final Double posXn = Double.valueOf(variant);
            final Length posXl = new Length(posXn, UNITS.REFERENCEFRAME);
            for (int image = 0; image < nPlanes; image++) {
                store.setPlanePositionX(posXl, numDatasets, image);
            }
            if (numChannels == 0)
                xPos.add(posXl);
        } else if (attribute.equals("YPos")) {
            int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
            int nPlanes = coreMeta.imageCount;
            final Double posYn = Double.valueOf(variant);
            final Length posYl = new Length(posYn, UNITS.REFERENCEFRAME);
            for (int image = 0; image < nPlanes; image++) {
                store.setPlanePositionY(posYl, numDatasets, image);
            }
            if (numChannels == 0)
                yPos.add(posYl);
        } else if (attribute.equals("ZPos")) {
            int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
            int nPlanes = coreMeta.imageCount;
            final Double posZn = Double.valueOf(variant);
            final Length posZl = new Length(posZn, UNITS.REFERENCEFRAME);
            for (int image = 0; image < nPlanes; image++) {
                store.setPlanePositionZ(posZl, numDatasets, image);
            }
            if (numChannels == 0)
                zPos.add(posZl);
        } else if (objectClass.equals("CSpectrophotometerUnit")) {
            Double v = null;
            try {
                v = Double.parseDouble(variant);
            } catch (NumberFormatException e) {
            }
            if (attributes.getValue("Description").endsWith("(left)")) {
                String id = MetadataTools.createLSID("Filter", numDatasets, nextFilter);
                store.setFilterID(id, numDatasets, nextFilter);
                store.setFilterModel(object, numDatasets, nextFilter);
                Length in = FormatTools.getCutIn(v);
                if (in != null) {
                    store.setTransmittanceRangeCutIn(in, numDatasets, nextFilter);
                }
            } else if (attributes.getValue("Description").endsWith("(right)")) {
                Length out = FormatTools.getCutOut(v);
                if (out != null) {
                    store.setTransmittanceRangeCutOut(out, numDatasets, nextFilter);
                    nextFilter++;
                }
            }
        }
    } else if (qName.equals("Detector") && level != MetadataLevel.MINIMUM) {
        String v = attributes.getValue("Gain");
        Double gain = v == null ? null : new Double(v);
        v = attributes.getValue("Offset");
        Double offset = v == null ? null : new Double(v);
        boolean active = "1".equals(attributes.getValue("IsActive"));
        if (active) {
            // find the corresponding MultiBand and Detector
            MultiBand m = null;
            Detector detector = null;
            Laser laser = lasers.isEmpty() ? null : lasers.get(lasers.size() - 1);
            String c = attributes.getValue("Channel");
            int channel = c == null ? 0 : Integer.parseInt(c);
            for (MultiBand mb : multiBands) {
                if (mb.channel == channel) {
                    m = mb;
                    break;
                }
            }
            for (Detector d : detectors) {
                if (d.channel == channel) {
                    detector = d;
                    break;
                }
            }
            String id = MetadataTools.createLSID("Detector", numDatasets, nextChannel);
            if (m != null) {
                String channelID = MetadataTools.createLSID("Channel", numDatasets, nextChannel);
                store.setChannelID(channelID, numDatasets, nextChannel);
                store.setChannelName(m.dyeName, numDatasets, nextChannel);
                String filter = MetadataTools.createLSID("Filter", numDatasets, nextFilter);
                store.setFilterID(filter, numDatasets, nextFilter);
                Length in = FormatTools.getCutIn(m.cutIn);
                Length out = FormatTools.getCutOut(m.cutOut);
                if (in != null) {
                    store.setTransmittanceRangeCutIn(in, numDatasets, nextFilter);
                }
                if (out != null) {
                    store.setTransmittanceRangeCutOut(out, numDatasets, nextFilter);
                }
                store.setLightPathEmissionFilterRef(filter, numDatasets, nextChannel, 0);
                nextFilter++;
                store.setDetectorID(id, numDatasets, nextChannel);
                store.setDetectorType(DetectorType.PMT, numDatasets, nextChannel);
                store.setDetectorSettingsGain(gain, numDatasets, nextChannel);
                store.setDetectorSettingsOffset(offset, numDatasets, nextChannel);
                store.setDetectorSettingsID(id, numDatasets, nextChannel);
            }
            store.setDetectorID(id, numDatasets, nextChannel);
            if (detector != null) {
                store.setDetectorSettingsGain(gain, numDatasets, nextChannel);
                store.setDetectorSettingsOffset(offset, numDatasets, nextChannel);
                store.setDetectorSettingsID(id, numDatasets, nextChannel);
                try {
                    DetectorTypeEnumHandler handler = new DetectorTypeEnumHandler();
                    store.setDetectorType((DetectorType) handler.getEnumeration(detector.type), numDatasets, nextChannel);
                } catch (EnumerationException e) {
                }
                store.setDetectorModel(detector.model, numDatasets, nextChannel);
                store.setDetectorZoom(detector.zoom, numDatasets, nextChannel);
                store.setDetectorOffset(detector.offset, numDatasets, nextChannel);
                store.setDetectorVoltage(new ElectricPotential(detector.voltage, UNITS.VOLT), numDatasets, nextChannel);
            }
            if (laser != null && laser.intensity < 100) {
                store.setChannelLightSourceSettingsID(laser.id, numDatasets, nextChannel);
                store.setChannelLightSourceSettingsAttenuation(new PercentFraction((float) laser.intensity / 100f), numDatasets, nextChannel);
                Length wavelength = FormatTools.getExcitationWavelength(laser.wavelength);
                if (wavelength != null) {
                    store.setChannelExcitationWavelength(wavelength, numDatasets, nextChannel);
                }
            }
            nextChannel++;
        }
    } else if (qName.equals("LaserLineSetting") && level != MetadataLevel.MINIMUM) {
        Laser l = new Laser();
        String lineIndex = attributes.getValue("LineIndex");
        String qual = attributes.getValue("Qualifier");
        l.index = lineIndex == null ? 0 : Integer.parseInt(lineIndex);
        int qualifier = qual == null ? 0 : Integer.parseInt(qual);
        l.index += (2 - (qualifier / 10));
        if (l.index < 0)
            l.index = 0;
        l.id = MetadataTools.createLSID("LightSource", numDatasets, l.index);
        l.wavelength = new Double(attributes.getValue("LaserLine"));
        while (l.index > laserCount) {
            String lsid = MetadataTools.createLSID("LightSource", numDatasets, laserCount);
            store.setLaserID(lsid, numDatasets, laserCount);
            laserCount++;
        }
        store.setLaserID(l.id, numDatasets, l.index);
        laserCount++;
        Length wavelength = FormatTools.getWavelength(l.wavelength);
        if (wavelength != null) {
            store.setLaserWavelength(wavelength, numDatasets, l.index);
        }
        store.setLaserType(LaserType.OTHER, numDatasets, l.index);
        store.setLaserLaserMedium(LaserMedium.OTHER, numDatasets, l.index);
        String intensity = attributes.getValue("IntensityDev");
        l.intensity = intensity == null ? 0d : Double.parseDouble(intensity);
        if (l.intensity > 0) {
            l.intensity = 100d - l.intensity;
            lasers.add(l);
        }
    } else if (qName.equals("TimeStamp") && numDatasets >= 0) {
        String stampHigh = attributes.getValue("HighInteger");
        String stampLow = attributes.getValue("LowInteger");
        long high = stampHigh == null ? 0 : Long.parseLong(stampHigh);
        long low = stampLow == null ? 0 : Long.parseLong(stampLow);
        long ms = DateTools.getMillisFromTicks(high, low);
        if (count == 0) {
            String date = DateTools.convertDate(ms, DateTools.COBOL);
            Timestamp timestamp = Timestamp.valueOf(date);
            if (timestamp != null && timestamp.asInstant().getMillis() < System.currentTimeMillis()) {
                store.setImageAcquisitionDate(new Timestamp(date), numDatasets);
            }
            firstStamp = ms;
            store.setPlaneDeltaT(new Time(0.0, UNITS.SECOND), numDatasets, count);
        } else if (level != MetadataLevel.MINIMUM) {
            CoreMetadata coreMeta = core.get(numDatasets);
            int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC;
            if (count < nImages) {
                ms -= firstStamp;
                store.setPlaneDeltaT(new Time(ms / 1000.0, UNITS.SECOND), numDatasets, count);
            }
        }
        count++;
    } else if (qName.equals("RelTimeStamp") && level != MetadataLevel.MINIMUM) {
        CoreMetadata coreMeta = core.get(numDatasets);
        int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC;
        if (count < nImages) {
            Double time = new Double(attributes.getValue("Time"));
            if (time != null) {
                store.setPlaneDeltaT(new Time(time, UNITS.SECOND), numDatasets, count++);
            }
        }
    } else if (qName.equals("Annotation") && level != MetadataLevel.MINIMUM) {
        roi = new ROI();
        String type = attributes.getValue("type");
        if (type != null)
            roi.type = Integer.parseInt(type);
        String color = attributes.getValue("color");
        if (color != null)
            roi.color = Integer.parseInt(color);
        roi.name = attributes.getValue("name");
        roi.fontName = attributes.getValue("fontName");
        roi.fontSize = attributes.getValue("fontSize");
        roi.transX = parseDouble(attributes.getValue("transTransX"));
        roi.transY = parseDouble(attributes.getValue("transTransY"));
        roi.scaleX = parseDouble(attributes.getValue("transScalingX"));
        roi.scaleY = parseDouble(attributes.getValue("transScalingY"));
        roi.rotation = parseDouble(attributes.getValue("transRotation"));
        String linewidth = attributes.getValue("linewidth");
        if (linewidth != null)
            roi.linewidth = Integer.parseInt(linewidth);
        roi.text = attributes.getValue("text");
    } else if (qName.equals("Vertex") && level != MetadataLevel.MINIMUM) {
        String x = attributes.getValue("x");
        String y = attributes.getValue("y");
        if (x != null) {
            x = x.replaceAll(",", ".");
            roi.x.add(new Double(x));
        }
        if (y != null) {
            y = y.replaceAll(",", ".");
            roi.y.add(new Double(y));
        }
    } else if (qName.equals("ROI")) {
        alternateCenter = true;
    } else if (qName.equals("MultiBand") && level != MetadataLevel.MINIMUM) {
        MultiBand m = new MultiBand();
        m.dyeName = attributes.getValue("DyeName");
        m.channel = Integer.parseInt(attributes.getValue("Channel"));
        m.cutIn = (double) Math.round(Double.parseDouble(attributes.getValue("LeftWorld")));
        m.cutOut = (double) Math.round(Double.parseDouble(attributes.getValue("RightWorld")));
        multiBands.add(m);
    } else if (qName.equals("ChannelInfo")) {
        int index = Integer.parseInt(attributes.getValue("Index"));
        channels.remove(numDatasets + "-" + index);
    } else
        count = 0;
    if (numDatasets == oldSeriesCount)
        storeSeriesHashtable(numDatasets, h);
}
Also used : Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp) DetectorTypeEnumHandler(ome.xml.model.enums.handlers.DetectorTypeEnumHandler) Hashtable(java.util.Hashtable) ElectricPotential(ome.units.quantity.ElectricPotential) CoreMetadata(loci.formats.CoreMetadata) ImmersionEnumHandler(ome.xml.model.enums.handlers.ImmersionEnumHandler) StringTokenizer(java.util.StringTokenizer) Length(ome.units.quantity.Length) CorrectionEnumHandler(ome.xml.model.enums.handlers.CorrectionEnumHandler) PercentFraction(ome.xml.model.primitives.PercentFraction) EnumerationException(ome.xml.model.enums.EnumerationException)

Example 69 with Timestamp

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

the class MIASReader method parseTemplateFile.

/**
 * Parse metadata from the Nugenesistemplate.txt file.
 */
private void parseTemplateFile(MetadataStore store) throws IOException {
    if (templateFile == null)
        return;
    Double physicalSizeX = null, physicalSizeY = null, exposure = null;
    final List<String> channelNames = new ArrayList<String>();
    String date = null;
    String data = DataTools.readFile(templateFile);
    String[] lines = data.split("\r\n");
    for (String line : lines) {
        int eq = line.indexOf('=');
        if (eq != -1) {
            String key = line.substring(0, eq);
            String value = line.substring(eq + 1);
            if (key.equals("Barcode")) {
                store.setPlateExternalIdentifier(value, 0);
            } else if (key.equals("Carrier")) {
                store.setPlateName(value, 0);
            } else if (key.equals("Pixel_X")) {
                physicalSizeX = new Double(value);
            } else if (key.equals("Pixel_Y")) {
                physicalSizeY = new Double(value);
            } else if (key.equals("Objective_ID")) {
                store.setObjectiveID(MetadataTools.createLSID("Objective", 0, 0), 0, 0);
                store.setObjectiveModel(value, 0, 0);
            } else if (key.equals("Magnification")) {
                Double mag = Double.parseDouble(value);
                store.setObjectiveNominalMagnification(mag, 0, 0);
            } else if (key.startsWith("Mode_")) {
                channelNames.add(value);
            } else if (key.equals("Date")) {
                date = value;
            } else if (key.equals("Time")) {
                date += " " + value;
            } else if (key.equals("Exposure")) {
                exposure = new Double(value);
            }
        }
    }
    for (int well = 0; well < tiffs.length; well++) {
        Length sizeX = FormatTools.getPhysicalSizeX(physicalSizeX);
        Length sizeY = FormatTools.getPhysicalSizeY(physicalSizeY);
        if (sizeX != null) {
            store.setPixelsPhysicalSizeX(sizeX, well);
        }
        if (sizeY != null) {
            store.setPixelsPhysicalSizeY(sizeY, well);
        }
        for (int c = 0; c < channelNames.size(); c++) {
            if (c < getEffectiveSizeC()) {
                store.setChannelName(channelNames.get(c), well, c);
            }
        }
        date = DateTools.formatDate(date, "dd/MM/yyyy HH:mm:ss");
        if (date != null) {
            store.setImageAcquisitionDate(new Timestamp(date), well);
        }
        if (exposure != null) {
            for (int i = 0; i < getImageCount(); i++) {
                store.setPlaneExposureTime(new Time(exposure, UNITS.SECOND), well, i);
            }
        }
    }
}
Also used : Length(ome.units.quantity.Length) ArrayList(java.util.ArrayList) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp)

Example 70 with Timestamp

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

the class ImarisTiffReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    // hack up the IFDs
    // 
    // Imaris TIFFs store a thumbnail in the first IFD; each of the remaining
    // IFDs defines a stack of tiled planes.
    // MinimalTiffReader.initFile(String) removes thumbnail IFDs.
    LOGGER.info("Verifying IFD sanity");
    IFDList tmp = new IFDList();
    for (IFD ifd : ifds) {
        long[] byteCounts = ifd.getStripByteCounts();
        long[] offsets = ifd.getStripOffsets();
        for (int i = 0; i < byteCounts.length; i++) {
            IFD t = new IFD(ifd);
            t.putIFDValue(IFD.TILE_BYTE_COUNTS, byteCounts[i]);
            t.putIFDValue(IFD.TILE_OFFSETS, offsets[i]);
            tmp.add(t);
        }
    }
    String comment = ifds.get(0).getComment();
    LOGGER.info("Populating metadata");
    CoreMetadata m = core.get(0);
    m.sizeC = ifds.size();
    m.sizeZ = tmp.size() / getSizeC();
    m.sizeT = 1;
    m.sizeX = (int) ifds.get(0).getImageWidth();
    m.sizeY = (int) ifds.get(0).getImageLength();
    ifds = tmp;
    m.imageCount = getSizeC() * getSizeZ();
    m.dimensionOrder = "XYZCT";
    m.interleaved = false;
    m.rgb = getImageCount() != getSizeZ() * getSizeC() * getSizeT();
    m.pixelType = ifds.get(0).getPixelType();
    LOGGER.info("Parsing comment");
    // likely an INI-style comment, although we can't be sure
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        String description = null, creationDate = null;
        final List<Double> emWave = new ArrayList<Double>();
        final List<Double> exWave = new ArrayList<Double>();
        final List<String> channelNames = new ArrayList<String>();
        if (comment != null && comment.startsWith("[")) {
            // parse key/value pairs
            StringTokenizer st = new StringTokenizer(comment, "\n");
            while (st.hasMoreTokens()) {
                String line = st.nextToken();
                int equals = line.indexOf('=');
                if (equals < 0)
                    continue;
                String key = line.substring(0, equals).trim();
                String value = line.substring(equals + 1).trim();
                addGlobalMeta(key, value);
                if (key.equals("Description")) {
                    description = value;
                } else if (key.equals("LSMEmissionWavelength") && !value.equals("0")) {
                    emWave.add(new Double(value));
                } else if (key.equals("LSMExcitationWavelength") && !value.equals("0")) {
                    exWave.add(new Double(value));
                } else if (key.equals("Name") && !currentId.endsWith(value)) {
                    channelNames.add(value);
                } else if (key.equals("RecordingDate")) {
                    value = value.replaceAll(" ", "T");
                    creationDate = value.substring(0, value.indexOf('.'));
                }
            }
            metadata.remove("Comment");
        }
        // populate Image data
        store.setImageDescription(description, 0);
        if (creationDate != null) {
            store.setImageAcquisitionDate(new Timestamp(creationDate), 0);
        }
        // populate LogicalChannel data
        for (int i = 0; i < emWave.size(); i++) {
            Length emission = FormatTools.getEmissionWavelength(emWave.get(i));
            Length excitation = FormatTools.getExcitationWavelength(exWave.get(i));
            if (emission != null) {
                store.setChannelEmissionWavelength(emission, 0, i);
            }
            if (excitation != null) {
                store.setChannelExcitationWavelength(excitation, 0, i);
            }
            store.setChannelName(channelNames.get(i), 0, i);
        }
    }
}
Also used : IFD(loci.formats.tiff.IFD) ArrayList(java.util.ArrayList) CoreMetadata(loci.formats.CoreMetadata) Timestamp(ome.xml.model.primitives.Timestamp) MetadataStore(loci.formats.meta.MetadataStore) StringTokenizer(java.util.StringTokenizer) Length(ome.units.quantity.Length) IFDList(loci.formats.tiff.IFDList)

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