Search in sources :

Example 21 with Location

use of loci.common.Location in project bioformats by openmicroscopy.

the class FujiReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    if (checkSuffix(id, "inf")) {
        infFile = new Location(id).getAbsolutePath();
        pixelsFile = infFile.substring(0, infFile.lastIndexOf(".")) + ".img";
    } else {
        pixelsFile = new Location(id).getAbsolutePath();
        infFile = pixelsFile.substring(0, pixelsFile.lastIndexOf(".")) + ".inf";
    }
    String[] lines = DataTools.readFile(infFile).split("\r{0,1}\n");
    int bits = Integer.parseInt(lines[5]);
    CoreMetadata m = core.get(0);
    m.pixelType = FormatTools.pixelTypeFromBytes(bits / 8, false, false);
    m.sizeX = Integer.parseInt(lines[6]);
    m.sizeY = Integer.parseInt(lines[7]);
    m.sizeC = 1;
    m.sizeT = 1;
    m.sizeZ = 1;
    m.imageCount = getSizeZ() * getSizeC() * getSizeT();
    m.dimensionOrder = "XYCZT";
    for (String line : lines) {
        addGlobalMetaList("Line", line);
    }
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
    String imageName = lines[1];
    String timestamp = lines[10];
    timestamp = DateTools.formatDate(timestamp, DATE_FORMAT);
    store.setImageName(imageName, 0);
    if (timestamp != null) {
        store.setImageAcquisitionDate(new Timestamp(timestamp), 0);
    }
    double physicalWidth = Double.parseDouble(lines[3]);
    double physicalHeight = Double.parseDouble(lines[4]);
    Length sizeX = FormatTools.getPhysicalSizeX(physicalWidth);
    Length sizeY = FormatTools.getPhysicalSizeY(physicalHeight);
    if (sizeX != null) {
        store.setPixelsPhysicalSizeX(sizeX, 0);
    }
    if (sizeY != null) {
        store.setPixelsPhysicalSizeY(sizeY, 0);
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        String instrument = lines[13];
        String instrumentID = MetadataTools.createLSID("Instrument", 0);
        store.setInstrumentID(instrumentID, 0);
        store.setMicroscopeModel(instrument, 0);
    }
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) CoreMetadata(loci.formats.CoreMetadata) Timestamp(ome.xml.model.primitives.Timestamp) Location(loci.common.Location)

Example 22 with Location

use of loci.common.Location in project bioformats by openmicroscopy.

