Search in sources :

Example 1 with Timestamp

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

the class ImagePlusReader method constructSliceLabel.

private String constructSliceLabel(int ndx, IFormatReader r, IMetadata meta, int series, int zCount, int cCount, int tCount) {
    r.setSeries(series);
    String sliceLabelPattern = LociPrefs.getSliceLabelPattern();
    String order = r.getDimensionOrder();
    int sizeC = r.getEffectiveSizeC();
    int sizeT = r.getSizeT();
    int sizeZ = r.getSizeZ();
    int seriesCount = r.getImageCount();
    int indexBase = LociPrefs.getSliceLabelBaseIndex();
    int[] coordinates = FormatTools.getZCTCoords(order, sizeZ, sizeC, sizeT, sizeZ * sizeC * sizeT, ndx);
    MetadataStore store = r.getMetadataStore();
    MetadataRetrieve retrieve = store instanceof MetadataRetrieve ? (MetadataRetrieve) store : new DummyMetadata();
    String filename = sliceLabelPattern.replaceAll(FormatTools.SERIES_NUM, String.format("%d", series));
    String imageName = retrieve.getImageName(series);
    if (imageName == null)
        imageName = "Series" + series;
    filename = sliceLabelPattern;
    filename = filename.replaceAll(FormatTools.SERIES_NUM, String.format("%d", series));
    filename = filename.replaceAll(FormatTools.SERIES_NAME, imageName);
    if (sizeC > 1) {
        int[] subC;
        String[] subCTypes;
        Modulo moduloC = r.getModuloC();
        if (moduloC.length() > 1) {
            subC = new int[] { r.getSizeC() / moduloC.length(), moduloC.length() };
            subCTypes = new String[] { moduloC.parentType, moduloC.type };
        } else {
            subC = new int[] { r.getSizeC() };
            subCTypes = new String[] { FormatTools.CHANNEL };
        }
        int[] subCPos = FormatTools.rasterToPosition(subC, coordinates[1]);
        StringBuffer channelString = new StringBuffer();
        for (int i = 0; i < subC.length; i++) {
            boolean ch = subCTypes[i] == null || FormatTools.CHANNEL.equals(subCTypes[i]);
            channelString.append(ch ? "c" : subCTypes[i]);
            channelString.append(":");
            channelString.append(subCPos[i] + 1);
            channelString.append("/");
            channelString.append(subC[i]);
            if (i < subC.length - 1)
                channelString.append(", ");
        }
        filename = filename.replaceAll(FormatTools.CHANNEL_NUM, channelString.toString() + " ");
        int channelCount = retrieve.getChannelCount(series);
        if (coordinates[1] < channelCount) {
            String channelName = retrieve.getChannelName(series, coordinates[1]);
            if (channelName == null)
                channelName = String.valueOf(coordinates[1]);
            filename = filename.replaceAll(FormatTools.CHANNEL_NAME, channelName);
        } else {
            filename = filename.replaceAll(FormatTools.CHANNEL_NAME, String.valueOf(coordinates[1]));
        }
    } else {
        filename = filename.replaceAll(FormatTools.CHANNEL_NUM, "");
        filename = filename.replaceAll(FormatTools.CHANNEL_NAME, "");
    }
    if (sizeZ > 1) {
        filename = filename.replaceAll(FormatTools.Z_NUM, "z:" + String.format("%d", coordinates[0] + 1) + "/" + String.format("%d", sizeZ) + " ");
    } else {
        filename = filename.replaceAll(FormatTools.Z_NUM, "");
    }
    if (sizeT > 1) {
        filename = filename.replaceAll(FormatTools.T_NUM, "t:" + String.format("%d", coordinates[2] + 1) + "/" + String.format("%d", sizeT) + " ");
    } else {
        filename = filename.replaceAll(FormatTools.T_NUM, "");
    }
    Timestamp timestamp = retrieve.getImageAcquisitionDate(series);
    long stamp = 0;
    String date = null;
    if (timestamp != null) {
        date = timestamp.getValue();
        if (retrieve.getPlaneCount(series) > ndx) {
            Time deltaT = retrieve.getPlaneDeltaT(series, ndx);
            if (deltaT != null) {
                stamp = (long) (deltaT.value(UNITS.SECOND).doubleValue() * 1000);
            }
        }
        stamp += DateTools.getTime(date, DateTools.ISO8601_FORMAT);
    } else {
        stamp = System.currentTimeMillis();
    }
    date = DateTools.convertDate(stamp, (int) DateTools.UNIX_EPOCH);
    filename = filename.replaceAll(FormatTools.TIMESTAMP, date);
    return filename;
}
Also used : Modulo(loci.formats.Modulo) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp) MetadataStore(loci.formats.meta.MetadataStore) DummyMetadata(loci.formats.meta.DummyMetadata) MetadataRetrieve(loci.formats.meta.MetadataRetrieve)

Example 2 with Timestamp

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

