Search in sources :

Example 1 with ElectricPotential

use of ome.units.quantity.ElectricPotential in project bioformats by openmicroscopy.

the class LeicaReader method parseInstrumentData.

private void parseInstrumentData(MetadataStore store, int blockNum) throws FormatException, IOException {
    int series = getSeries();
    // read 24 byte SAFEARRAY
    in.skipBytes(4);
    int cbElements = in.readInt();
    in.skipBytes(8);
    int nElements = in.readInt();
    in.skipBytes(4);
    long initialOffset = in.getFilePointer();
    long elementOffset = 0;
    LOGGER.trace("Element LOOP; series {} at offset {}", series, initialOffset);
    for (int j = 0; j < nElements; j++) {
        elementOffset = initialOffset + j * cbElements;
        LOGGER.trace("Seeking to: {}", elementOffset);
        in.seek(elementOffset);
        String contentID = getString(128);
        LOGGER.trace("contentID: {}", contentID);
        String description = getString(64);
        LOGGER.trace("description: {}", description);
        String data = getString(64);
        int dataType = in.readShort();
        LOGGER.trace("dataType: {}", dataType);
        in.skipBytes(6);
        // read data
        switch(dataType) {
            case 2:
                data = String.valueOf(in.readShort());
                break;
            case 3:
                data = String.valueOf(in.readInt());
                break;
            case 4:
                data = String.valueOf(in.readFloat());
                break;
            case 5:
                data = String.valueOf(in.readDouble());
                break;
            case 7:
            case 11:
                data = in.read() == 0 ? "false" : "true";
                break;
            case 17:
                data = in.readString(1);
                break;
        }
        LOGGER.trace("data: {}", data);
        if (data.trim().length() == 0) {
            LOGGER.trace("Zero length dat string, continuing...");
            continue;
        }
        String[] tokens = contentID.split("\\|");
        LOGGER.trace("Parsing tokens: {}", tokens);
        if (tokens[0].startsWith("CDetectionUnit")) {
            if (tokens[1].startsWith("PMT")) {
                // detector information
                Detector detector = new Detector();
                int lastDetector = detectors.size() - 1;
                if (detectors.size() > 0 && detectors.get(lastDetector).id == Integer.parseInt(tokens[3])) {
                    detector = detectors.get(lastDetector);
                } else {
                    detectors.add(detector);
                }
                detector.id = Integer.parseInt(tokens[3]);
                detector.name = tokens[1];
                try {
                    if (tokens[2].equals("VideoOffset")) {
                        detector.offset = new Double(data);
                    } else if (tokens[2].equals("HighVoltage")) {
                        detector.voltage = new Double(data);
                    } else if (tokens[2].equals("State")) {
                        detector.active = data.equals("Active");
                        String index = tokens[1].substring(tokens[1].indexOf(' ') + 1);
                        detector.index = -1;
                        try {
                            detector.index = Integer.parseInt(index) - 1;
                        } catch (NumberFormatException e) {
                        }
                        if (detector.active && detector.index >= 0) {
                            activeChannelIndices.add(detector.index);
                        }
                    }
                } catch (NumberFormatException e) {
                    LOGGER.debug("Failed to parse detector metadata", e);
                }
            }
        } else if (tokens[0].startsWith("CTurret")) {
            // objective information
            int objective = Integer.parseInt(tokens[3]);
            if (tokens[2].equals("NumericalAperture")) {
                store.setObjectiveLensNA(new Double(data), series, objective);
            } else if (tokens[2].equals("Objective")) {
                String[] objectiveData = data.split(" ");
                final StringBuilder model = new StringBuilder();
                String mag = null, na = null;
                String immersion = null, correction = null;
                for (int i = 0; i < objectiveData.length; i++) {
                    if (objectiveData[i].indexOf('x') != -1 && mag == null && na == null) {
                        int xIndex = objectiveData[i].indexOf('x');
                        mag = objectiveData[i].substring(0, xIndex).trim();
                        na = objectiveData[i].substring(xIndex + 1).trim();
                    } else if (mag == null && na == null) {
                        model.append(objectiveData[i]);
                        model.append(" ");
                    } else if (correction == null) {
                        correction = objectiveData[i];
                    } else if (immersion == null) {
                        immersion = objectiveData[i];
                    }
                }
                if (immersion != null)
                    immersion = immersion.trim();
                if (correction != null)
                    correction = correction.trim();
                Correction realCorrection = getCorrection(correction);
                Correction testCorrection = getCorrection(immersion);
                Immersion realImmersion = getImmersion(immersion);
                Immersion testImmersion = getImmersion(correction);
                // Correction and Immersion are reversed
                if ((testCorrection != Correction.OTHER && realCorrection == Correction.OTHER) || (testImmersion != Immersion.OTHER && realImmersion == Immersion.OTHER)) {
                    String tmp = correction;
                    correction = immersion;
                    immersion = tmp;
                }
                store.setObjectiveImmersion(getImmersion(immersion), series, objective);
                store.setObjectiveCorrection(getCorrection(correction), series, objective);
                store.setObjectiveModel(model.toString().trim(), series, objective);
                store.setObjectiveLensNA(new Double(na), series, objective);
                Double magnification = Double.parseDouble(mag);
                store.setObjectiveNominalMagnification(magnification, series, objective);
            } else if (tokens[2].equals("OrderNumber")) {
                store.setObjectiveSerialNumber(data, series, objective);
            } else if (tokens[2].equals("RefractionIndex")) {
                store.setObjectiveSettingsRefractiveIndex(new Double(data), series);
            }
            // link Objective to Image
            String objectiveID = MetadataTools.createLSID("Objective", series, objective);
            store.setObjectiveID(objectiveID, series, objective);
            if (objective == 0) {
                store.setObjectiveSettingsID(objectiveID, series);
            }
        } else if (tokens[0].startsWith("CSpectrophotometerUnit")) {
            int ndx = tokens[1].lastIndexOf(" ");
            int channel = Integer.parseInt(tokens[1].substring(ndx + 1)) - 1;
            if (tokens[2].equals("Wavelength")) {
                Double wavelength = Double.parseDouble(data);
                store.setFilterModel(tokens[1], series, channel);
                String filterID = MetadataTools.createLSID("Filter", series, channel);
                store.setFilterID(filterID, series, channel);
                int index = activeChannelIndices.indexOf(channel);
                if (index >= 0 && index < getEffectiveSizeC()) {
                    if (!filterRefPopulated[series][index]) {
                        store.setLightPathEmissionFilterRef(filterID, series, index, 0);
                        filterRefPopulated[series][index] = true;
                    }
                    if (tokens[3].equals("0") && !cutInPopulated[series][index]) {
                        Length cutIn = FormatTools.getCutIn(wavelength);
                        if (cutIn != null) {
                            store.setTransmittanceRangeCutIn(cutIn, series, channel);
                        }
                        cutInPopulated[series][index] = true;
                    } else if (tokens[3].equals("1") && !cutOutPopulated[series][index]) {
                        Length cutOut = FormatTools.getCutOut(wavelength);
                        if (cutOut != null) {
                            store.setTransmittanceRangeCutOut(cutOut, series, channel);
                        }
                        cutOutPopulated[series][index] = true;
                    }
                }
            } else if (tokens[2].equals("Stain")) {
                if (activeChannelIndices.contains(channel)) {
                    int nNames = channelNames[series].size();
                    String prevValue = nNames == 0 ? "" : (String) channelNames[series].get(nNames - 1);
                    if (!prevValue.equals(data)) {
                        channelNames[series].add(data);
                    }
                }
            }
        } else if (tokens[0].startsWith("CXYZStage")) {
            CoreMetadata ms = core.get(series);
            // NB: there is only one stage position specified for each series
            if (tokens[2].equals("XPos")) {
                for (int q = 0; q < ms.imageCount; q++) {
                    final Double number = Double.valueOf(data);
                    final Length length = new Length(number, UNITS.REFERENCEFRAME);
                    store.setPlanePositionX(length, series, q);
                    if (q == 0) {
                        addGlobalMetaList("X position for position", data);
                    }
                }
            } else if (tokens[2].equals("YPos")) {
                for (int q = 0; q < ms.imageCount; q++) {
                    final Double number = Double.valueOf(data);
                    final Length length = new Length(number, UNITS.REFERENCEFRAME);
                    store.setPlanePositionY(length, series, q);
                    if (q == 0) {
                        addGlobalMetaList("Y position for position", data);
                    }
                }
            } else if (tokens[2].equals("ZPos")) {
                final Double number = Double.valueOf(data);
                final Length length = new Length(number, UNITS.REFERENCEFRAME);
                store.setStageLabelName("Position", series);
                store.setStageLabelZ(length, series);
                addGlobalMetaList("Z position for position", data);
            }
        } else if (tokens[0].equals("CScanActuator") && tokens[1].equals("Z Scan Actuator") && tokens[2].equals("Position")) {
            final double pos = Double.parseDouble(data) * 1000000;
            store.setStageLabelName("Position", series);
            store.setStageLabelZ(new Length(pos, UNITS.REFERENCEFRAME), series);
            addGlobalMetaList("Z position for position", pos);
        }
        if (contentID.equals("dblVoxelX")) {
            physicalSizes[series][0] = Double.parseDouble(data);
        } else if (contentID.equals("dblVoxelY")) {
            physicalSizes[series][1] = Double.parseDouble(data);
        } else if (contentID.equals("dblStepSize")) {
            double size = Double.parseDouble(data);
            if (size > 0) {
                physicalSizes[series][2] = size;
            }
        } else if (contentID.equals("dblPinhole")) {
            // pinhole is stored in meters
            pinhole[series] = Double.parseDouble(data) * 1000000;
        } else if (contentID.startsWith("nDelayTime")) {
            exposureTime[series] = Double.parseDouble(data);
            if (contentID.endsWith("_ms")) {
                exposureTime[series] /= 1000;
            }
        }
        addSeriesMeta("Block " + blockNum + " " + contentID, data);
    }
    for (Detector detector : detectors) {
        // link Detector to Image, if the detector was actually used
        if (detector.active) {
            store.setDetectorOffset(detector.offset, series, nextDetector);
            store.setDetectorVoltage(new ElectricPotential(detector.voltage, UNITS.VOLT), series, nextDetector);
            store.setDetectorType(getDetectorType("PMT"), series, nextDetector);
            String detectorID = MetadataTools.createLSID("Detector", series, nextDetector);
            store.setDetectorID(detectorID, series, nextDetector);
            if (nextDetector == 0) {
                // overwritten
                for (int c = 0; c < getEffectiveSizeC(); c++) {
                    store.setDetectorSettingsID(detectorID, series, c);
                }
            }
            if (nextChannel < getEffectiveSizeC()) {
                store.setDetectorSettingsID(detectorID, series, nextChannel);
                if (nextChannel < channelNames[series].size()) {
                    String name = (String) channelNames[series].get(nextChannel);
                    if (name == null || name.trim().equals("") || name.equals("None")) {
                        channelNames[series].set(nextChannel, detector.name);
                    }
                } else {
                    while (channelNames[series].size() < nextChannel) {
                        channelNames[series].add("");
                    }
                    channelNames[series].add(detector.name);
                }
                nextChannel++;
            }
            nextDetector++;
        }
    }
    detectors.clear();
    for (int i = 0; i < getSeriesCount(); i++) {
        setSeries(i);
        for (int channel = 0; channel < getEffectiveSizeC(); channel++) {
            if (channel < channelNames[i].size()) {
                String name = (String) channelNames[i].get(channel);
                if (name != null && !name.trim().equals("") && !name.equals("None")) {
                    store.setChannelName(name, i, channel);
                }
            }
            if (channel < emWaves[i].size()) {
                Double wave = new Double(emWaves[i].get(channel).toString());
                Length emission = FormatTools.getEmissionWavelength(wave);
                if (emission != null) {
                    store.setChannelEmissionWavelength(emission, i, channel);
                }
            }
            if (channel < exWaves[i].size()) {
                Double wave = new Double(exWaves[i].get(channel).toString());
                Length ex = FormatTools.getExcitationWavelength(wave);
                if (ex != null) {
                    store.setChannelExcitationWavelength(ex, i, channel);
                }
            }
            if (i < pinhole.length) {
                store.setChannelPinholeSize(new Length(pinhole[i], UNITS.MICROMETER), i, channel);
            }
            if (channel < channelColor[i].length) {
                store.setChannelColor(channelColor[i][channel], i, channel);
            }
        }
    }
    setSeries(0);
}
Also used : Immersion(ome.xml.model.enums.Immersion) Correction(ome.xml.model.enums.Correction) CoreMetadata(loci.formats.CoreMetadata) ElectricPotential(ome.units.quantity.ElectricPotential) Length(ome.units.quantity.Length)

