Search in sources :

Example 71 with Length

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

the class FakeReader method parseSeriesTable.

/**
 * Translate key/value pairs from the INI table for the specified series.
 */
private void parseSeriesTable(IniTable table, MetadataStore store, int newSeries) {
    int s = getSeries();
    setSeries(newSeries);
    for (int i = 0; i < getImageCount(); i++) {
        String exposureTime = table.get("ExposureTime_" + i);
        String exposureTimeUnit = table.get("ExposureTimeUnit_" + i);
        if (exposureTime != null) {
            try {
                Double v = Double.valueOf(exposureTime);
                Time exposure = FormatTools.getTime(v, exposureTimeUnit);
                if (exposure != null) {
                    store.setPlaneExposureTime(exposure, newSeries, i);
                }
            } catch (NumberFormatException e) {
                LOGGER.trace("Could not parse ExposureTime for series #" + s + " plane #" + i, e);
            }
        }
        // TODO: could be cleaned up further when Java 8 is the minimum version
        Length x = parsePosition("X", s, i, table);
        if (x != null) {
            store.setPlanePositionX(x, newSeries, i);
        }
        Length y = parsePosition("Y", s, i, table);
        if (y != null) {
            store.setPlanePositionY(y, newSeries, i);
        }
        Length z = parsePosition("Z", s, i, table);
        if (z != null) {
            store.setPlanePositionZ(z, newSeries, i);
        }
    }
    setSeries(s);
}
Also used : UnitsLength(ome.xml.model.enums.UnitsLength) Length(ome.units.quantity.Length) Time(ome.units.quantity.Time)

Example 72 with Length

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

the class FakeReader method parsePosition.

private Length parsePosition(String axis, int s, int index, IniTable table) {
    String position = table.get("Position" + axis + "_" + index);
    String positionUnit = table.get("Position" + axis + "Unit_" + index);
    if (position != null) {
        try {
            Double v = Double.valueOf(position);
            Length size = new Length(v, UNITS.MICROM);
            if (positionUnit != null) {
                try {
                    UnitsLength ul = UnitsLength.fromString(positionUnit);
                    size = UnitsLength.create(v, ul);
                } catch (EnumerationException e) {
                    LOGGER.trace("Could not parse Position" + axis + "Unit for series #" + s + " plane #" + index, e);
                }
            }
            return size;
        } catch (NumberFormatException e) {
            LOGGER.trace("Could not parse Position" + axis + " for series #" + s + " plane #" + index, e);
        }
    }
    return null;
}
Also used : UnitsLength(ome.xml.model.enums.UnitsLength) UnitsLength(ome.xml.model.enums.UnitsLength) Length(ome.units.quantity.Length) EnumerationException(ome.xml.model.enums.EnumerationException)

Example 73 with Length

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

the class TiffWriter method prepareToWriteImage.

/**
 * Performs the preparation for work prior to the usage of the TIFF saver.
 * This method is factored out from <code>saveBytes()</code> in an attempt to
 * ensure thread safety.
 */
