Search in sources :

Example 36 with Timestamp

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

the class MetadataTools method setDefaultCreationDate.

/**
 * Sets a default creation date.  If the named file exists, then the creation
 * date is set to the file's last modification date.  Otherwise, it is set
 * to the current date.
 *
 * @see #setDefaultDateEnabled(boolean)
 */
public static void setDefaultCreationDate(MetadataStore store, String id, int series) {
    if (!defaultDateEnabled) {
        return;
    }
    Location file = id == null ? null : new Location(id).getAbsoluteFile();
    long time = System.currentTimeMillis();
    if (file != null && file.exists())
        time = file.lastModified();
    store.setImageAcquisitionDate(new Timestamp(DateTools.convertDate(time, DateTools.UNIX)), series);
}
Also used : Timestamp(ome.xml.model.primitives.Timestamp) Location(loci.common.Location)

Example 37 with Timestamp

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

Example 38 with Timestamp

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

the class BaseTiffReader method initMetadataStore.

/**
 * Populates the metadata store using the data parsed in
 * {@link #initStandardMetadata()} along with some further parsing done in
 * the method itself.
 *
 * All calls to the active <code>MetadataStore</code> should be made in this
 * method and <b>only</b> in this method. This is especially important for
 * sub-classes that override the getters for pixel set array size, etc.
 */
protected void initMetadataStore() throws FormatException {
    LOGGER.info("Populating OME metadata");
    // the metadata store we're working with
    MetadataStore store = makeFilterMetadata();
    IFD firstIFD = ifds.get(0);
    IFD exif = null;
    if (ifds.get(0).containsKey(IFD.EXIF)) {
        try {
            IFDList exifIFDs = tiffParser.getExifIFDs();
            if (exifIFDs.size() > 0) {
                exif = exifIFDs.get(0);
            }
            tiffParser.fillInIFD(exif);
        } catch (IOException e) {
            LOGGER.debug("Could not read EXIF IFDs", e);
        }
    }
    MetadataTools.populatePixels(store, this, exif != null);
    // format the creation date to ISO 8601
    String creationDate = getImageCreationDate();
    String date = DateTools.formatDate(creationDate, DATE_FORMATS, ".");
    if (creationDate != null && date == null) {
        LOGGER.warn("unknown creation date format: {}", creationDate);
    }
    creationDate = date;
    if (creationDate != null) {
        store.setImageAcquisitionDate(new Timestamp(creationDate), 0);
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        // populate Experimenter
        String artist = firstIFD.getIFDTextValue(IFD.ARTIST);
        if (artist != null) {
            String firstName = null, lastName = null;
            int ndx = artist.indexOf(' ');
            if (ndx < 0)
                lastName = artist;
            else {
                firstName = artist.substring(0, ndx);
                lastName = artist.substring(ndx + 1);
            }
            String email = firstIFD.getIFDStringValue(IFD.HOST_COMPUTER);
            store.setExperimenterFirstName(firstName, 0);
            store.setExperimenterLastName(lastName, 0);
            store.setExperimenterEmail(email, 0);
            store.setExperimenterID(MetadataTools.createLSID("Experimenter", 0), 0);
        }
        store.setImageDescription(firstIFD.getComment(), 0);
        // set the X and Y pixel dimensions
        double pixX = firstIFD.getXResolution();
        double pixY = firstIFD.getYResolution();
        String unit = getResolutionUnitFromComment(firstIFD);
        Length sizeX = FormatTools.getPhysicalSizeX(pixX, unit);
        Length sizeY = FormatTools.getPhysicalSizeY(pixY, unit);
        if (sizeX != null) {
            store.setPixelsPhysicalSizeX(sizeX, 0);
        }
        if (sizeY != null) {
            store.setPixelsPhysicalSizeY(sizeY, 0);
        }
        store.setPixelsPhysicalSizeZ(null, 0);
        if (exif != null) {
            if (exif.containsKey(IFD.EXPOSURE_TIME)) {
                Object exp = exif.get(IFD.EXPOSURE_TIME);
                if (exp instanceof TiffRational) {
                    Time exposure = new Time(((TiffRational) exp).doubleValue(), UNITS.SECOND);
                    for (int i = 0; i < getImageCount(); i++) {
                        store.setPlaneExposureTime(exposure, 0, i);
                    }
                }
            }
        }
    }
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) IFD(loci.formats.tiff.IFD) IFDList(loci.formats.tiff.IFDList) TiffRational(loci.formats.tiff.TiffRational) Time(ome.units.quantity.Time) IOException(java.io.IOException) Timestamp(ome.xml.model.primitives.Timestamp)