Example 2 with ElectricPotential

use of ome.units.quantity.ElectricPotential in project bioformats by openmicroscopy.

the class NativeND2Reader method populateMetadataStore.

private void populateMetadataStore(ND2Handler handler) throws FormatException {
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);
    String filename = new Location(getCurrentFile()).getName();
    if (handler != null) {
        ArrayList<String> posNames = handler.getPositionNames();
        int nameWidth = String.valueOf(getSeriesCount()).length();
        for (int i = 0; i < getSeriesCount(); i++) {
            String seriesSuffix = String.format("(series %0" + nameWidth + "d)", i + 1);
            String suffix = (i < posNames.size() && !posNames.get(i).equals("")) ? posNames.get(i) : seriesSuffix;
            String name = filename + " " + suffix;
            store.setImageName(name.trim(), i);
        }
    }
    colors = new int[getEffectiveSizeC()];
    ArrayList<String> channelNames = null;
    if (handler != null) {
        channelNames = handler.getChannelNames();
        if (channelNames.size() < getEffectiveSizeC() && backupHandler != null) {
            channelNames = backupHandler.getChannelNames();
        } else if (channelNames.size() < getEffectiveSizeC()) {
            channelNames = textChannelNames;
        }
        for (int c = 0; c < getEffectiveSizeC(); c++) {
            if (c < channelNames.size()) {
                String channelName = channelNames.get(c);
                Integer channelColor = channelColors.get(channelName);
                colors[c] = channelColor == null ? 0 : channelColor.intValue();
            }
        }
    }
    if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) {
        return;
    }
    String instrumentID = MetadataTools.createLSID("Instrument", 0);
    store.setInstrumentID(instrumentID, 0);
    for (int i = 0; i < getSeriesCount(); i++) {
        // link Instrument and Image
        store.setImageInstrumentRef(instrumentID, i);
        // set the channel color
        for (int c = 0; c < getEffectiveSizeC(); c++) {
            int red = colors[c] & 0xff;
            int green = (colors[c] & 0xff00) >> 8;
            int blue = (colors[c] & 0xff0000) >> 16;
            // doing so can prevent the image from displaying correctly
            if (red != 0 || green != 0 || blue != 0) {
                // always set the alpha to 255, otherwise the colors may not appear
                store.setChannelColor(new Color(red, green, blue, 255), i, c);
            }
        }
    }
    // populate Dimensions data
    if (handler != null) {
        for (int i = 0; i < getSeriesCount(); i++) {
            double sizeX = handler.getPixelSizeX();
            double sizeY = handler.getPixelSizeY();
            double sizeZ = handler.getPixelSizeZ();
            if (trueSizeX > 0) {
                store.setPixelsPhysicalSizeX(FormatTools.getPhysicalSizeX(trueSizeX), i);
            } else {
                Length size = FormatTools.getPhysicalSizeX(sizeX);
                if (size != null) {
                    store.setPixelsPhysicalSizeX(size, i);
                }
            }
            if (trueSizeY > 0) {
                store.setPixelsPhysicalSizeY(FormatTools.getPhysicalSizeY(trueSizeY), i);
            } else if (trueSizeX > 0) {
                // if the X size is set, assume X and Y are equal
                store.setPixelsPhysicalSizeY(FormatTools.getPhysicalSizeY(trueSizeX), i);
            } else {
                Length size = FormatTools.getPhysicalSizeY(sizeY);
                if (size == null) {
                    // if the X size is set, assume X and Y are equal
                    size = FormatTools.getPhysicalSizeY(sizeX);
                }
                if (size != null) {
                    store.setPixelsPhysicalSizeY(size, i);
                }
            }
            if (trueSizeZ != null && trueSizeZ > 0) {
                store.setPixelsPhysicalSizeZ(FormatTools.getPhysicalSizeZ(trueSizeZ), i);
            } else {
                Length size = FormatTools.getPhysicalSizeZ(sizeZ);
                if (size != null) {
                    store.setPixelsPhysicalSizeZ(size, i);
                }
            }
        }
    }
    // populate PlaneTiming and StagePosition data
    if (handler != null && handler.getExposureTimes().size() > 0) {
        exposureTime = handler.getExposureTimes();
    }
    int zcPlanes = getImageCount() / ((split ? getSizeC() : 1) * getSizeT());
    for (int i = 0; i < getSeriesCount(); i++) {
        if (tsT.size() > 0) {
            setSeries(i);
            for (int n = 0; n < getImageCount(); n++) {
                int[] coords = getZCTCoords(n);
                int stampIndex = getIndex(coords[0], split ? 0 : coords[1], 0);
                stampIndex += (coords[2] * getSeriesCount() + i) * zcPlanes;
                if (tsT.size() == getImageCount())
                    stampIndex = n;
                else if (tsT.size() == getSizeZ()) {
                    stampIndex = coords[0];
                }
                if (stampIndex < tsT.size()) {
                    double stamp = tsT.get(stampIndex).doubleValue();
                    store.setPlaneDeltaT(new Time(stamp, UNITS.SECOND), i, n);
                }
                int index = i * getSizeC() + coords[1];
                if (exposureTime.size() == getSizeC()) {
                    index = coords[1];
                }
                if (exposureTime != null && index < exposureTime.size() && exposureTime.get(index) != null) {
                    store.setPlaneExposureTime(new Time(exposureTime.get(index), UNITS.SECOND), i, n);
                }
            }
        }
        if (handler != null) {
            if (posX == null)
                posX = handler.getXPositions();
            if (posY == null)
                posY = handler.getYPositions();
            if (posZ == null)
                posZ = handler.getZPositions();
        }
        String pos = "for position";
        for (int n = 0; n < getImageCount(); n++) {
            int[] coords = getZCTCoords(n);
            int index = coords[0];
            index += (coords[2] * getSeriesCount() + i) * zcPlanes;
            if (posX != null) {
                if (index >= posX.size())
                    index = i;
                if (index < posX.size()) {
                    String key = "X position ";
                    store.setPlanePositionX(posX.get(index), i, n);
                    addSeriesMetaList(key, posX.get(index));
                    addGlobalMetaList(key + pos, posX.get(index));
                }
            }
            if (posY != null) {
                if (index < posY.size()) {
                    String key = "Y position ";
                    store.setPlanePositionY(posY.get(index), i, n);
                    addSeriesMetaList(key, posY.get(index));
                    addGlobalMetaList(key + pos, posY.get(index));
                }
            }
            if (posZ != null) {
                if (index < posZ.size()) {
                    store.setPlanePositionZ(posZ.get(index), i, n);
                    String key = "Z position " + pos + ", plane";
                    addSeriesMetaList(key, posZ.get(index));
                    addGlobalMetaList(key, posZ.get(index));
                }
            }
        }
    }
    if (handler == null) {
        setSeries(0);
        return;
    }
    String detectorID = MetadataTools.createLSID("Detector", 0, 0);
    store.setDetectorID(detectorID, 0, 0);
    store.setDetectorModel(handler.getCameraModel(), 0, 0);
    store.setDetectorType(getDetectorType("Other"), 0, 0);
    ArrayList<String> modality = handler.getModalities();
    ArrayList<String> binning = handler.getBinnings();
    ArrayList<Double> speed = handler.getSpeeds();
    ArrayList<Double> gain = handler.getGains();
    ArrayList<Double> temperature = handler.getTemperatures();
    ArrayList<Double> exWave = handler.getExcitationWavelengths();
    ArrayList<Double> emWave = handler.getEmissionWavelengths();
    ArrayList<Integer> power = handler.getPowers();
    ArrayList<Hashtable<String, String>> rois = handler.getROIs();
    if (backupHandler != null) {
        if (emWave.size() == 0) {
            emWave = backupHandler.getEmissionWavelengths();
        }
        if (exWave.size() == 0) {
            exWave = backupHandler.getExcitationWavelengths();
        }
    }
    for (int i = 0; i < getSeriesCount(); i++) {
        for (int c = 0; c < getEffectiveSizeC(); c++) {
            int index = c;
            Double pinholeSize = handler.getPinholeSize();
            if (pinholeSize != null) {
                store.setChannelPinholeSize(new Length(pinholeSize, UNITS.MICROMETER), i, c);
            }
            if (index < channelNames.size()) {
                String channelName = channelNames.get(index);
                store.setChannelName(channelName, i, c);
            } else if (channelNames.size() >= getEffectiveSizeC()) {
                store.setChannelName(channelNames.get(c), i, c);
            }
            if (index < modality.size()) {
                store.setChannelAcquisitionMode(getAcquisitionMode(modality.get(index)), i, c);
            }
            if (index < emWave.size() || index < textEmissionWavelengths.size()) {
                Double value = index < emWave.size() ? emWave.get(index) : textEmissionWavelengths.get(index);
                Length emission = FormatTools.getEmissionWavelength(value);
                if (emission != null) {
                    store.setChannelEmissionWavelength(emission, i, c);
                }
            } else if (emWave.size() > 0 || textEmissionWavelengths.size() > 0) {
                store.setChannelColor(new Color(255, 255, 255, 255), i, c);
            }
            if (index < exWave.size()) {
                Length excitation = FormatTools.getExcitationWavelength(exWave.get(index));
                if (excitation != null) {
                    store.setChannelExcitationWavelength(excitation, i, c);
                }
            }
            if (index < binning.size()) {
                store.setDetectorSettingsBinning(getBinning(binning.get(index)), i, c);
            }
            if (index < gain.size()) {
                store.setDetectorSettingsGain(gain.get(index), i, c);
            }
            if (index < speed.size()) {
                store.setDetectorSettingsReadOutRate(new Frequency(speed.get(index), UNITS.HERTZ), i, c);
            }
            store.setDetectorSettingsID(detectorID, i, c);
        }
    }
    for (int i = 0; i < getSeriesCount(); i++) {
        if (i * getSizeC() < temperature.size()) {
            Double temp = temperature.get(i * getSizeC());
            store.setImagingEnvironmentTemperature(new Temperature(temp, UNITS.CELSIUS), i);
        }
    }
    // populate DetectorSettings
    Double voltage = handler.getVoltage();
    if (voltage != null) {
        store.setDetectorSettingsVoltage(new ElectricPotential(voltage, UNITS.VOLT), 0, 0);
    }
    // populate Objective
    Double na = handler.getNumericalAperture();
    if (na != null) {
        store.setObjectiveLensNA(na, 0, 0);
    }
    Double mag = handler.getMagnification();
    if (mag != null) {
        store.setObjectiveCalibratedMagnification(mag, 0, 0);
    }
    store.setObjectiveModel(handler.getObjectiveModel(), 0, 0);
    String immersion = handler.getImmersion();
    if (immersion == null)
        immersion = "Other";
    store.setObjectiveImmersion(getImmersion(immersion), 0, 0);
    String correction = handler.getCorrection();
    if (correction == null || correction.length() == 0)
        correction = "Other";
    store.setObjectiveCorrection(getCorrection(correction), 0, 0);
    // link Objective to Image
    String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
    store.setObjectiveID(objectiveID, 0, 0);
    if (refractiveIndex == null) {
        refractiveIndex = handler.getRefractiveIndex();
    }
    for (int i = 0; i < getSeriesCount(); i++) {
        store.setObjectiveSettingsID(objectiveID, i);
        if (refractiveIndex != null) {
            store.setObjectiveSettingsRefractiveIndex(refractiveIndex, i);
        }
    }
    setSeries(0);
    if (getMetadataOptions().getMetadataLevel() == MetadataLevel.NO_OVERLAYS) {
        return;
    }
    handler.populateROIs(store);
}
Also used : Temperature(ome.units.quantity.Temperature) Color(ome.xml.model.primitives.Color) Time(ome.units.quantity.Time) ElectricPotential(ome.units.quantity.ElectricPotential) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) Frequency(ome.units.quantity.Frequency) Location(loci.common.Location)