the class HamamatsuVMSReader 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);
    IniParser parser = new IniParser();
    IniList layout = parser.parseINI(new BufferedReader(new InputStreamReader(in, Constants.ENCODING)));
    IniTable slideInfo = layout.getTable("Virtual Microscope Specimen");
    int nLayers = Integer.parseInt(slideInfo.get("NoLayers"));
    nRows = Integer.parseInt(slideInfo.get("NoJpegRows"));
    nCols = Integer.parseInt(slideInfo.get("NoJpegColumns"));
    String imageFile = slideInfo.get("ImageFile");
    mapFile = slideInfo.get("MapFile");
    String optimisationFile = slideInfo.get("OptimisationFile");
    macroFile = slideInfo.get("MacroImage");
    Double physicalWidth = new Double(slideInfo.get("PhysicalWidth"));
    Double physicalHeight = new Double(slideInfo.get("PhysicalHeight"));
    Double magnification = new Double(slideInfo.get("SourceLens"));
    Double macroWidth = new Double(slideInfo.get("PhysicalMacroWidth"));
    Double macroHeight = new Double(slideInfo.get("PhysicalMacroHeight"));
    for (String key : slideInfo.keySet()) {
        addGlobalMeta(key, slideInfo.get(key));
    }
    Location dir = new Location(id).getAbsoluteFile().getParentFile();
    if (imageFile != null) {
        imageFile = new Location(dir, imageFile).getAbsolutePath();
        files.add(imageFile);
    }
    tileFiles = new String[nLayers][nRows][nCols];
    tileFiles[0][0][0] = imageFile;
    for (int layer = 0; layer < nLayers; layer++) {
        for (int row = 0; row < nRows; row++) {
            for (int col = 0; col < nCols; col++) {
                String f = slideInfo.get("ImageFile(" + col + "," + row + ")");
                if (f != null) {
                    f = new Location(dir, f).getAbsolutePath();
                    tileFiles[layer][row][col] = f;
                    files.add(f);
                }
            }
        }
    }
    if (mapFile != null) {
        mapFile = new Location(dir, mapFile).getAbsolutePath();
        files.add(mapFile);
    }
    if (optimisationFile != null) {
        optimisationFile = new Location(dir, optimisationFile).getAbsolutePath();
        files.add(optimisationFile);
    }
    if (macroFile != null) {
        macroFile = new Location(dir, macroFile).getAbsolutePath();
        files.add(macroFile);
    }
    int seriesCount = 3;
    core.clear();
    for (int i = 0; i < seriesCount; i++) {
        String file = null;
        switch(i) {
            case 0:
                file = tileFiles[0][nRows - 1][nCols - 1];
                break;
            case 1:
                file = macroFile;
                break;
            case 2:
                file = mapFile;
                break;
        }
        int[] dims;
        try (RandomAccessInputStream s = new RandomAccessInputStream(file);
            JPEGTileDecoder decoder = new JPEGTileDecoder()) {
            dims = decoder.preprocess(s);
        }
        CoreMetadata m = new CoreMetadata();
        if (i == 0) {
            m.sizeX = (MAX_JPEG_SIZE * (nCols - 1)) + dims[0];
            m.sizeY = (MAX_JPEG_SIZE * (nRows - 1)) + dims[1];
        } else {
            m.sizeX = dims[0];
            m.sizeY = dims[1];
        }
        m.sizeZ = 1;
        m.sizeC = 3;
        m.sizeT = 1;
        m.rgb = true;
        m.imageCount = 1;
        m.dimensionOrder = "XYCZT";
        m.pixelType = FormatTools.UINT8;
        m.interleaved = m.sizeX > MAX_SIZE && m.sizeY > MAX_SIZE;
        m.thumbnail = i > 0;
        core.add(m);
    }
    CoreMetadata ms0 = core.get(0);
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
    String path = new Location(currentId).getAbsoluteFile().getName();
    store.setImageName(path + " full resolution", 0);
    store.setImageName(path + " macro", 1);
    store.setImageName(path + " map", 2);
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        Length sizeX = FormatTools.getPhysicalSizeX(physicalWidth / ms0.sizeX);
        Length sizeY = FormatTools.getPhysicalSizeY(physicalHeight / ms0.sizeY);
        Length macroSizeX = FormatTools.getPhysicalSizeX(macroWidth / core.get(1).sizeX);
        Length macroSizeY = FormatTools.getPhysicalSizeY(macroHeight / core.get(1).sizeY);
        if (sizeX != null) {
            store.setPixelsPhysicalSizeX(sizeX, 0);
        }
        if (sizeY != null) {
            store.setPixelsPhysicalSizeY(sizeY, 0);
        }
        if (macroSizeX != null) {
            store.setPixelsPhysicalSizeX(macroSizeX, 1);
        }
        if (macroSizeY != null) {
            store.setPixelsPhysicalSizeY(macroSizeY, 1);
        }
        String instrumentID = MetadataTools.createLSID("Instrument", 0);
        store.setInstrumentID(instrumentID, 0);
        store.setImageInstrumentRef(instrumentID, 0);
        String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
        store.setObjectiveID(objectiveID, 0, 0);
        store.setObjectiveNominalMagnification(magnification, 0, 0);
        store.setObjectiveSettingsID(objectiveID, 0);
    }
}
Also used : IniParser(loci.common.IniParser) InputStreamReader(java.io.InputStreamReader) IniList(loci.common.IniList) CoreMetadata(loci.formats.CoreMetadata) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) IniTable(loci.common.IniTable) JPEGTileDecoder(loci.formats.codec.JPEGTileDecoder) BufferedReader(java.io.BufferedReader) RandomAccessInputStream(loci.common.RandomAccessInputStream) Location(loci.common.Location)

Example 23 with Location

use of loci.common.Location in project bioformats by openmicroscopy.

