Search in sources :

Example 31 with MetadataStore

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

the class PSDReader 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);
    m.littleEndian = false;
    if (!in.readString(4).equals("8BPS")) {
        throw new FormatException("Not a valid Photoshop file.");
    }
    addGlobalMeta("Version", in.readShort());
    // reserved, set to 0
    in.skipBytes(6);
    m.sizeC = in.readShort();
    m.sizeY = in.readInt();
    m.sizeX = in.readInt();
    int bits = in.readShort();
    addGlobalMeta("Bits per pixel", bits);
    m.pixelType = FormatTools.pixelTypeFromBytes(bits / 8, false, false);
    int colorMode = in.readShort();
    String modeString = null;
    switch(colorMode) {
        case 0:
            modeString = "monochrome";
            break;
        case 1:
            modeString = "gray-scale";
            break;
        case 2:
            modeString = "palette color";
            break;
        case 3:
            modeString = "RGB";
            break;
        case 4:
            modeString = "CMYK";
            break;
        case 6:
            modeString = "Duotone";
            break;
        case 7:
            modeString = "Multichannel color";
            break;
        case 8:
            modeString = "Duotone";
            break;
        case 9:
            modeString = "LAB color";
            break;
    }
    addGlobalMeta("Color mode", modeString);
    // read color mode block, if present
    int modeDataLength = in.readInt();
    long fp = in.getFilePointer();
    if (modeDataLength != 0) {
        if (colorMode == 2) {
            lut = new byte[3][256];
            for (int i = 0; i < lut.length; i++) {
                in.read(lut[i]);
            }
        }
        in.seek(fp + modeDataLength);
    }
    // read image resources block
    in.skipBytes(4);
    while (in.readString(4).equals("8BIM")) {
        int tag = in.readShort();
        int read = 1;
        while (in.read() != 0) read++;
        if (read % 2 == 1)
            in.skipBytes(1);
        int size = in.readInt();
        if (size % 2 == 1)
            size++;
        in.skipBytes(size);
    }
    in.seek(in.getFilePointer() - 4);
    int blockLen = in.readInt();
    if (blockLen == 0) {
        offset = in.getFilePointer();
    } else {
        int layerLen = in.readInt();
        int layerCount = in.readShort();
        if (layerCount < 0) {
            throw new FormatException("Vector data is not supported.");
        }
        if (layerLen == 0 && layerCount == 0) {
            in.skipBytes(2);
            int check = in.readShort();
            in.seek(in.getFilePointer() - (check == 0 ? 4 : 2));
        }
        int[] w = new int[layerCount];
        int[] h = new int[layerCount];
        int[] c = new int[layerCount];
        for (int i = 0; i < layerCount; i++) {
            int top = in.readInt();
            int left = in.readInt();
            int bottom = in.readInt();
            int right = in.readInt();
            w[i] = right - left;
            h[i] = bottom - top;
            c[i] = in.readShort();
            in.skipBytes(c[i] * 6 + 12);
            int len = in.readInt();
            if (len % 2 == 1)
                len++;
            in.skipBytes(len);
        }
        // skip over pixel data for each layer
        for (int i = 0; i < layerCount; i++) {
            if (h[i] < 0) {
                continue;
            }
            int[] lens = new int[h[i]];
            for (int cc = 0; cc < c[i]; cc++) {
                boolean compressed = in.readShort() == 1;
                if (!compressed)
                    in.skipBytes(w[i] * h[i]);
                else {
                    for (int y = 0; y < h[i]; y++) {
                        lens[y] = in.readShort();
                    }
                    for (int y = 0; y < h[i]; y++) {
                        in.skipBytes(lens[y]);
                    }
                }
            }
        }
        long start = in.getFilePointer();
        while (in.read() != '8') ;
        in.skipBytes(7);
        if (in.getFilePointer() - start > 1024) {
            in.seek(start);
        }
        int len = in.readInt();
        if ((len % 4) != 0)
            len += 4 - (len % 4);
        if (len > in.length() - in.getFilePointer() || (len & 0xff0000) >> 16 == 1) {
            in.seek(start);
            len = 0;
        }
        in.skipBytes(len);
        String s = in.readString(4);
        while (s.equals("8BIM")) {
            in.skipBytes(4);
            len = in.readInt();
            if ((len % 4) != 0)
                len += 4 - (len % 4);
            in.skipBytes(len);
            s = in.readString(4);
        }
        offset = in.getFilePointer() - 4;
    }
    m.sizeZ = 1;
    m.sizeT = 1;
    m.rgb = modeString.equals("RGB") || modeString.equals("CMYK");
    m.imageCount = getSizeC() / (isRGB() ? 3 : 1);
    m.indexed = modeString.equals("palette color");
    m.falseColor = false;
    m.dimensionOrder = "XYCZT";
    m.interleaved = false;
    m.metadataComplete = true;
    in.seek(offset);
    compressed = in.readShort() == 1;
    lens = new int[getSizeC()][getSizeY()];
    if (compressed) {
        for (int c = 0; c < getSizeC(); c++) {
            for (int row = 0; row < getSizeY(); row++) {
                lens[c][row] = in.readShort();
            }
        }
    }
    offset = in.getFilePointer();
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) RandomAccessInputStream(loci.common.RandomAccessInputStream) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException)