protected int prepareToWriteImage(int no, byte[] buf, IFD ifd, int x, int y, int w, int h) throws IOException, FormatException {
    MetadataRetrieve retrieve = getMetadataRetrieve();
    boolean littleEndian = false;
    if (retrieve.getPixelsBigEndian(series) != null) {
        littleEndian = !retrieve.getPixelsBigEndian(series).booleanValue();
    } else if (retrieve.getPixelsBinDataCount(series) == 0) {
        littleEndian = !retrieve.getPixelsBinDataBigEndian(series, 0).booleanValue();
    }
    // at one time.
    synchronized (this) {
        if (!initialized[series][no]) {
            initialized[series][no] = true;
            RandomAccessInputStream tmp = createInputStream();
            if (tmp.length() == 0) {
                synchronized (this) {
                    // write TIFF header
                    tiffSaver.writeHeader();
                }
            }
            tmp.close();
        }
    }
    int c = getSamplesPerPixel();
    int type = FormatTools.pixelTypeFromString(retrieve.getPixelsType(series).toString());
    int bytesPerPixel = FormatTools.getBytesPerPixel(type);
    int blockSize = w * h * c * bytesPerPixel;
    if (blockSize > buf.length) {
        c = buf.length / (w * h * bytesPerPixel);
    }
    formatCompression(ifd);
    byte[][] lut = AWTImageTools.get8BitLookupTable(cm);
    if (lut != null) {
        int[] colorMap = new int[lut.length * lut[0].length];
        for (int i = 0; i < lut.length; i++) {
            for (int j = 0; j < lut[0].length; j++) {
                colorMap[i * lut[0].length + j] = (int) ((lut[i][j] & 0xff) << 8);
            }
        }
        ifd.putIFDValue(IFD.COLOR_MAP, colorMap);
    } else {
        short[][] lut16 = AWTImageTools.getLookupTable(cm);
        if (lut16 != null) {
            int[] colorMap = new int[lut16.length * lut16[0].length];
            for (int i = 0; i < lut16.length; i++) {
                for (int j = 0; j < lut16[0].length; j++) {
                    colorMap[i * lut16[0].length + j] = (int) (lut16[i][j] & 0xffff);
                }
            }
            ifd.putIFDValue(IFD.COLOR_MAP, colorMap);
        }
    }
    int width = retrieve.getPixelsSizeX(series).getValue().intValue();
    int height = retrieve.getPixelsSizeY(series).getValue().intValue();
    ifd.put(new Integer(IFD.IMAGE_WIDTH), new Long(width));
    ifd.put(new Integer(IFD.IMAGE_LENGTH), new Long(height));
    Length px = retrieve.getPixelsPhysicalSizeX(series);
    Double physicalSizeX = px == null || px.value(UNITS.MICROMETER) == null ? null : px.value(UNITS.MICROMETER).doubleValue();
    if (physicalSizeX == null || physicalSizeX.doubleValue() == 0) {
        physicalSizeX = 0d;
    } else
        physicalSizeX = 1d / physicalSizeX;
    Length py = retrieve.getPixelsPhysicalSizeY(series);
    Double physicalSizeY = py == null || py.value(UNITS.MICROMETER) == null ? null : py.value(UNITS.MICROMETER).doubleValue();
    if (physicalSizeY == null || physicalSizeY.doubleValue() == 0) {
        physicalSizeY = 0d;
    } else
        physicalSizeY = 1d / physicalSizeY;
    ifd.put(IFD.RESOLUTION_UNIT, 3);
    ifd.put(IFD.X_RESOLUTION, new TiffRational((long) (physicalSizeX * 1000 * 10000), 1000));
    ifd.put(IFD.Y_RESOLUTION, new TiffRational((long) (physicalSizeY * 1000 * 10000), 1000));
    if (!isBigTiff) {
        isBigTiff = (out.length() + 2 * (width * height * c * bytesPerPixel)) >= 4294967296L;
        if (isBigTiff) {
            throw new FormatException("File is too large; call setBigTiff(true)");
        }
    }
    // write the image
    ifd.put(new Integer(IFD.LITTLE_ENDIAN), new Boolean(littleEndian));
    if (!ifd.containsKey(IFD.REUSE)) {
        ifd.put(IFD.REUSE, out.length());
        out.seek(out.length());
    } else {
        out.seek((Long) ifd.get(IFD.REUSE));
    }
    ifd.putIFDValue(IFD.PLANAR_CONFIGURATION, interleaved || getSamplesPerPixel() == 1 ? 1 : 2);
    int sampleFormat = 1;
    if (FormatTools.isSigned(type))
        sampleFormat = 2;
    if (FormatTools.isFloatingPoint(type))
        sampleFormat = 3;
    ifd.putIFDValue(IFD.SAMPLE_FORMAT, sampleFormat);
    int channels = retrieve.getPixelsSizeC(series).getValue().intValue();
    int z = retrieve.getPixelsSizeZ(series).getValue().intValue();
    int t = retrieve.getPixelsSizeT(series).getValue().intValue();
    ifd.putIFDValue(IFD.IMAGE_DESCRIPTION, "ImageJ=\nhyperstack=true\nimages=" + (channels * z * t) + "\nchannels=" + channels + "\nslices=" + z + "\nframes=" + t);
    int index = no;
    for (int i = 0; i < getSeries(); i++) {
        index += getPlaneCount(i);
    }
    return index;
}
Also used : TiffRational(loci.formats.tiff.TiffRational) FormatException(loci.formats.FormatException) Length(ome.units.quantity.Length) RandomAccessInputStream(loci.common.RandomAccessInputStream) MetadataRetrieve(loci.formats.meta.MetadataRetrieve)

Example 74 with Length

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

the class ROIHandler method storeLine.

/**
 * Stores the Line ROI into the specified metadata store.
 *
 * @param roi The roi to convert.
 * @param store The store to handle.
 * @param roiNum The roi number
 * @param shape The index of the shape.
 * @param c The selected channel.
 * @param z The selected slice.
 * @param t The selected timepoint.
 */
private static void storeLine(Line roi, MetadataStore store, int roiNum, int shape, int c, int z, int t) {
    store.setLineX1(new Double(roi.x1), roiNum, shape);
    store.setLineX2(new Double(roi.x2), roiNum, shape);
    store.setLineY1(new Double(roi.y1), roiNum, shape);
    store.setLineY2(new Double(roi.y2), roiNum, shape);
    if (c >= 0) {
        store.setLineTheC(unwrap(c), roiNum, shape);
    }
    if (z >= 0) {
        store.setLineTheZ(unwrap(z), roiNum, shape);
    }
    if (t >= 0) {
        store.setLineTheT(unwrap(t), roiNum, shape);
    }
    store.setLineText(roi.getName(), roiNum, shape);
    if (roi.getStrokeWidth() > 0) {
        store.setLineStrokeWidth(new Length((roi.getStrokeWidth()), UNITS.PIXEL), roiNum, shape);
    }
    if (roi.getStrokeColor() != null) {
        store.setLineStrokeColor(toOMExmlColor(roi.getStrokeColor()), roiNum, shape);
    }
    if (roi.getFillColor() != null) {
        store.setLineFillColor(toOMExmlColor(roi.getFillColor()), roiNum, shape);
    }
}
Also used : Length(ome.units.quantity.Length)

Example 75 with Length

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