the class PCORAWReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    if (checkSuffix(id, "rec")) {
        paramFile = new Location(id).getAbsolutePath();
        String base = new Location(id).getAbsoluteFile().getAbsolutePath();
        base = base.substring(0, base.lastIndexOf("."));
        id = base + ".pcoraw";
        if (!new Location(id).exists()) {
            throw new FormatException("Could not find image file.");
        }
    }
    super.initFile(id);
    imageFile = new Location(id).getAbsolutePath();
    reader.close();
    reader.setMetadataStore(getMetadataStore());
    reader.setId(id);
    core = reader.getCoreMetadataList();
    metadata = reader.getGlobalMetadata();
    in = new RandomAccessInputStream(id);
    try {
        if (in.length() >= Math.pow(2, 32)) {
            // even though BigTIFF is likely being used, the offsets
            // are still recorded as though only 32 bits are available
            long add = 0;
            long prevOffset = 0;
            for (IFD ifd : reader.ifds) {
                long[] offsets = ifd.getStripOffsets();
                for (int i = 0; i < offsets.length; i++) {
                    offsets[i] += add;
                    if (offsets[i] < prevOffset) {
                        add += 0x100000000L;
                        offsets[i] += 0x100000000L;
                    }
                    prevOffset = offsets[i];
                }
                ifd.put(IFD.STRIP_OFFSETS, offsets);
            }
        }
    } finally {
        in.close();
    }
    if (paramFile == null) {
        String base = imageFile.substring(0, imageFile.lastIndexOf("."));
        base += ".rec";
        if (new Location(base).exists()) {
            paramFile = base;
        }
    }
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);
    if (paramFile != null) {
        // parse extra metadata from the parameter file
        store.setInstrumentID(MetadataTools.createLSID("Instrument", 0), 0);
        String detector = MetadataTools.createLSID("Detector", 0, 0);
        store.setDetectorID(detector, 0, 0);
        String[] lines = DataTools.readFile(paramFile).split("\n");
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            int sep = line.indexOf(':');
            if (sep < 0) {
                continue;
            }
            String key = line.substring(0, sep).trim();
            String value = line.substring(sep + 1).trim();
            addGlobalMeta(key, value);
            if (key.equals("Exposure / Delay")) {
                // set the exposure time
                String exp = value.substring(0, value.indexOf(' '));
                Double parsedExp = new Double(exp);
                Time exposure = null;
                if (parsedExp != null) {
                    exposure = new Time(parsedExp / 1000, UNITS.SECOND);
                }
                for (int plane = 0; plane < getImageCount(); plane++) {
                    store.setPlaneExposureTime(exposure, 0, plane);
                }
            } else if (key.equals("Camera serial number")) {
                // set the serial number
                store.setDetectorSerialNumber(value, 0, 0);
            } else if (key.equals("Binning horz./vert.")) {
                store.setDetectorSettingsID(detector, 0, 0);
                value = value.charAt(1) + value;
                value = value.substring(0, 3);
                store.setDetectorSettingsBinning(getBinning(value), 0, 0);
            } else if (key.equals("Comment")) {
                final StringBuilder description = new StringBuilder();
                for (int j = i + 1; j < lines.length; j++) {
                    lines[j] = lines[j].trim();
                    if (lines[j].length() > 0) {
                        description.append(lines[j]);
                        description.append(" ");
                    }
                }
                store.setImageDescription(description.toString().trim(), 0);
                break;
            }
        }
    }
}
Also used : IFD(loci.formats.tiff.IFD) Time(ome.units.quantity.Time) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) RandomAccessInputStream(loci.common.RandomAccessInputStream) Location(loci.common.Location)

Example 24 with Location

use of loci.common.Location in project bioformats by openmicroscopy.