the class LeicaReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    close();
    String leiFile = findLEIFile(id);
    if (leiFile == null || leiFile.trim().length() == 0 || new Location(leiFile).isDirectory()) {
        if (checkSuffix(id, TiffReader.TIFF_SUFFIXES)) {
            super.initFile(id);
            TiffReader r = new TiffReader();
            r.setMetadataStore(getMetadataStore());
            r.setId(id);
            core = new ArrayList<CoreMetadata>(r.getCoreMetadataList());
            metadataStore = r.getMetadataStore();
            final Map<String, Object> globalMetadata = r.getGlobalMetadata();
            for (final Map.Entry<String, Object> entry : globalMetadata.entrySet()) {
                addGlobalMeta(entry.getKey(), entry.getValue());
            }
            r.close();
            files = new List[] { new ArrayList<String>() };
            files[0].add(id);
            tiff = new MinimalTiffReader();
            return;
        } else {
            throw new FormatException("LEI file not found.");
        }
    }
    // parse the LEI file
    super.initFile(leiFile);
    leiFilename = new File(leiFile).exists() ? new Location(leiFile).getAbsolutePath() : id;
    in = new RandomAccessInputStream(leiFile);
    byte[] data = null;
    try {
        data = new byte[(int) in.length()];
        in.read(data);
    } finally {
        in.close();
    }
    in = new RandomAccessInputStream(data);
    MetadataLevel metadataLevel = metadataOptions.getMetadataLevel();
    seriesNames = new ArrayList<String>();
    byte[] fourBytes = new byte[4];
    in.read(fourBytes);
    core.get(0).littleEndian = (fourBytes[0] == TiffConstants.LITTLE && fourBytes[1] == TiffConstants.LITTLE && fourBytes[2] == TiffConstants.LITTLE && fourBytes[3] == TiffConstants.LITTLE);
    boolean realLittleEndian = isLittleEndian();
    in.order(isLittleEndian());
    LOGGER.info("Reading metadata blocks");
    in.skipBytes(8);
    int addr = in.readInt();
    headerIFDs = new IFDList();
    while (addr != 0) {
        IFD ifd = new IFD();
        headerIFDs.add(ifd);
        in.seek(addr + 4);
        int tag = in.readInt();
        while (tag != 0) {
            // create the IFD structure
            int offset = in.readInt();
            long pos = in.getFilePointer();
            in.seek(offset + 12);
            int size = in.readInt();
            ifd.putIFDValue(tag, in.getFilePointer());
            in.seek(pos);
            tag = in.readInt();
        }
        addr = in.readInt();
    }
    numSeries = headerIFDs.size();
    tileWidth = new int[numSeries];
    tileHeight = new int[numSeries];
    core.clear();
    for (int i = 0; i < numSeries; i++) {
        core.add(new CoreMetadata());
    }
    files = new List[numSeries];
    channelNames = new List[getSeriesCount()];
    emWaves = new List[getSeriesCount()];
    exWaves = new List[getSeriesCount()];
    cutInPopulated = new boolean[getSeriesCount()][];
    cutOutPopulated = new boolean[getSeriesCount()][];
    filterRefPopulated = new boolean[getSeriesCount()][];
    for (int i = 0; i < getSeriesCount(); i++) {
        channelNames[i] = new ArrayList();
        emWaves[i] = new ArrayList();
        exWaves[i] = new ArrayList();
    }
    // determine the length of a filename
    LOGGER.info("Parsing metadata blocks");
    core.get(0).littleEndian = !isLittleEndian();
    int seriesIndex = 0;
    int invalidCount = 0;
    valid = new boolean[numSeries];
    timestamps = new String[headerIFDs.size()][];
    for (int i = 0; i < headerIFDs.size(); i++) {
        IFD ifd = headerIFDs.get(i);
        valid[i] = true;
        if (ifd.get(SERIES) != null) {
            long offset = ((Long) ifd.get(SERIES)).longValue();
            in.seek(offset + 8);
            nameLength = in.readInt() * 2;
        }
        in.seek(((Long) ifd.get(IMAGES)).longValue());
        parseFilenames(i);
        if (!valid[i])
            invalidCount++;
    }
    numSeries -= invalidCount;
    if (numSeries <= 0) {
        throw new FormatException("TIFF files not found");
    }
    int[] count = new int[getSeriesCount()];
    for (int i = 0; i < getSeriesCount(); i++) {
        count[i] = core.get(i).imageCount;
    }
    final List<String>[] tempFiles = files;
    IFDList tempIFDs = headerIFDs;
    core = new ArrayList<CoreMetadata>(numSeries);
    files = new List[numSeries];
    headerIFDs = new IFDList();
    int index = 0;
    core.clear();
    for (int i = 0; i < numSeries; i++) {
        CoreMetadata ms = new CoreMetadata();
        while (index < valid.length && !valid[index]) index++;
        if (index >= valid.length) {
            break;
        }
        ms.imageCount = count[index];
        files[i] = tempFiles[index];
        Collections.sort(files[i]);
        headerIFDs.add(tempIFDs.get(index));
        index++;
        core.add(ms);
    }
    tiff = new MinimalTiffReader();
    LOGGER.info("Populating metadata");
    if (headerIFDs == null)
        headerIFDs = ifds;
    seriesDescriptions = new ArrayList<String>();
    physicalSizes = new double[headerIFDs.size()][5];
    pinhole = new double[headerIFDs.size()];
    exposureTime = new double[headerIFDs.size()];
    channelColor = new Color[headerIFDs.size()][];
    for (int i = 0; i < headerIFDs.size(); i++) {
        IFD ifd = headerIFDs.get(i);
        CoreMetadata ms = core.get(i);
        ms.littleEndian = isLittleEndian();
        setSeries(i);
        Integer[] keys = ifd.keySet().toArray(new Integer[ifd.size()]);
        Arrays.sort(keys);
        for (Integer key : keys) {
            long offset = ((Long) ifd.get(key)).longValue();
            in.seek(offset);
            if (key.equals(SERIES)) {
                parseSeriesTag();
            } else if (key.equals(IMAGES)) {
                parseImageTag(i);
            } else if (key.equals(DIMDESCR)) {
                parseDimensionTag(i);
            } else if (key.equals(TIMEINFO) && metadataLevel != MetadataLevel.MINIMUM) {
                parseTimeTag(i);
            } else if (key.equals(EXPERIMENT) && metadataLevel != MetadataLevel.MINIMUM) {
                parseExperimentTag();
            } else if (key.equals(LUTDESC)) {
                parseLUT(i);
            } else if (key.equals(CHANDESC) && metadataLevel != MetadataLevel.MINIMUM) {
                parseChannelTag();
            }
        }
        ms.orderCertain = true;
        ms.littleEndian = isLittleEndian();
        ms.falseColor = true;
        ms.metadataComplete = true;
        ms.interleaved = false;
        String filename = (String) files[i].get(0);
        if (checkSuffix(filename, TiffReader.TIFF_SUFFIXES)) {
            RandomAccessInputStream s = new RandomAccessInputStream(filename, 16);
            try {
                TiffParser parser = new TiffParser(s);
                parser.setDoCaching(false);
                IFD firstIFD = parser.getFirstIFD();
                parser.fillInIFD(firstIFD);
                ms.sizeX = (int) firstIFD.getImageWidth();
                ms.sizeY = (int) firstIFD.getImageLength();
                // override the .lei pixel type, in case a TIFF file was overwritten
                ms.pixelType = firstIFD.getPixelType();
                // won't affect the pixel data
                if (FormatTools.getBytesPerPixel(ms.pixelType) > 1) {
                    ms.littleEndian = firstIFD.isLittleEndian();
                } else {
                    ms.littleEndian = realLittleEndian;
                }
                tileWidth[i] = (int) firstIFD.getTileWidth();
                tileHeight[i] = (int) firstIFD.getTileLength();
            } finally {
                s.close();
            }
        } else {
            ms.littleEndian = realLittleEndian;
        }
    }
    for (int i = 0; i < getSeriesCount(); i++) {
        setSeries(i);
        CoreMetadata ms = core.get(i);
        if (getSizeZ() == 0)
            ms.sizeZ = 1;
        if (getSizeT() == 0)
            ms.sizeT = 1;
        if (getSizeC() == 0)
            ms.sizeC = 1;
        if (getImageCount() == 0)
            ms.imageCount = 1;
        if (getImageCount() == 1 && getSizeZ() * getSizeT() > 1) {
            ms.sizeZ = 1;
            ms.sizeT = 1;
        }
        if (getSizeY() == 1 || getSizeY() == getSizeZ() || getSizeY() == getSizeT()) {
            // XZ or XT scan
            if (getSizeZ() > 1 && getImageCount() == getSizeC() * getSizeT()) {
                ms.sizeY = getSizeZ();
                ms.sizeZ = 1;
            } else if (getSizeT() > 1 && getImageCount() == getSizeC() * getSizeZ()) {
                ms.sizeY = getSizeT();
                ms.sizeT = 1;
            }
        }
        if (isRGB())
            ms.indexed = false;
        ms.dimensionOrder = MetadataTools.makeSaneDimensionOrder(getDimensionOrder());
    }
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);
    // minimum metadata level.
    for (int i = 0; i < getSeriesCount(); i++) {
        store.setImageName(seriesNames.get(i), i);
    }
    if (metadataLevel == MetadataLevel.MINIMUM)
        return;
    for (int i = 0; i < getSeriesCount(); i++) {
        CoreMetadata ms = core.get(i);
        IFD ifd = headerIFDs.get(i);
        long firstPlane = 0;
        if (i < timestamps.length && timestamps[i] != null && timestamps[i].length > 0) {
            firstPlane = DateTools.getTime(timestamps[i][0], DATE_FORMAT, ":");
            String date = DateTools.formatDate(timestamps[i][0], DATE_FORMAT);
            if (date != null) {
                store.setImageAcquisitionDate(new Timestamp(date), i);
            }
        }
        store.setImageDescription(seriesDescriptions.get(i), i);
        String instrumentID = MetadataTools.createLSID("Instrument", i);
        store.setInstrumentID(instrumentID, i);
        // parse instrument data
        nextDetector = 0;
        nextChannel = 0;
        detectors.clear();
        cutInPopulated[i] = new boolean[ms.sizeC];
        cutOutPopulated[i] = new boolean[ms.sizeC];
        filterRefPopulated[i] = new boolean[ms.sizeC];
        Integer[] keys = ifd.keySet().toArray(new Integer[ifd.size()]);
        Arrays.sort(keys);
        int nextInstrumentBlock = 1;
        sequential = DataTools.indexOf(keys, SEQ_SCANNERSET) != -1;
        for (Integer key : keys) {
            if (key.equals(FILTERSET) || key.equals(SCANNERSET) || key.equals(SEQ_SCANNERSET) || key.equals(SEQ_FILTERSET) || (key > SEQ_SCANNERSET && key < SEQ_SCANNERSET_END) || (key > SEQ_FILTERSET && key < SEQ_FILTERSET_END)) {
                if (sequential && (key.equals(FILTERSET) || key.equals(SCANNERSET))) {
                    continue;
                }
                long offset = ((Long) ifd.get(key)).longValue();
                in.seek(offset);
                setSeries(i);
                parseInstrumentData(store, nextInstrumentBlock++);
            }
        }
        activeChannelIndices.clear();
        // link Instrument and Image
        store.setImageInstrumentRef(instrumentID, i);
        Length sizeX = FormatTools.getPhysicalSizeX(physicalSizes[i][0]);
        Length sizeY = FormatTools.getPhysicalSizeY(physicalSizes[i][1]);
        Length sizeZ = FormatTools.getPhysicalSizeZ(physicalSizes[i][2]);
        if (sizeX != null) {
            store.setPixelsPhysicalSizeX(sizeX, i);
        }
        if (sizeY != null) {
            store.setPixelsPhysicalSizeY(sizeY, i);
        }
        if (sizeZ != null) {
            store.setPixelsPhysicalSizeZ(sizeZ, i);
        }
        if ((int) physicalSizes[i][4] > 0) {
            store.setPixelsTimeIncrement(new Time(physicalSizes[i][4], UNITS.SECOND), i);
        }
        for (int j = 0; j < ms.imageCount; j++) {
            if (timestamps[i] != null && j < timestamps[i].length) {
                long time = DateTools.getTime(timestamps[i][j], DATE_FORMAT, ":");
                double elapsedTime = (double) (time - firstPlane) / 1000;
                store.setPlaneDeltaT(new Time(elapsedTime, UNITS.SECOND), i, j);
                if (exposureTime[i] > 0) {
                    store.setPlaneExposureTime(new Time(exposureTime[i], UNITS.SECOND), i, j);
                }
            }
        }
    }
    setSeries(0);
}
Also used : IFD(loci.formats.tiff.IFD) ArrayList(java.util.ArrayList) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp) ArrayList(java.util.ArrayList) IFDList(loci.formats.tiff.IFDList) List(java.util.List) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) IFDList(loci.formats.tiff.IFDList) TiffParser(loci.formats.tiff.TiffParser) RandomAccessInputStream(loci.common.RandomAccessInputStream) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) File(java.io.File) Location(loci.common.Location)

