Search in sources :

Example 6 with Temperature

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

the class MetamorphTiffReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    List<String> uniqueChannels = new ArrayList<String>();
    final List<Double> uniqueZs = new ArrayList<Double>();
    final List<Length> stageX = new ArrayList<Length>();
    final List<Length> stageY = new ArrayList<Length>();
    CoreMetadata m = core.get(0);
    String filename = id.substring(id.lastIndexOf(File.separator) + 1);
    filename = filename.substring(0, filename.indexOf('.'));
    boolean integerFilename = true;
    try {
        Integer.parseInt(filename);
    } catch (NumberFormatException e) {
        integerFilename = false;
    }
    if (integerFilename && ifds.size() == 1 && ifds.get(0).getIFDIntValue(IFD.NEW_SUBFILE_TYPE) == 2) {
        // look for other files in the dataset
        findTIFFs();
        String stageLabel = null;
        for (String tiff : files) {
            MetamorphHandler handler = new MetamorphHandler();
            parseFile(tiff, handler);
            String label = handler.getStageLabel();
            if (stageLabel == null) {
                stageLabel = label;
            } else if (!label.equals(stageLabel)) {
                break;
            }
            if (!uniqueChannels.contains(handler.getChannelName())) {
                uniqueChannels.add(handler.getChannelName());
            }
            final List<Double> zPositions = handler.getZPositions();
            Double pos = Math.rint(zPositions.get(0));
            if (!uniqueZs.contains(pos)) {
                uniqueZs.add(pos);
            }
        }
        MetamorphHandler handler = new MetamorphHandler();
        parseFile(files[files.length - 1], handler);
        String lastStageLabel = handler.getStageLabel();
        int lastField = getField(lastStageLabel);
        int lastWellRow = getWellRow(lastStageLabel);
        int lastWellColumn = getWellColumn(lastStageLabel);
        int field = getField(stageLabel);
        int fieldRow = getWellRow(stageLabel);
        int fieldColumn = getWellColumn(stageLabel);
        wellCount = lastField - field + 1;
        fieldRowCount = lastWellRow - fieldRow + 1;
        fieldColumnCount = lastWellColumn - fieldColumn + 1;
        m.sizeC = uniqueChannels.size();
        m.sizeZ = uniqueZs.size();
    } else {
        files = new String[] { id };
        wellCount = 1;
        fieldRowCount = 1;
        fieldColumnCount = 1;
        m.sizeC = 0;
    }
    // parse XML comment
    MetamorphHandler handler = new MetamorphHandler(getGlobalMetadata());
    final List<Length> xPositions = new ArrayList<Length>();
    final List<Length> yPositions = new ArrayList<Length>();
    for (IFD ifd : ifds) {
        String xml = XMLTools.sanitizeXML(ifd.getComment());
        XMLTools.parseXML(xml, handler);
        final Length x = handler.getStagePositionX();
        final Length y = handler.getStagePositionY();
        if (xPositions.isEmpty()) {
            xPositions.add(x);
            yPositions.add(y);
        } else {
            final Length previousX = xPositions.get(xPositions.size() - 1);
            final Length previousY = yPositions.get(yPositions.size() - 1);
            final double x1 = x.value(UNITS.REFERENCEFRAME).doubleValue();
            final double x2 = previousX.value(UNITS.REFERENCEFRAME).doubleValue();
            final double y1 = y.value(UNITS.REFERENCEFRAME).doubleValue();
            final double y2 = previousY.value(UNITS.REFERENCEFRAME).doubleValue();
            if (Math.abs(x1 - x2) > 0.21 || Math.abs(y1 - y2) > 0.21) {
                xPositions.add(x);
                yPositions.add(y);
            }
        }
    }
    if (xPositions.size() > 1) {
        fieldRowCount = xPositions.size();
    }
    final List<Integer> wavelengths = handler.getWavelengths();
    final List<Double> zPositions = handler.getZPositions();
    dualCamera = handler.hasDualCamera();
    // calculate axis sizes
    final List<Integer> uniqueC = new ArrayList<Integer>();
    for (Integer c : wavelengths) {
        if (!uniqueC.contains(c)) {
            uniqueC.add(c);
        }
    }
    int effectiveC = uniqueC.size();
    if (effectiveC == 0)
        effectiveC = 1;
    if (getSizeC() == 0)
        m.sizeC = 1;
    int samples = ifds.get(0).getSamplesPerPixel();
    m.sizeC *= effectiveC * samples;
    final List<Double> uniqueZ = new ArrayList<Double>();
    for (Double z : zPositions) {
        if (!uniqueZ.contains(z))
            uniqueZ.add(z);
    }
    if (getSizeZ() == 0)
        m.sizeZ = 1;
    if (uniqueZ.size() > 1)
        m.sizeZ *= uniqueZ.size();
    Double physicalSizeZ = null;
    if (m.sizeZ > 1) {
        Double zRange = zPositions.get(zPositions.size() - 1) - zPositions.get(0);
        physicalSizeZ = Math.abs(zRange);
        physicalSizeZ /= (m.sizeZ - 1);
    }
    int totalPlanes = files.length * ifds.size();
    effectiveC = getSizeC() / samples;
    // account for the multiple actual Z sections
    if (effectiveC * getSizeZ() > totalPlanes && (effectiveC * (getSizeZ() / uniqueC.size()) == totalPlanes || effectiveC == totalPlanes)) {
        if (getSizeZ() >= uniqueC.size()) {
            m.sizeZ /= uniqueC.size();
        } else {
            m.sizeZ = 1;
        }
    }
    m.sizeT = totalPlanes / (wellCount * fieldRowCount * fieldColumnCount * getSizeZ() * effectiveC);
    if (getSizeT() == 0)
        m.sizeT = 1;
    int seriesCount = wellCount * fieldRowCount * fieldColumnCount;
    if (seriesCount > 1 && getSizeZ() > totalPlanes / seriesCount || totalPlanes > getSizeZ() * getSizeT() * effectiveC) {
        m.sizeZ = 1;
        m.sizeT = totalPlanes / (seriesCount * effectiveC);
    }
    m.imageCount = getSizeZ() * getSizeT() * effectiveC;
    if (dualCamera) {
        m.sizeX /= 2;
        m.sizeC *= 2;
        m.imageCount *= 2;
    }
    if (seriesCount > 1) {
        core.clear();
        for (int i = 0; i < seriesCount; i++) {
            core.add(m);
        }
    }
    for (int s = 0; s < wellCount * fieldRowCount * fieldColumnCount; s++) {
        if (files.length > 1) {
            int[] lengths = new int[] { getSizeZ(), getEffectiveSizeC(), fieldColumnCount, fieldRowCount, wellCount, getSizeT() };
            Well well = getWell(s);
            int[] position = new int[] { 0, 0, well.fieldCol, well.fieldRow, well.well, 0 };
            int fileIndex = FormatTools.positionToRaster(lengths, position);
            parseFile(files[fileIndex], handler);
            stageX.add(handler.getStagePositionX());
            stageY.add(handler.getStagePositionY());
        } else {
            stageX.add(xPositions.get(s));
            stageY.add(yPositions.get(s));
        }
    }
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
    // effectively useless).
    if (wellCount > 1) {
        store.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
        store.setPlateRows(new PositiveInteger(1), 0);
        store.setPlateColumns(new PositiveInteger(wellCount), 0);
        store.setPlateRowNamingConvention(NamingConvention.LETTER, 0);
        store.setPlateColumnNamingConvention(NamingConvention.NUMBER, 0);
        store.setPlateAcquisitionID(MetadataTools.createLSID("PlateAcquisition", 0, 0), 0, 0);
        for (int well = 0; well < wellCount; well++) {
            store.setWellID(MetadataTools.createLSID("Well", 0, well), 0, well);
            store.setWellRow(new NonNegativeInteger(0), 0, well);
            store.setWellColumn(new NonNegativeInteger(well), 0, well);
            for (int row = 0; row < fieldRowCount; row++) {
                for (int col = 0; col < fieldColumnCount; col++) {
                    int field = row * fieldColumnCount + col;
                    String wellSampleID = MetadataTools.createLSID("WellSample", 0, well, field);
                    store.setWellSampleID(wellSampleID, 0, well, field);
                    int seriesIndex = getSeriesIndex(row, col, well);
                    String imageID = MetadataTools.createLSID("Image", seriesIndex);
                    store.setImageID(imageID, seriesIndex);
                    store.setWellSampleImageRef(imageID, 0, well, field);
                    store.setWellSampleIndex(new NonNegativeInteger(seriesIndex), 0, well, field);
                    store.setPlateAcquisitionWellSampleRef(wellSampleID, 0, 0, seriesIndex);
                }
            }
        }
    }
    final List<String> timestamps = handler.getTimestamps();
    final List<Double> exposures = handler.getExposures();
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        for (int i = 0; i < timestamps.size(); i++) {
            long timestamp = DateTools.getTime(timestamps.get(i), DATE_FORMAT, ".");
            addGlobalMetaList("timestamp", timestamp);
        }
        for (int i = 0; i < exposures.size(); i++) {
            addGlobalMetaList("exposure time (ms)", exposures.get(i).floatValue() * 1000);
        }
    }
    for (int s = 0; s < seriesCount; s++) {
        setSeries(s);
        Well well = getWell(s);
        String name = handler.getImageName();
        if (seriesCount > 1) {
            name = "Field " + (char) (well.fieldRow + 'A') + (well.fieldCol + 1) + ", Well " + (well.well + 1) + ": " + name;
        }
        store.setImageName(name, s);
        String date = DateTools.formatDate(handler.getDate(), DateTools.ISO8601_FORMAT, ".");
        if (date != null) {
            store.setImageAcquisitionDate(new Timestamp(date), s);
        }
        if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
            long startDate = 0;
            if (timestamps.size() > 0) {
                startDate = DateTools.getTime(timestamps.get(0), DATE_FORMAT, ".");
            }
            store.setImageDescription("", s);
            int image = 0;
            for (int c = 0; c < getEffectiveSizeC(); c++) {
                for (int t = 0; t < getSizeT(); t++) {
                    store.setPlaneTheZ(new NonNegativeInteger(0), s, image);
                    store.setPlaneTheC(new NonNegativeInteger(c), s, image);
                    store.setPlaneTheT(new NonNegativeInteger(t), s, image);
                    if (t < timestamps.size()) {
                        String stamp = timestamps.get(t);
                        long ms = DateTools.getTime(stamp, DATE_FORMAT, ".");
                        store.setPlaneDeltaT(new Time((ms - startDate) / 1000.0, UNITS.SECOND), s, image);
                    }
                    int exposureIndex = image;
                    if (dualCamera) {
                        exposureIndex /= getEffectiveSizeC();
                    }
                    if (exposures.size() == 1) {
                        exposureIndex = 0;
                    }
                    if (exposureIndex < exposures.size() && exposures.get(exposureIndex) != null) {
                        store.setPlaneExposureTime(new Time(exposures.get(exposureIndex), UNITS.SECOND), s, image);
                    }
                    if (s < stageX.size()) {
                        store.setPlanePositionX(stageX.get(s), s, image);
                    }
                    if (s < stageY.size()) {
                        store.setPlanePositionY(stageY.get(s), s, image);
                    }
                    image++;
                }
            }
            store.setImagingEnvironmentTemperature(new Temperature(handler.getTemperature(), UNITS.CELSIUS), s);
            Length sizeX = FormatTools.getPhysicalSizeX(handler.getPixelSizeX());
            Length sizeY = FormatTools.getPhysicalSizeY(handler.getPixelSizeY());
            Length sizeZ = physicalSizeZ == null ? null : FormatTools.getPhysicalSizeZ(physicalSizeZ);
            if (sizeX != null) {
                store.setPixelsPhysicalSizeX(sizeX, s);
            }
            if (sizeY != null) {
                store.setPixelsPhysicalSizeY(sizeY, s);
            }
            if (sizeZ != null) {
                store.setPixelsPhysicalSizeZ(sizeZ, s);
            }
            if (uniqueChannels.size() == 0) {
                uniqueChannels = handler.getChannelNames();
            }
            for (int c = 0; c < getEffectiveSizeC(); c++) {
                if (uniqueChannels.size() > c) {
                    store.setChannelName(uniqueChannels.get(c), s, c);
                } else
                    store.setChannelName(handler.getChannelName(), s, c);
                if (c < wavelengths.size()) {
                    store.setChannelEmissionWavelength(FormatTools.getEmissionWavelength(Double.valueOf(wavelengths.get(c))), s, c);
                }
            }
        }
    }
}
Also used : Temperature(ome.units.quantity.Temperature) IFD(loci.formats.tiff.IFD) ArrayList(java.util.ArrayList) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp) PositiveInteger(ome.xml.model.primitives.PositiveInteger) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) CoreMetadata(loci.formats.CoreMetadata) PositiveInteger(ome.xml.model.primitives.PositiveInteger) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length)

