Search in sources :

Example 86 with MetadataStore

use of loci.formats.meta.MetadataStore in project bioformats by openmicroscopy.

the class FormatTools method getFilename.

/**
 * @throws FormatException Never actually thrown.
 * @throws IOException Never actually thrown.
 */
public static String getFilename(int series, int image, IFormatReader r, String pattern, boolean padded) throws FormatException, IOException {
    MetadataStore store = r.getMetadataStore();
    MetadataRetrieve retrieve = store instanceof MetadataRetrieve ? (MetadataRetrieve) store : new DummyMetadata();
    return getFilename(series, image, retrieve, pattern, padded);
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) DummyMetadata(loci.formats.meta.DummyMetadata) MetadataRetrieve(loci.formats.meta.MetadataRetrieve)

Example 87 with MetadataStore

use of loci.formats.meta.MetadataStore in project bioformats by openmicroscopy.

the class MetadataTools method populatePixels.

/**
 * Populates the Pixels element of the given metadata store, using core
 * metadata from the given reader.  If the {@code doPlane} flag is set,
 * then the Plane elements will be populated as well. If the
 * {@code doImageName} flag is set, then the image name will be populated as
 * well.
 *
 * @param store       The metadata store whose Pixels should be populated
 * @param r           The format reader whose core metadata should be used
 * @param doPlane     Specifies whether Plane elements should be populated
 * @param doImageName Specifies whether the Image name should be populated
 */
public static void populatePixels(MetadataStore store, IFormatReader r, boolean doPlane, boolean doImageName) {
    if (store == null || r == null)
        return;
    int oldSeries = r.getSeries();
    for (int i = 0; i < r.getSeriesCount(); i++) {
        r.setSeries(i);
        String imageName = null;
        if (doImageName) {
            Location f = new Location(r.getCurrentFile());
            imageName = f.getName();
            if (r.getSeriesCount() > 1) {
                imageName += " #" + (i + 1);
            }
        }
        String pixelType = FormatTools.getPixelTypeString(r.getPixelType());
        populateMetadata(store, r.getCurrentFile(), i, imageName, r.isLittleEndian(), r.getDimensionOrder(), pixelType, r.getSizeX(), r.getSizeY(), r.getSizeZ(), r.getSizeC(), r.getSizeT(), r.getRGBChannelCount());
        store.setPixelsInterleaved(r.isInterleaved(), i);
        store.setPixelsSignificantBits(new PositiveInteger(r.getBitsPerPixel()), i);
        try {
            OMEXMLService service = new ServiceFactory().getInstance(OMEXMLService.class);
            if (service.isOMEXMLRoot(store.getRoot())) {
                MetadataStore baseStore = r.getMetadataStore();
                if (service.isOMEXMLMetadata(baseStore)) {
                    OMEXMLMetadata omeMeta;
                    try {
                        omeMeta = service.getOMEMetadata(service.asRetrieve(baseStore));
                        if (omeMeta.getTiffDataCount(i) == 0 && omeMeta.getPixelsBinDataCount(i) == 0) {
                            service.addMetadataOnly(omeMeta, i, i == 0);
                        }
                    } catch (ServiceException e) {
                        LOGGER.warn("Failed to add MetadataOnly", e);
                    }
                }
            }
        } catch (DependencyException exc) {
            LOGGER.warn("Failed to add MetadataOnly", exc);
        }
        if (doPlane) {
            for (int q = 0; q < r.getImageCount(); q++) {
                int[] coords = r.getZCTCoords(q);
                store.setPlaneTheZ(new NonNegativeInteger(coords[0]), i, q);
                store.setPlaneTheC(new NonNegativeInteger(coords[1]), i, q);
                store.setPlaneTheT(new NonNegativeInteger(coords[2]), i, q);
            }
        }
    }
    r.setSeries(oldSeries);
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) PositiveInteger(ome.xml.model.primitives.PositiveInteger) ServiceException(loci.common.services.ServiceException) ServiceFactory(loci.common.services.ServiceFactory) OMEXMLMetadata(loci.formats.ome.OMEXMLMetadata) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) DependencyException(loci.common.services.DependencyException) OMEXMLService(loci.formats.services.OMEXMLService) Location(loci.common.Location)

Example 88 with MetadataStore

use of loci.formats.meta.MetadataStore in project bioformats by openmicroscopy.

the class FlowSightReader method initFile.