Example 39 with Timestamp

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

the class CellVoyagerReader method readInfo.

private void readInfo(final Document msDocument, final Document omeDocument) throws FormatException {
    /*
     * Magnification.
     *
     * We need it early, because the file format reports only un-magnified
     * sizes. So if we are to put proper metadata, we need to make the
     * conversion to size measured at the sample level ourselves. I feel
     * like this is fragile and most likely to change in a future version of
     * the file format.
     */
    final Element msRoot = msDocument.getDocumentElement();
    final double objectiveMagnification = Double.parseDouble(getChildText(msRoot, new String[] { "ObjectiveLens", "Magnification" }));
    // final double zoomLensMagnification = Double.parseDouble(
    // getChildText( msRoot, new String[] { "ZoomLens", "Magnification",
    // "Value" } ) );
    // *
    final double magnification = objectiveMagnification;
    // zoomLensMagnification;
    /*
     * Read the ome.xml file. Since it is malformed, we need to parse all
     * nodes, and add an "ID" attribute to those who do not have it.
     */
    final NodeList nodeList = omeDocument.getElementsByTagName("*");
    for (int i = 0; i < nodeList.getLength(); i++) {
        final Node node = nodeList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            final NamedNodeMap atts = node.getAttributes();
            final Node namedItem = atts.getNamedItem("ID");
            if (namedItem == null) {
                final String name = node.getNodeName();
                final String id = name + ":" + i;
                if (!node.getParentNode().getNodeName().equals("LightSource")) {
                    ((Element) node).setAttribute("ID", id);
                }
            }
        }
    }
    /*
     * For single-slice image, the PhysicalSizeZ can be 0, which will make
     * the metadata read fail. Correct that.
     */
    final Element pszEl = getChild(omeDocument.getDocumentElement(), new String[] { "Image", "Pixels" });
    final double physicalSizeZ = Double.parseDouble(pszEl.getAttribute("PhysicalSizeZ"));
    if (physicalSizeZ <= 0) {
        // default to 1 whatever
        pszEl.setAttribute("PhysicalSizeZ", "" + 1);
    }
    /*
     * Now that the XML document is properly formed, we can build a metadata
     * object from it.
     */
    OMEXMLService service = null;
    String xml = null;
    try {
        xml = XMLTools.getXML(omeDocument);
    } catch (final TransformerConfigurationException e2) {
        LOGGER.debug("", e2);
    } catch (final TransformerException e2) {
        LOGGER.debug("", e2);
    }
    try {
        service = new ServiceFactory().getInstance(OMEXMLService.class);
    } catch (final DependencyException e1) {
        LOGGER.debug("", e1);
    }
    OMEXMLMetadata omeMD = null;
    try {
        omeMD = service.createOMEXMLMetadata(xml);
    } catch (final ServiceException e) {
        LOGGER.debug("", e);
    } catch (final NullPointerException npe) {
        LOGGER.debug("", npe);
        throw npe;
    }
    // Correct pixel size for magnification
    omeMD.setPixelsPhysicalSizeX(FormatTools.createLength(omeMD.getPixelsPhysicalSizeX(0).value().doubleValue() / magnification, omeMD.getPixelsPhysicalSizeX(0).unit()), 0);
    omeMD.setPixelsPhysicalSizeY(FormatTools.createLength(omeMD.getPixelsPhysicalSizeY(0).value().doubleValue() / magnification, omeMD.getPixelsPhysicalSizeY(0).unit()), 0);
    // Time interval
    if (Double.valueOf(readFrameInterval(msDocument)) != null) {
        omeMD.setPixelsTimeIncrement(new Time(Double.valueOf(readFrameInterval(msDocument)), UNITS.SECOND), 0);
    }
    /*
     * Channels
     */
    final Element channelsEl = getChild(msRoot, "Channels");
    final List<Element> channelEls = getChildren(channelsEl, "Channel");
    channelInfos = new ArrayList<ChannelInfo>();
    for (final Element channelEl : channelEls) {
        final boolean isEnabled = Boolean.parseBoolean(getChildText(channelEl, "IsEnabled"));
        if (!isEnabled) {
            continue;
        }
        final ChannelInfo ci = readChannel(channelEl);
        channelInfos.add(ci);
    }
    /*
     * Fix missing IDs.
     *
     * Some IDs are missing in the malformed OME.XML file. We must put them
     * back manually. Some are fixed here
     */
    omeMD.setProjectID(MetadataTools.createLSID("Project", 0), 0);
    omeMD.setScreenID(MetadataTools.createLSID("Screen", 0), 0);
    omeMD.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
    omeMD.setInstrumentID(MetadataTools.createLSID("Instrument", 0), 0);
    // Read pixel sizes from OME metadata.
    final double pixelWidth = omeMD.getPixelsPhysicalSizeX(0).value().doubleValue();
    final double pixelHeight = omeMD.getPixelsPhysicalSizeY(0).value().doubleValue();
    /*
     * Read tile size from channel info. This is weird, but it's like that.
     * Since we build a multi-C image, we have to assume that all channels
     * have the same dimension, even if the file format allows for changing
     * the size, binning, etc. from channel to channel. Failure to load
     * datasets that have this exoticity is to be sought here.
     */
    final int tileWidth = channelInfos.get(0).tileWidth;
    final int tileHeight = channelInfos.get(0).tileHeight;
    /*
     * Handle multiple wells.
     *
     * The same kind of remark apply: We assume that a channel setting can
     * be applied to ALL wells. So this file reader will fail for dataset
     * that have one well that has a different dimension that of others.
     */
    /*
     * First remark: there can be two modes to store Areas in the xml file:
     * Either we define different areas for each well, and in that case, the
     * areas are found as a child element of the well element. Either the
     * definition of areas is common to all wells, and in that case they
     * area defined in a separate element.
     */
    final boolean sameAreaPerWell = Boolean.parseBoolean(getChildText(msRoot, "UsesSameAreaParWell"));
    List<AreaInfo> areas = null;
    if (sameAreaPerWell) {
        final Element areasEl = getChild(msRoot, new String[] { "SameAreaUsingWell", "Areas" });
        final List<Element> areaEls = getChildren(areasEl, "Area");
        int areaIndex = 0;
        areas = new ArrayList<AreaInfo>(areaEls.size());
        int fieldIndex = 1;
        for (final Element areaEl : areaEls) {
            final AreaInfo area = readArea(areaEl, fieldIndex, pixelWidth, pixelHeight, tileWidth, tileHeight);
            area.index = areaIndex++;
            areas.add(area);
            // Continue incrementing field index across areas.
            fieldIndex = area.fields.get(area.fields.size() - 1).index + 1;
        }
    }
    final Element wellsEl = getChild(msRoot, "Wells");
    final List<Element> wellEls = getChildren(wellsEl, "Well");
    wells = new ArrayList<WellInfo>();
    for (final Element wellEl : wellEls) {
        final boolean isWellEnabled = Boolean.parseBoolean(getChild(wellEl, "IsEnabled").getTextContent());
        if (isWellEnabled) {
            final WellInfo wi = readWellInfo(wellEl, pixelWidth, pixelHeight, tileWidth, tileHeight);
            if (sameAreaPerWell) {
                wi.areas = areas;
            }
            wells.add(wi);
        }
    }
    /*
     * Z range.
     *
     * In this file format, the Z range appears to be general: it applies to
     * all fields of all wells.
     */
    final int nZSlices = Integer.parseInt(getChildText(msRoot, new String[] { "ZStackConditions", "NumberOfSlices" }));
    /*
     * Time points. They are general as well. Which just makes sense.
     */
    timePoints = readTimePoints(msDocument);
    /*
     * Populate CORE metadata for each area.
     *
     * This reader takes to convention that state that 1 area = 1 series. So
     * if you have 10 wells with 2 areas in each well, and each area is made
     * of 20 fields, you will get 20 series, and each series will be
     * stitched from 20 fields.
     */
    OMEXMLMetadataRoot root = (OMEXMLMetadataRoot) omeMD.getRoot();
    Image firstImage = root.getImage(0);
    core.clear();
    for (final WellInfo well : wells) {
        for (final AreaInfo area : well.areas) {
            final CoreMetadata ms = new CoreMetadata();
            core.add(ms);
            if (core.size() > 1) {
                root.addImage(firstImage);
            }
            ms.sizeX = area.width;
            ms.sizeY = area.height;
            ms.sizeZ = nZSlices;
            ms.sizeC = channelInfos.size();
            ms.sizeT = timePoints.size();
            ms.dimensionOrder = "XYCZT";
            ms.rgb = false;
            ms.imageCount = nZSlices * channelInfos.size() * timePoints.size();
            // Bit depth.
            switch(omeMD.getPixelsType(0)) {
                case UINT8:
                    ms.pixelType = FormatTools.UINT8;
                    ms.bitsPerPixel = 8;
                    break;
                case UINT16:
                    ms.pixelType = FormatTools.UINT16;
                    ms.bitsPerPixel = 16;
                    break;
                case UINT32:
                    ms.pixelType = FormatTools.UINT32;
                    ms.bitsPerPixel = 32;
                    break;
                default:
                    throw new FormatException("Cannot read image with pixel type = " + omeMD.getPixelsType(0));
            }
            // Determined manually on sample data. Check here is the image
            // you get is weird.
            ms.littleEndian = true;
        }
    }
    omeMD.setRoot(root);
    /*
     * Populate the MetadataStore.
     */
    final MetadataStore store = makeFilterMetadata();
    MetadataConverter.convertMetadata(omeMD, store);
    MetadataTools.populatePixels(store, this, true);
    /*
     * Pinhole disk
     */
    final double pinholeSize = Double.parseDouble(getChildText(msRoot, new String[] { "PinholeDisk", "PinholeSize_um" }));
    /*
     * MicroPlate specific stuff
     */
    final Element containerEl = getChild(msRoot, new String[] { "Attachment", "HolderInfoList", "HolderInfo", "MountedSampleContainer" });
    final String type = containerEl.getAttribute("xsi:type");
    boolean plateMetadata = false;
    if (type.equals("WellPlate")) {
        plateMetadata = true;
        final int nrows = Integer.parseInt(getChildText(containerEl, "RowCount"));
        final int ncols = Integer.parseInt(getChildText(containerEl, "ColumnCount"));
        store.setPlateRows(new PositiveInteger(nrows), 0);
        store.setPlateColumns(new PositiveInteger(ncols), 0);
        final String plateAcqID = MetadataTools.createLSID("PlateAcquisition", 0, 0);
        store.setPlateAcquisitionID(plateAcqID, 0, 0);
        final Element dimInfoEl = getChild(msRoot, "DimensionsInfo");
        final int maxNFields = Integer.parseInt(getChild(dimInfoEl, "F").getAttribute("Max"));
        final PositiveInteger fieldCount = FormatTools.getMaxFieldCount(maxNFields);
        if (fieldCount != null) {
            store.setPlateAcquisitionMaximumFieldCount(fieldCount, 0, 0);
        }
        // Plate acquisition time
        final String beginTime = getChildText(msRoot, "BeginTime");
        final String endTime = getChildText(msRoot, "EndTime");
        store.setPlateAcquisitionStartTime(new Timestamp(beginTime), 0, 0);
        store.setPlateAcquisitionEndTime(new Timestamp(endTime), 0, 0);
        store.setPlateName(beginTime, 0);
    } else if (!type.equals("PreparedSlide")) {
        LOGGER.warn("Unexpected acquisition type: {}", type);
    }
    // Wells position on the plate
    int seriesIndex = -1;
    int wellIndex = -1;
    for (final WellInfo well : wells) {
        wellIndex++;
        final int wellNumber = well.number;
        if (plateMetadata) {
            store.setWellID(MetadataTools.createLSID("Well", 0, wellIndex), 0, wellIndex);
            store.setWellRow(new NonNegativeInteger(well.row), 0, wellIndex);
            store.setWellColumn(new NonNegativeInteger(well.col), 0, wellIndex);
        }
        int areaIndex = -1;
        for (final AreaInfo area : well.areas) {
            seriesIndex++;
            areaIndex++;
            String imageID = MetadataTools.createLSID("Image", seriesIndex);
            store.setImageID(imageID, seriesIndex);
            final String imageName = "Well " + wellNumber + " (UID=" + well.UID + ", r=" + well.row + ", c=" + well.col + ") - Area " + areaIndex;
            store.setImageName(imageName, seriesIndex);
            if (plateMetadata) {
                Length posX = new Length(Double.valueOf(well.centerX), UNITS.REFERENCEFRAME);
                Length posY = new Length(Double.valueOf(well.centerY), UNITS.REFERENCEFRAME);
                String wellSample = MetadataTools.createLSID("WellSample", 0, wellIndex, areaIndex);
                store.setWellSampleID(wellSample, 0, wellIndex, areaIndex);
                store.setWellSampleImageRef(imageID, 0, wellIndex, areaIndex);
                store.setWellSampleIndex(new NonNegativeInteger(area.index), 0, wellIndex, areaIndex);
                store.setWellSamplePositionX(posX, 0, wellIndex, areaIndex);
                store.setWellSamplePositionY(posY, 0, wellIndex, areaIndex);
                store.setPlateAcquisitionWellSampleRef(wellSample, 0, 0, seriesIndex);
            }
            store.setImageInstrumentRef(MetadataTools.createLSID("Instrument", 0), seriesIndex);
            for (int i = 0; i < channelInfos.size(); i++) {
                store.setChannelPinholeSize(new Length(pinholeSize, UNITS.MICROMETER), seriesIndex, i);
                store.setChannelName(channelInfos.get(i).name, seriesIndex, i);
                store.setChannelColor(channelInfos.get(i).color, seriesIndex, i);
            }
        }
    }
}
Also used : TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) ServiceFactory(loci.common.services.ServiceFactory) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) Time(ome.units.quantity.Time) Image(ome.xml.model.Image) Timestamp(ome.xml.model.primitives.Timestamp) OMEXMLService(loci.formats.services.OMEXMLService) TransformerException(javax.xml.transform.TransformerException) PositiveInteger(ome.xml.model.primitives.PositiveInteger) NamedNodeMap(org.w3c.dom.NamedNodeMap) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) NodeList(org.w3c.dom.NodeList) DependencyException(loci.common.services.DependencyException) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) ServiceException(loci.common.services.ServiceException) Length(ome.units.quantity.Length) OMEXMLMetadata(loci.formats.ome.OMEXMLMetadata) OMEXMLMetadataRoot(ome.xml.meta.OMEXMLMetadataRoot)