Example 7 with Temperature

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

the class NikonElementsTiffReader method initMetadataStore.

/* @see BaseTiffReader#initMetadataStore() */
@Override
protected void initMetadataStore() throws FormatException {
    super.initMetadataStore();
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);
    String date = handler.getDate();
    if (date != null) {
        store.setImageAcquisitionDate(new Timestamp(date), 0);
    }
    if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) {
        return;
    }
    Length sizeX = FormatTools.getPhysicalSizeX(handler.getPixelSizeX());
    Length sizeY = FormatTools.getPhysicalSizeY(handler.getPixelSizeY());
    Length sizeZ = FormatTools.getPhysicalSizeZ(handler.getPixelSizeZ());
    if (sizeX != null) {
        store.setPixelsPhysicalSizeX(sizeX, 0);
    }
    if (sizeY != null) {
        store.setPixelsPhysicalSizeY(sizeY, 0);
    }
    if (sizeZ != null) {
        store.setPixelsPhysicalSizeZ(sizeZ, 0);
    }
    String instrument = MetadataTools.createLSID("Instrument", 0);
    store.setInstrumentID(instrument, 0);
    store.setImageInstrumentRef(instrument, 0);
    ArrayList<Double> exposureTimes = handler.getExposureTimes();
    ArrayList<Length> posX = handler.getXPositions();
    ArrayList<Length> posY = handler.getYPositions();
    ArrayList<Length> posZ = handler.getZPositions();
    for (int i = 0; i < getImageCount(); i++) {
        int c = getZCTCoords(i)[1];
        if (c < exposureTimes.size() && exposureTimes.get(c) != null) {
            store.setPlaneExposureTime(new Time(exposureTimes.get(c), UNITS.SECOND), 0, i);
        }
        if (i < posX.size()) {
            store.setPlanePositionX(posX.get(i), 0, i);
        }
        if (i < posY.size()) {
            store.setPlanePositionY(posY.get(i), 0, i);
        }
        if (i < posZ.size()) {
            store.setPlanePositionZ(posZ.get(i), 0, i);
        }
    }
    String detector = MetadataTools.createLSID("Detector", 0, 0);
    store.setDetectorID(detector, 0, 0);
    store.setDetectorModel(handler.getCameraModel(), 0, 0);
    store.setDetectorType(getDetectorType("Other"), 0, 0);
    ArrayList<String> channelNames = handler.getChannelNames();
    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();
    Double pinholeSize = handler.getPinholeSize();
    for (int c = 0; c < getEffectiveSizeC(); c++) {
        if (pinholeSize != null) {
            store.setChannelPinholeSize(new Length(pinholeSize, UNITS.MICROMETER), 0, c);
        }
        if (c < channelNames.size()) {
            store.setChannelName(channelNames.get(c), 0, c);
        }
        if (c < modality.size()) {
            store.setChannelAcquisitionMode(getAcquisitionMode(modality.get(c)), 0, c);
        }
        if (c < emWave.size()) {
            Length em = FormatTools.getEmissionWavelength(emWave.get(c));
            if (em != null) {
                store.setChannelEmissionWavelength(em, 0, c);
            }
        }
        if (c < exWave.size()) {
            Length ex = FormatTools.getExcitationWavelength(exWave.get(c));
            if (ex != null) {
                store.setChannelExcitationWavelength(ex, 0, c);
            }
        }
        if (c < binning.size()) {
            store.setDetectorSettingsBinning(getBinning(binning.get(c)), 0, c);
        }
        if (c < gain.size()) {
            store.setDetectorSettingsGain(gain.get(c), 0, c);
        }
        if (c < speed.size()) {
            store.setDetectorSettingsReadOutRate(new Frequency(speed.get(c), UNITS.HERTZ), 0, c);
        }
        store.setDetectorSettingsID(detector, 0, c);
    }
    if (temperature.size() > 0) {
        store.setImagingEnvironmentTemperature(new Temperature(temperature.get(0), UNITS.CELSIUS), 0);
    }
    Double voltage = handler.getVoltage();
    if (voltage != null) {
        store.setDetectorSettingsVoltage(new ElectricPotential(voltage, UNITS.VOLT), 0, 0);
    }
    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);
    String objective = MetadataTools.createLSID("Objective", 0, 0);
    store.setObjectiveID(objective, 0, 0);
    store.setObjectiveSettingsID(objective, 0);
    Double refractiveIndex = handler.getRefractiveIndex();
    if (refractiveIndex != null) {
        store.setObjectiveSettingsRefractiveIndex(refractiveIndex, 0);
    }
    if (getMetadataOptions().getMetadataLevel() == MetadataLevel.NO_OVERLAYS) {
        return;
    }
    handler.populateROIs(store);
}
Also used : Temperature(ome.units.quantity.Temperature) Hashtable(java.util.Hashtable) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp) ElectricPotential(ome.units.quantity.ElectricPotential) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) Frequency(ome.units.quantity.Frequency)

