Search in sources :

Example 11 with Time

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

the class PerkinElmerReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    if (currentId != null && (id.equals(currentId) || isUsedFile(id)))
        return;
    LOGGER.info("Finding HTML companion file");
    if (!checkSuffix(id, HTM_SUFFIX)) {
        Location parent = new Location(id).getAbsoluteFile().getParentFile();
        String[] ls = parent.list();
        for (String file : ls) {
            if (checkSuffix(file, HTM_SUFFIX) && !file.startsWith(".")) {
                id = new Location(parent.getAbsolutePath(), file).getAbsolutePath();
                break;
            }
        }
    }
    super.initFile(id);
    allFiles = new ArrayList<String>();
    // get the working directory
    Location tmpFile = new Location(id).getAbsoluteFile();
    Location workingDir = tmpFile.getParentFile();
    if (workingDir == null)
        workingDir = new Location(".");
    String workingDirPath = workingDir.getPath();
    if (!workingDirPath.equals(""))
        workingDirPath += File.separator;
    String[] ls = workingDir.list(true);
    if (!new Location(id).exists()) {
        ls = Location.getIdMap().keySet().toArray(new String[0]);
        workingDirPath = "";
    }
    LOGGER.info("Searching for all metadata companion files");
    // check if we have any of the required header file types
    String cfgFile = null, anoFile = null, recFile = null;
    String timFile = null, csvFile = null, zpoFile = null;
    String htmFile = null;
    final List<PixelsFile> tempFiles = new ArrayList<PixelsFile>();
    int dot = id.lastIndexOf(".");
    String check = dot < 0 ? id : id.substring(0, dot);
    check = check.substring(check.lastIndexOf(File.separator) + 1);
    // locate appropriate .tim, .csv, .zpo, .htm and .tif files
    String prefix = null;
    Arrays.sort(ls);
    for (int i = 0; i < ls.length; i++) {
        // make sure that the file has a name similar to the name of the
        // specified file
        int d = ls[i].lastIndexOf(".");
        while (d == -1 && i < ls.length - 1) {
            i++;
            d = ls[i].lastIndexOf(".");
        }
        String s = d < 0 ? ls[i] : ls[i].substring(0, d);
        if (s.startsWith(check) || check.startsWith(s) || ((prefix != null) && (s.startsWith(prefix)))) {
            prefix = ls[i].substring(0, d);
            if (cfgFile == null && checkSuffix(ls[i], CFG_SUFFIX))
                cfgFile = ls[i];
            if (anoFile == null && checkSuffix(ls[i], ANO_SUFFIX))
                anoFile = ls[i];
            if (recFile == null && checkSuffix(ls[i], REC_SUFFIX))
                recFile = ls[i];
            if (timFile == null && checkSuffix(ls[i], TIM_SUFFIX))
                timFile = ls[i];
            if (csvFile == null && checkSuffix(ls[i], CSV_SUFFIX))
                csvFile = ls[i];
            if (zpoFile == null && checkSuffix(ls[i], ZPO_SUFFIX))
                zpoFile = ls[i];
            if (htmFile == null && checkSuffix(ls[i], HTM_SUFFIX))
                htmFile = ls[i];
            dot = ls[i].lastIndexOf(".");
            PixelsFile f = new PixelsFile();
            f.path = workingDirPath + ls[i];
            if (checkSuffix(ls[i], TiffReader.TIFF_SUFFIXES)) {
                if (dot - 4 >= 0 && dot - 4 < ls[i].length() && ls[i].charAt(dot - 4) == '_') {
                    f.firstIndex = Integer.parseInt(ls[i].substring(dot - 3, dot));
                } else {
                    f.firstIndex = -1;
                }
                if (dot - 9 >= 0 && dot - 9 < ls[i].length() && ls[i].charAt(dot - 9) == '_') {
                    f.extIndex = Integer.parseInt(ls[i].substring(dot - 8, dot - 4));
                } else {
                    f.firstIndex = i;
                    f.extIndex = 0;
                }
                tempFiles.add(f);
            } else {
                try {
                    if (dot - 4 >= 0 && dot - 4 < ls[i].length() && ls[i].charAt(dot - 4) == '_') {
                        f.firstIndex = Integer.parseInt(ls[i].substring(dot - 3, dot));
                    } else {
                        f.firstIndex = -1;
                    }
                    String ext = dot + 1 < ls[i].length() ? ls[i].substring(dot + 1) : "";
                    f.extIndex = Integer.parseInt(ext, 16);
                    isTiff = false;
                    tempFiles.add(f);
                } catch (NumberFormatException exc) {
                    LOGGER.debug("Failed to parse file extension", exc);
                }
            }
        }
    }
    files = tempFiles.toArray(new PixelsFile[tempFiles.size()]);
    // determine the number of different extensions we have
    LOGGER.info("Finding image files");
    List<Integer> foundExts = new ArrayList<Integer>();
    for (PixelsFile f : files) {
        if (!foundExts.contains(f.extIndex)) {
            foundExts.add(f.extIndex);
        }
    }
    extCount = foundExts.size();
    foundExts = null;
    CoreMetadata ms0 = core.get(0);
    ms0.imageCount = 0;
    for (PixelsFile f : files) {
        allFiles.add(f.path);
        ms0.imageCount++;
        if (f.firstIndex < 0 && files.length > extCount) {
            ms0.imageCount += ((files.length - 1) / (extCount - 1)) - 1;
        }
    }
    tiff = new MinimalTiffReader();
    // we always parse the .tim and .htm files if they exist, along with
    // either the .csv file or the .zpo file
    LOGGER.info("Parsing metadata values");
    addUsedFile(workingDirPath, cfgFile);
    addUsedFile(workingDirPath, anoFile);
    addUsedFile(workingDirPath, recFile);
    addUsedFile(workingDirPath, timFile);
    if (timFile != null)
        timFile = allFiles.get(allFiles.size() - 1);
    addUsedFile(workingDirPath, csvFile);
    if (csvFile != null)
        csvFile = allFiles.get(allFiles.size() - 1);
    addUsedFile(workingDirPath, zpoFile);
    if (zpoFile != null)
        zpoFile = allFiles.get(allFiles.size() - 1);
    addUsedFile(workingDirPath, htmFile);
    if (htmFile != null)
        htmFile = allFiles.get(allFiles.size() - 1);
    if (timFile != null)
        parseTimFile(timFile);
    if (csvFile != null)
        parseCSVFile(csvFile);
    if (zpoFile != null && csvFile == null)
        parseZpoFile(zpoFile);
    // be aggressive about parsing the HTML file, since it's the only one that
    // explicitly defines the number of wavelengths and timepoints
    final List<Double> exposureTimes = new ArrayList<Double>();
    final List<Double> zPositions = new ArrayList<Double>();
    final List<Double> emWaves = new ArrayList<Double>();
    final List<Double> exWaves = new ArrayList<Double>();
    if (htmFile != null) {
        String[] tokens = DataTools.readFile(htmFile).split(HTML_REGEX);
        for (int j = 0; j < tokens.length; j++) {
            if (tokens[j].indexOf('<') != -1)
                tokens[j] = "";
        }
        for (int j = 0; j < tokens.length - 1; j += 2) {
            if (tokens[j].indexOf("Exposure") != -1) {
                addGlobalMeta("Camera Data " + tokens[j].charAt(13), tokens[j]);
                int ndx = tokens[j].indexOf("Exposure") + 9;
                String exposure = tokens[j].substring(ndx, tokens[j].indexOf(" ", ndx)).trim();
                if (exposure.endsWith(",")) {
                    exposure = exposure.substring(0, exposure.length() - 1);
                }
                exposureTimes.add(new Double(Double.parseDouble(exposure) / 1000));
                if (tokens[j].indexOf("nm") != -1) {
                    int nmIndex = tokens[j].indexOf("nm");
                    int paren = tokens[j].lastIndexOf("(", nmIndex);
                    int slash = tokens[j].lastIndexOf("/", nmIndex);
                    if (slash == -1)
                        slash = nmIndex;
                    emWaves.add(new Double(tokens[j].substring(paren + 1, slash).trim()));
                    if (tokens[j].indexOf("nm", nmIndex + 3) != -1) {
                        nmIndex = tokens[j].indexOf("nm", nmIndex + 3);
                        paren = tokens[j].lastIndexOf(" ", nmIndex);
                        slash = tokens[j].lastIndexOf("/", nmIndex);
                        if (slash == -1)
                            slash = nmIndex + 2;
                        exWaves.add(new Double(tokens[j].substring(paren + 1, slash).trim()));
                    }
                }
                j--;
            } else if (tokens[j + 1].trim().equals("Slice Z positions")) {
                for (int q = j + 2; q < tokens.length; q++) {
                    if (!tokens[q].trim().equals("")) {
                        try {
                            zPositions.add(new Double(tokens[q].trim()));
                        } catch (NumberFormatException e) {
                        }
                    }
                }
            } else if (!tokens[j].trim().equals("")) {
                tokens[j] = tokens[j].trim();
                tokens[j + 1] = tokens[j + 1].trim();
                parseKeyValue(tokens[j], tokens[j + 1]);
            }
        }
    } else {
        throw new FormatException("Valid header files not found.");
    }
    if (details != null) {
        String[] tokens = details.split("\\s");
        int n = 0;
        for (String token : tokens) {
            if (token.equals("Wavelengths"))
                ms0.sizeC = n;
            else if (token.equals("Frames"))
                ms0.sizeT = n;
            else if (token.equals("Slices"))
                ms0.sizeZ = n;
            try {
                n = Integer.parseInt(token);
            } catch (NumberFormatException e) {
                n = 0;
            }
        }
    }
    LOGGER.info("Populating metadata");
    if (files.length == 0) {
        throw new FormatException("TIFF files not found.");
    }
    if (isTiff) {
        tiff.setId(getFile(0));
        ms0.pixelType = tiff.getPixelType();
    } else {
        RandomAccessInputStream tmp = new RandomAccessInputStream(getFile(0));
        int bpp = (int) (tmp.length() - 6) / (getSizeX() * getSizeY());
        tmp.close();
        if (bpp % 3 == 0)
            bpp /= 3;
        ms0.pixelType = FormatTools.pixelTypeFromBytes(bpp, false, false);
    }
    if (getSizeZ() <= 0)
        ms0.sizeZ = 1;
    if (getSizeC() <= 0)
        ms0.sizeC = 1;
    if (getSizeT() <= 0 || getImageCount() % (getSizeZ() * getSizeC()) == 0) {
        ms0.sizeT = getImageCount() / (getSizeZ() * getSizeC());
    } else {
        ms0.imageCount = getSizeZ() * getSizeC() * getSizeT();
        if (getImageCount() > files.length) {
            ms0.imageCount = files.length;
            ms0.sizeT = getImageCount() / (getSizeZ() * getSizeC());
        }
    }
    ms0.dimensionOrder = "XYCTZ";
    ms0.rgb = isTiff ? tiff.isRGB() : false;
    ms0.interleaved = false;
    ms0.littleEndian = isTiff ? tiff.isLittleEndian() : true;
    ms0.metadataComplete = true;
    ms0.indexed = isTiff ? tiff.isIndexed() : false;
    ms0.falseColor = false;
    if (getImageCount() != getSizeZ() * getSizeC() * getSizeT()) {
        ms0.imageCount = getSizeZ() * getSizeC() * getSizeT();
    }
    if (!isTiff && extCount > getSizeT()) {
        extCount = getSizeT() * getSizeC();
    }
    // Populate metadata store
    // The metadata store we're working with.
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);
    // populate Image element
    if (finishTime != null) {
        Timestamp timestamp = Timestamp.valueOf(DateTools.formatDate(finishTime, DATE_FORMAT));
        if (timestamp != null)
            store.setImageAcquisitionDate(timestamp, 0);
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        // populate Dimensions element
        Length sizeX = FormatTools.getPhysicalSizeX(pixelSizeX);
        Length sizeY = FormatTools.getPhysicalSizeY(pixelSizeY);
        if (sizeX != null) {
            store.setPixelsPhysicalSizeX(sizeX, 0);
        }
        if (sizeY != null) {
            store.setPixelsPhysicalSizeY(sizeY, 0);
        }
        // link Instrument and Image
        String instrumentID = MetadataTools.createLSID("Instrument", 0);
        store.setInstrumentID(instrumentID, 0);
        store.setImageInstrumentRef(instrumentID, 0);
        // populate LogicalChannel element
        for (int i = 0; i < getEffectiveSizeC(); i++) {
            if (i < emWaves.size()) {
                Length em = FormatTools.getEmissionWavelength(emWaves.get(i));
                if (em != null) {
                    store.setChannelEmissionWavelength(em, 0, i);
                }
            }
            if (i < exWaves.size()) {
                Length ex = FormatTools.getExcitationWavelength(exWaves.get(i));
                if (ex != null) {
                    store.setChannelExcitationWavelength(ex, 0, i);
                }
            }
        }
        // populate PlaneTiming and StagePosition
        long start = 0, end = 0;
        if (startTime != null) {
            start = DateTools.getTime(startTime, DATE_FORMAT);
        }
        if (finishTime != null) {
            end = DateTools.getTime(finishTime, DateTools.ISO8601_FORMAT);
        }
        double secondsPerPlane = (double) (end - start) / getImageCount() / 1000;
        for (int i = 0; i < getImageCount(); i++) {
            int[] zct = getZCTCoords(i);
            store.setPlaneDeltaT(new Time(i * secondsPerPlane, UNITS.SECOND), 0, i);
            if (zct[1] < exposureTimes.size() && exposureTimes.get(zct[1]) != null) {
                store.setPlaneExposureTime(new Time(exposureTimes.get(zct[1]), UNITS.SECOND), 0, i);
            }
            if (zct[0] < zPositions.size()) {
                final Double zPosition = zPositions.get(zct[0]);
                final Length xl = new Length(0d, UNITS.REFERENCEFRAME);
                final Length yl = new Length(0d, UNITS.REFERENCEFRAME);
                final Length zl;
                if (zPosition == null) {
                    zl = null;
                } else {
                    zl = new Length(zPosition, UNITS.REFERENCEFRAME);
                }
                store.setPlanePositionX(xl, 0, i);
                store.setPlanePositionY(yl, 0, i);
                store.setPlanePositionZ(zl, 0, i);
            }
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Time(ome.units.quantity.Time) CoreMetadata(loci.formats.CoreMetadata) Timestamp(ome.xml.model.primitives.Timestamp) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) RandomAccessInputStream(loci.common.RandomAccessInputStream) Location(loci.common.Location)

Example 12 with Time

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

the class IvisionReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    in = new RandomAccessInputStream(id);
    LOGGER.info("Populating metadata");
    String version = in.readString(4);
    addGlobalMeta("Version", version);
    int fileFormat = in.read();
    int dataType = in.read();
    CoreMetadata m = core.get(0);
    m.sizeC = 1;
    switch(dataType) {
        case 0:
            m.pixelType = FormatTools.UINT8;
            break;
        case 1:
            m.pixelType = FormatTools.INT16;
            break;
        case 2:
            m.pixelType = FormatTools.INT32;
            break;
        case 3:
            m.pixelType = FormatTools.FLOAT;
            break;
        case 4:
            m.pixelType = FormatTools.UINT8;
            m.sizeC = 3;
            color16 = true;
            break;
        case 5:
            m.pixelType = FormatTools.UINT8;
            m.sizeC = 3;
            hasPaddingByte = true;
            break;
        case 6:
            m.pixelType = FormatTools.UINT16;
            break;
        case 7:
            m.pixelType = FormatTools.FLOAT;
            squareRoot = true;
            break;
        case 8:
            m.pixelType = FormatTools.UINT16;
            m.sizeC = 3;
            break;
    }
    m.sizeX = in.readInt();
    m.sizeY = in.readInt();
    in.skipBytes(6);
    m.sizeZ = in.readShort();
    in.skipBytes(50);
    m.sizeT = 1;
    if (getSizeX() > 1 && getSizeY() > 1) {
        lut = new byte[2048];
        in.read(lut);
    }
    imageOffset = in.getFilePointer();
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        in.skipBytes(getSizeZ() * getSizeC() * getSizeT() * getSizeX() * getSizeY() * FormatTools.getBytesPerPixel(getPixelType()));
        // look for block of XML data
        LOGGER.info("Looking for XML metadata");
        in.findString(false, "<?xml");
        if (in.getFilePointer() < in.length()) {
            in.seek(in.getFilePointer() - 5);
            String xml = in.readString((int) (in.length() - in.getFilePointer()));
            xml = xml.substring(xml.indexOf('<'), xml.lastIndexOf("plist>") + 6);
            IvisionHandler handler = new IvisionHandler();
            try {
                XMLTools.parseXML(xml, handler);
            } catch (IOException e) {
                LOGGER.debug("", e);
            }
        } else
            LOGGER.debug("XML metadata not found");
    }
    LOGGER.info("Populating core metadata");
    m.rgb = getSizeC() > 1;
    m.dimensionOrder = "XYCZT";
    m.littleEndian = false;
    m.interleaved = true;
    m.indexed = false;
    m.imageCount = getSizeZ() * getSizeT();
    LOGGER.info("Populating MetadataStore");
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);
    if (creationDate != null) {
        String date = DateTools.formatDate(creationDate, DATE_FORMAT);
        if (date != null) {
            store.setImageAcquisitionDate(new Timestamp(date), 0);
        }
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        String instrumentID = MetadataTools.createLSID("Instrument", 0);
        store.setInstrumentID(instrumentID, 0);
        store.setImageInstrumentRef(instrumentID, 0);
        if (deltaT != null) {
            Double increment = 0d;
            try {
                increment = new Double(deltaT);
            } catch (NumberFormatException e) {
                LOGGER.debug("Failed to parse time increment", e);
            }
            if (increment != null) {
                store.setPixelsTimeIncrement(new Time(increment, UNITS.SECOND), 0);
            }
        }
        String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
        store.setObjectiveID(objectiveID, 0, 0);
        store.setObjectiveSettingsID(objectiveID, 0);
        store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
        store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
        if (lensNA != null)
            store.setObjectiveLensNA(lensNA, 0, 0);
        if (magnification != null) {
            store.setObjectiveNominalMagnification(magnification, 0, 0);
        }
        if (refractiveIndex != null) {
            store.setObjectiveSettingsRefractiveIndex(refractiveIndex, 0);
        }
        String detectorID = MetadataTools.createLSID("Detector", 0, 0);
        store.setDetectorID(detectorID, 0, 0);
        store.setDetectorSettingsID(detectorID, 0, 0);
        store.setDetectorType(getDetectorType("Other"), 0, 0);
        store.setDetectorSettingsBinning(getBinning(binX + "x" + binY), 0, 0);
        if (gain != null) {
            try {
                store.setDetectorSettingsGain(new Double(gain), 0, 0);
            } catch (NumberFormatException e) {
                LOGGER.debug("Failed to parse detector gain", e);
            }
        }
    }
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) Time(ome.units.quantity.Time) RandomAccessInputStream(loci.common.RandomAccessInputStream) IOException(java.io.IOException) CoreMetadata(loci.formats.CoreMetadata) Timestamp(ome.xml.model.primitives.Timestamp)