Example 3 with Timestamp

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

the class MetamorphReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    if (checkSuffix(id, ND_SUFFIX)) {
        LOGGER.info("Initializing " + id);
        // find an associated STK file
        String stkFile = id.substring(0, id.lastIndexOf("."));
        if (stkFile.indexOf(File.separatorChar) != -1) {
            stkFile = stkFile.substring(stkFile.lastIndexOf(File.separator) + 1);
        }
        Location parent = new Location(id).getAbsoluteFile().getParentFile();
        LOGGER.info("Looking for STK file in {}", parent.getAbsolutePath());
        String[] dirList = parent.list(true);
        Arrays.sort(dirList);
        for (String f : dirList) {
            int underscore = f.indexOf('_');
            if (underscore < 0)
                underscore = f.indexOf('.');
            if (underscore < 0)
                underscore = f.length();
            String prefix = f.substring(0, underscore);
            if ((f.equals(stkFile) || stkFile.startsWith(prefix)) && checkSuffix(f, STK_SUFFIX)) {
                stkFile = new Location(parent.getAbsolutePath(), f).getAbsolutePath();
                break;
            }
        }
        if (!checkSuffix(stkFile, STK_SUFFIX)) {
            throw new FormatException("STK file not found in " + parent.getAbsolutePath() + ".");
        }
        super.initFile(stkFile);
    } else
        super.initFile(id);
    Location ndfile = null;
    if (checkSuffix(id, ND_SUFFIX))
        ndfile = new Location(id);
    else if (canLookForND && isGroupFiles()) {
        // an STK file was passed to initFile
        // let's check the parent directory for an .nd file
        Location stk = new Location(id).getAbsoluteFile();
        String stkName = stk.getName();
        String stkPrefix = stkName;
        if (stkPrefix.indexOf('_') >= 0) {
            stkPrefix = stkPrefix.substring(0, stkPrefix.indexOf('_') + 1);
        }
        Location parent = stk.getParentFile();
        String[] list = parent.list(true);
        int matchingChars = 0;
        for (String f : list) {
            if (checkSuffix(f, ND_SUFFIX)) {
                String prefix = f.substring(0, f.lastIndexOf("."));
                if (prefix.indexOf('_') >= 0) {
                    prefix = prefix.substring(0, prefix.indexOf('_') + 1);
                }
                if (stkName.startsWith(prefix) || prefix.equals(stkPrefix)) {
                    int charCount = 0;
                    for (int i = 0; i < f.length(); i++) {
                        if (i >= stkName.length()) {
                            break;
                        }
                        if (f.charAt(i) == stkName.charAt(i)) {
                            charCount++;
                        } else {
                            break;
                        }
                    }
                    if (charCount > matchingChars || (charCount == matchingChars && f.charAt(charCount) == '.')) {
                        ndfile = new Location(parent, f).getAbsoluteFile();
                        matchingChars = charCount;
                    }
                }
            }
        }
    }
    String creationTime = null;
    if (ndfile != null && ndfile.exists() && (fileGroupOption(id) == FormatTools.MUST_GROUP || isGroupFiles())) {
        // parse key/value pairs from .nd file
        int zc = getSizeZ(), cc = getSizeC(), tc = getSizeT();
        int nstages = 0;
        String z = null, c = null, t = null;
        final List<Boolean> hasZ = new ArrayList<Boolean>();
        waveNames = new ArrayList<String>();
        stageNames = new ArrayList<String>();
        boolean useWaveNames = true;
        ndFilename = ndfile.getAbsolutePath();
        String[] lines = DataTools.readFile(ndFilename).split("\n");
        boolean globalDoZ = true;
        boolean doTimelapse = false;
        StringBuilder currentValue = new StringBuilder();
        String key = "";
        for (String line : lines) {
            int comma = line.indexOf(',');
            if (comma <= 0) {
                currentValue.append("\n");
                currentValue.append(line);
                continue;
            }
            String value = currentValue.toString();
            addGlobalMeta(key, value);
            if (key.equals("NZSteps"))
                z = value;
            else if (key.equals("DoTimelapse")) {
                doTimelapse = Boolean.parseBoolean(value);
            } else if (key.equals("NWavelengths"))
                c = value;
            else if (key.equals("NTimePoints"))
                t = value;
            else if (key.startsWith("WaveDoZ")) {
                hasZ.add(Boolean.parseBoolean(value));
            } else if (key.startsWith("WaveName")) {
                String waveName = value.substring(1, value.length() - 1);
                if (waveName.equals("Both lasers") || waveName.startsWith("DUAL")) {
                    bizarreMultichannelAcquisition = true;
                }
                waveNames.add(waveName);
            } else if (key.startsWith("Stage")) {
                stageNames.add(value);
            } else if (key.startsWith("StartTime")) {
                creationTime = value;
            } else if (key.equals("ZStepSize")) {
                value = value.replace(',', '.');
                stepSize = Double.parseDouble(value);
            } else if (key.equals("NStagePositions")) {
                nstages = Integer.parseInt(value);
            } else if (key.equals("WaveInFileName")) {
                useWaveNames = Boolean.parseBoolean(value);
            } else if (key.equals("DoZSeries")) {
                globalDoZ = Boolean.parseBoolean(value);
            }
            key = line.substring(1, comma - 1).trim();
            currentValue.delete(0, currentValue.length());
            currentValue.append(line.substring(comma + 1).trim());
        }
        if (!globalDoZ) {
            for (int i = 0; i < hasZ.size(); i++) {
                hasZ.set(i, false);
            }
        }
        if (z != null)
            zc = Integer.parseInt(z);
        if (c != null)
            cc = Integer.parseInt(c);
        if (t != null)
            tc = Integer.parseInt(t);
        else if (!doTimelapse) {
            tc = 1;
        }
        if (cc == 0)
            cc = 1;
        if (cc == 1 && bizarreMultichannelAcquisition) {
            cc = 2;
        }
        if (tc == 0) {
            tc = 1;
        }
        int numFiles = cc * tc;
        if (nstages > 0)
            numFiles *= nstages;
        // determine series count
        int stagesCount = nstages == 0 ? 1 : nstages;
        int seriesCount = stagesCount;
        firstSeriesChannels = new boolean[cc];
        Arrays.fill(firstSeriesChannels, true);
        boolean differentZs = false;
        for (int i = 0; i < cc; i++) {
            boolean hasZ1 = i < hasZ.size() && hasZ.get(i);
            boolean hasZ2 = i != 0 && (i - 1 < hasZ.size()) && hasZ.get(i - 1);
            if (i > 0 && hasZ1 != hasZ2 && globalDoZ) {
                if (!differentZs)
                    seriesCount *= 2;
                differentZs = true;
            }
        }
        int channelsInFirstSeries = cc;
        if (differentZs) {
            channelsInFirstSeries = 0;
            for (int i = 0; i < cc; i++) {
                if ((!hasZ.get(0) && i == 0) || (hasZ.get(0) && hasZ.get(i))) {
                    channelsInFirstSeries++;
                } else
                    firstSeriesChannels[i] = false;
            }
        }
        stks = new String[seriesCount][];
        if (seriesCount == 1)
            stks[0] = new String[numFiles];
        else if (differentZs) {
            for (int i = 0; i < stagesCount; i++) {
                stks[i * 2] = new String[channelsInFirstSeries * tc];
                stks[i * 2 + 1] = new String[(cc - channelsInFirstSeries) * tc];
            }
        } else {
            for (int i = 0; i < stks.length; i++) {
                stks[i] = new String[numFiles / stks.length];
            }
        }
        String prefix = ndfile.getPath();
        prefix = prefix.substring(prefix.lastIndexOf(File.separator) + 1, prefix.lastIndexOf("."));
        // build list of STK files
        boolean anyZ = hasZ.contains(Boolean.TRUE);
        int[] pt = new int[seriesCount];
        for (int i = 0; i < tc; i++) {
            for (int s = 0; s < stagesCount; s++) {
                for (int j = 0; j < cc; j++) {
                    boolean validZ = j >= hasZ.size() || hasZ.get(j);
                    int seriesNdx = s * (seriesCount / stagesCount);
                    if ((seriesCount != 1 && (!validZ || (hasZ.size() > 0 && !hasZ.get(0)))) || (nstages == 0 && ((!validZ && cc > 1) || seriesCount > 1))) {
                        if (anyZ && j > 0 && seriesNdx < seriesCount - 1 && (!validZ || !hasZ.get(0))) {
                            seriesNdx++;
                        }
                    }
                    if (seriesNdx >= stks.length || seriesNdx >= pt.length || pt[seriesNdx] >= stks[seriesNdx].length) {
                        continue;
                    }
                    stks[seriesNdx][pt[seriesNdx]] = prefix;
                    if (j < waveNames.size() && waveNames.get(j) != null) {
                        stks[seriesNdx][pt[seriesNdx]] += "_w" + (j + 1);
                        if (useWaveNames) {
                            String waveName = waveNames.get(j);
                            // If there are underscores in the wavelength name, translate
                            // them to hyphens. (See #558)
                            waveName = waveName.replace('_', '-');
                            // If there are slashes (forward or backward) in the wavelength
                            // name, translate them to hyphens. (See #5922)
                            waveName = waveName.replace('/', '-');
                            waveName = waveName.replace('\\', '-');
                            waveName = waveName.replace('(', '-');
                            waveName = waveName.replace(')', '-');
                            stks[seriesNdx][pt[seriesNdx]] += waveName;
                        }
                    }
                    if (nstages > 0) {
                        stks[seriesNdx][pt[seriesNdx]] += "_s" + (s + 1);
                    }
                    if (tc > 1 || doTimelapse) {
                        stks[seriesNdx][pt[seriesNdx]] += "_t" + (i + 1) + ".STK";
                    } else
                        stks[seriesNdx][pt[seriesNdx]] += ".STK";
                    pt[seriesNdx]++;
                }
            }
        }
        ndfile = ndfile.getAbsoluteFile();
        for (int s = 0; s < stks.length; s++) {
            for (int f = 0; f < stks[s].length; f++) {
                Location l = new Location(ndfile.getParent(), stks[s][f]);
                stks[s][f] = getRealSTKFile(l);
            }
        }
        String file = locateFirstValidFile();
        if (file == null) {
            throw new FormatException("Unable to locate at least one valid STK file!");
        }
        RandomAccessInputStream s = new RandomAccessInputStream(file, 16);
        TiffParser tp = new TiffParser(s);
        IFD ifd = tp.getFirstIFD();
        CoreMetadata ms0 = core.get(0);
        s.close();
        ms0.sizeX = (int) ifd.getImageWidth();
        ms0.sizeY = (int) ifd.getImageLength();
        if (bizarreMultichannelAcquisition) {
            ms0.sizeX /= 2;
        }
        ms0.sizeZ = hasZ.size() > 0 && !hasZ.get(0) ? 1 : zc;
        ms0.sizeC = cc;
        ms0.sizeT = tc;
        ms0.imageCount = getSizeZ() * getSizeC() * getSizeT();
        ms0.dimensionOrder = "XYZCT";
        if (stks != null && stks.length > 1) {
            // Note that core can't be replaced with newCore until the end of this block.
            ArrayList<CoreMetadata> newCore = new ArrayList<CoreMetadata>();
            for (int i = 0; i < stks.length; i++) {
                CoreMetadata ms = new CoreMetadata();
                newCore.add(ms);
                ms.sizeX = getSizeX();
                ms.sizeY = getSizeY();
                ms.sizeZ = getSizeZ();
                ms.sizeC = getSizeC();
                ms.sizeT = getSizeT();
                ms.pixelType = getPixelType();
                ms.imageCount = getImageCount();
                ms.dimensionOrder = getDimensionOrder();
                ms.rgb = isRGB();
                ms.littleEndian = isLittleEndian();
                ms.interleaved = isInterleaved();
                ms.orderCertain = true;
            }
            if (stks.length > nstages) {
                for (int j = 0; j < stagesCount; j++) {
                    int idx = j * 2 + 1;
                    CoreMetadata midx = newCore.get(idx);
                    CoreMetadata pmidx = newCore.get(j * 2);
                    pmidx.sizeC = stks[j * 2].length / getSizeT();
                    midx.sizeC = stks[idx].length / midx.sizeT;
                    midx.sizeZ = hasZ.size() > 1 && hasZ.get(1) && core.get(0).sizeZ == 1 ? zc : 1;
                    pmidx.imageCount = pmidx.sizeC * pmidx.sizeT * pmidx.sizeZ;
                    midx.imageCount = midx.sizeC * midx.sizeT * midx.sizeZ;
                }
            }
            core = newCore;
        }
    }
    if (stks == null) {
        stkReaders = new MetamorphReader[1][1];
        stkReaders[0][0] = new MetamorphReader();
        stkReaders[0][0].setCanLookForND(false);
    } else {
        stkReaders = new MetamorphReader[stks.length][];
        for (int i = 0; i < stks.length; i++) {
            stkReaders[i] = new MetamorphReader[stks[i].length];
            for (int j = 0; j < stkReaders[i].length; j++) {
                stkReaders[i][j] = new MetamorphReader();
                stkReaders[i][j].setCanLookForND(false);
                if (j > 0) {
                    stkReaders[i][j].setMetadataOptions(new DefaultMetadataOptions(MetadataLevel.MINIMUM));
                }
            }
        }
    }
    // check stage labels for plate data
    int rows = 0;
    int cols = 0;
    Map<String, Integer> rowMap = null;
    Map<String, Integer> colMap = null;
    isHCS = true;
    if (null == stageLabels) {
        isHCS = false;
    } else {
        Set<Map.Entry<Integer, Integer>> uniqueWells = new HashSet<Map.Entry<Integer, Integer>>();
        rowMap = new HashMap<String, Integer>();
        colMap = new HashMap<String, Integer>();
        for (String label : stageLabels) {
            if (null == label) {
                isHCS = false;
                break;
            }
            Map.Entry<Integer, Integer> wellCoords = getWellCoords(label);
            if (null == wellCoords) {
                isHCS = false;
                break;
            }
            uniqueWells.add(wellCoords);
            rowMap.put(label, wellCoords.getKey());
            colMap.put(label, wellCoords.getValue());
        }
        if (uniqueWells.size() != stageLabels.length) {
            isHCS = false;
        } else {
            rows = Collections.max(rowMap.values());
            cols = Collections.max(colMap.values());
            CoreMetadata c = core.get(0);
            core.clear();
            c.sizeZ = 1;
            c.sizeT = 1;
            c.imageCount = 1;
            for (int s = 0; s < uniqueWells.size(); s++) {
                CoreMetadata toAdd = new CoreMetadata(c);
                if (s > 0) {
                    toAdd.seriesMetadata.clear();
                }
                core.add(toAdd);
            }
            seriesToIFD = true;
        }
    }
    List<String> timestamps = null;
    MetamorphHandler handler = null;
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);
    if (isHCS) {
        store.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
        store.setPlateRows(new PositiveInteger(rows), 0);
        store.setPlateColumns(new PositiveInteger(cols), 0);
        store.setPlateRowNamingConvention(NamingConvention.LETTER, 0);
        store.setPlateColumnNamingConvention(NamingConvention.NUMBER, 0);
    }
    int nextObjective = 0;
    String instrumentID = MetadataTools.createLSID("Instrument", 0);
    String detectorID = MetadataTools.createLSID("Detector", 0, 0);
    store.setInstrumentID(instrumentID, 0);
    store.setDetectorID(detectorID, 0, 0);
    store.setDetectorType(getDetectorType("Other"), 0, 0);
    for (int i = 0; i < getSeriesCount(); i++) {
        setSeries(i);
        // do not reparse the same XML for every well
        if (i == 0 || !isHCS) {
            handler = new MetamorphHandler(getSeriesMetadata());
        }
        if (isHCS) {
            String label = stageLabels[i];
            String wellID = MetadataTools.createLSID("Well", 0, i);
            store.setWellID(wellID, 0, i);
            store.setWellColumn(new NonNegativeInteger(colMap.get(label)), 0, i);
            store.setWellRow(new NonNegativeInteger(rowMap.get(label)), 0, i);
            store.setWellSampleID(MetadataTools.createLSID("WellSample", 0, i, 0), 0, i, 0);
            store.setWellSampleImageRef(MetadataTools.createLSID("Image", i), 0, i, 0);
            store.setWellSampleIndex(new NonNegativeInteger(i), 0, i, 0);
        }
        store.setImageInstrumentRef(instrumentID, i);
        String comment = getFirstComment(i);
        if (i == 0 || !isHCS) {
            if (comment != null && comment.startsWith("<MetaData>")) {
                try {
                    XMLTools.parseXML(XMLTools.sanitizeXML(comment), handler);
                } catch (IOException e) {
                }
            }
        }
        if (creationTime != null) {
            String date = DateTools.formatDate(creationTime, SHORT_DATE_FORMAT, ".");
            if (date != null) {
                store.setImageAcquisitionDate(new Timestamp(date), 0);
            }
        }
        store.setImageName(makeImageName(i).trim(), i);
        if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) {
            continue;
        }
        store.setImageDescription("", i);
        store.setImagingEnvironmentTemperature(new Temperature(handler.getTemperature(), UNITS.CELSIUS), i);
        if (sizeX == null)
            sizeX = handler.getPixelSizeX();
        if (sizeY == null)
            sizeY = handler.getPixelSizeY();
        Length physicalSizeX = FormatTools.getPhysicalSizeX(sizeX);
        Length physicalSizeY = FormatTools.getPhysicalSizeY(sizeY);
        if (physicalSizeX != null) {
            store.setPixelsPhysicalSizeX(physicalSizeX, i);
        }
        if (physicalSizeY != null) {
            store.setPixelsPhysicalSizeY(physicalSizeY, i);
        }
        if (zDistances != null) {
            stepSize = zDistances[0];
        } else {
            List<Double> zPositions = new ArrayList<Double>();
            final List<Double> uniqueZ = new ArrayList<Double>();
            for (IFD ifd : ifds) {
                MetamorphHandler zPlaneHandler = new MetamorphHandler();
                String zComment = ifd.getComment();
                if (zComment != null && zComment.startsWith("<MetaData>")) {
                    try {
                        XMLTools.parseXML(XMLTools.sanitizeXML(zComment), zPlaneHandler);
                    } catch (IOException e) {
                    }
                }
                zPositions = zPlaneHandler.getZPositions();
                for (Double z : zPositions) {
                    if (!uniqueZ.contains(z))
                        uniqueZ.add(z);
                }
            }
            if (uniqueZ.size() > 1 && uniqueZ.size() == getSizeZ()) {
                BigDecimal lastZ = BigDecimal.valueOf(uniqueZ.get(uniqueZ.size() - 1));
                BigDecimal firstZ = BigDecimal.valueOf(uniqueZ.get(0));
                BigDecimal zRange = (lastZ.subtract(firstZ)).abs();
                BigDecimal zSize = BigDecimal.valueOf((double) (getSizeZ() - 1));
                MathContext mc = new MathContext(10, RoundingMode.HALF_UP);
                stepSize = zRange.divide(zSize, mc).doubleValue();
            }
        }
        Length physicalSizeZ = FormatTools.getPhysicalSizeZ(stepSize);
        if (physicalSizeZ != null) {
            store.setPixelsPhysicalSizeZ(physicalSizeZ, i);
        }
        if (handler.getLensNA() != 0 || handler.getLensRI() != 0) {
            String objectiveID = MetadataTools.createLSID("Objective", 0, nextObjective);
            store.setObjectiveID(objectiveID, 0, nextObjective);
            if (handler.getLensNA() != 0) {
                store.setObjectiveLensNA(handler.getLensNA(), 0, nextObjective);
            }
            store.setObjectiveSettingsID(objectiveID, i);
            if (handler.getLensRI() != 0) {
                store.setObjectiveSettingsRefractiveIndex(handler.getLensRI(), i);
            }
            nextObjective++;
        }
        int waveIndex = 0;
        for (int c = 0; c < getEffectiveSizeC(); c++) {
            if (firstSeriesChannels == null || (stageNames != null && stageNames.size() == getSeriesCount())) {
                waveIndex = c;
            } else if (firstSeriesChannels != null) {
                int s = i % 2;
                while (firstSeriesChannels[waveIndex] == (s == 1) && waveIndex < firstSeriesChannels.length) {
                    waveIndex++;
                }
            }
            if (waveNames != null && waveIndex < waveNames.size()) {
                store.setChannelName(waveNames.get(waveIndex).trim(), i, c);
            }
            if (handler.getBinning() != null)
                binning = handler.getBinning();
            if (binning != null) {
                store.setDetectorSettingsBinning(getBinning(binning), i, c);
            }
            if (handler.getReadOutRate() != 0) {
                store.setDetectorSettingsReadOutRate(new Frequency(handler.getReadOutRate(), UNITS.HERTZ), i, c);
            }
            if (gain == null) {
                gain = handler.getGain();
            }
            if (gain != null) {
                store.setDetectorSettingsGain(gain, i, c);
            }
            store.setDetectorSettingsID(detectorID, i, c);
            if (wave != null && waveIndex < wave.length) {
                Length wavelength = FormatTools.getWavelength(wave[waveIndex]);
                if ((int) wave[waveIndex] >= 1) {
                    // link LightSource to Image
                    int laserIndex = i * getEffectiveSizeC() + c;
                    String lightSourceID = MetadataTools.createLSID("LightSource", 0, laserIndex);
                    store.setLaserID(lightSourceID, 0, laserIndex);
                    store.setChannelLightSourceSettingsID(lightSourceID, i, c);
                    store.setLaserType(getLaserType("Other"), 0, laserIndex);
                    store.setLaserLaserMedium(getLaserMedium("Other"), 0, laserIndex);
                    if (wavelength != null) {
                        store.setChannelLightSourceSettingsWavelength(wavelength, i, c);
                    }
                }
            }
            waveIndex++;
        }
        timestamps = handler.getTimestamps();
        for (int t = 0; t < timestamps.size(); t++) {
            String date = DateTools.convertDate(DateTools.getTime(timestamps.get(t), SHORT_DATE_FORMAT, "."), DateTools.UNIX, SHORT_DATE_FORMAT + ".SSS");
            addSeriesMetaList("timestamp", date);
        }
        long startDate = 0;
        if (timestamps.size() > 0) {
            startDate = DateTools.getTime(timestamps.get(0), SHORT_DATE_FORMAT, ".");
        }
        final Length positionX = handler.getStagePositionX();
        final Length positionY = handler.getStagePositionY();
        final List<Double> exposureTimes = handler.getExposures();
        if (exposureTimes.size() == 0) {
            for (int p = 0; p < getImageCount(); p++) {
                exposureTimes.add(exposureTime);
            }
        } else if (exposureTimes.size() == 1 && exposureTimes.size() < getSizeC()) {
            for (int c = 1; c < getSizeC(); c++) {
                MetamorphHandler channelHandler = new MetamorphHandler();
                String channelComment = getComment(i, c);
                if (channelComment != null && channelComment.startsWith("<MetaData>")) {
                    try {
                        XMLTools.parseXML(XMLTools.sanitizeXML(channelComment), channelHandler);
                    } catch (IOException e) {
                    }
                }
                final List<Double> channelExpTime = channelHandler.getExposures();
                exposureTimes.add(channelExpTime.get(0));
            }
        }
        int lastFile = -1;
        IFDList lastIFDs = null;
        IFD lastIFD = null;
        double distance = zStart;
        TiffParser tp = null;
        RandomAccessInputStream stream = null;
        for (int p = 0; p < getImageCount(); p++) {
            int[] coords = getZCTCoords(p);
            Double deltaT = 0d;
            Double expTime = exposureTime;
            Double xmlZPosition = null;
            int fileIndex = getIndex(0, coords[1], coords[2]) / getSizeZ();
            if (fileIndex >= 0) {
                String file = stks == null ? currentId : stks[i][fileIndex];
                if (file != null) {
                    if (fileIndex != lastFile) {
                        if (stream != null) {
                            stream.close();
                        }
                        stream = new RandomAccessInputStream(file, 16);
                        tp = new TiffParser(stream);
                        tp.checkHeader();
                        IFDList f = tp.getIFDs();
                        if (f.size() > 0) {
                            lastFile = fileIndex;
                            lastIFDs = f;
                        } else {
                            file = null;
                            stks[i][fileIndex] = null;
                        }
                    }
                }
                if (file != null) {
                    lastIFD = lastIFDs.get(p % lastIFDs.size());
                    Object commentEntry = lastIFD.get(IFD.IMAGE_DESCRIPTION);
                    if (commentEntry != null) {
                        if (commentEntry instanceof String) {
                            comment = (String) commentEntry;
                        } else if (commentEntry instanceof TiffIFDEntry) {
                            comment = tp.getIFDValue((TiffIFDEntry) commentEntry).toString();
                        }
                    }
                    if (comment != null)
                        comment = comment.trim();
                    if (comment != null && comment.startsWith("<MetaData>")) {
                        String[] lines = comment.split("\n");
                        timestamps = new ArrayList<String>();
                        for (String line : lines) {
                            line = line.trim();
                            if (line.startsWith("<prop")) {
                                int firstQuote = line.indexOf("\"") + 1;
                                int lastQuote = line.lastIndexOf("\"");
                                String key = line.substring(firstQuote, line.indexOf("\"", firstQuote));
                                String value = line.substring(line.lastIndexOf("\"", lastQuote - 1) + 1, lastQuote);
                                if (key.equals("z-position")) {
                                    xmlZPosition = new Double(value);
                                } else if (key.equals("acquisition-time-local")) {
                                    timestamps.add(value);
                                }
                            }
                        }
                    }
                }
            }
            int index = 0;
            if (timestamps.size() > 0) {
                if (coords[2] < timestamps.size())
                    index = coords[2];
                String stamp = timestamps.get(index);
                long ms = DateTools.getTime(stamp, SHORT_DATE_FORMAT, ".");
                deltaT = (ms - startDate) / 1000.0;
            } else if (internalStamps != null && p < internalStamps.length) {
                long delta = internalStamps[p] - internalStamps[0];
                deltaT = delta / 1000.0;
                if (coords[2] < exposureTimes.size())
                    index = coords[2];
            }
            if (index == 0 && p > 0 && exposureTimes.size() > 0) {
                index = coords[1] % exposureTimes.size();
            }
            if (index < exposureTimes.size()) {
                expTime = exposureTimes.get(index);
            }
            if (deltaT != null) {
                store.setPlaneDeltaT(new Time(deltaT, UNITS.SECOND), i, p);
            }
            if (expTime != null) {
                store.setPlaneExposureTime(new Time(expTime, UNITS.SECOND), i, p);
            }
            if (stageX != null && p < stageX.length) {
                store.setPlanePositionX(stageX[p], i, p);
            } else if (positionX != null) {
                store.setPlanePositionX(positionX, i, p);
            }
            if (stageY != null && p < stageY.length) {
                store.setPlanePositionY(stageY[p], i, p);
            } else if (positionY != null) {
                store.setPlanePositionY(positionY, i, p);
            }
            if (zDistances != null && p < zDistances.length) {
                if (p > 0) {
                    if (zDistances[p] != 0d)
                        distance += zDistances[p];
                    else
                        distance += zDistances[0];
                }
                final Length zPos = new Length(distance, UNITS.REFERENCEFRAME);
                store.setPlanePositionZ(zPos, i, p);
            } else if (xmlZPosition != null) {
                final Length zPos = new Length(xmlZPosition, UNITS.REFERENCEFRAME);
                store.setPlanePositionZ(zPos, i, p);
            }
        }
        if (stream != null) {
            stream.close();
        }
    }
    setSeries(0);
}
Also used : Temperature(ome.units.quantity.Temperature) IFD(loci.formats.tiff.IFD) ArrayList(java.util.ArrayList) DateTime(org.joda.time.DateTime) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp) TiffIFDEntry(loci.formats.tiff.TiffIFDEntry) TiffIFDEntry(loci.formats.tiff.TiffIFDEntry) ArrayList(java.util.ArrayList) IFDList(loci.formats.tiff.IFDList) List(java.util.List) HashSet(java.util.HashSet) PositiveInteger(ome.xml.model.primitives.PositiveInteger) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) IOException(java.io.IOException) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) BigDecimal(java.math.BigDecimal) MathContext(java.math.MathContext) PositiveInteger(ome.xml.model.primitives.PositiveInteger) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) Frequency(ome.units.quantity.Frequency) IFDList(loci.formats.tiff.IFDList) TiffParser(loci.formats.tiff.TiffParser) RandomAccessInputStream(loci.common.RandomAccessInputStream) HashMap(java.util.HashMap) Map(java.util.Map) AbstractMap(java.util.AbstractMap) Location(loci.common.Location)

