Search in sources :

Example 1 with PercentFraction

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

use of ome.xml.model.primitives.PercentFraction 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)

Aggregations

CoreMetadata (loci.formats.CoreMetadata)2 Length (ome.units.quantity.Length)2 Time (ome.units.quantity.Time)2 PercentFraction (ome.xml.model.primitives.PercentFraction)2 Timestamp (ome.xml.model.primitives.Timestamp)2 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 Hashtable (java.util.Hashtable)1 StringTokenizer (java.util.StringTokenizer)1 DependencyException (loci.common.services.DependencyException)1 ServiceException (loci.common.services.ServiceException)1 ServiceFactory (loci.common.services.ServiceFactory)1 FormatException (loci.formats.FormatException)1 MetadataStore (loci.formats.meta.MetadataStore)1 OMEXMLService (loci.formats.services.OMEXMLService)1 ElectricPotential (ome.units.quantity.ElectricPotential)1 EnumerationException (ome.xml.model.enums.EnumerationException)1 CorrectionEnumHandler (ome.xml.model.enums.handlers.CorrectionEnumHandler)1 DetectorTypeEnumHandler (ome.xml.model.enums.handlers.DetectorTypeEnumHandler)1 ImmersionEnumHandler (ome.xml.model.enums.handlers.ImmersionEnumHandler)1