Example 8 with Temperature

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

the class KodakReader method readExtraMetadata.

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

Example 9 with Temperature

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

the class InCellReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    // make sure that we have the .xdce (or .xml) file
    if (checkSuffix(id, PIXELS_SUFFIXES) || checkSuffix(id, "xlog")) {
        Location currentFile = new Location(id).getAbsoluteFile();
        Location parent = currentFile.getParentFile();
        String[] list = parent.list(true);
        for (String f : list) {
            if (checkSuffix(f, new String[] { "xdce", "xml" })) {
                String path = new Location(parent, f).getAbsolutePath();
                if (isThisType(path)) {
                    // make sure that the .xdce file references the current file
                    // this ensures that the correct file is chosen if multiple
                    // .xdce files are the same directory
                    String data = DataTools.readFile(path);
                    if (data.indexOf(currentFile.getName()) >= 0) {
                        id = path;
                        break;
                    }
                }
            }
        }
    }
    super.initFile(id);
    in = new RandomAccessInputStream(id);
    channelNames = new ArrayList<String>();
    emWaves = new ArrayList<Double>();
    exWaves = new ArrayList<Double>();
    channelsPerTimepoint = new ArrayList<Integer>();
    metadataFiles = new ArrayList<String>();
    // parse metadata from the .xdce or .xml file
    wellCoordinates = new HashMap<Integer, int[]>();
    posX = new HashMap<Integer, Length>();
    posY = new HashMap<Integer, Length>();
    offsetPointCounter = 0;
    byte[] b = new byte[(int) in.length()];
    in.read(b);
    CoreMetadata ms0 = core.get(0);
    ms0.dimensionOrder = "XYZCT";
    MetadataStore store = makeFilterMetadata();
    DefaultHandler handler = new MinimalInCellHandler();
    XMLTools.parseXML(b, handler);
    if (getSizeZ() == 0)
        ms0.sizeZ = 1;
    if (getSizeC() == 0)
        ms0.sizeC = 1;
    if (getSizeT() == 0)
        ms0.sizeT = 1;
    if (totalImages == 0) {
        ms0.imageCount = getSizeC() * getSizeZ() * getSizeT();
        totalImages = getImageCount() * wellRows * wellCols * fieldCount;
        Location parent = new Location(currentId).getAbsoluteFile().getParentFile();
        for (int row = 0; row < wellRows; row++) {
            for (int col = 0; col < wellCols; col++) {
                plateMap[row][col] = true;
                for (int field = 0; field < fieldCount; field++) {
                    for (int t = 0; t < getSizeT(); t++) {
                        for (int image = 0; image < getSizeC() * getSizeZ(); image++) {
                            // this could be expanded to allow for timepoint indexes
                            // in the file name, as well as allowing the filter names to
                            // be omitted
                            int channel = getZCTCoords(image)[1];
                            Image plane = new Image();
                            String filename = (char) ('A' + row) + " - " + (col + 1) + "(fld " + (field + 1) + " wv " + exFilters.get(channel) + " - " + emFilters.get(channel) + ").tif";
                            Location path = new Location(parent, filename);
                            if (path.exists()) {
                                plane.filename = path.getAbsolutePath();
                            } else {
                                LOGGER.debug("Missing file {}", filename);
                            }
                            imageFiles[row * wellCols + col][field][t][image] = plane;
                        }
                    }
                }
            }
        }
    }
    for (int t = imageFiles[0][0].length - 1; t >= 0; t--) {
        boolean allNull = true;
        for (int well = 0; well < imageFiles.length; well++) {
            for (int field = 0; field < imageFiles[well].length; field++) {
                for (int p = 0; p < imageFiles[well][field][t].length; p++) {
                    if (imageFiles[well][field][t][p] != null) {
                        allNull = false;
                        break;
                    }
                }
            }
        }
        if (allNull) {
            ms0.sizeT--;
        }
    }
    int seriesCount = 0;
    if (exclude != null) {
        for (int row = 0; row < wellRows; row++) {
            for (int col = 0; col < wellCols; col++) {
                if (!exclude[row][col]) {
                    int well = row * wellCols + col;
                    boolean hasNonNullImage = false;
                    for (int field = 0; field < imageFiles[well].length; field++) {
                        for (int t = 0; t < imageFiles[well][field].length; t++) {
                            for (int p = 0; p < imageFiles[well][field][t].length; p++) {
                                if (imageFiles[well][field][t][p] != null) {
                                    hasNonNullImage = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (hasNonNullImage) {
                        seriesCount += imageFiles[well].length;
                    }
                }
            }
        }
        int expectedSeries = totalImages / (getSizeZ() * getSizeC() * getSizeT());
        if (expectedSeries > 0) {
            seriesCount = (int) Math.min(seriesCount, expectedSeries);
        }
    } else
        seriesCount = totalImages / (getSizeZ() * getSizeC() * getSizeT());
    totalChannels = getSizeC();
    oneTimepointPerSeries = false;
    for (int i = 1; i < channelsPerTimepoint.size(); i++) {
        if (!channelsPerTimepoint.get(i).equals(channelsPerTimepoint.get(i - 1))) {
            oneTimepointPerSeries = true;
            break;
        }
    }
    if (oneTimepointPerSeries) {
        int imageCount = 0;
        for (Integer timepoint : channelsPerTimepoint) {
            imageCount += timepoint.intValue() * getSizeZ();
        }
        seriesCount = (totalImages / imageCount) * getSizeT();
    }
    int sizeT = getSizeT();
    int sizeC = getSizeC();
    int z = getSizeZ();
    int t = oneTimepointPerSeries ? 1 : getSizeT();
    core.clear();
    for (int i = 0; i < seriesCount; i++) {
        int c = oneTimepointPerSeries ? channelsPerTimepoint.get(i % sizeT).intValue() : sizeC;
        CoreMetadata ms = new CoreMetadata();
        core.add(ms);
        ms.sizeZ = z;
        ms.sizeC = c;
        ms.sizeT = t;
        ms.imageCount = z * c * t;
        ms.dimensionOrder = "XYZCT";
    }
    int wellIndex = getWellFromSeries(0);
    int fieldIndex = getFieldFromSeries(0);
    String filename = imageFiles[wellIndex][fieldIndex][0][0].filename;
    boolean isTiff = imageFiles[wellIndex][fieldIndex][0][0].isTiff;
    if (isTiff && filename != null) {
        tiffReader = new MinimalTiffReader();
        tiffReader.setId(filename);
        for (int i = 0; i < seriesCount; i++) {
            CoreMetadata ms = core.get(i);
            ms.sizeX = tiffReader.getSizeX();
            ms.sizeY = tiffReader.getSizeY();
            ms.interleaved = tiffReader.isInterleaved();
            ms.indexed = tiffReader.isIndexed();
            ms.rgb = tiffReader.isRGB();
            ms.pixelType = tiffReader.getPixelType();
            ms.littleEndian = tiffReader.isLittleEndian();
        }
    } else {
        for (int i = 0; i < seriesCount; i++) {
            CoreMetadata ms = core.get(i);
            ms.sizeX = imageWidth;
            ms.sizeY = imageHeight;
            ms.interleaved = false;
            ms.indexed = false;
            ms.rgb = false;
            ms.pixelType = FormatTools.UINT16;
            ms.littleEndian = true;
        }
    }
    MetadataTools.populatePixels(store, this, true);
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        handler = new InCellHandler(store);
        XMLTools.parseXML(b, handler);
    }
    String rowNaming = Character.isDigit(rowName.charAt(0)) ? "Number" : "Letter";
    String colNaming = Character.isDigit(colName.charAt(0)) ? "Number" : "Letter";
    String plateName = currentId;
    int begin = plateName.lastIndexOf(File.separator) + 1;
    int end = plateName.lastIndexOf(".");
    plateName = plateName.substring(begin, end);
    store.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
    store.setPlateName(plateName, 0);
    store.setPlateRowNamingConvention(getNamingConvention(rowNaming), 0);
    store.setPlateColumnNamingConvention(getNamingConvention(colNaming), 0);
    store.setPlateRows(new PositiveInteger(wellRows), 0);
    store.setPlateColumns(new PositiveInteger(wellCols), 0);
    String plateAcqID = MetadataTools.createLSID("PlateAcquisition", 0, 0);
    store.setPlateAcquisitionID(plateAcqID, 0, 0);
    PositiveInteger maxFieldCount = FormatTools.getMaxFieldCount(fieldCount);
    if (maxFieldCount != null) {
        store.setPlateAcquisitionMaximumFieldCount(maxFieldCount, 0, 0);
    }
    // populate Image data
    String instrumentID = MetadataTools.createLSID("Instrument", 0);
    String experimentID = MetadataTools.createLSID("Experiment", 0);
    store.setInstrumentID(instrumentID, 0);
    store.setExperimentID(experimentID, 0);
    String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
    store.setObjectiveID(objectiveID, 0, 0);
    String detectorID = MetadataTools.createLSID("Detector", 0, 0);
    store.setDetectorID(detectorID, 0, 0);
    int prevWell = -1;
    for (int i = 0; i < seriesCount; i++) {
        store.setObjectiveSettingsID(objectiveID, i);
        if (refractive != null) {
            store.setObjectiveSettingsRefractiveIndex(refractive, i);
        }
        if (x != null) {
            store.setPixelsPhysicalSizeX(x, i);
        }
        if (y != null) {
            store.setPixelsPhysicalSizeY(y, i);
        }
        int well = getWellFromSeries(i);
        int field = getFieldFromSeries(i);
        int totalTimepoints = oneTimepointPerSeries ? channelsPerTimepoint.size() : 1;
        int timepoint = oneTimepointPerSeries ? (i % totalTimepoints) + 1 : -1;
        String imageID = MetadataTools.createLSID("Image", i);
        store.setImageID(imageID, i);
        store.setImageInstrumentRef(instrumentID, i);
        store.setImageExperimentRef(experimentID, i);
        int wellRow = well / wellCols;
        int wellCol = well % wellCols;
        wellIndex = i / (fieldCount * totalTimepoints);
        if (well != prevWell) {
            String wellID = MetadataTools.createLSID("Well", 0, wellIndex);
            store.setWellID(wellID, 0, wellIndex);
            store.setWellRow(new NonNegativeInteger(wellRow), 0, wellIndex);
            store.setWellColumn(new NonNegativeInteger(wellCol), 0, wellIndex);
            prevWell = well;
        }
        char rowChar = rowName.charAt(rowName.length() - 1);
        char colChar = colName.charAt(colName.length() - 1);
        String row = rowName.substring(0, rowName.length() - 1);
        String col = colName.substring(0, colName.length() - 1);
        if (Character.isDigit(rowChar)) {
            row += wellRow + Integer.parseInt(String.valueOf(rowChar));
        } else
            row += (char) (rowChar + wellRow);
        if (Character.isDigit(colChar)) {
            col += wellCol + Integer.parseInt(String.valueOf(colChar));
        } else
            col += (char) (colChar + wellCol);
        String imageName = "Well " + row + "-" + col + ", Field #" + (field + 1);
        if (timepoint >= 0) {
            imageName += ", Timepoint #" + timepoint;
        }
        store.setImageName(imageName, i);
        if (creationDate != null) {
            store.setImageAcquisitionDate(new Timestamp(creationDate), i);
        }
        timepoint--;
        if (timepoint < 0)
            timepoint = 0;
        int sampleIndex = field * totalTimepoints + timepoint;
        String wellSampleID = MetadataTools.createLSID("WellSample", 0, wellIndex, sampleIndex);
        store.setWellSampleID(wellSampleID, 0, wellIndex, sampleIndex);
        store.setWellSampleIndex(new NonNegativeInteger(i), 0, wellIndex, sampleIndex);
        store.setWellSampleImageRef(imageID, 0, wellIndex, sampleIndex);
        if (posX.containsKey(field)) {
            store.setWellSamplePositionX(posX.get(field), 0, wellIndex, sampleIndex);
        }
        if (posY.containsKey(field)) {
            store.setWellSamplePositionY(posY.get(field), 0, wellIndex, sampleIndex);
        }
        store.setPlateAcquisitionWellSampleRef(wellSampleID, 0, 0, i);
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        for (int i = 0; i < seriesCount; i++) {
            setSeries(i);
            int well = getWellFromSeries(i);
            int field = getFieldFromSeries(i);
            int timepoint = oneTimepointPerSeries ? i % channelsPerTimepoint.size() : 0;
            for (int time = 0; time < getSizeT(); time++) {
                if (!oneTimepointPerSeries)
                    timepoint = time;
                int c = channelsPerTimepoint.get(timepoint).intValue();
                for (int q = 0; q < getSizeZ() * c; q++) {
                    Image img = imageFiles[well][field][timepoint][q];
                    if (img == null)
                        continue;
                    int plane = time * getSizeZ() * c + q;
                    if (img.deltaT != null) {
                        store.setPlaneDeltaT(new Time(img.deltaT, UNITS.SECOND), i, plane);
                    }
                    if (img.exposure != null) {
                        store.setPlaneExposureTime(new Time(img.exposure, UNITS.SECOND), i, plane);
                    }
                    store.setPlanePositionX(posX.get(field), i, plane);
                    store.setPlanePositionY(posY.get(field), i, plane);
                    store.setPlanePositionZ(img.zPosition, i, plane);
                }
            }
            // populate LogicalChannel data
            for (int q = 0; q < getEffectiveSizeC(); q++) {
                if (q < channelNames.size()) {
                    store.setChannelName(channelNames.get(q), i, q);
                }
                if (q < emWaves.size()) {
                    Double wave = emWaves.get(q);
                    Length emission = FormatTools.getEmissionWavelength(wave);
                    if (emission != null) {
                        store.setChannelEmissionWavelength(emission, i, q);
                    }
                }
                if (q < exWaves.size()) {
                    Double wave = exWaves.get(q);
                    Length excitation = FormatTools.getExcitationWavelength(wave);
                    if (excitation != null) {
                        store.setChannelExcitationWavelength(excitation, i, q);
                    }
                }
                if (detectorID != null) {
                    store.setDetectorSettingsID(detectorID, i, q);
                    if (bin != null) {
                        store.setDetectorSettingsBinning(bin, i, q);
                    }
                    if (gain != null) {
                        store.setDetectorSettingsGain(gain, i, q);
                    }
                }
            }
            if (temperature != null) {
                store.setImagingEnvironmentTemperature(new Temperature(temperature, UNITS.CELSIUS), i);
            }
        }
        setSeries(0);
        // populate Plate data
        store.setPlateWellOriginX(new Length(0.5, UNITS.MICROMETER), 0);
        store.setPlateWellOriginY(new Length(0.5, UNITS.MICROMETER), 0);
    }
}
Also used : Temperature(ome.units.quantity.Temperature) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp) PositiveInteger(ome.xml.model.primitives.PositiveInteger) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) CoreMetadata(loci.formats.CoreMetadata) DefaultHandler(org.xml.sax.helpers.DefaultHandler) PositiveInteger(ome.xml.model.primitives.PositiveInteger) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) RandomAccessInputStream(loci.common.RandomAccessInputStream) Location(loci.common.Location)

Aggregations

Temperature (ome.units.quantity.Temperature)9 Time (ome.units.quantity.Time)9 Length (ome.units.quantity.Length)8 MetadataStore (loci.formats.meta.MetadataStore)7 Timestamp (ome.xml.model.primitives.Timestamp)7 Location (loci.common.Location)5 CoreMetadata (loci.formats.CoreMetadata)4 Frequency (ome.units.quantity.Frequency)4 ArrayList (java.util.ArrayList)3 RandomAccessInputStream (loci.common.RandomAccessInputStream)3 ElectricPotential (ome.units.quantity.ElectricPotential)3 NonNegativeInteger (ome.xml.model.primitives.NonNegativeInteger)3 PositiveInteger (ome.xml.model.primitives.PositiveInteger)3 FormatException (loci.formats.FormatException)2 IFD (loci.formats.tiff.IFD)2 Color (ome.xml.model.primitives.Color)2 IOException (java.io.IOException)1 BigDecimal (java.math.BigDecimal)1 MathContext (java.math.MathContext)1 AbstractMap (java.util.AbstractMap)1