Example 3 with ElectricPotential

use of ome.units.quantity.ElectricPotential in project bioformats by openmicroscopy.

the class GatanReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    in = new RandomAccessInputStream(id);
    pixelOffset = 0;
    CoreMetadata m = core.get(0);
    LOGGER.info("Verifying Gatan format");
    m.littleEndian = false;
    pixelSizes = new ArrayList<Double>();
    units = new ArrayList<String>();
    shapes = new ArrayList<ROIShape>();
    in.order(isLittleEndian());
    // only support version 3
    version = in.readInt();
    if (version != 3 && version != 4) {
        throw new FormatException("invalid header");
    }
    LOGGER.info("Reading tags");
    in.skipBytes(4);
    skipPadding();
    m.littleEndian = in.readInt() != 1;
    in.order(isLittleEndian());
    // TagGroup instance
    in.skipBytes(2);
    skipPadding();
    int numTags = in.readInt();
    if (numTags > in.length()) {
        m.littleEndian = !isLittleEndian();
        in.order(isLittleEndian());
        adjustEndianness = false;
    }
    LOGGER.debug("tags ({}) {", numTags);
    try {
        parseTags(numTags, null, "  ");
    } catch (Exception e) {
        throw new FormatException("Unable to parse metadata tag", e);
    }
    LOGGER.debug("}");
    LOGGER.info("Populating metadata");
    m.littleEndian = true;
    if (getSizeX() == 0 || getSizeY() == 0) {
        throw new FormatException("Dimensions information not found");
    }
    if (m.sizeZ == 0) {
        m.sizeZ = 1;
    }
    m.sizeC = 1;
    m.sizeT = 1;
    m.dimensionOrder = "XYZTC";
    m.imageCount = getSizeZ() * getSizeC() * getSizeT();
    int bytes = (int) (numPixelBytes / (getSizeX() * getSizeY() * (long) getImageCount()));
    if (bytes != FormatTools.getBytesPerPixel(getPixelType())) {
        m.pixelType = FormatTools.pixelTypeFromBytes(bytes, signed, false);
    }
    m.rgb = false;
    m.interleaved = false;
    m.metadataComplete = true;
    m.indexed = false;
    m.falseColor = false;
    // The metadata store we're working with.
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        int index = 0;
        if (pixelSizes.size() > 4) {
            index = pixelSizes.size() - 3;
        } else if (pixelSizes.size() == 4) {
            if (Math.abs(pixelSizes.get(0) - 1.0) < Constants.EPSILON) {
                index = pixelSizes.size() - 2;
            }
        }
        if (index + 2 < pixelSizes.size() && Math.abs(pixelSizes.get(index + 1) - pixelSizes.get(index + 2)) < Constants.EPSILON) {
            if (Math.abs(pixelSizes.get(index) - pixelSizes.get(index + 1)) > Constants.EPSILON && getSizeY() > 1) {
                index++;
            }
        }
        if (index < pixelSizes.size() - 1) {
            Double x = pixelSizes.get(index);
            Double y = pixelSizes.get(index + 1);
            String xUnits = index < units.size() ? units.get(index) : "";
            String yUnits = index + 1 < units.size() ? units.get(index + 1) : "";
            Length sizeX = FormatTools.getPhysicalSizeX(x, convertUnits(xUnits));
            Length sizeY = FormatTools.getPhysicalSizeY(y, convertUnits(yUnits));
            if (sizeX != null) {
                store.setPixelsPhysicalSizeX(sizeX, 0);
            }
            if (sizeY != null) {
                store.setPixelsPhysicalSizeY(sizeY, 0);
            }
            if (index < pixelSizes.size() - 2) {
                Double z = pixelSizes.get(index + 2);
                String zUnits = index + 2 < units.size() ? units.get(index + 2) : "";
                Length sizeZ = FormatTools.getPhysicalSizeZ(z, convertUnits(zUnits));
                if (sizeZ != null) {
                    store.setPixelsPhysicalSizeZ(sizeZ, 0);
                }
            }
        }
        String instrument = MetadataTools.createLSID("Instrument", 0);
        store.setInstrumentID(instrument, 0);
        store.setImageInstrumentRef(instrument, 0);
        String objective = MetadataTools.createLSID("Objective", 0, 0);
        store.setObjectiveID(objective, 0, 0);
        store.setObjectiveCorrection(getCorrection("Unknown"), 0, 0);
        store.setObjectiveImmersion(getImmersion("Unknown"), 0, 0);
        store.setObjectiveNominalMagnification(mag, 0, 0);
        store.setObjectiveSettingsID(objective, 0);
        String detector = MetadataTools.createLSID("Detector", 0, 0);
        store.setDetectorID(detector, 0, 0);
        store.setDetectorSettingsID(detector, 0, 0);
        store.setDetectorSettingsVoltage(new ElectricPotential(voltage, UNITS.VOLT), 0, 0);
        if (info == null)
            info = "";
        String[] scopeInfo = info.split("\\(");
        for (String token : scopeInfo) {
            token = token.trim();
            if (token.startsWith("Mode")) {
                token = token.substring(token.indexOf(' ')).trim();
                String mode = token.substring(0, token.indexOf(' ')).trim();
                if (mode.equals("TEM"))
                    mode = "Other";
                store.setChannelAcquisitionMode(getAcquisitionMode(mode), 0, 0);
            }
        }
        store.setPlanePositionX(posX, 0, 0);
        store.setPlanePositionY(posY, 0, 0);
        store.setPlanePositionZ(posZ, 0, 0);
        for (int i = 0; i < getImageCount(); i++) {
            store.setPlaneExposureTime(new Time(sampleTime, UNITS.SECOND), 0, i);
        }
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.NO_OVERLAYS && shapes.size() > 0) {
        for (int i = 0; i < shapes.size(); i++) {
            String roi = MetadataTools.createLSID("ROI", i);
            store.setROIID(roi, i);
            store.setImageROIRef(roi, 0, i);
            String shapeID = MetadataTools.createLSID("Shape", i, 0);
            ROIShape shape = shapes.get(i);
            switch(shape.type) {
                case LINE:
                    store.setLineID(shapeID, i, 0);
                    store.setLineX1(shape.x1, i, 0);
                    store.setLineY1(shape.y1, i, 0);
                    store.setLineX2(shape.x2, i, 0);
                    store.setLineY2(shape.y2, i, 0);
                    store.setLineText(shape.text, i, 0);
                    store.setLineFontSize(shape.fontSize, i, 0);
                    store.setLineStrokeColor(shape.strokeColor, i, 0);
                    break;
                case TEXT:
                    store.setLabelID(shapeID, i, 0);
                    store.setLabelX(shape.x1, i, 0);
                    store.setLabelY(shape.y1, i, 0);
                    store.setLabelText(shape.text, i, 0);
                    store.setLabelFontSize(shape.fontSize, i, 0);
                    store.setLabelStrokeColor(shape.strokeColor, i, 0);
                    break;
                case ELLIPSE:
                    store.setEllipseID(shapeID, i, 0);
                    double radiusX = (shape.x2 - shape.x1) / 2;
                    double radiusY = (shape.y2 - shape.y1) / 2;
                    store.setEllipseX(shape.x1 + radiusX, i, 0);
                    store.setEllipseY(shape.y1 + radiusY, i, 0);
                    store.setEllipseRadiusX(radiusX, i, 0);
                    store.setEllipseRadiusY(radiusY, i, 0);
                    store.setEllipseText(shape.text, i, 0);
                    store.setEllipseFontSize(shape.fontSize, i, 0);
                    store.setEllipseStrokeColor(shape.strokeColor, i, 0);
                    break;
                case RECTANGLE:
                    store.setRectangleID(shapeID, i, 0);
                    store.setRectangleX(shape.x1, i, 0);
                    store.setRectangleY(shape.y1, i, 0);
                    store.setRectangleWidth(shape.x2 - shape.x1, i, 0);
                    store.setRectangleHeight(shape.y2 - shape.y1, i, 0);
                    store.setRectangleText(shape.text, i, 0);
                    store.setRectangleFontSize(shape.fontSize, i, 0);
                    store.setRectangleStrokeColor(shape.strokeColor, i, 0);
                    break;
                default:
                    LOGGER.warn("Unknown ROI type: {}", shape.type);
            }
        }
    }
}
Also used : Time(ome.units.quantity.Time) CoreMetadata(loci.formats.CoreMetadata) ElectricPotential(ome.units.quantity.ElectricPotential) FormatException(loci.formats.FormatException) FormatException(loci.formats.FormatException) IOException(java.io.IOException) ParseException(java.text.ParseException) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) RandomAccessInputStream(loci.common.RandomAccessInputStream)

