Search in sources :

Example 1 with Frequency

use of ome.units.quantity.Frequency 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 2 with Frequency

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

the class NativeND2Reader method populateMetadataStore.

private void populateMetadataStore(ND2Handler handler) throws FormatException {
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);
    String filename = new Location(getCurrentFile()).getName();
    if (handler != null) {
        ArrayList<String> posNames = handler.getPositionNames();
        int nameWidth = String.valueOf(getSeriesCount()).length();
        for (int i = 0; i < getSeriesCount(); i++) {
            String seriesSuffix = String.format("(series %0" + nameWidth + "d)", i + 1);
            String suffix = (i < posNames.size() && !posNames.get(i).equals("")) ? posNames.get(i) : seriesSuffix;
            String name = filename + " " + suffix;
            store.setImageName(name.trim(), i);
        }
    }
    colors = new int[getEffectiveSizeC()];
    ArrayList<String> channelNames = null;
    if (handler != null) {
        channelNames = handler.getChannelNames();
        if (channelNames.size() < getEffectiveSizeC() && backupHandler != null) {
            channelNames = backupHandler.getChannelNames();
        } else if (channelNames.size() < getEffectiveSizeC()) {
            channelNames = textChannelNames;
        }
        for (int c = 0; c < getEffectiveSizeC(); c++) {
            if (c < channelNames.size()) {
                String channelName = channelNames.get(c);
                Integer channelColor = channelColors.get(channelName);
                colors[c] = channelColor == null ? 0 : channelColor.intValue();
            }
        }
    }
    if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) {
        return;
    }
    String instrumentID = MetadataTools.createLSID("Instrument", 0);
    store.setInstrumentID(instrumentID, 0);
    for (int i = 0; i < getSeriesCount(); i++) {
        // link Instrument and Image
        store.setImageInstrumentRef(instrumentID, i);
        // set the channel color
        for (int c = 0; c < getEffectiveSizeC(); c++) {
            int red = colors[c] & 0xff;
            int green = (colors[c] & 0xff00) >> 8;
            int blue = (colors[c] & 0xff0000) >> 16;
            // doing so can prevent the image from displaying correctly
            if (red != 0 || green != 0 || blue != 0) {
                // always set the alpha to 255, otherwise the colors may not appear
                store.setChannelColor(new Color(red, green, blue, 255), i, c);
            }
        }
    }
    // populate Dimensions data
    if (handler != null) {
        for (int i = 0; i < getSeriesCount(); i++) {
            double sizeX = handler.getPixelSizeX();
            double sizeY = handler.getPixelSizeY();
            double sizeZ = handler.getPixelSizeZ();
            if (trueSizeX > 0) {
                store.setPixelsPhysicalSizeX(FormatTools.getPhysicalSizeX(trueSizeX), i);
            } else {
                Length size = FormatTools.getPhysicalSizeX(sizeX);
                if (size != null) {
                    store.setPixelsPhysicalSizeX(size, i);
                }
            }
            if (trueSizeY > 0) {
                store.setPixelsPhysicalSizeY(FormatTools.getPhysicalSizeY(trueSizeY), i);
            } else if (trueSizeX > 0) {
                // if the X size is set, assume X and Y are equal
                store.setPixelsPhysicalSizeY(FormatTools.getPhysicalSizeY(trueSizeX), i);
            } else {
                Length size = FormatTools.getPhysicalSizeY(sizeY);
                if (size == null) {
                    // if the X size is set, assume X and Y are equal
                    size = FormatTools.getPhysicalSizeY(sizeX);
                }
                if (size != null) {
                    store.setPixelsPhysicalSizeY(size, i);
                }
            }
            if (trueSizeZ != null && trueSizeZ > 0) {
                store.setPixelsPhysicalSizeZ(FormatTools.getPhysicalSizeZ(trueSizeZ), i);
            } else {
                Length size = FormatTools.getPhysicalSizeZ(sizeZ);
                if (size != null) {
                    store.setPixelsPhysicalSizeZ(size, i);
                }
            }
        }
    }
    // populate PlaneTiming and StagePosition data
    if (handler != null && handler.getExposureTimes().size() > 0) {
        exposureTime = handler.getExposureTimes();
    }
    int zcPlanes = getImageCount() / ((split ? getSizeC() : 1) * getSizeT());
    for (int i = 0; i < getSeriesCount(); i++) {
        if (tsT.size() > 0) {
            setSeries(i);
            for (int n = 0; n < getImageCount(); n++) {
                int[] coords = getZCTCoords(n);
                int stampIndex = getIndex(coords[0], split ? 0 : coords[1], 0);
                stampIndex += (coords[2] * getSeriesCount() + i) * zcPlanes;
                if (tsT.size() == getImageCount())
                    stampIndex = n;
                else if (tsT.size() == getSizeZ()) {
                    stampIndex = coords[0];
                }
                if (stampIndex < tsT.size()) {
                    double stamp = tsT.get(stampIndex).doubleValue();
                    store.setPlaneDeltaT(new Time(stamp, UNITS.SECOND), i, n);
                }
                int index = i * getSizeC() + coords[1];
                if (exposureTime.size() == getSizeC()) {
                    index = coords[1];
                }
                if (exposureTime != null && index < exposureTime.size() && exposureTime.get(index) != null) {
                    store.setPlaneExposureTime(new Time(exposureTime.get(index), UNITS.SECOND), i, n);
                }
            }
        }
        if (handler != null) {
            if (posX == null)
                posX = handler.getXPositions();
            if (posY == null)
                posY = handler.getYPositions();
            if (posZ == null)
                posZ = handler.getZPositions();
        }
        String pos = "for position";
        for (int n = 0; n < getImageCount(); n++) {
            int[] coords = getZCTCoords(n);
            int index = coords[0];
            index += (coords[2] * getSeriesCount() + i) * zcPlanes;
            if (posX != null) {
                if (index >= posX.size())
                    index = i;
                if (index < posX.size()) {
                    String key = "X position ";
                    store.setPlanePositionX(posX.get(index), i, n);
                    addSeriesMetaList(key, posX.get(index));
                    addGlobalMetaList(key + pos, posX.get(index));
                }
            }
            if (posY != null) {
                if (index < posY.size()) {
                    String key = "Y position ";
                    store.setPlanePositionY(posY.get(index), i, n);
                    addSeriesMetaList(key, posY.get(index));
                    addGlobalMetaList(key + pos, posY.get(index));
                }
            }
            if (posZ != null) {
                if (index < posZ.size()) {
                    store.setPlanePositionZ(posZ.get(index), i, n);
                    String key = "Z position " + pos + ", plane";
                    addSeriesMetaList(key, posZ.get(index));
                    addGlobalMetaList(key, posZ.get(index));
                }
            }
        }
    }
    if (handler == null) {
        setSeries(0);
        return;
    }
    String detectorID = MetadataTools.createLSID("Detector", 0, 0);
    store.setDetectorID(detectorID, 0, 0);
    store.setDetectorModel(handler.getCameraModel(), 0, 0);
    store.setDetectorType(getDetectorType("Other"), 0, 0);
    ArrayList<String> modality = handler.getModalities();
    ArrayList<String> binning = handler.getBinnings();
    ArrayList<Double> speed = handler.getSpeeds();
    ArrayList<Double> gain = handler.getGains();
    ArrayList<Double> temperature = handler.getTemperatures();
    ArrayList<Double> exWave = handler.getExcitationWavelengths();
    ArrayList<Double> emWave = handler.getEmissionWavelengths();
    ArrayList<Integer> power = handler.getPowers();
    ArrayList<Hashtable<String, String>> rois = handler.getROIs();
    if (backupHandler != null) {
        if (emWave.size() == 0) {
            emWave = backupHandler.getEmissionWavelengths();
        }
        if (exWave.size() == 0) {
            exWave = backupHandler.getExcitationWavelengths();
        }
    }
    for (int i = 0; i < getSeriesCount(); i++) {
        for (int c = 0; c < getEffectiveSizeC(); c++) {
            int index = c;
            Double pinholeSize = handler.getPinholeSize();
            if (pinholeSize != null) {
                store.setChannelPinholeSize(new Length(pinholeSize, UNITS.MICROMETER), i, c);
            }
            if (index < channelNames.size()) {
                String channelName = channelNames.get(index);
                store.setChannelName(channelName, i, c);
            } else if (channelNames.size() >= getEffectiveSizeC()) {
                store.setChannelName(channelNames.get(c), i, c);
            }
            if (index < modality.size()) {
                store.setChannelAcquisitionMode(getAcquisitionMode(modality.get(index)), i, c);
            }
            if (index < emWave.size() || index < textEmissionWavelengths.size()) {
                Double value = index < emWave.size() ? emWave.get(index) : textEmissionWavelengths.get(index);
                Length emission = FormatTools.getEmissionWavelength(value);
                if (emission != null) {
                    store.setChannelEmissionWavelength(emission, i, c);
                }
            } else if (emWave.size() > 0 || textEmissionWavelengths.size() > 0) {
                store.setChannelColor(new Color(255, 255, 255, 255), i, c);
            }
            if (index < exWave.size()) {
                Length excitation = FormatTools.getExcitationWavelength(exWave.get(index));
                if (excitation != null) {
                    store.setChannelExcitationWavelength(excitation, i, c);
                }
            }
            if (index < binning.size()) {
                store.setDetectorSettingsBinning(getBinning(binning.get(index)), i, c);
            }
            if (index < gain.size()) {
                store.setDetectorSettingsGain(gain.get(index), i, c);
            }
            if (index < speed.size()) {
                store.setDetectorSettingsReadOutRate(new Frequency(speed.get(index), UNITS.HERTZ), i, c);
            }
            store.setDetectorSettingsID(detectorID, i, c);
        }
    }
    for (int i = 0; i < getSeriesCount(); i++) {
        if (i * getSizeC() < temperature.size()) {
            Double temp = temperature.get(i * getSizeC());
            store.setImagingEnvironmentTemperature(new Temperature(temp, UNITS.CELSIUS), i);
        }
    }
    // populate DetectorSettings
    Double voltage = handler.getVoltage();
    if (voltage != null) {
        store.setDetectorSettingsVoltage(new ElectricPotential(voltage, UNITS.VOLT), 0, 0);
    }
    // populate Objective
    Double na = handler.getNumericalAperture();
    if (na != null) {
        store.setObjectiveLensNA(na, 0, 0);
    }
    Double mag = handler.getMagnification();
    if (mag != null) {
        store.setObjectiveCalibratedMagnification(mag, 0, 0);
    }
    store.setObjectiveModel(handler.getObjectiveModel(), 0, 0);
    String immersion = handler.getImmersion();
    if (immersion == null)
        immersion = "Other";
    store.setObjectiveImmersion(getImmersion(immersion), 0, 0);
    String correction = handler.getCorrection();
    if (correction == null || correction.length() == 0)
        correction = "Other";
    store.setObjectiveCorrection(getCorrection(correction), 0, 0);
    // link Objective to Image
    String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
    store.setObjectiveID(objectiveID, 0, 0);
    if (refractiveIndex == null) {
        refractiveIndex = handler.getRefractiveIndex();
    }
    for (int i = 0; i < getSeriesCount(); i++) {
        store.setObjectiveSettingsID(objectiveID, i);
        if (refractiveIndex != null) {
            store.setObjectiveSettingsRefractiveIndex(refractiveIndex, i);
        }
    }
    setSeries(0);
    if (getMetadataOptions().getMetadataLevel() == MetadataLevel.NO_OVERLAYS) {
        return;
    }
    handler.populateROIs(store);
}
Also used : Temperature(ome.units.quantity.Temperature) Color(ome.xml.model.primitives.Color) Time(ome.units.quantity.Time) ElectricPotential(ome.units.quantity.ElectricPotential) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) Frequency(ome.units.quantity.Frequency) Location(loci.common.Location)