Example 4 with Timestamp

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

the class NDPIReader method initMetadataStore.

/* @see loci.formats.BaseTiffReader#initMetadataStore() */
@Override
protected void initMetadataStore() throws FormatException {
    super.initMetadataStore();
    MetadataStore store = makeFilterMetadata();
    String instrumentID = MetadataTools.createLSID("Instrument", 0);
    String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
    store.setInstrumentID(instrumentID, 0);
    store.setObjectiveID(objectiveID, 0, 0);
    if (instrumentModel != null) {
        store.setMicroscopeModel(instrumentModel, 0);
    }
    if (magnification != null) {
        store.setObjectiveNominalMagnification(magnification, 0, 0);
    }
    for (int i = 0; i < getSeriesCount(); i++) {
        store.setImageName("Series " + (i + 1), i);
        store.setImageInstrumentRef(instrumentID, i);
        store.setObjectiveSettingsID(objectiveID, i);
        if (i > 0) {
            int ifdIndex = getIFDIndex(i, 0);
            String creationDate = ifds.get(ifdIndex).getIFDTextValue(IFD.DATE_TIME);
            creationDate = DateTools.formatDate(creationDate, DATE_FORMATS, ".");
            if (creationDate != null) {
                store.setImageAcquisitionDate(new Timestamp(creationDate), i);
            }
            double xResolution = ifds.get(ifdIndex).getXResolution();
            double yResolution = ifds.get(ifdIndex).getYResolution();
            Length sizeX = FormatTools.getPhysicalSizeX(xResolution);
            Length sizeY = FormatTools.getPhysicalSizeY(yResolution);
            if (sizeX != null) {
                store.setPixelsPhysicalSizeX(sizeX, i);
            }
            if (sizeY != null) {
                store.setPixelsPhysicalSizeY(sizeY, i);
            }
        } else {
            store.setImageDescription(serialNumber, i);
        }
    }
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) Timestamp(ome.xml.model.primitives.Timestamp)