Example 4 with ElectricPotential

use of ome.units.quantity.ElectricPotential in project bioformats by openmicroscopy.

the class FV1000Reader method populateMetadataStore.

private void populateMetadataStore(MetadataStore store, String path) throws FormatException, IOException {
    String instrumentID = MetadataTools.createLSID("Instrument", 0);
    store.setInstrumentID(instrumentID, 0);
    for (int i = 0; i < getSeriesCount(); i++) {
        // link Instrument and Image
        store.setImageInstrumentRef(instrumentID, i);
        if (pixelSizeX != null) {
            Double sizeX = new Double(pixelSizeX);
            Length size = FormatTools.getPhysicalSizeX(sizeX);
            if (size != null) {
                store.setPixelsPhysicalSizeX(size, i);
            }
        }
        if (pixelSizeY != null) {
            Double sizeY = new Double(pixelSizeY);
            Length size = FormatTools.getPhysicalSizeY(sizeY);
            if (size != null) {
                store.setPixelsPhysicalSizeY(size, i);
            }
        }
        if (pixelSizeZ == Double.NEGATIVE_INFINITY || pixelSizeZ == Double.POSITIVE_INFINITY || getSizeZ() == 1) {
            pixelSizeZ = 1d;
        }
        if (pixelSizeT == Double.NEGATIVE_INFINITY || pixelSizeT == Double.POSITIVE_INFINITY || getSizeT() == 1) {
            pixelSizeT = 1d;
        }
        Length sizeZ = FormatTools.getPhysicalSizeZ(pixelSizeZ);
        if (sizeZ != null) {
            store.setPixelsPhysicalSizeZ(sizeZ, i);
        }
        store.setPixelsTimeIncrement(new Time(pixelSizeT, UNITS.SECOND), i);
        for (int p = 0; p < core.get(i).imageCount; p++) {
            store.setPlaneDeltaT(new Time(pixelSizeT * p, UNITS.SECOND), i, p);
        }
        for (int c = 0; c < core.get(i).sizeC; c++) {
            if (c < illuminations.size()) {
                store.setChannelIlluminationType(getIlluminationType(illuminations.get(c)), i, c);
            }
        }
    }
    int channelIndex = 0;
    for (ChannelData channel : channels) {
        if (!channel.active)
            continue;
        if (channelIndex >= getEffectiveSizeC())
            break;
        // populate Detector data
        String detectorID = MetadataTools.createLSID("Detector", 0, channelIndex);
        store.setDetectorID(detectorID, 0, channelIndex);
        store.setDetectorSettingsID(detectorID, 0, channelIndex);
        store.setDetectorGain(channel.gain, 0, channelIndex);
        ElectricPotential theVoltage = FormatTools.createElectricPotential(channel.voltage, UNITS.VOLT);
        if (theVoltage != null) {
            store.setDetectorVoltage(theVoltage, 0, channelIndex);
        }
        store.setDetectorType(getDetectorType("PMT"), 0, channelIndex);
        // populate LogicalChannel data
        store.setChannelName(channel.name, 0, channelIndex);
        String lightSourceID = MetadataTools.createLSID("LightSource", 0, channelIndex);
        store.setChannelLightSourceSettingsID(lightSourceID, 0, channelIndex);
        Length wavelength = FormatTools.getWavelength(channel.exWave);
        Length emission = FormatTools.getEmissionWavelength(channel.emWave);
        Length excitation = FormatTools.getExcitationWavelength(channel.exWave);
        if (emission != null) {
            store.setChannelEmissionWavelength(emission, 0, channelIndex);
        }
        if (excitation != null) {
            store.setChannelExcitationWavelength(excitation, 0, channelIndex);
        }
        if (wavelength != null) {
            store.setChannelLightSourceSettingsWavelength(wavelength, 0, channelIndex);
        }
        // populate Filter data
        if (channel.barrierFilter != null) {
            String filterID = MetadataTools.createLSID("Filter", 0, channelIndex);
            store.setFilterID(filterID, 0, channelIndex);
            store.setFilterModel(channel.barrierFilter, 0, channelIndex);
            if (channel.barrierFilter.indexOf('-') != -1) {
                String[] emValues = channel.barrierFilter.split("-");
                for (int i = 0; i < emValues.length; i++) {
                    emValues[i] = emValues[i].replaceAll("\\D", "");
                }
                try {
                    Double cutIn = new Double(emValues[0]);
                    Double cutOut = new Double(emValues[1]);
                    Length in = FormatTools.getCutIn(cutIn);
                    Length out = FormatTools.getCutOut(cutOut);
                    if (in != null) {
                        store.setTransmittanceRangeCutIn(in, 0, channelIndex);
                    }
                    if (out != null) {
                        store.setTransmittanceRangeCutOut(out, 0, channelIndex);
                    }
                } catch (NumberFormatException e) {
                }
            }
            store.setLightPathEmissionFilterRef(filterID, 0, channelIndex, 0);
        }
        // populate FilterSet data
        int emIndex = channelIndex * 2;
        int exIndex = channelIndex * 2 + 1;
        String emFilter = MetadataTools.createLSID("Dichroic", 0, emIndex);
        String exFilter = MetadataTools.createLSID("Dichroic", 0, exIndex);
        // populate Dichroic data
        store.setDichroicID(emFilter, 0, emIndex);
        store.setDichroicModel(channel.emissionFilter, 0, emIndex);
        store.setDichroicID(exFilter, 0, exIndex);
        store.setDichroicModel(channel.excitationFilter, 0, exIndex);
        store.setLightPathDichroicRef(exFilter, 0, channelIndex);
        // populate Laser data
        store.setLaserID(lightSourceID, 0, channelIndex);
        store.setLaserLaserMedium(getLaserMedium(channel.dyeName), 0, channelIndex);
        if (channelIndex < wavelengths.size()) {
            Length wave = FormatTools.getWavelength(wavelengths.get(channelIndex));
            if (wave != null) {
                store.setLaserWavelength(wave, 0, channelIndex);
            }
        }
        store.setLaserType(getLaserType("Other"), 0, channelIndex);
        channelIndex++;
    }
    if (lensNA != null)
        store.setObjectiveLensNA(new Double(lensNA), 0, 0);
    store.setObjectiveModel(objectiveName, 0, 0);
    if (magnification != null) {
        Double mag = Double.parseDouble(magnification);
        store.setObjectiveNominalMagnification(mag, 0, 0);
    }
    if (workingDistance != null) {
        store.setObjectiveWorkingDistance(new Length(new Double(workingDistance), UNITS.MICROMETER), 0, 0);
    }
    store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
    store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
    // link Objective to Image using ObjectiveSettings
    String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
    store.setObjectiveID(objectiveID, 0, 0);
    store.setObjectiveSettingsID(objectiveID, 0);
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.NO_OVERLAYS) {
        int nextROI = -1;
        // populate ROI data - there is one ROI file per plane
        for (int i = 0; i < roiFilenames.size(); i++) {
            if (i >= getImageCount())
                break;
            String filename = roiFilenames.get(i);
            filename = sanitizeFile(filename, path);
            nextROI = parseROIFile(filename, store, nextROI, i);
        }
    }
    // Populate metadata for the planes
    for (int i = 0; i < planes.size(); i++) {
        PlaneData plane = planes.get(i);
        if (plane.deltaT != null) {
            store.setPlaneDeltaT(new Time(plane.deltaT, UNITS.SECOND), 0, i);
        }
        store.setPlanePositionX(plane.positionX, 0, i);
        store.setPlanePositionY(plane.positionY, 0, i);
        store.setPlanePositionZ(plane.positionZ, 0, i);
    }
}
Also used : Length(ome.units.quantity.Length) Time(ome.units.quantity.Time) ElectricPotential(ome.units.quantity.ElectricPotential)