Example 40 with Timestamp

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

the class CellWorxReader method parseWellLogFile.

/**
 * Parse metadata from a well log file.
 */
private void parseWellLogFile(int wellIndex, MetadataStore store) throws IOException {
    int seriesIndex = wellIndex * fieldCount;
    int row = getWellRow(seriesIndex);
    int col = getWellColumn(seriesIndex);
    int well = row * wellFiles[0].length + col;
    String logFile = logFiles[row][col];
    if (!new Location(logFile).exists()) {
        return;
    }
    LOGGER.debug("Parsing log file for well {}{}", (char) (row + 'A'), col + 1);
    int oldSeries = getSeries();
    setSeries(seriesIndex);
    String data = DataTools.readFile(logFile);
    String[] lines = data.split("\n");
    for (String line : lines) {
        line = line.trim();
        int separator = line.indexOf(':');
        if (separator < 0)
            continue;
        String key = line.substring(0, separator).trim();
        String value = line.substring(separator + 1).trim();
        addSeriesMeta(key, value);
        if (key.equals("Date")) {
            String date = DateTools.formatDate(value, DATE_FORMAT);
            for (int field = 0; field < fieldCount; field++) {
                if (date != null) {
                    int imageIndex = seriesIndex + field;
                    timestamps.put(imageIndex, new Timestamp(date));
                    store.setImageAcquisitionDate(timestamps.get(imageIndex), imageIndex);
                }
            }
        } else if (key.equals("Scan Origin")) {
            String[] axes = value.split(",");
            Double posX = new Double(axes[0]);
            Double posY = new Double(axes[1]);
            for (int fieldRow = 0; fieldRow < fieldMap.length; fieldRow++) {
                for (int fieldCol = 0; fieldCol < fieldMap[fieldRow].length; fieldCol++) {
                    if (fieldMap[fieldRow][fieldCol] && wellFiles[row][col] != null) {
                        int field = fieldRow * fieldMap[fieldRow].length + fieldCol;
                        Length px = new Length(posX, UNITS.REFERENCEFRAME);
                        Length py = new Length(posY, UNITS.REFERENCEFRAME);
                        store.setWellSamplePositionX(px, 0, well, field);
                        store.setWellSamplePositionY(py, 0, well, field);
                        addGlobalMetaList("X position for position", axes[0]);
                        addGlobalMetaList("Y position for position", axes[1]);
                    }
                }
            }
        } else if (key.equals("Scan Area")) {
            int s = value.indexOf('x');
            if (s > 0) {
                int end = value.indexOf(" ", s + 2);
                Double xSize = new Double(value.substring(0, s).trim());
                Double ySize = new Double(value.substring(s + 1, end).trim());
                Length x = FormatTools.getPhysicalSizeX(xSize / getSizeX());
                Length y = FormatTools.getPhysicalSizeY(ySize / getSizeY());
                for (int field = 0; field < fieldCount; field++) {
                    int index = seriesIndex + field;
                    if (x != null) {
                        store.setPixelsPhysicalSizeX(x, index);
                    }
                    if (y != null) {
                        store.setPixelsPhysicalSizeY(y, index);
                    }
                }
            }
        } else if (key.startsWith("Channel")) {
            int start = key.indexOf(' ') + 1;
            int end = key.indexOf(" ", start);
            if (end < 0)
                end = key.length();
            int index = Integer.parseInt(key.substring(start, end)) - 1;
            String[] tokens = value.split(",");
            for (String token : tokens) {
                token = token.trim();
                if (token.startsWith("gain")) {
                    String instrumentID = MetadataTools.createLSID("Instrument", 0);
                    Double gain = new Double(token.replaceAll("gain ", ""));
                    String detectorID = MetadataTools.createLSID("Detector", 0, 0);
                    store.setInstrumentID(instrumentID, 0);
                    store.setDetectorID(detectorID, 0, 0);
                    for (int field = 0; field < fieldCount; field++) {
                        store.setImageInstrumentRef(instrumentID, seriesIndex + field);
                        store.setDetectorSettingsGain(gain, seriesIndex + field, index);
                        store.setDetectorSettingsID(detectorID, seriesIndex + field, index);
                    }
                } else if (token.startsWith("EX")) {
                    int slash = token.indexOf('/');
                    if (slash > 0) {
                        String ex = token.substring(0, slash).trim();
                        String em = token.substring(slash + 1).trim();
                        if (ex.indexOf(' ') > 0)
                            ex = ex.substring(ex.indexOf(' ') + 1);
                        if (em.indexOf(' ') > 0) {
                            em = em.substring(em.indexOf(' ') + 1);
                            if (em.indexOf(' ') > 0) {
                                em = em.substring(0, em.indexOf(' '));
                            }
                        }
                        Double emission = new Double(em);
                        Double excitation = new Double(ex);
                        Length exWave = FormatTools.getExcitationWavelength(excitation);
                        Length emWave = FormatTools.getEmissionWavelength(emission);
                        for (int field = 0; field < fieldCount; field++) {
                            if (exWave != null) {
                                store.setChannelExcitationWavelength(exWave, seriesIndex + field, index);
                            }
                            if (emWave != null) {
                                store.setChannelEmissionWavelength(emWave, seriesIndex + field, index);
                            }
                        }
                    }
                }
            }
        }
    }
    setSeries(oldSeries);
}
Also used : Length(ome.units.quantity.Length) Timestamp(ome.xml.model.primitives.Timestamp) Location(loci.common.Location)

Aggregations

Timestamp (ome.xml.model.primitives.Timestamp)76 MetadataStore (loci.formats.meta.MetadataStore)54 Length (ome.units.quantity.Length)52 CoreMetadata (loci.formats.CoreMetadata)44 Time (ome.units.quantity.Time)33 Location (loci.common.Location)28 RandomAccessInputStream (loci.common.RandomAccessInputStream)28 FormatException (loci.formats.FormatException)23 ArrayList (java.util.ArrayList)20 IFD (loci.formats.tiff.IFD)11 NonNegativeInteger (ome.xml.model.primitives.NonNegativeInteger)10 TiffParser (loci.formats.tiff.TiffParser)9 IOException (java.io.IOException)8 IFDList (loci.formats.tiff.IFDList)8 PositiveInteger (ome.xml.model.primitives.PositiveInteger)8 Temperature (ome.units.quantity.Temperature)7 Hashtable (java.util.Hashtable)4 StringTokenizer (java.util.StringTokenizer)4 Frequency (ome.units.quantity.Frequency)4 File (java.io.File)3