Example 13 with Time

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

the class SIFReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    in = new RandomAccessInputStream(id);
    CoreMetadata m = core.get(0);
    double[] timestamp = null;
    int lineNumber = 1;
    String line = in.readLine();
    int endLine = -1;
    while (endLine < 0 || lineNumber < endLine) {
        lineNumber++;
        if (line.startsWith("Pixel number")) {
            String[] tokens = line.split(" ");
            if (tokens.length > 2) {
                m.sizeC = Integer.parseInt(tokens[2]);
                m.sizeX = Integer.parseInt(tokens[3]);
                m.sizeY = Integer.parseInt(tokens[4]);
                m.sizeZ = Integer.parseInt(tokens[5]);
                m.sizeT = Integer.parseInt(tokens[6]);
                m.imageCount = getSizeZ() * getSizeT() * getSizeC();
                timestamp = new double[getImageCount()];
                endLine = lineNumber;
            }
        } else if (lineNumber < endLine) {
            int index = lineNumber - (endLine - getImageCount()) - 1;
            if (index >= 0) {
                try {
                    timestamp[index] = Double.parseDouble(line.trim());
                } catch (NumberFormatException e) {
                    LOGGER.debug("Could not parse timestamp #" + index, e);
                }
            }
        } else {
            addGlobalMetaList("Line", line.trim());
        }
        line = in.readLine();
        if (endLine > 0 && endLine == lineNumber) {
            String[] tokens = line.split(" ");
            int x1 = Integer.parseInt(tokens[1]);
            int y1 = Integer.parseInt(tokens[2]);
            int x2 = Integer.parseInt(tokens[3]);
            int y2 = Integer.parseInt(tokens[4]);
            int x3 = Integer.parseInt(tokens[5]);
            int y3 = Integer.parseInt(tokens[6]);
            m.sizeX = (int) (Math.abs(x1 - x2) + x3);
            m.sizeY = (int) (Math.abs(y1 - y2) + y3);
            pixelOffset = in.length() - FOOTER_SIZE - (getImageCount() * getSizeX() * getSizeY() * 4);
        }
    }
    m.pixelType = FormatTools.FLOAT;
    m.dimensionOrder = "XYCZT";
    m.littleEndian = true;
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM);
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        for (int i = 0; i < getImageCount(); i++) {
            store.setPlaneDeltaT(new Time(timestamp[i], UNITS.SECOND), 0, i);
        }
    }
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) Time(ome.units.quantity.Time) RandomAccessInputStream(loci.common.RandomAccessInputStream) CoreMetadata(loci.formats.CoreMetadata)