Example 32 with MetadataStore

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

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

the class ImagicReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    if (!checkSuffix(id, "hed")) {
        id = id.substring(0, id.lastIndexOf(".")) + ".hed";
    }
    super.initFile(id);
    in = new RandomAccessInputStream(id);
    pixels = id.substring(0, id.lastIndexOf(".")) + ".img";
    pixelsFile = new RandomAccessInputStream(pixels);
    CoreMetadata m = core.get(0);
    m.littleEndian = true;
    in.order(isLittleEndian());
    pixelsFile.order(isLittleEndian());
    int nImages = (int) (in.length() / 1024);
    String imageName = null;
    double physicalXSize = 0d;
    double physicalYSize = 0d;
    double physicalZSize = 0d;
    for (int i = 0; i < nImages; i++) {
        in.seek(i * 1024);
        in.skipBytes(16);
        int month = in.readInt();
        int day = in.readInt();
        int year = in.readInt();
        int hour = in.readInt();
        int minute = in.readInt();
        int seconds = in.readInt();
        in.skipBytes(8);
        m.sizeY = in.readInt();
        m.sizeX = in.readInt();
        String type = in.readString(4);
        if (type.equals("REAL")) {
            m.pixelType = FormatTools.FLOAT;
        } else if (type.equals("INTG")) {
            m.pixelType = FormatTools.UINT16;
        } else if (type.equals("PACK")) {
            m.pixelType = FormatTools.UINT8;
        } else if (type.equals("COMP")) {
            throw new FormatException("Unsupported pixel type 'COMP'");
        } else if (type.equals("RECO")) {
            throw new FormatException("Unsupported pixel type 'RECO'");
        }
        int ixold = in.readInt();
        int iyold = in.readInt();
        float averageDensity = in.readFloat();
        float sigma = in.readFloat();
        in.skipBytes(8);
        float maxDensity = in.readFloat();
        float minDensity = in.readFloat();
        in.skipBytes(4);
        float defocus1 = in.readFloat();
        float defocus2 = in.readFloat();
        float defocusAngle = in.readFloat();
        float startAngle = in.readFloat();
        float endAngle = in.readFloat();
        imageName = in.readString(80);
        float ccc3d = in.readFloat();
        int ref3d = in.readInt();
        int micrographID = in.readInt();
        int zShift = in.readInt();
        float alpha = in.readFloat();
        float beta = in.readFloat();
        float gamma = in.readFloat();
        in.skipBytes(8);
        int nAliSum = in.readInt();
        int pointGroup = in.readInt();
        in.skipBytes(28);
        int version = in.readInt();
        int stamp = in.readInt();
        in.skipBytes(120);
        float angle = in.readFloat();
        float voltage = in.readFloat();
        float sphericalAberration = in.readFloat();
        float partialCoherence = in.readFloat();
        float ccc = in.readFloat();
        float errar = in.readFloat();
        float err3d = in.readFloat();
        int ref = in.readInt();
        float classNumber = in.readFloat();
        in.skipBytes(4);
        float representationQuality = in.readFloat();
        float eqZShift = in.readFloat();
        float xShift = in.readFloat();
        float yShift = in.readFloat();
        float numcls = in.readFloat();
        float overallQuality = in.readFloat();
        float equivalentAngle = in.readFloat();
        float eqXShift = in.readFloat();
        float eqYShift = in.readFloat();
        float cmToVar = in.readFloat();
        float informat = in.readFloat();
        int nEigenvalues = in.readInt();
        int nActiveImages = in.readInt();
        physicalXSize = in.readFloat();
        physicalYSize = in.readFloat();
        physicalZSize = in.readFloat();
        addGlobalMeta("IXOLD", ixold);
        addGlobalMeta("IYOLD", iyold);
        addGlobalMeta("Average density (AVDENS)", averageDensity);
        addGlobalMeta("SIGMA", sigma);
        addGlobalMeta("Maximum density (DENSMAX)", maxDensity);
        addGlobalMeta("Minimum density (DENSMIN)", minDensity);
        addGlobalMeta("DEFOCUS1", defocus1);
        addGlobalMeta("DEFOCUS2", defocus2);
        addGlobalMeta("Defocus angle (DEFANGLE)", defocusAngle);
        addGlobalMeta("SINOSTRT", startAngle);
        addGlobalMeta("SINOEND", endAngle);
        addGlobalMeta("Image name", imageName);
        addGlobalMeta("CCC3D", ccc3d);
        addGlobalMeta("REF3D", ref3d);
        addGlobalMeta("MIDENT", micrographID);
        addGlobalMeta("EZSHIFT", zShift);
        addGlobalMeta("EALPHA", alpha);
        addGlobalMeta("EBETA", beta);
        addGlobalMeta("EGAMMA", gamma);
        addGlobalMeta("NALISUM", nAliSum);
        addGlobalMeta("PGROUP", pointGroup);
        addGlobalMeta("IMAGIC Version (IMAVERS)", version);
        addGlobalMeta("REALTYPE", stamp);
        addGlobalMeta("ANGLE", angle);
        addGlobalMeta("VOLTAGE (in kV)", voltage);
        addGlobalMeta("SPABERR (in mm)", sphericalAberration);
        addGlobalMeta("PCOHER", partialCoherence);
        addGlobalMeta("CCC", ccc);
        addGlobalMeta("ERRAR", errar);
        addGlobalMeta("ERR3D", err3d);
        addGlobalMeta("REF", ref);
        addGlobalMeta("CLASSNO", classNumber);
        addGlobalMeta("REPQUAL", representationQuality);
        addGlobalMeta("ZSHIFT", eqZShift);
        addGlobalMeta("XSHIFT", xShift);
        addGlobalMeta("YSHIFT", yShift);
        addGlobalMeta("NUMCLS", numcls);
        addGlobalMeta("OVQUAL", overallQuality);
        addGlobalMeta("EANGLE", equivalentAngle);
        addGlobalMeta("EXSHIFT", eqXShift);
        addGlobalMeta("EYSHIFT", eqYShift);
        addGlobalMeta("CMTOTVAR", cmToVar);
        addGlobalMeta("INFORMAT", informat);
        addGlobalMeta("NUMEIGEN", nEigenvalues);
        addGlobalMeta("NIACTIVE", nActiveImages);
        addGlobalMeta("RESOLX", physicalXSize);
        addGlobalMeta("RESOLY", physicalYSize);
        addGlobalMeta("RESOLZ", physicalZSize);
    }
    m.sizeZ = nImages;
    m.sizeC = 1;
    m.sizeT = 1;
    m.imageCount = nImages;
    m.dimensionOrder = "XYZCT";
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
    store.setImageName(imageName.trim(), 0);
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        Length sizeX = FormatTools.getPhysicalSizeX(physicalXSize * 0.0001);
        Length sizeY = FormatTools.getPhysicalSizeY(physicalYSize * 0.0001);
        Length sizeZ = FormatTools.getPhysicalSizeZ(physicalZSize * 0.0001);
        if (sizeX != null) {
            store.setPixelsPhysicalSizeX(sizeX, 0);
        }
        if (sizeY != null) {
            store.setPixelsPhysicalSizeY(sizeY, 0);
        }
        if (sizeZ != null) {
            store.setPixelsPhysicalSizeZ(sizeZ, 0);
        }
    }
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) RandomAccessInputStream(loci.common.RandomAccessInputStream) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException)