the class ICSReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    LOGGER.info("Finding companion file");
    String icsId = id, idsId = id;
    int dot = id.lastIndexOf(".");
    String ext = dot < 0 ? "" : id.substring(dot + 1).toLowerCase();
    if (ext.equals("ics")) {
        // convert C to D regardless of case
        char[] c = idsId.toCharArray();
        c[c.length - 2]++;
        idsId = new String(c);
    } else if (ext.equals("ids")) {
        // convert D to C regardless of case
        char[] c = icsId.toCharArray();
        c[c.length - 2]--;
        icsId = new String(c);
    }
    if (icsId == null)
        throw new FormatException("No ICS file found.");
    Location icsFile = new Location(icsId);
    if (!icsFile.exists())
        throw new FormatException("ICS file not found.");
    LOGGER.info("Checking file version");
    // check if we have a v2 ICS file - means there is no companion IDS file
    RandomAccessInputStream f = new RandomAccessInputStream(icsId);
    if (f.readString(17).trim().equals("ics_version\t2.0")) {
        in = new RandomAccessInputStream(icsId);
        versionTwo = true;
    } else {
        if (idsId == null) {
            f.close();
            throw new FormatException("No IDS file found.");
        }
        Location idsFile = new Location(idsId);
        if (!idsFile.exists()) {
            f.close();
            throw new FormatException("IDS file not found.");
        }
        currentIdsId = idsId;
        in = new RandomAccessInputStream(currentIdsId);
    }
    f.close();
    currentIcsId = icsId;
    LOGGER.info("Reading metadata");
    CoreMetadata m = core.get(0);
    Double[] scales = null;
    Double[] timestamps = null;
    String[] units = null;
    String[] axes = null;
    int[] axisLengths = null;
    String byteOrder = null, rFormat = null, compression = null;
    // parse key/value pairs from beginning of ICS file
    RandomAccessInputStream reader = new RandomAccessInputStream(icsId);
    reader.seek(0);
    reader.readString(NL);
    String line = reader.readString(NL);
    boolean signed = false;
    final StringBuilder textBlock = new StringBuilder();
    double[] sizes = null;
    Double[] emWaves = null, exWaves = null;
    Length[] stagePos = null;
    String imageName = null, date = null, description = null;
    Double magnification = null, lensNA = null, workingDistance = null;
    String objectiveModel = null, immersion = null, lastName = null;
    Hashtable<Integer, Double> gains = new Hashtable<Integer, Double>();
    Hashtable<Integer, Double> pinholes = new Hashtable<Integer, Double>();
    Hashtable<Integer, Double> wavelengths = new Hashtable<Integer, Double>();
    Hashtable<Integer, String> channelNames = new Hashtable<Integer, String>();
    String laserModel = null;
    String laserManufacturer = null;
    Double laserPower = null;
    Double laserRepetitionRate = null;
    String detectorManufacturer = null;
    String detectorModel = null;
    String microscopeModel = null;
    String microscopeManufacturer = null;
    String experimentType = null;
    Time exposureTime = null;
    String filterSetModel = null;
    String dichroicModel = null;
    String excitationModel = null;
    String emissionModel = null;
    while (line != null && !line.trim().equals("end") && reader.getFilePointer() < reader.length() - 1) {
        line = line.trim();
        if (line.length() > 0) {
            // split the line into tokens
            String[] tokens = tokenize(line);
            String token0 = tokens[0].toLowerCase();
            String[] keyValue = null;
            // version category
            if (token0.equals("ics_version")) {
                String value = concatenateTokens(tokens, 1, tokens.length);
                addGlobalMeta(token0, value);
            } else // filename category
            if (token0.equals("filename")) {
                imageName = concatenateTokens(tokens, 1, tokens.length);
                addGlobalMeta(token0, imageName);
            } else // layout category
            if (token0.equals("layout")) {
                keyValue = findKeyValue(tokens, LAYOUT_KEYS);
                String key = keyValue[0];
                String value = keyValue[1];
                addGlobalMeta(key, value);
                if (key.equalsIgnoreCase("layout sizes")) {
                    StringTokenizer t = new StringTokenizer(value);
                    axisLengths = new int[t.countTokens()];
                    for (int n = 0; n < axisLengths.length; n++) {
                        try {
                            axisLengths[n] = Integer.parseInt(t.nextToken().trim());
                        } catch (NumberFormatException e) {
                            LOGGER.debug("Could not parse axis length", e);
                        }
                    }
                } else if (key.equalsIgnoreCase("layout order")) {
                    StringTokenizer t = new StringTokenizer(value);
                    axes = new String[t.countTokens()];
                    for (int n = 0; n < axes.length; n++) {
                        axes[n] = t.nextToken().trim();
                    }
                } else if (key.equalsIgnoreCase("layout significant_bits")) {
                    m.bitsPerPixel = Integer.parseInt(value);
                }
            } else // representation category
            if (token0.equals("representation")) {
                keyValue = findKeyValue(tokens, REPRESENTATION_KEYS);
                String key = keyValue[0];
                String value = keyValue[1];
                addGlobalMeta(key, value);
                if (key.equalsIgnoreCase("representation byte_order")) {
                    byteOrder = value;
                } else if (key.equalsIgnoreCase("representation format")) {
                    rFormat = value;
                } else if (key.equalsIgnoreCase("representation compression")) {
                    compression = value;
                } else if (key.equalsIgnoreCase("representation sign")) {
                    signed = value.equals("signed");
                }
            } else // parameter category
            if (token0.equals("parameter")) {
                keyValue = findKeyValue(tokens, PARAMETER_KEYS);
                String key = keyValue[0];
                String value = keyValue[1];
                addGlobalMeta(key, value);
                if (key.equalsIgnoreCase("parameter scale")) {
                    // parse physical pixel sizes and time increment
                    scales = splitDoubles(value);
                } else if (key.equalsIgnoreCase("parameter t")) {
                    // parse explicit timestamps
                    timestamps = splitDoubles(value);
                } else if (key.equalsIgnoreCase("parameter units")) {
                    // parse units for scale
                    units = value.split("\\s+");
                }
                if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
                    if (key.equalsIgnoreCase("parameter ch")) {
                        String[] names = value.split(" ");
                        for (int n = 0; n < names.length; n++) {
                            channelNames.put(new Integer(n), names[n].trim());
                        }
                    }
                }
            } else // history category
            if (token0.equals("history")) {
                keyValue = findKeyValue(tokens, HISTORY_KEYS);
                String key = keyValue[0];
                String value = keyValue[1];
                addGlobalMeta(key, value);
                Double doubleValue = null;
                try {
                    doubleValue = new Double(value);
                } catch (NumberFormatException e) {
                    // ARG this happens a lot; spurious error in most cases
                    LOGGER.debug("Could not parse double value '{}'", value, e);
                }
                if (key.equalsIgnoreCase("history software") && value.indexOf("SVI") != -1) {
                    // ICS files written by SVI Huygens are inverted on the Y axis
                    invertY = true;
                } else if (key.equalsIgnoreCase("history date") || key.equalsIgnoreCase("history created on")) {
                    if (value.indexOf(' ') > 0) {
                        date = value.substring(0, value.lastIndexOf(" "));
                        date = DateTools.formatDate(date, DATE_FORMATS);
                    }
                } else if (key.equalsIgnoreCase("history creation date")) {
                    date = DateTools.formatDate(value, DATE_FORMATS);
                } else if (key.equalsIgnoreCase("history type")) {
                    // HACK - support for Gray Institute at Oxford's ICS lifetime data
                    if (value.equalsIgnoreCase("time resolved") || value.equalsIgnoreCase("FluorescenceLifetime")) {
                        lifetime = true;
                    }
                    experimentType = value;
                } else if (key.equalsIgnoreCase("history labels")) {
                    // HACK - support for Gray Institute at Oxford's ICS lifetime data
                    labels = value;
                } else if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
                    if (key.equalsIgnoreCase("history") || key.equalsIgnoreCase("history text")) {
                        textBlock.append(value);
                        textBlock.append("\n");
                        metadata.remove(key);
                    } else if (key.startsWith("history gain")) {
                        Integer n = 0;
                        try {
                            n = new Integer(key.substring(12).trim());
                            n = new Integer(n.intValue() - 1);
                        } catch (NumberFormatException e) {
                        }
                        if (doubleValue != null) {
                            gains.put(n, doubleValue);
                        }
                    } else if (key.startsWith("history laser") && key.endsWith("wavelength")) {
                        int laser = Integer.parseInt(key.substring(13, key.indexOf(" ", 13))) - 1;
                        value = value.replaceAll("nm", "").trim();
                        try {
                            wavelengths.put(new Integer(laser), new Double(value));
                        } catch (NumberFormatException e) {
                            LOGGER.debug("Could not parse wavelength", e);
                        }
                    } else if (key.equalsIgnoreCase("history Wavelength*")) {
                        String[] waves = value.split(" ");
                        for (int i = 0; i < waves.length; i++) {
                            wavelengths.put(new Integer(i), new Double(waves[i]));
                        }
                    } else if (key.equalsIgnoreCase("history laser manufacturer")) {
                        laserManufacturer = value;
                    } else if (key.equalsIgnoreCase("history laser model")) {
                        laserModel = value;
                    } else if (key.equalsIgnoreCase("history laser power")) {
                        try {
                            // TODO ARG i.e. doubleValue
                            laserPower = new Double(value);
                        } catch (NumberFormatException e) {
                        }
                    } else if (key.equalsIgnoreCase("history laser rep rate")) {
                        String repRate = value;
                        if (repRate.indexOf(' ') != -1) {
                            repRate = repRate.substring(0, repRate.lastIndexOf(" "));
                        }
                        laserRepetitionRate = new Double(repRate);
                    } else if (key.equalsIgnoreCase("history objective type") || key.equalsIgnoreCase("history objective")) {
                        objectiveModel = value;
                    } else if (key.equalsIgnoreCase("history objective immersion")) {
                        immersion = value;
                    } else if (key.equalsIgnoreCase("history objective NA")) {
                        lensNA = doubleValue;
                    } else if (key.equalsIgnoreCase("history objective WorkingDistance")) {
                        workingDistance = doubleValue;
                    } else if (key.equalsIgnoreCase("history objective magnification") || key.equalsIgnoreCase("history objective mag")) {
                        magnification = doubleValue;
                    } else if (key.equalsIgnoreCase("history camera manufacturer")) {
                        detectorManufacturer = value;
                    } else if (key.equalsIgnoreCase("history camera model")) {
                        detectorModel = value;
                    } else if (key.equalsIgnoreCase("history author") || key.equalsIgnoreCase("history experimenter")) {
                        lastName = value;
                    } else if (key.equalsIgnoreCase("history extents")) {
                        String[] lengths = value.split(" ");
                        sizes = new double[lengths.length];
                        for (int n = 0; n < sizes.length; n++) {
                            try {
                                sizes[n] = Double.parseDouble(lengths[n].trim());
                            } catch (NumberFormatException e) {
                                LOGGER.debug("Could not parse axis length", e);
                            }
                        }
                    } else if (key.equalsIgnoreCase("history stage_xyzum")) {
                        String[] positions = value.split(" ");
                        stagePos = new Length[positions.length];
                        for (int n = 0; n < stagePos.length; n++) {
                            try {
                                final Double number = Double.valueOf(positions[n]);
                                stagePos[n] = new Length(number, UNITS.REFERENCEFRAME);
                            } catch (NumberFormatException e) {
                                LOGGER.debug("Could not parse stage position", e);
                            }
                        }
                    } else if (key.equalsIgnoreCase("history stage positionx")) {
                        if (stagePos == null) {
                            stagePos = new Length[3];
                        }
                        final Double number = Double.valueOf(value);
                        stagePos[0] = new Length(number, UNITS.REFERENCEFRAME);
                    } else if (key.equalsIgnoreCase("history stage positiony")) {
                        if (stagePos == null) {
                            stagePos = new Length[3];
                        }
                        final Double number = Double.valueOf(value);
                        stagePos[1] = new Length(number, UNITS.REFERENCEFRAME);
                    } else if (key.equalsIgnoreCase("history stage positionz")) {
                        if (stagePos == null) {
                            stagePos = new Length[3];
                        }
                        final Double number = Double.valueOf(value);
                        stagePos[2] = new Length(number, UNITS.REFERENCEFRAME);
                    } else if (key.equalsIgnoreCase("history other text")) {
                        description = value;
                    } else if (key.startsWith("history step") && key.endsWith("name")) {
                        Integer n = new Integer(key.substring(12, key.indexOf(" ", 12)));
                        channelNames.put(n, value);
                    } else if (key.equalsIgnoreCase("history cube")) {
                        channelNames.put(new Integer(channelNames.size()), value);
                    } else if (key.equalsIgnoreCase("history cube emm nm")) {
                        if (emWaves == null) {
                            emWaves = new Double[1];
                        }
                        emWaves[0] = new Double(value.split(" ")[1].trim());
                    } else if (key.equalsIgnoreCase("history cube exc nm")) {
                        if (exWaves == null) {
                            exWaves = new Double[1];
                        }
                        exWaves[0] = new Double(value.split(" ")[1].trim());
                    } else if (key.equalsIgnoreCase("history microscope")) {
                        microscopeModel = value;
                    } else if (key.equalsIgnoreCase("history manufacturer")) {
                        microscopeManufacturer = value;
                    } else if (key.equalsIgnoreCase("history Exposure")) {
                        String expTime = value;
                        if (expTime.indexOf(' ') != -1) {
                            expTime = expTime.substring(0, expTime.indexOf(' '));
                        }
                        Double expDouble = new Double(expTime);
                        if (expDouble != null) {
                            exposureTime = new Time(expDouble, UNITS.SECOND);
                        }
                    } else if (key.equalsIgnoreCase("history filterset")) {
                        filterSetModel = value;
                    } else if (key.equalsIgnoreCase("history filterset dichroic name")) {
                        dichroicModel = value;
                    } else if (key.equalsIgnoreCase("history filterset exc name")) {
                        excitationModel = value;
                    } else if (key.equalsIgnoreCase("history filterset emm name")) {
                        emissionModel = value;
                    }
                }
            } else // document category
            if (token0.equals("document")) {
                keyValue = findKeyValue(tokens, DOCUMENT_KEYS);
                String key = keyValue[0];
                String value = keyValue[1];
                addGlobalMeta(key, value);
            } else // sensor category
            if (token0.equals("sensor")) {
                keyValue = findKeyValue(tokens, SENSOR_KEYS);
                String key = keyValue[0];
                String value = keyValue[1];
                addGlobalMeta(key, value);
                if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
                    if (key.equalsIgnoreCase("sensor s_params LambdaEm")) {
                        String[] waves = value.split(" ");
                        emWaves = new Double[waves.length];
                        for (int n = 0; n < emWaves.length; n++) {
                            try {
                                emWaves[n] = new Double(Double.parseDouble(waves[n]));
                            } catch (NumberFormatException e) {
                                LOGGER.debug("Could not parse emission wavelength", e);
                            }
                        }
                    } else if (key.equalsIgnoreCase("sensor s_params LambdaEx")) {
                        String[] waves = value.split(" ");
                        exWaves = new Double[waves.length];
                        for (int n = 0; n < exWaves.length; n++) {
                            try {
                                exWaves[n] = new Double(Double.parseDouble(waves[n]));
                            } catch (NumberFormatException e) {
                                LOGGER.debug("Could not parse excitation wavelength", e);
                            }
                        }
                    } else if (key.equalsIgnoreCase("sensor s_params PinholeRadius")) {
                        String[] pins = value.split(" ");
                        int channel = 0;
                        for (int n = 0; n < pins.length; n++) {
                            if (pins[n].trim().equals(""))
                                continue;
                            try {
                                pinholes.put(new Integer(channel++), new Double(pins[n]));
                            } catch (NumberFormatException e) {
                                LOGGER.debug("Could not parse pinhole", e);
                            }
                        }
                    }
                }
            } else // view category
            if (token0.equals("view")) {
                keyValue = findKeyValue(tokens, VIEW_KEYS);
                String key = keyValue[0];
                String value = keyValue[1];
                // handle "view view color lib lut Green Fire green", etc.
                if (key.equalsIgnoreCase("view view color lib lut")) {
                    int index;
                    int redIndex = value.toLowerCase().lastIndexOf("red");
                    int greenIndex = value.toLowerCase().lastIndexOf("green");
                    int blueIndex = value.toLowerCase().lastIndexOf("blue");
                    if (redIndex > 0 && redIndex > greenIndex && redIndex > blueIndex) {
                        index = redIndex + "red".length();
                    } else if (greenIndex > 0 && greenIndex > redIndex && greenIndex > blueIndex) {
                        index = greenIndex + "green".length();
                    } else if (blueIndex > 0 && blueIndex > redIndex && blueIndex > greenIndex) {
                        index = blueIndex + "blue".length();
                    } else {
                        index = value.indexOf(' ');
                    }
                    if (index > 0) {
                        key = key + ' ' + value.substring(0, index);
                        value = value.substring(index + 1);
                    }
                } else // "view view color mode rgb set blue-green-red", etc.
                if (key.equalsIgnoreCase("view view color mode rgb set")) {
                    int index = value.toLowerCase().lastIndexOf("colors");
                    if (index > 0) {
                        index += "colors".length();
                    } else {
                        index = value.indexOf(' ');
                    }
                    if (index > 0) {
                        key = key + ' ' + value.substring(0, index);
                        value = value.substring(index + 1);
                    }
                }
                addGlobalMeta(key, value);
            } else {
                LOGGER.debug("Unknown category " + token0);
            }
        }
        line = reader.readString(NL);
    }
    reader.close();
    hasInstrumentData = emWaves != null || exWaves != null || lensNA != null || stagePos != null || magnification != null || workingDistance != null || objectiveModel != null || immersion != null;
    addGlobalMeta("history text", textBlock.toString());
    LOGGER.info("Populating core metadata");
    m.rgb = false;
    m.dimensionOrder = "XY";
    // find axis sizes
    channelLengths = new Vector<Integer>();
    channelTypes = new Vector<String>();
    int bitsPerPixel = 0;
    for (int i = 0; i < axes.length; i++) {
        if (i >= axisLengths.length)
            break;
        if (axes[i].equals("bits")) {
            bitsPerPixel = axisLengths[i];
            while (bitsPerPixel % 8 != 0) bitsPerPixel++;
            if (bitsPerPixel == 24 || bitsPerPixel == 48)
                bitsPerPixel /= 3;
        } else if (axes[i].equals("x")) {
            m.sizeX = axisLengths[i];
        } else if (axes[i].equals("y")) {
            m.sizeY = axisLengths[i];
        } else if (axes[i].equals("z")) {
            m.sizeZ = axisLengths[i];
            if (getDimensionOrder().indexOf('Z') == -1) {
                m.dimensionOrder += 'Z';
            }
        } else if (axes[i].equals("t")) {
            if (getSizeT() == 0)
                m.sizeT = axisLengths[i];
            else
                m.sizeT *= axisLengths[i];
            if (getDimensionOrder().indexOf('T') == -1) {
                m.dimensionOrder += 'T';
            }
        } else {
            if (m.sizeC == 0)
                m.sizeC = axisLengths[i];
            else
                m.sizeC *= axisLengths[i];
            channelLengths.add(new Integer(axisLengths[i]));
            storedRGB = getSizeX() == 0;
            m.rgb = getSizeX() == 0 && getSizeC() <= 4 && getSizeC() > 1;
            if (getDimensionOrder().indexOf('C') == -1) {
                m.dimensionOrder += 'C';
            }
            if (axes[i].startsWith("c")) {
                channelTypes.add(FormatTools.CHANNEL);
            } else if (axes[i].equals("p")) {
                channelTypes.add(FormatTools.PHASE);
            } else if (axes[i].equals("f")) {
                channelTypes.add(FormatTools.FREQUENCY);
            } else
                channelTypes.add("");
        }
    }
    if (channelLengths.isEmpty()) {
        channelLengths.add(1);
        channelTypes.add(FormatTools.CHANNEL);
    }
    if (isRGB() && emWaves != null && emWaves.length == getSizeC()) {
        m.rgb = false;
        storedRGB = true;
    }
    m.dimensionOrder = MetadataTools.makeSaneDimensionOrder(getDimensionOrder());
    if (getSizeZ() == 0)
        m.sizeZ = 1;
    if (getSizeC() == 0)
        m.sizeC = 1;
    if (getSizeT() == 0)
        m.sizeT = 1;
    // length and type.
    if (channelLengths.size() > 0) {
        int clen0 = channelLengths.get(0);
        String ctype0 = channelTypes.get(0);
        boolean same = true;
        for (Integer len : channelLengths) {
            if (clen0 != len)
                same = false;
        }
        for (String type : channelTypes) {
            if (!ctype0.equals(type))
                same = false;
        }
        if (same) {
            m.moduloC.type = ctype0;
            if (FormatTools.LIFETIME.equals(ctype0)) {
                m.moduloC.parentType = FormatTools.SPECTRA;
            }
            m.moduloC.typeDescription = "TCSPC";
            m.moduloC.start = 0;
            m.moduloC.step = 1;
            m.moduloC.end = clen0 - 1;
        }
    }
    m.interleaved = isRGB();
    m.indexed = false;
    m.falseColor = false;
    m.metadataComplete = true;
    m.littleEndian = true;
    // HACK - support for Gray Institute at Oxford's ICS lifetime data
    if (lifetime && labels != null) {
        int binCount = 0;
        String newOrder = null;
        if (labels.equalsIgnoreCase("t x y")) {
            // nominal X Y Z is actually C X Y (which is X Y C interleaved)
            newOrder = "XYCZT";
            m.interleaved = true;
            binCount = m.sizeX;
            m.sizeX = m.sizeY;
            m.sizeY = m.sizeZ;
            m.sizeZ = 1;
        } else if (labels.equalsIgnoreCase("x y t")) {
            // nominal X Y Z is actually X Y C
            newOrder = "XYCZT";
            binCount = m.sizeZ;
            m.sizeZ = 1;
        } else {
            LOGGER.debug("Lifetime data, unexpected 'history labels' " + labels);
        }
        if (newOrder != null) {
            m.dimensionOrder = newOrder;
            m.sizeC = binCount;
            m.moduloC.parentType = FormatTools.LIFETIME;
        }
    }
    // do not modify the Z, T, or channel counts after this point
    m.imageCount = getSizeZ() * getSizeT();
    if (!isRGB())
        m.imageCount *= getSizeC();
    if (byteOrder != null) {
        String firstByte = byteOrder.split(" ")[0];
        int first = Integer.parseInt(firstByte);
        m.littleEndian = rFormat.equals("real") ? first == 1 : first != 1;
    }
    gzip = (compression == null) ? false : compression.equals("gzip");
    if (versionTwo) {
        String s = in.readString(NL);
        while (!s.trim().equals("end")) s = in.readString(NL);
    }
    offset = in.getFilePointer();
    int bytes = bitsPerPixel / 8;
    if (bitsPerPixel < 32)
        m.littleEndian = !isLittleEndian();
    boolean fp = rFormat.equals("real");
    m.pixelType = FormatTools.pixelTypeFromBytes(bytes, signed, fp);
    LOGGER.info("Populating OME metadata");
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);
    // populate Image data
    store.setImageName(imageName, 0);
    if (date != null)
        store.setImageAcquisitionDate(new Timestamp(date), 0);
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        store.setImageDescription(description, 0);
        // link Instrument and Image
        String instrumentID = MetadataTools.createLSID("Instrument", 0);
        store.setInstrumentID(instrumentID, 0);
        store.setMicroscopeModel(microscopeModel, 0);
        store.setMicroscopeManufacturer(microscopeManufacturer, 0);
        store.setImageInstrumentRef(instrumentID, 0);
        store.setExperimentID(MetadataTools.createLSID("Experiment", 0), 0);
        store.setExperimentType(getExperimentType(experimentType), 0);
        if (scales != null) {
            if (units != null && units.length == scales.length - 1) {
                // correct for missing units
                // sometimes, the units for the C axis are missing entirely
                ArrayList<String> realUnits = new ArrayList<String>();
                int unitIndex = 0;
                for (int i = 0; i < axes.length; i++) {
                    if (axes[i].toLowerCase().equals("ch")) {
                        realUnits.add("nm");
                    } else {
                        realUnits.add(units[unitIndex++]);
                    }
                }
                units = realUnits.toArray(new String[realUnits.size()]);
            }
            for (int i = 0; i < scales.length; i++) {
                Double scale = scales[i];
                if (scale == null) {
                    continue;
                }
                String axis = axes != null && axes.length > i ? axes[i] : "";
                String unit = units != null && units.length > i ? units[i] : "";
                if (axis.equals("x")) {
                    if (checkUnit(unit, "um", "microns", "micrometers")) {
                        Length x = FormatTools.getPhysicalSizeX(scale);
                        if (x != null) {
                            store.setPixelsPhysicalSizeX(x, 0);
                        }
                    }
                } else if (axis.equals("y")) {
                    if (checkUnit(unit, "um", "microns", "micrometers")) {
                        Length y = FormatTools.getPhysicalSizeY(scale);
                        if (y != null) {
                            store.setPixelsPhysicalSizeY(y, 0);
                        }
                    }
                } else if (axis.equals("z")) {
                    if (checkUnit(unit, "um", "microns", "micrometers")) {
                        Length z = FormatTools.getPhysicalSizeZ(scale);
                        if (z != null) {
                            store.setPixelsPhysicalSizeZ(z, 0);
                        }
                    }
                } else if (axis.equals("t") && scale != null) {
                    if (checkUnit(unit, "ms")) {
                        store.setPixelsTimeIncrement(new Time(scale, UNITS.MILLISECOND), 0);
                    } else if (checkUnit(unit, "seconds") || checkUnit(unit, "s")) {
                        store.setPixelsTimeIncrement(new Time(scale, UNITS.SECOND), 0);
                    }
                }
            }
        } else if (sizes != null) {
            if (sizes.length > 0) {
                Length x = FormatTools.getPhysicalSizeX(sizes[0]);
                if (x != null) {
                    store.setPixelsPhysicalSizeX(x, 0);
                }
            }
            if (sizes.length > 1) {
                sizes[1] /= getSizeY();
                Length y = FormatTools.getPhysicalSizeY(sizes[1]);
                if (y != null) {
                    store.setPixelsPhysicalSizeY(y, 0);
                }
            }
        }
        if (timestamps != null) {
            for (int t = 0; t < timestamps.length; t++) {
                // ignore superfluous timestamps
                if (t >= getSizeT())
                    break;
                // ignore missing timestamp
                if (timestamps[t] == null)
                    continue;
                Time deltaT = new Time(timestamps[t], UNITS.SECOND);
                // ignore invalid timestamp
                if (Double.isNaN(deltaT.value().doubleValue()))
                    continue;
                // assign timestamp to all relevant planes
                for (int z = 0; z < getSizeZ(); z++) {
                    for (int c = 0; c < getEffectiveSizeC(); c++) {
                        int index = getIndex(z, c, t);
                        store.setPlaneDeltaT(deltaT, 0, index);
                    }
                }
            }
        }
        for (int i = 0; i < getEffectiveSizeC(); i++) {
            if (channelNames.containsKey(i)) {
                store.setChannelName(channelNames.get(i), 0, i);
            }
            if (pinholes.containsKey(i)) {
                store.setChannelPinholeSize(new Length(pinholes.get(i), UNITS.MICROMETER), 0, i);
            }
            if (emWaves != null && i < emWaves.length) {
                Length em = FormatTools.getEmissionWavelength(emWaves[i]);
                if (em != null) {
                    store.setChannelEmissionWavelength(em, 0, i);
                }
            }
            if (exWaves != null && i < exWaves.length) {
                Length ex = FormatTools.getExcitationWavelength(exWaves[i]);
                if (ex != null) {
                    store.setChannelExcitationWavelength(ex, 0, i);
                }
            }
        }
        // populate Laser data
        Integer[] lasers = wavelengths.keySet().toArray(new Integer[0]);
        Arrays.sort(lasers);
        for (int i = 0; i < lasers.length; i++) {
            store.setLaserID(MetadataTools.createLSID("LightSource", 0, i), 0, i);
            Length wave = FormatTools.getWavelength(wavelengths.get(lasers[i]));
            if (wave != null) {
                store.setLaserWavelength(wave, 0, i);
            }
            store.setLaserType(getLaserType("Other"), 0, i);
            store.setLaserLaserMedium(getLaserMedium("Other"), 0, i);
            store.setLaserManufacturer(laserManufacturer, 0, i);
            store.setLaserModel(laserModel, 0, i);
            Power theLaserPower = FormatTools.createPower(laserPower, UNITS.MILLIWATT);
            if (theLaserPower != null) {
                store.setLaserPower(theLaserPower, 0, i);
            }
            Frequency theLaserRepetitionRate = FormatTools.createFrequency(laserRepetitionRate, UNITS.HERTZ);
            if (theLaserRepetitionRate != null) {
                store.setLaserRepetitionRate(theLaserRepetitionRate, 0, i);
            }
        }
        if (lasers.length == 0 && laserManufacturer != null) {
            store.setLaserID(MetadataTools.createLSID("LightSource", 0, 0), 0, 0);
            store.setLaserType(getLaserType("Other"), 0, 0);
            store.setLaserLaserMedium(getLaserMedium("Other"), 0, 0);
            store.setLaserManufacturer(laserManufacturer, 0, 0);
            store.setLaserModel(laserModel, 0, 0);
            Power theLaserPower = FormatTools.createPower(laserPower, UNITS.MILLIWATT);
            if (theLaserPower != null) {
                store.setLaserPower(theLaserPower, 0, 0);
            }
            Frequency theLaserRepetitionRate = FormatTools.createFrequency(laserRepetitionRate, UNITS.HERTZ);
            if (theLaserRepetitionRate != null) {
                store.setLaserRepetitionRate(theLaserRepetitionRate, 0, 0);
            }
        }
        if (filterSetModel != null) {
            store.setFilterSetID(MetadataTools.createLSID("FilterSet", 0, 0), 0, 0);
            store.setFilterSetModel(filterSetModel, 0, 0);
            String dichroicID = MetadataTools.createLSID("Dichroic", 0, 0);
            String emFilterID = MetadataTools.createLSID("Filter", 0, 0);
            String exFilterID = MetadataTools.createLSID("Filter", 0, 1);
            store.setDichroicID(dichroicID, 0, 0);
            store.setDichroicModel(dichroicModel, 0, 0);
            store.setFilterSetDichroicRef(dichroicID, 0, 0);
            store.setFilterID(emFilterID, 0, 0);
            store.setFilterModel(emissionModel, 0, 0);
            store.setFilterSetEmissionFilterRef(emFilterID, 0, 0, 0);
            store.setFilterID(exFilterID, 0, 1);
            store.setFilterModel(excitationModel, 0, 1);
            store.setFilterSetExcitationFilterRef(exFilterID, 0, 0, 0);
        }
        if (objectiveModel != null)
            store.setObjectiveModel(objectiveModel, 0, 0);
        if (immersion == null)
            immersion = "Other";
        store.setObjectiveImmersion(getImmersion(immersion), 0, 0);
        if (lensNA != null)
            store.setObjectiveLensNA(lensNA, 0, 0);
        if (workingDistance != null) {
            store.setObjectiveWorkingDistance(new Length(workingDistance, UNITS.MICROMETER), 0, 0);
        }
        if (magnification != null) {
            store.setObjectiveCalibratedMagnification(magnification, 0, 0);
        }
        store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
        // link Objective to Image
        String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
        store.setObjectiveID(objectiveID, 0, 0);
        store.setObjectiveSettingsID(objectiveID, 0);
        // populate Detector data
        String detectorID = MetadataTools.createLSID("Detector", 0, 0);
        store.setDetectorID(detectorID, 0, 0);
        store.setDetectorManufacturer(detectorManufacturer, 0, 0);
        store.setDetectorModel(detectorModel, 0, 0);
        store.setDetectorType(getDetectorType("Other"), 0, 0);
        for (Integer key : gains.keySet()) {
            int index = key.intValue();
            if (index < getEffectiveSizeC()) {
                store.setDetectorSettingsGain(gains.get(key), 0, index);
                store.setDetectorSettingsID(detectorID, 0, index);
            }
        }
        if (lastName != null) {
            String experimenterID = MetadataTools.createLSID("Experimenter", 0);
            store.setExperimenterID(experimenterID, 0);
            store.setExperimenterLastName(lastName, 0);
        }
        if (stagePos != null) {
            for (int i = 0; i < getImageCount(); i++) {
                if (stagePos.length > 0) {
                    store.setPlanePositionX(stagePos[0], 0, i);
                    addGlobalMeta("X position for position #1", stagePos[0]);
                }
                if (stagePos.length > 1) {
                    store.setPlanePositionY(stagePos[1], 0, i);
                    addGlobalMeta("Y position for position #1", stagePos[1]);
                }
                if (stagePos.length > 2) {
                    store.setPlanePositionZ(stagePos[2], 0, i);
                    addGlobalMeta("Z position for position #1", stagePos[2]);
                }
            }
        }
        if (exposureTime != null) {
            for (int i = 0; i < getImageCount(); i++) {
                store.setPlaneExposureTime(exposureTime, 0, i);
            }
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp) Hashtable(java.util.Hashtable) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) StringTokenizer(java.util.StringTokenizer) Length(ome.units.quantity.Length) Frequency(ome.units.quantity.Frequency) RandomAccessInputStream(loci.common.RandomAccessInputStream) Power(ome.units.quantity.Power) Location(loci.common.Location)

Aggregations

Length (ome.units.quantity.Length)154 MetadataStore (loci.formats.meta.MetadataStore)82 CoreMetadata (loci.formats.CoreMetadata)74 Timestamp (ome.xml.model.primitives.Timestamp)52 RandomAccessInputStream (loci.common.RandomAccessInputStream)48 Time (ome.units.quantity.Time)46 FormatException (loci.formats.FormatException)39 Location (loci.common.Location)34 ArrayList (java.util.ArrayList)29 IMetadata (loci.formats.meta.IMetadata)13 NonNegativeInteger (ome.xml.model.primitives.NonNegativeInteger)13 ServiceFactory (loci.common.services.ServiceFactory)12 IOException (java.io.IOException)11 DependencyException (loci.common.services.DependencyException)11 PositiveInteger (ome.xml.model.primitives.PositiveInteger)11 MetadataRetrieve (loci.formats.meta.MetadataRetrieve)10 ElectricPotential (ome.units.quantity.ElectricPotential)9 Test (org.testng.annotations.Test)9 Element (org.w3c.dom.Element)9 NodeList (org.w3c.dom.NodeList)9