Example 5 with ElectricPotential

use of ome.units.quantity.ElectricPotential in project bioformats by openmicroscopy.

the class AliconaReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    in = new RandomAccessInputStream(id);
    CoreMetadata m = core.get(0);
    // check that this is a valid AL3D file
    LOGGER.info("Verifying Alicona format");
    String magicString = in.readString(17);
    if (!magicString.trim().equals("AliconaImaging")) {
        throw new FormatException("Invalid magic string : " + "expected 'AliconaImaging', got " + magicString);
    }
    // now we read a series of tags
    // each one is 52 bytes - 20 byte key + 30 byte value + 2 byte CRLF
    LOGGER.info("Reading tags");
    int count = 2;
    boolean hasC = false;
    String voltage = null, magnification = null, workingDistance = null;
    String pntX = null, pntY = null;
    int depthOffset = 0;
    for (int i = 0; i < count; i++) {
        String key = in.readString(20).trim();
        String value = in.readString(30).trim();
        addGlobalMeta(key, value);
        in.skipBytes(2);
        if (key.equals("TagCount"))
            count += Integer.parseInt(value);
        else if (key.equals("Rows"))
            m.sizeY = Integer.parseInt(value);
        else if (key.equals("Cols"))
            m.sizeX = Integer.parseInt(value);
        else if (key.equals("NumberOfPlanes")) {
            m.imageCount = Integer.parseInt(value);
        } else if (key.equals("TextureImageOffset")) {
            textureOffset = Integer.parseInt(value);
        } else if (key.equals("TexturePtr") && !value.equals("7"))
            hasC = true;
        else if (key.equals("Voltage"))
            voltage = value;
        else if (key.equals("Magnification"))
            magnification = value;
        else if (key.equals("PixelSizeXMeter"))
            pntX = value;
        else if (key.equals("PixelSizeYMeter"))
            pntY = value;
        else if (key.equals("WorkingDistance"))
            workingDistance = value;
        else if (key.equals("DepthImageOffset")) {
            depthOffset = Integer.parseInt(value);
        }
    }
    LOGGER.info("Populating metadata");
    if (textureOffset != 0) {
        numBytes = (int) (in.length() - textureOffset) / (getSizeX() * getSizeY() * getImageCount());
        m.sizeC = hasC ? 3 : 1;
        m.sizeZ = 1;
        m.sizeT = getImageCount() / getSizeC();
        m.pixelType = FormatTools.pixelTypeFromBytes(numBytes, false, false);
    } else {
        textureOffset = depthOffset;
        m.pixelType = FormatTools.FLOAT;
        m.sizeC = 1;
        m.sizeZ = 1;
        m.sizeT = 1;
        m.imageCount = 1;
    }
    m.rgb = false;
    m.interleaved = false;
    m.littleEndian = true;
    m.dimensionOrder = "XYCTZ";
    m.metadataComplete = true;
    m.indexed = false;
    m.falseColor = false;
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        // link Image and Instrument
        String instrumentID = MetadataTools.createLSID("Instrument", 0);
        store.setInstrumentID(instrumentID, 0);
        store.setImageInstrumentRef(instrumentID, 0);
        // used when the dataset was acquired, i.e. detector settings.
        if (voltage != null) {
            store.setDetectorSettingsVoltage(new ElectricPotential(new Double(voltage), UNITS.VOLT), 0, 0);
            // link DetectorSettings to an actual Detector
            String detectorID = MetadataTools.createLSID("Detector", 0, 0);
            store.setDetectorID(detectorID, 0, 0);
            store.setDetectorSettingsID(detectorID, 0, 0);
            // set required Detector type
            store.setDetectorType(getDetectorType("Other"), 0, 0);
        }
        if (magnification != null) {
            store.setObjectiveCalibratedMagnification(new Double(magnification), 0, 0);
        }
        if (workingDistance != null) {
            store.setObjectiveWorkingDistance(new Length(new Double(workingDistance), UNITS.MICROMETER), 0, 0);
        }
        store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
        store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
        // link Objective to an Image using ObjectiveSettings
        String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
        store.setObjectiveID(objectiveID, 0, 0);
        store.setObjectiveSettingsID(objectiveID, 0);
        if (pntX != null && pntY != null) {
            double pixelSizeX = Double.parseDouble(pntX);
            double pixelSizeY = Double.parseDouble(pntY);
            Length sizeX = FormatTools.getPhysicalSizeX(pixelSizeX, UNITS.METER);
            Length sizeY = FormatTools.getPhysicalSizeY(pixelSizeY, UNITS.METER);
            if (sizeX != null) {
                store.setPixelsPhysicalSizeX(sizeX, 0);
            }
            if (sizeY != null) {
                store.setPixelsPhysicalSizeY(sizeY, 0);
            }
        }
    }
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) RandomAccessInputStream(loci.common.RandomAccessInputStream) CoreMetadata(loci.formats.CoreMetadata) ElectricPotential(ome.units.quantity.ElectricPotential) FormatException(loci.formats.FormatException)

Aggregations

ElectricPotential (ome.units.quantity.ElectricPotential)9 Length (ome.units.quantity.Length)9 Time (ome.units.quantity.Time)7 MetadataStore (loci.formats.meta.MetadataStore)6 CoreMetadata (loci.formats.CoreMetadata)4 Timestamp (ome.xml.model.primitives.Timestamp)4 Temperature (ome.units.quantity.Temperature)3 Hashtable (java.util.Hashtable)2 Location (loci.common.Location)2 RandomAccessInputStream (loci.common.RandomAccessInputStream)2 FormatException (loci.formats.FormatException)2 Frequency (ome.units.quantity.Frequency)2 IOException (java.io.IOException)1 ParseException (java.text.ParseException)1 StringTokenizer (java.util.StringTokenizer)1 Correction (ome.xml.model.enums.Correction)1 EnumerationException (ome.xml.model.enums.EnumerationException)1 Immersion (ome.xml.model.enums.Immersion)1 CorrectionEnumHandler (ome.xml.model.enums.handlers.CorrectionEnumHandler)1 DetectorTypeEnumHandler (ome.xml.model.enums.handlers.DetectorTypeEnumHandler)1