Example 14 with Time

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

the class VolocityReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    if (!checkSuffix(id, "mvd2")) {
        Location file = new Location(id).getAbsoluteFile();
        Location parent = file.getParentFile().getParentFile();
        String[] files = parent.list(true);
        for (String f : files) {
            if (checkSuffix(f, "mvd2")) {
                id = new Location(parent, f).getAbsolutePath();
                break;
            }
        }
    }
    super.initFile(id);
    stacks = new ArrayList<Stack>();
    extraFiles = new ArrayList<String>();
    Location file = new Location(id).getAbsoluteFile();
    extraFiles.add(file.getAbsolutePath());
    Location parentDir = file.getParentFile();
    dir = new Location(parentDir, DATA_DIR);
    if (dir.exists()) {
        String[] files = dir.list(true);
        for (String f : files) {
            if (!checkSuffix(f, "aisf") && !checkSuffix(f, "atsf")) {
                extraFiles.add(new Location(dir, f).getAbsolutePath());
            }
        }
    }
    try {
        ServiceFactory factory = new ServiceFactory();
        MetakitService reader = factory.getInstance(MetakitService.class);
        reader.initialize(id);
        sampleTable = reader.getTableData(1);
        stringTable = reader.getTableData(2);
        reader.close();
    } catch (DependencyException e) {
        throw new MissingLibraryException("Could not find Metakit library", e);
    }
    ArrayList<String> stackNames = new ArrayList<String>();
    ArrayList<Integer> parentIDs = new ArrayList<Integer>();
    for (int i = 0; i < sampleTable.length; i++) {
        Integer stringID = (Integer) sampleTable[i][11];
        String name = getString(stringID);
        int channelIndex = getChildIndex((Integer) sampleTable[i][0], "Channels");
        if (i > 0 && (Integer) sampleTable[i][2] == 1 && (channelIndex >= 0 || (sampleTable[i][14] != null && !sampleTable[i][14].equals(0)) || ((byte[]) sampleTable[i][13]).length > 21)) {
            if (channelIndex < 0) {
                RandomAccessInputStream s = getStream(i);
                s.seek(0);
                if (s.read() != 'I') {
                    s.order(false);
                }
                s.seek(22);
                int x = s.readInt();
                int y = s.readInt();
                int z = s.readInt();
                if (x * y * z > 0 && x * y * z < (s.length() * 3)) {
                    stackNames.add(name);
                    parentIDs.add((Integer) sampleTable[i][0]);
                }
                s.close();
            } else {
                stackNames.add(name);
                parentIDs.add((Integer) sampleTable[i][0]);
            }
        }
    }
    for (int i = 0; i < parentIDs.size(); i++) {
        Stack stack = new Stack();
        stack.core = new CoreMetadata();
        Integer parent = parentIDs.get(i);
        int channelIndex = getChildIndex(parent, "Channels");
        if (channelIndex >= 0) {
            Integer[] channels = getAllChildren((Integer) sampleTable[channelIndex][0]);
            stack.core.sizeC = channels.length;
            stack.pixelsFiles = new String[stack.core.sizeC];
            stack.channelNames = new String[channels.length];
            for (int c = 0; c < channels.length; c++) {
                stack.channelNames[c] = getString((Integer) sampleTable[channels[c]][11]);
                RandomAccessInputStream data = getStream(channels[c]);
                if (data.length() > 22) {
                    data.seek(22);
                    int stackID = data.readInt();
                    Location f = new Location(dir, stackID + ".aisf");
                    if (!f.exists()) {
                        f = new Location(dir, DataTools.swap(stackID) + ".aisf");
                    }
                    stack.pixelsFiles[c] = f.getAbsolutePath();
                } else {
                    Integer child = getAllChildren((Integer) sampleTable[channels[c]][0])[0];
                    stack.pixelsFiles[c] = getFile((Integer) sampleTable[child][0], dir);
                }
                data.close();
            }
        } else {
            stack.pixelsFiles = new String[1];
            stack.pixelsFiles[0] = getFile(parent, dir);
            if (stack.pixelsFiles[0] == null || !new Location(stack.pixelsFiles[0]).exists()) {
                int row = -1;
                for (int r = 0; r < sampleTable.length; r++) {
                    if (sampleTable[r][0].equals(parent)) {
                        row = r;
                        break;
                    }
                }
                stack.pixelsFiles[0] = EMBEDDED_STREAM;
                IRandomAccess data = new ByteArrayHandle((byte[]) sampleTable[row][13]);
                Location.mapFile(stack.pixelsFiles[0], data);
            }
        }
        RandomAccessInputStream data = null;
        int timestampIndex = getChildIndex(parent, "Timepoint times stream");
        if (timestampIndex >= 0) {
            data = getStream(timestampIndex);
            data.seek(22);
            int timestampID = data.readInt();
            Location f = new Location(dir, timestampID + ".atsf");
            if (!f.exists()) {
                f = new Location(dir, DataTools.swap(timestampID) + ".atsf");
            }
            stack.timestampFile = f.getAbsolutePath();
            data.close();
        }
        int xIndex = getChildIndex(parent, "um/pixel (X)");
        if (xIndex >= 0) {
            data = getStream(xIndex);
            data.seek(SIGNATURE_SIZE);
            stack.physicalX = data.readDouble();
            data.close();
        }
        int yIndex = getChildIndex(parent, "um/pixel (Y)");
        if (yIndex >= 0) {
            data = getStream(yIndex);
            data.seek(SIGNATURE_SIZE);
            stack.physicalY = data.readDouble();
            data.close();
        }
        int zIndex = getChildIndex(parent, "um/pixel (Z)");
        if (zIndex >= 0) {
            data = getStream(zIndex);
            data.seek(SIGNATURE_SIZE);
            stack.physicalZ = data.readDouble();
            data.close();
        }
        timestampIndex = getChildIndex(parent, "TimepointTimes");
        if (timestampIndex >= 0) {
            data = getStream(timestampIndex);
            data.seek(SIGNATURE_SIZE);
            data.close();
        }
        int objectiveIndex = getChildIndex(parent, "Microscope Objective");
        if (objectiveIndex >= 0) {
            data = getStream(objectiveIndex);
            data.seek(SIGNATURE_SIZE);
            stack.magnification = data.readDouble();
            data.close();
        }
        int detectorIndex = getChildIndex(parent, "Camera/Detector");
        if (detectorIndex >= 0) {
            data = getStream(detectorIndex);
            data.seek(SIGNATURE_SIZE);
            int len = data.readInt();
            stack.detector = data.readString(len);
            data.close();
        }
        int descriptionIndex = getChildIndex(parent, "Experiment Description");
        if (descriptionIndex >= 0) {
            data = getStream(descriptionIndex);
            data.seek(SIGNATURE_SIZE);
            int len = data.readInt();
            stack.description = data.readString(len);
            data.close();
        }
        int xLocationIndex = getChildIndex(parent, "X Location");
        if (xLocationIndex >= 0) {
            data = getStream(xLocationIndex);
            data.seek(SIGNATURE_SIZE);
            stack.xLocation = data.readDouble();
            data.close();
        }
        int yLocationIndex = getChildIndex(parent, "Y Location");
        if (yLocationIndex >= 0) {
            data = getStream(yLocationIndex);
            data.seek(SIGNATURE_SIZE);
            stack.yLocation = data.readDouble();
            data.close();
        }
        int zLocationIndex = getChildIndex(parent, "Z Location");
        if (zLocationIndex >= 0) {
            data = getStream(zLocationIndex);
            data.seek(SIGNATURE_SIZE);
            stack.zLocation = data.readDouble();
            data.close();
        }
        stacks.add(stack);
    }
    for (int i = 0; i < stacks.size(); i++) {
        Stack stack = stacks.get(i);
        if (!new Location(stack.pixelsFiles[0]).exists()) {
            stacks.remove(i);
            i--;
            continue;
        }
        RandomAccessInputStream base = new RandomAccessInputStream(stack.pixelsFiles[0]);
        long baseLength = base.length();
        base.close();
        for (int q = 1; q < stack.pixelsFiles.length; q++) {
            if (!new Location(stack.pixelsFiles[q]).exists()) {
                continue;
            }
            base = new RandomAccessInputStream(stack.pixelsFiles[q]);
            long length = base.length();
            base.close();
            if (length > baseLength) {
                // split the stack
                Stack newStack = new Stack();
                newStack.timestampFile = stack.timestampFile;
                newStack.core = new CoreMetadata();
                newStack.physicalX = stack.physicalX;
                newStack.physicalY = stack.physicalY;
                newStack.physicalZ = stack.physicalZ;
                newStack.magnification = stack.magnification;
                newStack.detector = stack.detector;
                newStack.description = stack.description;
                newStack.xLocation = stack.xLocation;
                newStack.yLocation = stack.yLocation;
                newStack.zLocation = stack.zLocation;
                String[] pixels = stack.pixelsFiles;
                newStack.pixelsFiles = new String[pixels.length - q];
                System.arraycopy(pixels, q, newStack.pixelsFiles, 0, newStack.pixelsFiles.length);
                stack.pixelsFiles = new String[q];
                System.arraycopy(pixels, 0, stack.pixelsFiles, 0, q);
                String[] channels = stack.channelNames;
                newStack.channelNames = new String[channels.length - q];
                System.arraycopy(channels, q, newStack.channelNames, 0, newStack.channelNames.length);
                stack.channelNames = new String[q];
                System.arraycopy(channels, 0, stack.channelNames, 0, q);
                newStack.core.sizeC = newStack.channelNames.length;
                stack.core.sizeC = stack.channelNames.length;
                stacks.add(i + 1, newStack);
                stackNames.add(i + 1, stackNames.get(i));
            }
        }
    }
    int seriesCount = stacks.size();
    core.clear();
    for (int i = 0; i < seriesCount; i++) {
        Stack stack = stacks.get(i);
        CoreMetadata ms = stack.core;
        core.add(ms);
        setSeries(i);
        ms.littleEndian = true;
        if (stack.timestampFile != null) {
            RandomAccessInputStream s = new RandomAccessInputStream(stack.timestampFile);
            s.seek(0);
            if (s.read() != 'I') {
                ms.littleEndian = false;
            }
            s.seek(17);
            s.order(isLittleEndian());
            ms.sizeT = s.readInt();
            Double firstStamp = null;
            Double[] stamps = new Double[ms.sizeT];
            for (int t = 0; t < ms.sizeT; t++) {
                // timestamps are stored in microseconds
                double timestamp = s.readLong() / 1000000.0;
                if (firstStamp == null) {
                    firstStamp = timestamp;
                }
                stamps[t] = timestamp - firstStamp;
            }
            timestamps.add(stamps);
            s.close();
        } else {
            ms.sizeT = 1;
        }
        ms.rgb = false;
        ms.interleaved = true;
        ms.dimensionOrder = "XYCZT";
        RandomAccessInputStream s = new RandomAccessInputStream(stack.pixelsFiles[0]);
        s.order(isLittleEndian());
        if (checkSuffix(stack.pixelsFiles[0], "aisf")) {
            s.seek(18);
            stack.blockSize = s.readShort() * 256;
            s.skipBytes(5);
            int x = s.readInt();
            int y = s.readInt();
            int zStart = s.readInt();
            int w = s.readInt();
            int h = s.readInt();
            if (w - x < 0 || h - y < 0 || (w - x) * (h - y) < 0) {
                ms.littleEndian = !isLittleEndian();
                s.order(isLittleEndian());
                s.seek(s.getFilePointer() - 20);
                x = s.readInt();
                y = s.readInt();
                zStart = s.readInt();
                w = s.readInt();
                h = s.readInt();
            }
            ms.sizeX = w - x;
            ms.sizeY = h - y;
            ms.sizeZ = s.readInt() - zStart;
            ms.imageCount = getSizeZ() * getSizeC() * getSizeT();
            ms.pixelType = FormatTools.INT8;
            int planesPerFile = getSizeZ() * getSizeT();
            int planeSize = FormatTools.getPlaneSize(this);
            int bytesPerPlane = (int) ((s.length() - stack.blockSize) / planesPerFile);
            int bytesPerPixel = 0;
            while (bytesPerPlane >= planeSize) {
                bytesPerPixel++;
                bytesPerPlane -= planeSize;
            }
            if ((bytesPerPixel % 3) == 0) {
                ms.sizeC *= 3;
                ms.rgb = true;
                bytesPerPixel /= 3;
            }
            ms.pixelType = FormatTools.pixelTypeFromBytes(bytesPerPixel, false, bytesPerPixel > 2);
            // full timepoints are padded to have a multiple of 256 bytes
            int timepoint = FormatTools.getPlaneSize(this) * getSizeZ();
            stack.planePadding = stack.blockSize - (timepoint % stack.blockSize);
            if (stack.planePadding == stack.blockSize) {
                stack.planePadding = 0;
            }
        } else {
            boolean embedded = Location.getMappedFile(EMBEDDED_STREAM) != null;
            s.seek(0);
            if (s.read() != 'I') {
                ms.littleEndian = false;
                s.order(false);
            }
            s.seek(22);
            ms.sizeX = s.readInt();
            ms.sizeY = s.readInt();
            ms.sizeZ = s.readInt();
            ms.sizeC = embedded ? 1 : 4;
            ms.imageCount = getSizeZ() * getSizeT();
            ms.rgb = ms.sizeC > 1;
            ms.pixelType = FormatTools.UINT8;
            stack.blockSize = embedded ? (int) s.getFilePointer() : 99;
            stack.planePadding = 0;
            if (s.length() > ms.sizeX * ms.sizeY * ms.sizeZ * 6) {
                ms.pixelType = FormatTools.UINT16;
                ms.sizeC = 3;
                ms.rgb = true;
            }
            if (s.length() < (ms.sizeX * ms.sizeY * ms.sizeZ * ms.sizeC)) {
                ms.rgb = false;
                ms.sizeC = 1;
                long pixels = ms.sizeX * ms.sizeY * ms.sizeZ;
                double approximateBytes = (double) s.length() / pixels;
                int bytes = (int) Math.ceil(approximateBytes);
                if (bytes == 0) {
                    bytes = 1;
                } else if (bytes == 3) {
                    bytes = 2;
                }
                ms.pixelType = FormatTools.pixelTypeFromBytes(bytes, false, false);
                s.seek(70);
                stack.blockSize = s.readInt();
                stack.clippingData = true;
            }
        }
        s.close();
    }
    setSeries(0);
    for (int i = 0; i < getSeriesCount(); i++) {
        setSeries(i);
        Stack stack = stacks.get(i);
        addSeriesMeta("Name", stackNames.get(i));
        addSeriesMeta("Pixel width (in microns)", stack.physicalX);
        addSeriesMeta("Pixel height (in microns)", stack.physicalY);
        addSeriesMeta("Z step (in microns)", stack.physicalZ);
        addSeriesMeta("Objective magnification", stack.magnification);
        addSeriesMeta("Camera/Detector", stack.detector);
        addSeriesMeta("Description", stack.description);
        addSeriesMeta("X Location", stack.xLocation);
        addSeriesMeta("Y Location", stack.yLocation);
        addSeriesMeta("Z Location", stack.zLocation);
        if (stack.channelNames != null) {
            for (int c = 0; c < stack.channelNames.length; c++) {
                addSeriesMetaList("Channel", stack.channelNames[c]);
            }
        }
    }
    setSeries(0);
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);
    String instrument = MetadataTools.createLSID("Instrument", 0);
    store.setInstrumentID(instrument, 0);
    for (int i = 0; i < getSeriesCount(); i++) {
        store.setImageInstrumentRef(instrument, i);
        setSeries(i);
        Stack stack = stacks.get(i);
        store.setImageName(stackNames.get(i), i);
        store.setImageDescription(stack.description, i);
        if (stack.channelNames != null) {
            for (int c = 0; c < getEffectiveSizeC(); c++) {
                store.setChannelName(stack.channelNames[c], i, c);
            }
        }
        Length sizeX = FormatTools.getPhysicalSizeX(stack.physicalX);
        Length sizeY = FormatTools.getPhysicalSizeY(stack.physicalY);
        Length sizeZ = FormatTools.getPhysicalSizeZ(stack.physicalZ);
        if (sizeX != null) {
            store.setPixelsPhysicalSizeX(sizeX, i);
        }
        if (sizeY != null) {
            store.setPixelsPhysicalSizeY(sizeY, i);
        }
        if (sizeZ != null) {
            store.setPixelsPhysicalSizeZ(sizeZ, i);
        }
        String objective = MetadataTools.createLSID("Objective", 0, i);
        store.setObjectiveID(objective, 0, i);
        store.setObjectiveNominalMagnification(stack.magnification, 0, i);
        store.setObjectiveCorrection(getCorrection("Other"), 0, i);
        store.setObjectiveImmersion(getImmersion("Other"), 0, i);
        store.setObjectiveSettingsID(objective, i);
        String detectorID = MetadataTools.createLSID("Detector", 0, i);
        store.setDetectorID(detectorID, 0, i);
        store.setDetectorModel(stack.detector, 0, i);
        for (int c = 0; c < getEffectiveSizeC(); c++) {
            store.setDetectorSettingsID(detectorID, i, c);
        }
        for (int img = 0; img < getImageCount(); img++) {
            int[] coords = getZCTCoords(img);
            int z = coords[0];
            final Length xLoc = new Length(stack.xLocation, UNITS.REFERENCEFRAME);
            final Length yLoc = new Length(stack.yLocation, UNITS.REFERENCEFRAME);
            store.setPlanePositionX(xLoc, i, img);
            store.setPlanePositionY(yLoc, i, img);
            if (stack.physicalZ != null) {
                final double zLocNumber = stack.zLocation + z * stack.physicalZ;
                final Length zLoc = new Length(zLocNumber, UNITS.REFERENCEFRAME);
                store.setPlanePositionZ(zLoc, i, img);
            }
            if (i < timestamps.size() && coords[2] < timestamps.get(i).length && timestamps.get(i)[coords[2]] != null) {
                store.setPlaneDeltaT(new Time(timestamps.get(i)[coords[2]], UNITS.SECOND), i, img);
            }
        }
    }
    setSeries(0);
}
Also used : ServiceFactory(loci.common.services.ServiceFactory) ArrayList(java.util.ArrayList) Time(ome.units.quantity.Time) IRandomAccess(loci.common.IRandomAccess) DependencyException(loci.common.services.DependencyException) CoreMetadata(loci.formats.CoreMetadata) MetadataStore(loci.formats.meta.MetadataStore) MetakitService(loci.formats.services.MetakitService) Length(ome.units.quantity.Length) MissingLibraryException(loci.formats.MissingLibraryException) RandomAccessInputStream(loci.common.RandomAccessInputStream) ByteArrayHandle(loci.common.ByteArrayHandle) Location(loci.common.Location)