Example 3 with Frequency

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

the class DeltavisionReader method parseLogFile.

/**
 * Extract metadata from associated log file, if it exists.
 */
private boolean parseLogFile(MetadataStore store) throws FormatException, IOException {
    if (logFile == null || !new Location(logFile).exists()) {
        logFile = null;
        return false;
    }
    LOGGER.info("Parsing log file");
    String[] lines = DataTools.readFile(logFile).split("[\r\n]");
    String key, value = "", prefix = "";
    int currentImage = 0;
    List<String> channelNames = new ArrayList<String>();
    List<Double> filters = new ArrayList<Double>();
    for (String line : lines) {
        int colon = line.indexOf(':');
        if (colon >= 0 && colon < line.length() - 1 && !line.startsWith("Created")) {
            key = line.substring(0, colon).trim();
            value = line.substring(colon + 1).trim();
            if (value.equals("") && !key.equals(""))
                prefix = key;
            addGlobalMeta(prefix + " " + key, value);
            // Objective properties
            if (key.equals("Objective")) {
                // assume first word is the manufacturer's name
                int space = value.indexOf(' ');
                if (space != -1) {
                    String manufacturer = value.substring(0, space);
                    String extra = value.substring(space + 1);
                    String[] tokens = extra.split(",");
                    store.setObjectiveManufacturer(manufacturer, 0, 0);
                    String magnification = "", na = "";
                    if (tokens.length >= 1) {
                        int end = tokens[0].indexOf('X');
                        if (end > 0)
                            magnification = tokens[0].substring(0, end);
                        int start = tokens[0].indexOf('/');
                        if (start >= 0)
                            na = tokens[0].substring(start + 1);
                    }
                    try {
                        Double mag = new Double(magnification);
                        store.setObjectiveNominalMagnification(mag, 0, 0);
                    } catch (NumberFormatException e) {
                        LOGGER.warn("Could not parse magnification '{}'", magnification);
                    }
                    try {
                        store.setObjectiveLensNA(new Double(na), 0, 0);
                    } catch (NumberFormatException e) {
                        LOGGER.warn("Could not parse N.A. '{}'", na);
                    }
                    if (tokens.length >= 2) {
                        store.setObjectiveCorrection(getCorrection(tokens[1]), 0, 0);
                    }
                    // TODO:  Token #2 is the microscope model name.
                    if (tokens.length > 3)
                        store.setObjectiveModel(tokens[3], 0, 0);
                }
            } else if (key.equalsIgnoreCase("Lens ID")) {
                if (value.indexOf(',') != -1) {
                    value = value.substring(0, value.indexOf(','));
                }
                if (value.indexOf(' ') != -1) {
                    value = value.substring(value.indexOf(' ') + 1);
                }
                if (!value.equals("null")) {
                    String objectiveID = "Objective:" + value;
                    store.setObjectiveID(objectiveID, 0, 0);
                    for (int series = 0; series < getSeriesCount(); series++) {
                        store.setObjectiveSettingsID(objectiveID, series);
                    }
                    store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
                    store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
                }
            } else // Image properties
            if (key.equals("Pixel Size")) {
                String[] pixelSizes = value.split(" ");
                for (int q = 0; q < pixelSizes.length; q++) {
                    Double size = null;
                    try {
                        size = new Double(pixelSizes[q].trim());
                    } catch (NumberFormatException e) {
                        LOGGER.warn("Could not parse pixel size '{}'", pixelSizes[q].trim());
                    }
                    if (q == 0) {
                        Length sizeX = FormatTools.getPhysicalSizeX(size);
                        if (sizeX != null) {
                            for (int series = 0; series < getSeriesCount(); series++) {
                                store.setPixelsPhysicalSizeX(sizeX, series);
                            }
                        }
                    }
                    if (q == 1) {
                        Length sizeY = FormatTools.getPhysicalSizeY(size);
                        if (sizeY != null) {
                            for (int series = 0; series < getSeriesCount(); series++) {
                                store.setPixelsPhysicalSizeY(sizeY, series);
                            }
                        }
                    }
                    if (q == 2) {
                        Length sizeZ = FormatTools.getPhysicalSizeZ(size);
                        if (sizeZ != null) {
                            for (int series = 0; series < getSeriesCount(); series++) {
                                store.setPixelsPhysicalSizeZ(sizeZ, series);
                            }
                        }
                    }
                }
            } else if (key.equals("Binning")) {
                store.setDetectorType(getDetectorType("Other"), 0, 0);
                String detectorID = MetadataTools.createLSID("Detector", 0, 0);
                store.setDetectorID(detectorID, 0, 0);
                for (int series = 0; series < getSeriesCount(); series++) {
                    for (int c = 0; c < getSizeC(); c++) {
                        store.setDetectorSettingsBinning(getBinning(value), series, c);
                        // link DetectorSettings to an actual Detector
                        store.setDetectorSettingsID(detectorID, series, c);
                    }
                }
            } else // Camera properties
            if (key.equals("Type")) {
                store.setDetectorModel(value, 0, 0);
            } else if (key.equals("Gain")) {
                value = value.replaceAll("X", "");
                try {
                    String detectorID = MetadataTools.createLSID("Detector", 0, 0);
                    store.setDetectorID(detectorID, 0, 0);
                    for (int series = 0; series < getSeriesCount(); series++) {
                        for (int c = 0; c < getSizeC(); c++) {
                            store.setDetectorSettingsGain(new Double(value), series, c);
                            store.setDetectorSettingsID(detectorID, series, c);
                        }
                    }
                } catch (NumberFormatException e) {
                    LOGGER.warn("Could not parse gain '{}'", value);
                }
            } else if (key.equals("Speed")) {
                value = value.replaceAll("KHz", "");
                try {
                    double khz = Double.parseDouble(value);
                    String detectorID = MetadataTools.createLSID("Detector", 0, 0);
                    store.setDetectorID(detectorID, 0, 0);
                    for (int series = 0; series < getSeriesCount(); series++) {
                        for (int c = 0; c < getSizeC(); c++) {
                            store.setDetectorSettingsReadOutRate(new Frequency(khz, UNITS.KILOHERTZ), series, c);
                            store.setDetectorSettingsID(detectorID, series, c);
                        }
                    }
                } catch (NumberFormatException e) {
                    LOGGER.warn("Could not parse read-out rate '{}'", value);
                }
            } else if (key.equals("Temp Setting")) {
                value = value.replaceAll("C", "").trim();
                try {
                // this is the camera temperature, not the environment temperature
                // store.setImagingEnvironmentTemperature(value, 0);
                } catch (NumberFormatException e) {
                    LOGGER.warn("Could not parse temperature '{}'", value);
                }
            } else // Plane properties
            if (key.equals("EM filter")) {
                if (!channelNames.contains(value)) {
                    channelNames.add(value);
                }
            } else if (key.equals("ND filter")) {
                value = value.replaceAll("%", "");
                try {
                    double nd = Double.parseDouble(value) / 100;
                    if (!filters.contains(nd)) {
                        filters.add(nd);
                    }
                } catch (NumberFormatException exc) {
                    // so no need to log it explicitly
                    if (!value.equals("BLANK")) {
                        LOGGER.warn("Could not parse ND filter '{}'", value);
                    }
                    filters.add(null);
                } catch (IllegalArgumentException e) {
                    LOGGER.debug("", e);
                }
            } else if (key.equals("Stage coordinates")) {
                if (value.length() > 1) {
                    value = value.substring(1, value.length() - 1);
                }
                String[] coords = value.split(",");
                for (int i = 0; i < coords.length; i++) {
                    Length p = null;
                    try {
                        final Double number = Double.valueOf(coords[i]);
                        p = new Length(number, UNITS.REFERENCEFRAME);
                    } catch (NumberFormatException e) {
                        LOGGER.warn("Could not parse stage coordinate '{}'", coords[i]);
                    }
                    if (currentImage < getImageCount() && getSeriesCount() == 1) {
                        // from the extended header.
                        if (i == 0) {
                            store.setPlanePositionX(p, 0, currentImage);
                        }
                        if (i == 1) {
                            store.setPlanePositionY(p, 0, currentImage);
                        }
                        if (i == 2) {
                            store.setPlanePositionZ(p, 0, currentImage);
                        }
                    }
                }
                currentImage++;
            }
        } else if (line.startsWith("Image"))
            prefix = line;
        else if (line.startsWith("Created")) {
            if (line.length() > 8)
                line = line.substring(8).trim();
            String date = DateTools.formatDate(line, DATE_FORMATS);
            if (date != null) {
                for (int series = 0; series < getSeriesCount(); series++) {
                    store.setImageAcquisitionDate(new Timestamp(date), series);
                }
            } else {
                LOGGER.warn("Could not parse date '{}'", line);
            }
        } else if (line.startsWith("#KEY")) {
            line = line.substring(line.indexOf(" ")).trim();
            int split = line.indexOf(":");
            if (split < 0) {
                split = line.indexOf(" ");
            }
            key = line.substring(0, split).trim();
            value = line.substring(split + 1).trim();
            addGlobalMeta(key, value);
        } else if (line.endsWith(":")) {
            prefix = line.substring(0, line.length() - 1);
        } else if (!line.startsWith("#") && !line.replace("-", "").isEmpty() && !prefix.isEmpty()) {
            addGlobalMetaList(prefix, line);
        }
    }
    for (int series = 0; series < getSeriesCount(); series++) {
        for (int c = 0; c < getEffectiveSizeC(); c++) {
            if (c < channelNames.size()) {
                store.setChannelName(channelNames.get(c), series, c);
            }
            if (c < filters.size()) {
                ndFilters[c] = filters.get(c);
            }
        }
    }
    return true;
}
Also used : ArrayList(java.util.ArrayList) Timestamp(ome.xml.model.primitives.Timestamp) Length(ome.units.quantity.Length) Frequency(ome.units.quantity.Frequency) Location(loci.common.Location)