Example 5 with Timestamp

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

the class OIRReader method parseImageProperties.

private void parseImageProperties(Element root) throws FormatException {
    CoreMetadata m = core.get(0);
    Element general = getFirstChild(root, "commonimage:general");
    if (general != null) {
        Element creationDate = getFirstChild(general, "base:creationDateTime");
        if (creationDate != null) {
            String date = creationDate.getTextContent();
            acquisitionDate = new Timestamp(date);
        }
    }
    Element lsm = getFirstChild(root, "commonimage:lsm");
    if (lsm != null) {
        NodeList laserNodes = lsm.getElementsByTagName("commonimage:laser");
        for (int i = 0; i < laserNodes.getLength(); i++) {
            Element laser = (Element) laserNodes.item(i);
            Element idNode = getFirstChild(laser, "commonimage:id");
            Element nameNode = getFirstChild(laser, "commonimage:name");
            Laser l = new Laser();
            if (idNode != null) {
                l.id = idNode.getTextContent();
            }
            if (nameNode != null) {
                l.name = nameNode.getTextContent();
            }
            lasers.add(l);
        }
    }
    Element imageInfo = getFirstChild(root, "commonimage:imageInfo");
    if (imageInfo != null) {
        Element width = getFirstChild(imageInfo, "commonimage:width");
        Element height = getFirstChild(imageInfo, "commonimage:height");
        if (width != null && getSizeX() == 0) {
            m.sizeX = Integer.parseInt(width.getTextContent());
        }
        if (height != null && getSizeY() == 0) {
            m.sizeY = Integer.parseInt(height.getTextContent());
        }
        NodeList axisNodes = imageInfo.getElementsByTagName("commonimage:axis");
        if (axisNodes != null) {
            for (int i = 0; i < axisNodes.getLength(); i++) {
                parseAxis((Element) axisNodes.item(i));
            }
        }
        NodeList channelNodes = imageInfo.getElementsByTagName("commonphase:channel");
        for (int i = 0; i < channelNodes.getLength(); i++) {
            Channel c = new Channel();
            Element channelNode = (Element) channelNodes.item(i);
            c.id = channelNode.getAttribute("id");
            int index = Integer.parseInt(channelNode.getAttribute("order")) - 1;
            Element name = getFirstChild(channelNode, "commonphase:name");
            if (name != null) {
                c.name = name.getTextContent();
            }
            Element pinhole = getFirstChild(channelNode, "fvCommonphase:pinholeDiameter");
            if (pinhole != null) {
                Double pinholeSize = DataTools.parseDouble(pinhole.getTextContent());
                if (pinholeSize != null) {
                    c.pinhole = new Length(pinholeSize, UNITS.MICROMETER);
                }
            }
            Element startWavelength = getFirstChild(channelNode, "opticalelement:startWavelength");
            Element endWavelength = getFirstChild(channelNode, "opticalelement:endWavelength");
            if (startWavelength != null) {
                Double wave = DataTools.parseDouble(startWavelength.getTextContent());
                if (wave != null) {
                    c.excitation = FormatTools.getExcitationWavelength(wave);
                }
            }
            if (endWavelength != null) {
                Double wave = DataTools.parseDouble(endWavelength.getTextContent());
                if (wave != null) {
                    c.emission = FormatTools.getEmissionWavelength(wave);
                }
            }
            Element imageDefinition = getFirstChild(channelNode, "commonphase:imageDefinition");
            if (imageDefinition != null) {
                Element depth = getFirstChild(imageDefinition, "commonphase:depth");
                Element bitCount = getFirstChild(imageDefinition, "commonphase:bitCounts");
                if (depth != null) {
                    int bytes = Integer.parseInt(depth.getTextContent());
                    m.pixelType = FormatTools.pixelTypeFromBytes(bytes, false, false);
                }
                if (bitCount != null) {
                    m.bitsPerPixel = Integer.parseInt(bitCount.getTextContent());
                }
            }
            Element length = getFirstChild(channelNode, "commonphase:length");
            Element pixelUnit = getFirstChild(channelNode, "commonphase:pixelUnit");
            if (length != null) {
                Element xLength = getFirstChild(length, "commonparam:x");
                Element xUnit = getFirstChild(pixelUnit, "commonphase:x");
                if (xLength != null) {
                    Double x = DataTools.parseDouble(xLength.getTextContent());
                    String unit = null;
                    if (xUnit != null) {
                        unit = xUnit.getTextContent();
                    }
                    physicalSizeX = FormatTools.getPhysicalSize(x, unit);
                }
                Element yLength = getFirstChild(length, "commonparam:y");
                Element yUnit = getFirstChild(pixelUnit, "commonphase:y");
                if (yLength != null) {
                    Double y = DataTools.parseDouble(yLength.getTextContent());
                    String unit = null;
                    if (yUnit != null) {
                        unit = yUnit.getTextContent();
                    }
                    physicalSizeY = FormatTools.getPhysicalSize(y, unit);
                }
                Element zLength = getFirstChild(length, "commonparam:z");
                Element zUnit = getFirstChild(pixelUnit, "commonphase:z");
                if (zLength != null) {
                    Double z = DataTools.parseDouble(zLength.getTextContent());
                    String unit = null;
                    if (zUnit != null) {
                        unit = zUnit.getTextContent();
                    }
                    physicalSizeZ = FormatTools.getPhysicalSize(z, unit);
                }
            }
            while (index > channels.size()) {
                channels.add(null);
            }
            if (index == channels.size()) {
                channels.add(c);
            } else {
                channels.set(index, c);
            }
        }
    }
    for (int i = 0; i < channels.size(); i++) {
        if (channels.get(i) == null) {
            channels.remove(i);
            i--;
        }
    }
    Element acquisition = getFirstChild(root, "commonimage:acquisition");
    if (acquisition == null) {
        acquisition = getFirstChild(root, "lsmimage:acquisition");
    }
    if (acquisition != null) {
        Element microscopeConfiguration = getFirstChild(acquisition, "commonimage:microscopeConfiguration");
        if (microscopeConfiguration != null) {
            NodeList objectiveLenses = microscopeConfiguration.getElementsByTagName("commonimage:objectiveLens");
            if (objectiveLenses != null) {
                for (int i = 0; i < objectiveLenses.getLength(); i++) {
                    Element lens = (Element) objectiveLenses.item(i);
                    Objective objective = new Objective();
                    Element lensName = getFirstChild(lens, "opticalelement:displayName");
                    Element magnification = getFirstChild(lens, "opticalelement:magnification");
                    Element na = getFirstChild(lens, "opticalelement:naValue");
                    Element wd = getFirstChild(lens, "opticalelement:wdValue");
                    Element refraction = getFirstChild(lens, "opticalelement:refraction");
                    Element immersion = getFirstChild(lens, "opticalelement:immersion");
                    if (lensName != null) {
                        objective.name = lensName.getTextContent();
                    }
                    if (magnification != null) {
                        objective.magnification = DataTools.parseDouble(magnification.getTextContent());
                    }
                    if (na != null) {
                        objective.na = DataTools.parseDouble(na.getTextContent());
                    }
                    if (wd != null) {
                        objective.wd = DataTools.parseDouble(wd.getTextContent());
                    }
                    if (refraction != null) {
                        objective.ri = DataTools.parseDouble(refraction.getTextContent());
                    }
                    if (immersion != null) {
                        objective.immersion = getImmersion(immersion.getTextContent());
                    }
                    objectives.add(objective);
                }
            }
        }
        Element imagingParam = getFirstChild(acquisition, "commonimage:imagingParam");
        if (imagingParam == null) {
            imagingParam = getFirstChild(acquisition, "lsmimage:imagingParam");
        }
        if (imagingParam != null) {
            NodeList axes = imagingParam.getElementsByTagName("commonparam:axis");
            if (axes != null) {
                for (int i = 0; i < axes.getLength(); i++) {
                    Element dimensionAxis = (Element) axes.item(i);
                    if (dimensionAxis.hasAttribute("enable") && dimensionAxis.getAttribute("enable").equals("true") && (!dimensionAxis.hasAttribute("paramEnable") || dimensionAxis.getAttribute("paramEnable").equals("true"))) {
                        parseAxis(dimensionAxis);
                    }
                }
            }
            NodeList pmts = imagingParam.getElementsByTagName("lsmparam:pmt");
            if (pmts != null) {
                for (int i = 0; i < pmts.getLength(); i++) {
                    Element pmt = (Element) pmts.item(i);
                    Detector detector = new Detector();
                    detector.id = pmt.getAttribute("detectorId");
                    detector.channelId = pmt.getAttribute("channelId");
                    Element voltage = getFirstChild(pmt, "lsmparam:voltage");
                    Element offset = getFirstChild(pmt, "lsmparam:offset");
                    Element gain = getFirstChild(pmt, "lsmparam:gain");
                    if (voltage != null) {
                        detector.voltage = DataTools.parseDouble(voltage.getTextContent());
                    }
                    if (offset != null) {
                        detector.offset = DataTools.parseDouble(offset.getTextContent());
                    }
                    if (gain != null) {
                        detector.gain = DataTools.parseDouble(gain.getTextContent());
                    }
                    detectors.add(detector);
                }
            }
            NodeList mainLasers = imagingParam.getElementsByTagName("lsmparam:mainLaser");
            if (mainLasers != null) {
                for (int i = 0; i < mainLasers.getLength(); i++) {
                    Element mainLaser = (Element) mainLasers.item(i);
                    String id = mainLaser.getAttribute("laserDataId");
                    Laser currentLaser = null;
                    for (int laser = 0; laser < lasers.size(); laser++) {
                        if (id.startsWith(lasers.get(laser).id)) {
                            currentLaser = lasers.get(laser);
                            break;
                        }
                    }
                    if (currentLaser == null) {
                        continue;
                    }
                    currentLaser.dataId = id;
                    Element power = getFirstChild(mainLaser, "commonparam:power");
                    Element transmissivity = getFirstChild(mainLaser, "commonparam:transmissivity");
                    if (power != null) {
                        currentLaser.power = DataTools.parseDouble(power.getTextContent());
                    }
                    if (transmissivity != null) {
                        currentLaser.transmissivity = DataTools.parseDouble(transmissivity.getTextContent());
                    }
                }
            }
            Element resolution = getFirstChild(imagingParam, "commonparam:pixelResolution");
            if (resolution != null) {
                Element x = getFirstChild(resolution, "commonparam:x");
                Element y = getFirstChild(resolution, "commonparam:y");
                Element z = getFirstChild(resolution, "commonparam:z");
                if (x != null && physicalSizeX == null) {
                    Double xValue = DataTools.parseDouble(x.getTextContent());
                    physicalSizeX = FormatTools.getPhysicalSize(xValue, null);
                }
                if (y != null && physicalSizeY == null) {
                    Double yValue = DataTools.parseDouble(y.getTextContent());
                    physicalSizeY = FormatTools.getPhysicalSize(yValue, null);
                }
                if (z != null && physicalSizeZ == null) {
                    Double zValue = DataTools.parseDouble(z.getTextContent());
                    physicalSizeZ = FormatTools.getPhysicalSize(zValue, null);
                }
            }
        }
        NodeList imagingMainLasers = acquisition.getElementsByTagName("lsmimage:imagingMainLaser");
        if (imagingMainLasers != null) {
            for (int i = 0; i < imagingMainLasers.getLength(); i++) {
                Element mainLaser = (Element) imagingMainLasers.item(i);
                String id = mainLaser.getAttribute("id");
                String enable = mainLaser.getAttribute("enable");
                if ("true".equals(enable)) {
                    Element wavelength = getFirstChild(mainLaser, "commonimage:wavelength");
                    if (wavelength != null) {
                        for (Laser l : lasers) {
                            if (id.equals(l.dataId)) {
                                l.wavelength = DataTools.parseDouble(wavelength.getTextContent());
                            }
                        }
                    }
                }
            }
        }
        NodeList channelLinkages = acquisition.getElementsByTagName("commonphase:channel");
        // if not, clear and re-populate the channel list
        for (int c = 0; c < channels.size(); c++) {
            String id = channels.get(c).id;
            boolean hasUID = false;
            for (String uid : pixelBlocks.keySet()) {
                if (uid.indexOf(id) >= 0) {
                    hasUID = true;
                    break;
                }
            }
            if (!hasUID) {
                channels.remove(c);
                c--;
            }
        }
        boolean appendChannels = channels.size() == 0;
        if (channelLinkages != null && channelLinkages.getLength() > 0) {
            for (int i = 0; i < channelLinkages.getLength(); i++) {
                Element channel = (Element) channelLinkages.item(i);
                parseChannel(channel, appendChannels);
            }
        } else {
            // so far seems to only be needed for the oldest (software version 1.2.x) files
            channelLinkages = acquisition.getElementsByTagName("lsmimage:channel");
            for (int i = 0; i < channelLinkages.getLength(); i++) {
                Element channel = (Element) channelLinkages.item(i);
                parseChannel(channel, appendChannels);
            }
        }
    }
}
Also used : Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) CoreMetadata(loci.formats.CoreMetadata) Timestamp(ome.xml.model.primitives.Timestamp) Length(ome.units.quantity.Length)

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