Example 15 with Time

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

the class ZeissCZIReader method translateInformation.

private void translateInformation(Element root) throws FormatException {
    NodeList informations = root.getElementsByTagName("Information");
    if (informations == null || informations.getLength() == 0) {
        return;
    }
    Element information = (Element) informations.item(0);
    Element image = getFirstNode(information, "Image");
    Element user = getFirstNode(information, "User");
    Element environment = getFirstNode(information, "Environment");
    Element instrument = getFirstNode(information, "Instrument");
    Element document = getFirstNode(information, "Document");
    if (image != null) {
        String bitCount = getFirstNodeValue(image, "ComponentBitCount");
        if (bitCount != null) {
            core.get(0).bitsPerPixel = Integer.parseInt(bitCount);
        }
        acquiredDate = getFirstNodeValue(image, "AcquisitionDateAndTime");
        Element objectiveSettings = getFirstNode(image, "ObjectiveSettings");
        correctionCollar = getFirstNodeValue(objectiveSettings, "CorrectionCollar");
        medium = getFirstNodeValue(objectiveSettings, "Medium");
        refractiveIndex = getFirstNodeValue(objectiveSettings, "RefractiveIndex");
        String sizeV = getFirstNodeValue(image, "SizeV");
        if (sizeV != null && angles == 1) {
            angles = Integer.parseInt(sizeV);
        }
        Element dimensions = getFirstNode(image, "Dimensions");
        Element tNode = getFirstNode(dimensions, "T");
        if (tNode != null) {
            Element positions = getFirstNode(tNode, "Positions");
            if (positions != null) {
                Element interval = getFirstNode(positions, "Interval");
                if (interval != null) {
                    Element incrementNode = getFirstNode(interval, "Increment");
                    if (incrementNode != null) {
                        String increment = incrementNode.getTextContent();
                        timeIncrement = new Time(DataTools.parseDouble(increment), UNITS.SECOND);
                    }
                }
            }
        }
        Element sNode = getFirstNode(dimensions, "S");
        if (sNode != null) {
            NodeList scenes = sNode.getElementsByTagName("Scene");
            int nextPosition = 0;
            for (int i = 0; i < scenes.getLength(); i++) {
                Element scene = (Element) scenes.item(i);
                NodeList positions = scene.getElementsByTagName("Position");
                for (int p = 0; p < positions.getLength(); p++) {
                    Element position = (Element) positions.item(p);
                    String x = position.getAttribute("X");
                    String y = position.getAttribute("Y");
                    String z = position.getAttribute("Z");
                    if (nextPosition < positionsX.length && positionsX[nextPosition] == null) {
                        positionsX[nextPosition] = new Length(DataTools.parseDouble(x), UNITS.MICROM);
                        positionsY[nextPosition] = new Length(DataTools.parseDouble(y), UNITS.MICROM);
                        positionsZ[nextPosition] = new Length(DataTools.parseDouble(z), UNITS.MICROM);
                        nextPosition++;
                    }
                }
            }
        }
        NodeList channelNodes = getGrandchildren(dimensions, "Channel");
        if (channelNodes == null) {
            channelNodes = image.getElementsByTagName("Channel");
        }
        if (channelNodes != null) {
            for (int i = 0; i < channelNodes.getLength(); i++) {
                Element channel = (Element) channelNodes.item(i);
                while (channels.size() <= i) {
                    channels.add(new Channel());
                }
                channels.get(i).emission = getFirstNodeValue(channel, "EmissionWavelength");
                channels.get(i).excitation = getFirstNodeValue(channel, "ExcitationWavelength");
                channels.get(i).pinhole = getFirstNodeValue(channel, "PinholeSize");
                channels.get(i).name = channel.getAttribute("Name");
                String illumination = getFirstNodeValue(channel, "IlluminationType");
                if (illumination != null) {
                    channels.get(i).illumination = getIlluminationType(illumination);
                }
                String acquisition = getFirstNodeValue(channel, "AcquisitionMode");
                if (acquisition != null) {
                    channels.get(i).acquisitionMode = getAcquisitionMode(acquisition);
                }
                Element detectorSettings = getFirstNode(channel, "DetectorSettings");
                String binning = getFirstNodeValue(detectorSettings, "Binning");
                if (binning != null) {
                    binning = binning.replaceAll(",", "x");
                    binnings.add(binning);
                }
                Element scanInfo = getFirstNode(channel, "LaserScanInfo");
                if (scanInfo != null) {
                    zoom = getFirstNodeValue(scanInfo, "ZoomX");
                }
                Element detector = getFirstNode(detectorSettings, "Detector");
                if (detector != null) {
                    String detectorID = detector.getAttribute("Id");
                    if (detectorID.indexOf(' ') != -1) {
                        detectorID = detectorID.substring(detectorID.lastIndexOf(" ") + 1);
                    }
                    if (!detectorID.startsWith("Detector:")) {
                        detectorID = "Detector:" + detectorID;
                    }
                    detectorRefs.add(detectorID);
                }
                Element filterSet = getFirstNode(channel, "FilterSetRef");
                if (filterSet != null) {
                    channels.get(i).filterSetRef = filterSet.getAttribute("Id");
                }
            }
        }
    }
    if (user != null) {
        userDisplayName = getFirstNodeValue(user, "DisplayName");
        userFirstName = getFirstNodeValue(user, "FirstName");
        userLastName = getFirstNodeValue(user, "LastName");
        userMiddleName = getFirstNodeValue(user, "MiddleName");
        userEmail = getFirstNodeValue(user, "Email");
        userInstitution = getFirstNodeValue(user, "Institution");
        userName = getFirstNodeValue(user, "UserName");
    }
    if (environment != null) {
        temperature = getFirstNodeValue(environment, "Temperature");
        airPressure = getFirstNodeValue(environment, "AirPressure");
        humidity = getFirstNodeValue(environment, "Humidity");
        co2Percent = getFirstNodeValue(environment, "CO2Percent");
    }
    if (instrument != null) {
        NodeList microscopes = getGrandchildren(instrument, "Microscope");
        Element manufacturerNode = null;
        store.setInstrumentID(MetadataTools.createLSID("Instrument", 0), 0);
        if (microscopes != null) {
            Element microscope = (Element) microscopes.item(0);
            manufacturerNode = getFirstNode(microscope, "Manufacturer");
            store.setMicroscopeManufacturer(getFirstNodeValue(manufacturerNode, "Manufacturer"), 0);
            store.setMicroscopeModel(getFirstNodeValue(manufacturerNode, "Model"), 0);
            store.setMicroscopeSerialNumber(getFirstNodeValue(manufacturerNode, "SerialNumber"), 0);
            store.setMicroscopeLotNumber(getFirstNodeValue(manufacturerNode, "LotNumber"), 0);
            String microscopeType = getFirstNodeValue(microscope, "Type");
            if (microscopeType != null) {
                store.setMicroscopeType(getMicroscopeType(microscopeType), 0);
            }
        }
        NodeList lightSources = getGrandchildren(instrument, "LightSource");
        if (lightSources != null) {
            for (int i = 0; i < lightSources.getLength(); i++) {
                Element lightSource = (Element) lightSources.item(i);
                manufacturerNode = getFirstNode(lightSource, "Manufacturer");
                String manufacturer = getFirstNodeValue(manufacturerNode, "Manufacturer");
                String model = getFirstNodeValue(manufacturerNode, "Model");
                String serialNumber = getFirstNodeValue(manufacturerNode, "SerialNumber");
                String lotNumber = getFirstNodeValue(manufacturerNode, "LotNumber");
                String type = getFirstNodeValue(lightSource, "LightSourceType");
                String power = getFirstNodeValue(lightSource, "Power");
                if ("Laser".equals(type)) {
                    if (power != null) {
                        store.setLaserPower(new Power(new Double(power), UNITS.MILLIWATT), 0, i);
                    }
                    store.setLaserLotNumber(lotNumber, 0, i);
                    store.setLaserManufacturer(manufacturer, 0, i);
                    store.setLaserModel(model, 0, i);
                    store.setLaserSerialNumber(serialNumber, 0, i);
                } else if ("Arc".equals(type)) {
                    if (power != null) {
                        store.setArcPower(new Power(new Double(power), UNITS.MILLIWATT), 0, i);
                    }
                    store.setArcLotNumber(lotNumber, 0, i);
                    store.setArcManufacturer(manufacturer, 0, i);
                    store.setArcModel(model, 0, i);
                    store.setArcSerialNumber(serialNumber, 0, i);
                } else if ("LightEmittingDiode".equals(type)) {
                    if (power != null) {
                        store.setLightEmittingDiodePower(new Power(new Double(power), UNITS.MILLIWATT), 0, i);
                    }
                    store.setLightEmittingDiodeLotNumber(lotNumber, 0, i);
                    store.setLightEmittingDiodeManufacturer(manufacturer, 0, i);
                    store.setLightEmittingDiodeModel(model, 0, i);
                    store.setLightEmittingDiodeSerialNumber(serialNumber, 0, i);
                } else if ("Filament".equals(type)) {
                    if (power != null) {
                        store.setFilamentPower(new Power(new Double(power), UNITS.MILLIWATT), 0, i);
                    }
                    store.setFilamentLotNumber(lotNumber, 0, i);
                    store.setFilamentManufacturer(manufacturer, 0, i);
                    store.setFilamentModel(model, 0, i);
                    store.setFilamentSerialNumber(serialNumber, 0, i);
                }
            }
        }
        NodeList detectors = getGrandchildren(instrument, "Detector");
        if (detectors != null) {
            HashSet<String> uniqueDetectors = new HashSet<String>();
            for (int i = 0; i < detectors.getLength(); i++) {
                Element detector = (Element) detectors.item(i);
                manufacturerNode = getFirstNode(detector, "Manufacturer");
                String manufacturer = getFirstNodeValue(manufacturerNode, "Manufacturer");
                String model = getFirstNodeValue(manufacturerNode, "Model");
                String serialNumber = getFirstNodeValue(manufacturerNode, "SerialNumber");
                String lotNumber = getFirstNodeValue(manufacturerNode, "LotNumber");
                String detectorID = detector.getAttribute("Id");
                if (detectorID.indexOf(' ') != -1) {
                    detectorID = detectorID.substring(detectorID.lastIndexOf(" ") + 1);
                }
                if (!detectorID.startsWith("Detector:")) {
                    detectorID = "Detector:" + detectorID;
                }
                if (uniqueDetectors.contains(detectorID)) {
                    continue;
                }
                uniqueDetectors.add(detectorID);
                int detectorIndex = uniqueDetectors.size() - 1;
                store.setDetectorID(detectorID, 0, detectorIndex);
                store.setDetectorManufacturer(manufacturer, 0, detectorIndex);
                store.setDetectorModel(model, 0, detectorIndex);
                store.setDetectorSerialNumber(serialNumber, 0, detectorIndex);
                store.setDetectorLotNumber(lotNumber, 0, detectorIndex);
                if (gain == null || gain.equals("0")) {
                    gain = getFirstNodeValue(detector, "Gain");
                }
                if (detectorIndex == 0 || detectorIndex >= gains.size()) {
                    store.setDetectorGain(DataTools.parseDouble(gain), 0, detectorIndex);
                } else {
                    store.setDetectorGain(DataTools.parseDouble(gains.get(detectorIndex)), 0, detectorIndex);
                }
                String offset = getFirstNodeValue(detector, "Offset");
                if (offset != null && !offset.equals("")) {
                    store.setDetectorOffset(new Double(offset), 0, detectorIndex);
                }
                if (zoom == null) {
                    zoom = getFirstNodeValue(detector, "Zoom");
                }
                if (zoom != null && !zoom.equals("")) {
                    store.setDetectorZoom(new Double(zoom), 0, detectorIndex);
                }
                String ampGain = getFirstNodeValue(detector, "AmplificationGain");
                if (ampGain != null && !ampGain.equals("")) {
                    store.setDetectorAmplificationGain(new Double(ampGain), 0, detectorIndex);
                }
                String detectorType = getFirstNodeValue(detector, "Type");
                if (detectorType != null && !detectorType.equals("")) {
                    store.setDetectorType(getDetectorType(detectorType), 0, detectorIndex);
                }
            }
        }
        NodeList objectives = getGrandchildren(instrument, "Objective");
        parseObjectives(objectives);
        NodeList filterSets = getGrandchildren(instrument, "FilterSet");
        if (filterSets != null) {
            for (int i = 0; i < filterSets.getLength(); i++) {
                Element filterSet = (Element) filterSets.item(i);
                manufacturerNode = getFirstNode(filterSet, "Manufacturer");
                String manufacturer = getFirstNodeValue(manufacturerNode, "Manufacturer");
                String model = getFirstNodeValue(manufacturerNode, "Model");
                String serialNumber = getFirstNodeValue(manufacturerNode, "SerialNumber");
                String lotNumber = getFirstNodeValue(manufacturerNode, "LotNumber");
                String dichroicRef = getFirstNodeValue(filterSet, "DichroicRef");
                NodeList excitations = getGrandchildren(filterSet, "ExcitationFilters", "ExcitationFilterRef");
                NodeList emissions = getGrandchildren(filterSet, "EmissionFilters", "EmissionFilterRef");
                if (dichroicRef == null || dichroicRef.length() <= 0) {
                    Element ref = getFirstNode(filterSet, "DichroicRef");
                    if (ref != null) {
                        dichroicRef = ref.getAttribute("Id");
                    }
                }
                if (excitations == null) {
                    excitations = filterSet.getElementsByTagName("ExcitationFilterRef");
                }
                if (emissions == null) {
                    emissions = filterSet.getElementsByTagName("EmissionFilterRef");
                }
                if (dichroicRef != null || excitations != null || emissions != null) {
                    store.setFilterSetID(filterSet.getAttribute("Id"), 0, i);
                    store.setFilterSetManufacturer(manufacturer, 0, i);
                    store.setFilterSetModel(model, 0, i);
                    store.setFilterSetSerialNumber(serialNumber, 0, i);
                    store.setFilterSetLotNumber(lotNumber, 0, i);
                }
                if (dichroicRef != null && dichroicRef.length() > 0) {
                    store.setFilterSetDichroicRef(dichroicRef, 0, i);
                }
                if (excitations != null) {
                    for (int ex = 0; ex < excitations.getLength(); ex++) {
                        Element excitation = (Element) excitations.item(ex);
                        String ref = excitation.getTextContent();
                        if (ref == null || ref.length() <= 0) {
                            ref = excitation.getAttribute("Id");
                        }
                        if (ref != null && ref.length() > 0) {
                            store.setFilterSetExcitationFilterRef(ref, 0, i, ex);
                        }
                    }
                }
                if (emissions != null) {
                    for (int em = 0; em < emissions.getLength(); em++) {
                        Element emission = (Element) emissions.item(em);
                        String ref = emission.getTextContent();
                        if (ref == null || ref.length() <= 0) {
                            ref = emission.getAttribute("Id");
                        }
                        if (ref != null && ref.length() > 0) {
                            store.setFilterSetEmissionFilterRef(ref, 0, i, em);
                        }
                    }
                }
            }
        }
        NodeList filters = getGrandchildren(instrument, "Filter");
        if (filters != null) {
            for (int i = 0; i < filters.getLength(); i++) {
                Element filter = (Element) filters.item(i);
                manufacturerNode = getFirstNode(filter, "Manufacturer");
                String manufacturer = getFirstNodeValue(manufacturerNode, "Manufacturer");
                String model = getFirstNodeValue(manufacturerNode, "Model");
                String serialNumber = getFirstNodeValue(manufacturerNode, "SerialNumber");
                String lotNumber = getFirstNodeValue(manufacturerNode, "LotNumber");
                store.setFilterID(filter.getAttribute("Id"), 0, i);
                store.setFilterManufacturer(manufacturer, 0, i);
                store.setFilterModel(model, 0, i);
                store.setFilterSerialNumber(serialNumber, 0, i);
                store.setFilterLotNumber(lotNumber, 0, i);
                String filterType = getFirstNodeValue(filter, "Type");
                if (filterType != null) {
                    store.setFilterType(getFilterType(filterType), 0, i);
                }
                store.setFilterFilterWheel(getFirstNodeValue(filter, "FilterWheel"), 0, i);
                Element transmittance = getFirstNode(filter, "TransmittanceRange");
                String cutIn = getFirstNodeValue(transmittance, "CutIn");
                String cutOut = getFirstNodeValue(transmittance, "CutOut");
                Double inWave = cutIn == null ? 0 : new Double(cutIn);
                Double outWave = cutOut == null ? 0 : new Double(cutOut);
                Length in = FormatTools.getCutIn(inWave);
                Length out = FormatTools.getCutOut(outWave);
                if (in != null) {
                    store.setTransmittanceRangeCutIn(in, 0, i);
                }
                if (out != null) {
                    store.setTransmittanceRangeCutOut(out, 0, i);
                }
                String inTolerance = getFirstNodeValue(transmittance, "CutInTolerance");
                String outTolerance = getFirstNodeValue(transmittance, "CutOutTolerance");
                if (inTolerance != null) {
                    Double cutInTolerance = new Double(inTolerance);
                    store.setTransmittanceRangeCutInTolerance(new Length(cutInTolerance, UNITS.NANOMETER), 0, i);
                }
                if (outTolerance != null) {
                    Double cutOutTolerance = new Double(outTolerance);
                    store.setTransmittanceRangeCutOutTolerance(new Length(cutOutTolerance, UNITS.NANOMETER), 0, i);
                }
                String transmittancePercent = getFirstNodeValue(transmittance, "Transmittance");
                if (transmittancePercent != null) {
                    store.setTransmittanceRangeTransmittance(PercentFraction.valueOf(transmittancePercent), 0, i);
                }
            }
        }
        NodeList dichroics = getGrandchildren(instrument, "Dichroic");
        if (dichroics != null) {
            for (int i = 0; i < dichroics.getLength(); i++) {
                Element dichroic = (Element) dichroics.item(i);
                manufacturerNode = getFirstNode(dichroic, "Manufacturer");
                String manufacturer = getFirstNodeValue(manufacturerNode, "Manufacturer");
                String model = getFirstNodeValue(manufacturerNode, "Model");
                String serialNumber = getFirstNodeValue(manufacturerNode, "SerialNumber");
                String lotNumber = getFirstNodeValue(manufacturerNode, "LotNumber");
                store.setDichroicID(dichroic.getAttribute("Id"), 0, i);
                store.setDichroicManufacturer(manufacturer, 0, i);
                store.setDichroicModel(model, 0, i);
                store.setDichroicSerialNumber(serialNumber, 0, i);
                store.setDichroicLotNumber(lotNumber, 0, i);
            }
        }
    }
    if (document != null) {
        description = getFirstNodeValue(document, "Description");
        if (userName == null) {
            userName = getFirstNodeValue(document, "UserName");
        }
        imageName = getFirstNodeValue(document, "Name");
    }
}
Also used : Length(ome.units.quantity.Length) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) Time(ome.units.quantity.Time) Power(ome.units.quantity.Power) HashSet(java.util.HashSet)

Aggregations

Time (ome.units.quantity.Time)74 Length (ome.units.quantity.Length)46 MetadataStore (loci.formats.meta.MetadataStore)41 Timestamp (ome.xml.model.primitives.Timestamp)33 CoreMetadata (loci.formats.CoreMetadata)30 FormatException (loci.formats.FormatException)24 RandomAccessInputStream (loci.common.RandomAccessInputStream)21 Location (loci.common.Location)20 ArrayList (java.util.ArrayList)17 PositiveInteger (ome.xml.model.primitives.PositiveInteger)13 NonNegativeInteger (ome.xml.model.primitives.NonNegativeInteger)12 IOException (java.io.IOException)10 Temperature (ome.units.quantity.Temperature)9 IFD (loci.formats.tiff.IFD)8 ElectricPotential (ome.units.quantity.ElectricPotential)7 Color (ome.xml.model.primitives.Color)7 IMetadata (loci.formats.meta.IMetadata)6 File (java.io.File)5 DependencyException (loci.common.services.DependencyException)5 ServiceException (loci.common.services.ServiceException)5