Example 34 with MetadataStore

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

the class InveonReader 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")) {
        id += ".hdr";
    }
    super.initFile(id);
    String headerData = DataTools.readFile(id);
    String[] lines = headerData.split("\n");
    String date = null;
    String institution = null, investigator = null;
    String model = null;
    String description = null;
    Double pixelSizeX = null;
    Double pixelSizeY = null;
    Double pixelSizeZ = null;
    int frames = 0;
    for (String line : lines) {
        line = line.trim();
        if (!line.startsWith("#")) {
            int space = line.indexOf(' ');
            if (space < 0) {
                continue;
            }
            String key = line.substring(0, space);
            String value = line.substring(space + 1);
            if (key.equals("institution")) {
                institution = value;
            } else if (key.equals("investigator")) {
                investigator = value;
            } else if (key.equals("study")) {
                description = value;
            } else if (key.equals("model")) {
                value = transformModel(value);
                model = value;
            } else if (key.equals("modality")) {
                value = transformModality(value);
            } else if (key.equals("modality_configuration")) {
                value = transformModalityConfiguration(value);
            } else if (key.equals("file_type")) {
                value = transformFileType(value);
            } else if (key.equals("acquisition_mode")) {
                value = transformAcquisitionMode(value);
            } else if (key.equals("bed_control")) {
                value = transformBedControl(value);
            } else if (key.equals("bed_motion")) {
                value = transformBedMotion(value);
            } else if (key.equals("registration_available")) {
                value = transformRegistrationAvailable(value);
            } else if (key.equals("normalization_applied")) {
                value = transformNormalizationApplied(value);
            } else if (key.equals("recon_algorithm")) {
                value = transformReconAlgorithm(value);
            } else if (key.equals("x_filter")) {
                value = transformFilter(value);
            } else if (key.equals("y_filter")) {
                value = transformFilter(value);
            } else if (key.equals("z_filter")) {
                value = transformFilter(value);
            } else if (key.equals("subject_orientation")) {
                value = transformSubjectOrientation(value);
            } else if (key.equals("subject_length_units")) {
                value = transformSubjectLengthUnits(value);
            } else if (key.equals("subject_weight_units")) {
                value = transformSubjectWeightUnits(value);
            } else if (key.equals("gantry_rotation")) {
                value = transformGantryRotation(value);
            } else if (key.equals("rotation_direction")) {
                value = transformRotationDirection(value);
            } else if (key.equals("ct_warping")) {
                value = transformCTWarping(value);
            } else if (key.equals("ct_projection_interpolation")) {
                value = transformCTProjectionInterpolation(value);
            } else if (key.equals("event_type")) {
                value = transformEventType(value);
            } else if (key.equals("projection") || key.equals("ct_projection_center_offset") || key.equals("ct_projection_horizontal_bed_offset")) {
                space = value.indexOf(' ');
                int index = Integer.parseInt(value.substring(0, space));
                value = value.substring(space + 1);
                key += " " + index;
            } else if (key.equals("user")) {
                space = value.indexOf(' ');
                key = value.substring(0, space);
                value = value.substring(space + 1);
            } else if (key.equals("file_name")) {
                // remove path from stored file name, if present
                value = value.replace('/', File.separatorChar);
                value = value.replace('\\', File.separatorChar);
                value = value.substring(value.lastIndexOf(File.separator) + 1);
                Location header = new Location(currentId).getAbsoluteFile();
                datFile = new Location(header.getParent(), value).getAbsolutePath();
            } else if (key.equals("time_frames")) {
                int sizeT = Integer.parseInt(value);
                for (int i = 0; i < core.size(); i++) {
                    core.get(i).sizeT = sizeT;
                }
            } else if (key.equals("total_frames")) {
                frames = Integer.parseInt(value);
            } else if (key.equals("number_of_bed_positions")) {
                int nPos = (int) Math.min(frames, Integer.parseInt(value));
                if (nPos > 1) {
                    CoreMetadata original = core.get(0);
                    core.clear();
                    for (int i = 0; i < nPos; i++) {
                        core.add(original);
                    }
                }
            } else if (key.equals("data_type")) {
                setDataType(value);
            } else if (key.equals("x_dimension")) {
                int sizeX = Integer.parseInt(value);
                for (int i = 0; i < core.size(); i++) {
                    core.get(i).sizeX = sizeX;
                }
            } else if (key.equals("y_dimension")) {
                int sizeY = Integer.parseInt(value);
                for (int i = 0; i < core.size(); i++) {
                    core.get(i).sizeY = sizeY;
                }
            } else if (key.equals("z_dimension")) {
                int sizeZ = Integer.parseInt(value);
                for (int i = 0; i < core.size(); i++) {
                    core.get(i).sizeZ = sizeZ;
                }
            } else if (key.equals("scan_time")) {
                date = value;
            } else if (key.equals("data_file_pointer")) {
                String[] values = value.split(" ");
                int[] ints = new int[values.length];
                for (int i = 0; i < ints.length; i++) {
                    ints[i] = Integer.parseInt(values[i]);
                }
                byte[] b = DataTools.intsToBytes(ints, false);
                dataPointers.add(DataTools.bytesToLong(b, false));
            } else // pixel sizes stored in mm
            if (key.equals("pixel_size_x")) {
                pixelSizeX = new Double(value) * 1000;
            } else if (key.equals("pixel_size_y")) {
                pixelSizeY = new Double(value) * 1000;
            } else if (key.equals("pixel_size_z")) {
                pixelSizeZ = new Double(value) * 1000;
            }
            addGlobalMeta(key, value);
        }
    }
    for (int i = 0; i < core.size(); i++) {
        CoreMetadata ms = core.get(i);
        if (ms.sizeZ == 0) {
            ms.sizeZ = 1;
        }
        if (ms.sizeT == 0) {
            ms.sizeT = 1;
        }
        ms.sizeC = 1;
        ms.rgb = false;
        ms.interleaved = false;
        ms.indexed = false;
        ms.dimensionOrder = "XYZCT";
        ms.imageCount = ms.sizeZ * ms.sizeC * ms.sizeT;
    }
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
    String experimenter = null, instrument = null;
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        experimenter = MetadataTools.createLSID("Experimenter", 0);
        store.setExperimenterID(experimenter, 0);
        store.setExperimenterUserName(investigator, 0);
        store.setExperimenterInstitution(institution, 0);
        instrument = MetadataTools.createLSID("Instrument", 0);
        store.setInstrumentID(instrument, 0);
        store.setMicroscopeModel(model, 0);
    }
    for (int i = 0; i < core.size(); i++) {
        if (date != null) {
            String newDate = DateTools.formatDate(date, "EEE MMM dd HH:mm:ss yyyy");
            if (newDate != null) {
                store.setImageAcquisitionDate(new Timestamp(newDate), i);
            }
        }
        if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
            if (experimenter != null) {
                store.setImageExperimenterRef(experimenter, i);
            }
            if (instrument != null) {
                store.setImageInstrumentRef(instrument, i);
            }
            store.setImageDescription(description, i);
            Length sizeX = FormatTools.getPhysicalSizeX(pixelSizeX);
            Length sizeY = FormatTools.getPhysicalSizeY(pixelSizeY);
            Length sizeZ = FormatTools.getPhysicalSizeZ(pixelSizeZ);
            if (sizeX != null) {
                store.setPixelsPhysicalSizeX(sizeX, i);
            }
            if (sizeY != null) {
                store.setPixelsPhysicalSizeY(sizeY, i);
            }
            if (sizeZ != null) {
                store.setPixelsPhysicalSizeZ(sizeZ, i);
            }
        }
    }
}
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 35 with MetadataStore

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

Aggregations

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