/* (non-Javadoc)
   * @see loci.formats.FormatReader#initFile(java.lang.String)
   */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    in = new RandomAccessInputStream(id);
    tiffParser = new TiffParser(in);
    tiffParser.setDoCaching(false);
    tiffParser.setUse64BitOffsets(false);
    final Boolean littleEndian = tiffParser.checkHeader();
    if (littleEndian == null) {
        throw new FormatException("Invalid FlowSight file");
    }
    final boolean little = littleEndian.booleanValue();
    in.order(little);
    LOGGER.info("Reading IFDs");
    ifdOffsets = tiffParser.getIFDOffsets();
    if (ifdOffsets.length < 2) {
        throw new FormatException("No IFDs found");
    }
    LOGGER.info("Populating metadata");
    /*
     * The first IFD contains file-scope metadata
     */
    final IFD ifd0 = tiffParser.getFirstIFD();
    tiffParser.fillInIFD(ifd0);
    int channelCount = ifd0.getIFDIntValue(CHANNEL_COUNT_TAG, 1);
    final String channelNamesString = ifd0.getIFDStringValue(CHANNEL_NAMES_TAG);
    if (channelNamesString != null) {
        channelNames = channelNamesString.split("\\|");
        if (channelNames.length != channelCount) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Channel count (%d) does not match number of " + "channel names (%d) in string \"%s\"", channelCount, channelNames.length, channelNamesString);
            }
            channelCount = channelNames.length;
        }
        LOGGER.debug("Found {} channels: {}", channelCount, channelNamesString.replace('|', ','));
    }
    final String channelDescsString = ifd0.getIFDStringValue(CHANNEL_DESCS_TAG);
    if (channelDescsString != null) {
        channelDescs = channelDescsString.split("\\|");
        if (channelDescs.length != channelCount) {
            throw new FormatException(String.format("Channel count (%d) does not match number of channel descriptions (%d) in string \"%s\"", channelCount, channelDescs.length, channelDescsString));
        }
    }
    String xml = ifd0.getIFDTextValue(METADATA_XML_TAG);
    xml = XMLTools.sanitizeXML(xml);
    try {
        Element xmlRoot = XMLTools.parseDOM(xml).getDocumentElement();
        NodeList imagingNodes = xmlRoot.getElementsByTagName("Imaging");
        if (imagingNodes.getLength() > 0) {
            Element imagingNode = (Element) imagingNodes.item(0);
            NodeList children = imagingNode.getChildNodes();
            for (int child = 0; child < children.getLength(); child++) {
                Node childNode = children.item(child);
                String name = childNode.getNodeName();
                if (name.startsWith("ChannelInUseIndicators")) {
                    channelCount = 0;
                    String text = childNode.getTextContent();
                    String[] tokens = text.split(" ");
                    for (String token : tokens) {
                        if (token.equals("1")) {
                            channelCount++;
                        }
                    }
                }
            }
        }
    } catch (ParserConfigurationException e) {
        LOGGER.debug("Could not parse XML", e);
    } catch (SAXException e) {
        LOGGER.debug("Could not parse XML", e);
    }
    /*
     * Scan the remaining IFDs
     * 
     * Unfortunately, each image can have a different width and height
     * and the images and masks have a different bit depth, so in the
     * OME scheme of things, we get one series per plane.
     */
    for (int idxOff = 1; idxOff < ifdOffsets.length; idxOff++) {
        // TODO: Record the channel names
        final long offset = ifdOffsets[idxOff];
        final boolean first = (idxOff == 1);
        final IFD ifd = tiffParser.getIFD(offset);
        tiffParser.fillInIFD(ifd);
        CoreMetadata ms = first ? core.get(0) : new CoreMetadata();
        ms.rgb = false;
        ms.interleaved = false;
        ms.littleEndian = ifd0.isLittleEndian();
        ms.sizeX = (int) ifd.getImageWidth() / channelCount;
        ms.sizeY = (int) ifd.getImageLength();
        ms.sizeZ = 1;
        ms.sizeC = channelCount;
        ms.sizeT = 1;
        ms.indexed = false;
        ms.dimensionOrder = "XYCZT";
        ms.bitsPerPixel = ifd.getIFDIntValue(IFD.BITS_PER_SAMPLE);
        ms.pixelType = (ms.bitsPerPixel == 8) ? FormatTools.UINT8 : FormatTools.UINT16;
        ms.imageCount = channelCount;
        ms.resolutionCount = 1;
        ms.thumbnail = false;
        ms.metadataComplete = true;
        if (!first) {
            core.add(ms);
        }
    }
    /*
     * Run through the metadata store, setting the channel names
     * for all the series.
     */
    final MetadataStore store = getMetadataStore();
    MetadataTools.populatePixels(store, this);
    if (channelNames != null && channelDescs != null) {
        String[] maskDescs = new String[channelCount];
        for (int i = 0; i < channelCount; i++) {
            maskDescs[i] = channelDescs[i] + " Mask";
        }
        for (int series = 0; series < ifdOffsets.length - 1; series++) {
            final boolean isMask = core.get(series).pixelType == FormatTools.UINT8;
            String[] descs = isMask ? maskDescs : channelDescs;
            for (int channel = 0; channel < channelCount; channel++) {
                store.setChannelName(descs[channel], series, channel);
                String cid = MetadataTools.createLSID("Channel", series, channel) + ":";
                store.setChannelID(cid + channelNames[channel], series, channel);
            }
        }
    }
}
Also used : IFD(loci.formats.tiff.IFD) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) SAXException(org.xml.sax.SAXException) MetadataStore(loci.formats.meta.MetadataStore) TiffParser(loci.formats.tiff.TiffParser) RandomAccessInputStream(loci.common.RandomAccessInputStream) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 89 with MetadataStore