Example 4 with Frequency

use of ome.units.quantity.Frequency 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 5 with Frequency

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

the class FluoviewReader method initAlternateMetadataStore.

private void initAlternateMetadataStore() throws FormatException {
    MetadataStore store = makeFilterMetadata();
    store.setImagingEnvironmentTemperature(new Temperature(new Double(temperature.floatValue()), UNITS.CELSIUS), 0);
    String instrumentID = MetadataTools.createLSID("Instrument", 0);
    String detectorID = MetadataTools.createLSID("Detector", 0, 0);
    store.setInstrumentID(instrumentID, 0);
    store.setDetectorID(detectorID, 0, 0);
    store.setDetectorModel(model, 0, 0);
    store.setImageInstrumentRef(instrumentID, 0);
    if (exposureTime != null) {
        for (int i = 0; i < getImageCount(); i++) {
            store.setPlaneExposureTime(new Time(new Double(exposureTime.floatValue()), UNITS.SECOND), 0, i);
        }
    }
    for (int i = 0; i < getEffectiveSizeC(); i++) {
        store.setDetectorSettingsID(detectorID, 0, i);
        store.setDetectorSettingsReadOutRate(new Frequency(new Double(readoutTime.floatValue()), UNITS.HERTZ), 0, i);
    }
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) Temperature(ome.units.quantity.Temperature) Frequency(ome.units.quantity.Frequency) Time(ome.units.quantity.Time)

Aggregations

Frequency (ome.units.quantity.Frequency)6 MetadataStore (loci.formats.meta.MetadataStore)5 Length (ome.units.quantity.Length)5 Time (ome.units.quantity.Time)5 Location (loci.common.Location)4 Temperature (ome.units.quantity.Temperature)4 Timestamp (ome.xml.model.primitives.Timestamp)4 ArrayList (java.util.ArrayList)3 Hashtable (java.util.Hashtable)2 RandomAccessInputStream (loci.common.RandomAccessInputStream)2 CoreMetadata (loci.formats.CoreMetadata)2 FormatException (loci.formats.FormatException)2 ElectricPotential (ome.units.quantity.ElectricPotential)2 IOException (java.io.IOException)1 BigDecimal (java.math.BigDecimal)1 MathContext (java.math.MathContext)1 AbstractMap (java.util.AbstractMap)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 List (java.util.List)1