the class PDSReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    if (!checkSuffix(id, "hdr")) {
        String headerFile = id.substring(0, id.lastIndexOf(".")) + ".hdr";
        if (!new Location(headerFile).exists()) {
            headerFile = id.substring(0, id.lastIndexOf(".")) + ".HDR";
            if (!new Location(headerFile).exists()) {
                throw new FormatException("Could not find matching .hdr file.");
            }
        }
        initFile(headerFile);
        return;
    }
    super.initFile(id);
    String[] headerData = DataTools.readFile(id).split("\r\n");
    if (headerData.length == 1) {
        headerData = headerData[0].split("\r");
    }
    Length xPos = null, yPos = null;
    Double deltaX = null, deltaY = null;
    String date = null;
    CoreMetadata m = core.get(0);
    for (String line : headerData) {
        int eq = line.indexOf('=');
        if (eq < 0)
            continue;
        int end = line.indexOf('/');
        if (end < 0)
            end = line.length();
        String key = line.substring(0, eq).trim();
        String value = line.substring(eq + 1, end).trim();
        if (key.equals("NXP")) {
            m.sizeX = Integer.parseInt(value);
        } else if (key.equals("NYP")) {
            m.sizeY = Integer.parseInt(value);
        } else if (key.equals("XPOS")) {
            final Double number = Double.valueOf(value);
            xPos = new Length(number, UNITS.REFERENCEFRAME);
            addGlobalMeta("X position for position #1", xPos);
        } else if (key.equals("YPOS")) {
            final Double number = Double.valueOf(value);
            yPos = new Length(number, UNITS.REFERENCEFRAME);
            addGlobalMeta("Y position for position #1", yPos);
        } else if (key.equals("SIGNX")) {
            reverseX = value.replaceAll("'", "").trim().equals("-");
        } else if (key.equals("SIGNY")) {
            reverseY = value.replaceAll("'", "").trim().equals("-");
        } else if (key.equals("DELTAX")) {
            deltaX = new Double(value);
        } else if (key.equals("DELTAY")) {
            deltaY = new Double(value);
        } else if (key.equals("COLOR")) {
            int color = Integer.parseInt(value);
            if (color == 4) {
                m.sizeC = 3;
                m.rgb = true;
            } else {
                m.sizeC = 1;
                m.rgb = false;
                lutIndex = color - 1;
                m.indexed = lutIndex >= 0;
            }
        } else if (key.equals("SCAN TIME")) {
            long modTime = new Location(currentId).getAbsoluteFile().lastModified();
            String year = DateTools.convertDate(modTime, DateTools.UNIX, "yyyy");
            date = value.replaceAll("'", "") + " " + year;
            date = DateTools.formatDate(date, DATE_FORMAT);
        } else if (key.equals("FILE REC LEN")) {
            recordWidth = Integer.parseInt(value) / 2;
        }
        addGlobalMeta(key, value);
    }
    m.sizeZ = 1;
    m.sizeT = 1;
    m.imageCount = 1;
    m.dimensionOrder = "XYCZT";
    m.pixelType = FormatTools.UINT16;
    m.littleEndian = true;
    String base = currentId.substring(0, currentId.lastIndexOf("."));
    pixelsFile = base + ".IMG";
    if (!new Location(pixelsFile).exists()) {
        pixelsFile = base + ".img";
    }
    boolean minimumMetadata = getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM;
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, !minimumMetadata);
    if (date != null) {
        store.setImageAcquisitionDate(new Timestamp(date), 0);
    }
    if (!minimumMetadata) {
        store.setPlanePositionX(xPos, 0, 0);
        store.setPlanePositionY(yPos, 0, 0);
        Length sizeX = FormatTools.getPhysicalSizeX(deltaX);
        Length sizeY = FormatTools.getPhysicalSizeY(deltaY);
        if (sizeX != null) {
            store.setPixelsPhysicalSizeX(sizeX, 0);
        }
        if (sizeY != null) {
            store.setPixelsPhysicalSizeY(sizeY, 0);
        }
    }
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) CoreMetadata(loci.formats.CoreMetadata) Timestamp(ome.xml.model.primitives.Timestamp) FormatException(loci.formats.FormatException) Location(loci.common.Location)

Example 25 with Location

use of loci.common.Location 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)

Aggregations

Location (loci.common.Location)185 CoreMetadata (loci.formats.CoreMetadata)55 MetadataStore (loci.formats.meta.MetadataStore)51 FormatException (loci.formats.FormatException)49 ArrayList (java.util.ArrayList)47 RandomAccessInputStream (loci.common.RandomAccessInputStream)47 Length (ome.units.quantity.Length)34 IOException (java.io.IOException)28 Timestamp (ome.xml.model.primitives.Timestamp)28 Time (ome.units.quantity.Time)20 IFD (loci.formats.tiff.IFD)15 TiffParser (loci.formats.tiff.TiffParser)15 NonNegativeInteger (ome.xml.model.primitives.NonNegativeInteger)15 PositiveInteger (ome.xml.model.primitives.PositiveInteger)15 DependencyException (loci.common.services.DependencyException)13 ServiceException (loci.common.services.ServiceException)12 File (java.io.File)11 ServiceFactory (loci.common.services.ServiceFactory)11 IniList (loci.common.IniList)10 FilePattern (loci.formats.FilePattern)10