use of loci.formats.meta.MetadataStore 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 90 with MetadataStore

use of loci.formats.meta.MetadataStore in project bioformats by openmicroscopy.

the class JPEG2000Reader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    in = new RandomAccessInputStream(id);
    CoreMetadata ms0 = core.get(0);
    JPEG2000MetadataParser metadataParser = new JPEG2000MetadataParser(in);
    if (metadataParser.isRawCodestream()) {
        LOGGER.info("Codestream is raw, using codestream dimensions.");
        ms0.sizeX = metadataParser.getCodestreamSizeX();
        ms0.sizeY = metadataParser.getCodestreamSizeY();
        ms0.sizeC = metadataParser.getCodestreamSizeC();
        ms0.pixelType = metadataParser.getCodestreamPixelType();
    } else {
        LOGGER.info("Codestream is JP2 boxed, using header dimensions.");
        ms0.sizeX = metadataParser.getHeaderSizeX();
        ms0.sizeY = metadataParser.getHeaderSizeY();
        ms0.sizeC = metadataParser.getHeaderSizeC();
        ms0.pixelType = metadataParser.getHeaderPixelType();
    }
    lut = metadataParser.getLookupTable();
    pixelsOffset = metadataParser.getCodestreamOffset();
    ms0.sizeZ = 1;
    ms0.sizeT = 1;
    ms0.imageCount = 1;
    ms0.dimensionOrder = "XYCZT";
    ms0.rgb = getSizeC() > 1;
    ms0.interleaved = true;
    ms0.littleEndian = false;
    ms0.indexed = !isRGB() && lut != null;
    // New core metadata now that we know how many sub-resolutions we have.
    if (resolutionLevels != null) {
        int seriesCount = resolutionLevels + 1;
        core.get(0).resolutionCount = seriesCount;
        for (int i = 1; i < seriesCount; i++) {
            CoreMetadata ms = new CoreMetadata(this, 0);
            core.add(ms);
            ms.sizeX = core.get(i - 1).sizeX / 2;
            ms.sizeY = core.get(i - 1).sizeY / 2;
            ms.thumbnail = true;
        }
    }
    ArrayList<String> comments = metadataParser.getComments();
    LOGGER.debug("Found {} comments", comments.size());
    for (int i = 0; i < comments.size(); i++) {
        String comment = comments.get(i);
        int equal = comment.indexOf('=');
        if (equal >= 0) {
            String key = comment.substring(0, equal);
            String value = comment.substring(equal + 1);
            addGlobalMeta(key, value);
        } else {
            addGlobalMetaList("Comment", comment);
        }
    }
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) RandomAccessInputStream(loci.common.RandomAccessInputStream) CoreMetadata(loci.formats.CoreMetadata)

Aggregations

MetadataStore (loci.formats.meta.MetadataStore)180 CoreMetadata (loci.formats.CoreMetadata)130 RandomAccessInputStream (loci.common.RandomAccessInputStream)97 Length (ome.units.quantity.Length)82 FormatException (loci.formats.FormatException)66 Timestamp (ome.xml.model.primitives.Timestamp)54 Location (loci.common.Location)51 Time (ome.units.quantity.Time)41 ArrayList (java.util.ArrayList)34 IFD (loci.formats.tiff.IFD)21 DependencyException (loci.common.services.DependencyException)16 IOException (java.io.IOException)15 TiffParser (loci.formats.tiff.TiffParser)15 NonNegativeInteger (ome.xml.model.primitives.NonNegativeInteger)15 ServiceFactory (loci.common.services.ServiceFactory)14 PositiveInteger (ome.xml.model.primitives.PositiveInteger)13 IFDList (loci.formats.tiff.IFDList)12 MetadataRetrieve (loci.formats.meta.MetadataRetrieve)11 ServiceException (loci.common.services.ServiceException)10 Map (java.util.Map)9