Search in sources :

Example 41 with Location

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

the class VisitechReader method isThisType.

/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
@Override
public boolean isThisType(String name, boolean open) {
    if (checkSuffix(name, "xys"))
        return true;
    // verify that there is an .xys file in the same directory
    if (name.indexOf(' ') == -1)
        return false;
    if (!open)
        return false;
    String prefix = name.substring(0, name.lastIndexOf(" "));
    Location xys = new Location(prefix + " 1.xys");
    return xys.exists();
}
Also used : Location(loci.common.Location)

Example 42 with Location

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

the class ScanrReader 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 (metadataFiles.size() > 0) {
        // this dataset has already been initialized
        return;
    }
    // make sure we have the .xml file
    if (!checkSuffix(id, "xml") && isGroupFiles()) {
        Location parent = new Location(id).getAbsoluteFile().getParentFile();
        if (checkSuffix(id, "tif") && parent.getName().equalsIgnoreCase("Data")) {
            parent = parent.getParentFile();
        }
        String[] list = parent.list();
        for (String file : list) {
            if (file.equals(XML_FILE)) {
                id = new Location(parent, file).getAbsolutePath();
                super.initFile(id);
                break;
            }
        }
        if (!checkSuffix(id, "xml")) {
            throw new FormatException("Could not find " + XML_FILE + " in " + parent.getAbsolutePath());
        }
    } else if (!isGroupFiles() && checkSuffix(id, "tif")) {
        TiffReader r = new TiffReader();
        r.setMetadataStore(getMetadataStore());
        r.setId(id);
        core = new ArrayList<CoreMetadata>(r.getCoreMetadataList());
        metadataStore = r.getMetadataStore();
        final Map<String, Object> globalMetadata = r.getGlobalMetadata();
        for (final Map.Entry<String, Object> entry : globalMetadata.entrySet()) {
            addGlobalMeta(entry.getKey(), entry.getValue());
        }
        r.close();
        tiffs = new String[] { id };
        reader = new MinimalTiffReader();
        return;
    }
    Location dir = new Location(id).getAbsoluteFile().getParentFile();
    String[] list = dir.list(true);
    for (String file : list) {
        Location f = new Location(dir, file);
        if (checkSuffix(file, METADATA_SUFFIXES) && !f.isDirectory()) {
            metadataFiles.add(f.getAbsolutePath());
        }
    }
    // parse XML metadata
    String xml = DataTools.readFile(id).trim();
    if (xml.startsWith("<?")) {
        xml = xml.substring(xml.indexOf("?>") + 2);
    }
    xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + xml;
    XMLTools.parseXML(xml, new ScanrHandler());
    final List<String> uniqueRows = new ArrayList<String>();
    final List<String> uniqueColumns = new ArrayList<String>();
    if (wellRows == 0 || wellColumns == 0) {
        for (String well : wellLabels.keySet()) {
            if (!Character.isLetter(well.charAt(0)))
                continue;
            String row = well.substring(0, 1).trim();
            String column = well.substring(1).trim();
            if (!uniqueRows.contains(row) && row.length() > 0)
                uniqueRows.add(row);
            if (!uniqueColumns.contains(column) && column.length() > 0) {
                uniqueColumns.add(column);
            }
        }
        wellRows = uniqueRows.size();
        wellColumns = uniqueColumns.size();
        if (wellRows * wellColumns != wellCount) {
            adjustWellDimensions();
        }
    }
    int nChannels = getSizeC() == 0 ? channelNames.size() : (int) Math.min(channelNames.size(), getSizeC());
    if (nChannels == 0)
        nChannels = 1;
    int nSlices = getSizeZ() == 0 ? 1 : getSizeZ();
    int nTimepoints = getSizeT();
    int nWells = wellCount;
    int nPos = 0;
    if (foundPositions)
        nPos = fieldPositionX.length;
    else
        nPos = fieldRows * fieldColumns;
    if (nPos == 0)
        nPos = 1;
    // get list of TIFF files
    Location dataDir = new Location(dir, "data");
    list = dataDir.list(true);
    if (list == null) {
        // try to find the TIFFs in the current directory
        list = dir.list(true);
    } else
        dir = dataDir;
    if (nTimepoints == 0 || list.length < nTimepoints * nChannels * nSlices * nWells * nPos) {
        nTimepoints = list.length / (nChannels * nWells * nPos * nSlices);
        if (nTimepoints == 0)
            nTimepoints = 1;
    }
    tiffs = new String[nChannels * nWells * nPos * nTimepoints * nSlices];
    Arrays.sort(list, new Comparator<String>() {

        @Override
        public int compare(String s1, String s2) {
            int lastSeparator1 = s1.lastIndexOf(File.separator) + 1;
            int lastSeparator2 = s2.lastIndexOf(File.separator) + 1;
            String dir1 = s1.substring(0, lastSeparator1);
            String dir2 = s2.substring(0, lastSeparator2);
            if (!dir1.equals(dir2)) {
                return dir1.compareTo(dir2);
            }
            int dash1 = s1.indexOf("-", lastSeparator1);
            int dash2 = s2.indexOf("-", lastSeparator2);
            String label1 = dash1 < 0 ? "" : s1.substring(lastSeparator1, dash1);
            String label2 = dash2 < 0 ? "" : s2.substring(lastSeparator2, dash2);
            if (label1.equals(label2)) {
                String remainder1 = dash1 < 0 ? s1 : s1.substring(dash1);
                String remainder2 = dash2 < 0 ? s2 : s2.substring(dash2);
                return remainder1.compareTo(remainder2);
            }
            Integer index1 = wellLabels.get(label1);
            Integer index2 = wellLabels.get(label2);
            if (index1 == null && index2 != null) {
                return 1;
            } else if (index1 != null && index2 == null) {
                return -1;
            }
            return index1.compareTo(index2);
        }
    });
    int lastListIndex = 0;
    int next = 0;
    String[] keys = wellLabels.keySet().toArray(new String[wellLabels.size()]);
    Arrays.sort(keys, new Comparator<String>() {

        @Override
        public int compare(String s1, String s2) {
            char row1 = s1.charAt(0);
            char row2 = s2.charAt(0);
            final Integer col1 = new Integer(s1.substring(1));
            final Integer col2 = new Integer(s2.substring(1));
            if (row1 < row2) {
                return -1;
            } else if (row1 > row2) {
                return 1;
            }
            return col1.compareTo(col2);
        }
    });
    int realPosCount = 0;
    for (int well = 0; well < nWells; well++) {
        int missingWellFiles = 0;
        int wellIndex = wellNumbers.get(well);
        String wellPos = getBlock(wellIndex, "W");
        int originalIndex = next;
        for (int pos = 0; pos < nPos; pos++) {
            String posPos = getBlock(pos + 1, "P");
            int posIndex = next;
            for (int z = 0; z < nSlices; z++) {
                String zPos = getBlock(z, "Z");
                for (int t = 0; t < nTimepoints; t++) {
                    String tPos = getBlock(t, "T");
                    for (int c = 0; c < nChannels; c++) {
                        for (int i = lastListIndex; i < list.length; i++) {
                            String file = list[i];
                            if (file.indexOf(wellPos) != -1 && file.indexOf(zPos) != -1 && file.indexOf(posPos) != -1 && file.indexOf(tPos) != -1 && file.indexOf(channelNames.get(c)) != -1) {
                                tiffs[next++] = new Location(dir, file).getAbsolutePath();
                                if (c == nChannels - 1) {
                                    lastListIndex = i;
                                }
                                break;
                            }
                        }
                        if (next == originalIndex) {
                            missingWellFiles++;
                        }
                    }
                }
            }
            if (posIndex != next)
                realPosCount++;
        }
        if (next == originalIndex && well < keys.length) {
            wellLabels.remove(keys[well]);
        }
        if (next == originalIndex && missingWellFiles == nSlices * nTimepoints * nChannels * nPos) {
            wellNumbers.remove(well);
        }
    }
    nWells = wellNumbers.size();
    if (wellLabels.size() > 0 && wellLabels.size() != nWells) {
        uniqueRows.clear();
        uniqueColumns.clear();
        for (String well : wellLabels.keySet()) {
            if (!Character.isLetter(well.charAt(0)))
                continue;
            String row = well.substring(0, 1).trim();
            String column = well.substring(1).trim();
            if (!uniqueRows.contains(row) && row.length() > 0)
                uniqueRows.add(row);
            if (!uniqueColumns.contains(column) && column.length() > 0) {
                uniqueColumns.add(column);
            }
        }
        nWells = uniqueRows.size() * uniqueColumns.size();
        adjustWellDimensions();
    }
    if (realPosCount < nPos) {
        nPos = realPosCount;
    }
    reader = new MinimalTiffReader();
    reader.setId(tiffs[0]);
    int sizeX = reader.getSizeX();
    int sizeY = reader.getSizeY();
    int pixelType = reader.getPixelType();
    tileWidth = reader.getOptimalTileWidth();
    tileHeight = reader.getOptimalTileHeight();
    switch(pixelType) {
        case FormatTools.INT8:
            pixelType = FormatTools.UINT8;
            break;
        case FormatTools.INT16:
            pixelType = FormatTools.UINT16;
            break;
    }
    boolean rgb = reader.isRGB();
    boolean interleaved = reader.isInterleaved();
    boolean indexed = reader.isIndexed();
    boolean littleEndian = reader.isLittleEndian();
    reader.close();
    int seriesCount = nWells * nPos;
    core.clear();
    for (int i = 0; i < seriesCount; i++) {
        CoreMetadata ms = new CoreMetadata();
        core.add(ms);
        ms.sizeC = nChannels;
        ms.sizeZ = nSlices;
        ms.sizeT = nTimepoints;
        ms.sizeX = sizeX;
        ms.sizeY = sizeY;
        ms.pixelType = pixelType;
        ms.rgb = rgb;
        ms.interleaved = interleaved;
        ms.indexed = indexed;
        ms.littleEndian = littleEndian;
        ms.dimensionOrder = "XYCTZ";
        ms.imageCount = nSlices * nTimepoints * nChannels;
        ms.bitsPerPixel = 12;
    }
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
    store.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
    store.setPlateColumns(new PositiveInteger(wellColumns), 0);
    store.setPlateRows(new PositiveInteger(wellRows), 0);
    String plateAcqID = MetadataTools.createLSID("PlateAcquisition", 0, 0);
    store.setPlateAcquisitionID(plateAcqID, 0, 0);
    int nFields = 0;
    if (foundPositions) {
        nFields = fieldPositionX.length;
    } else {
        nFields = fieldRows * fieldColumns;
    }
    PositiveInteger fieldCount = FormatTools.getMaxFieldCount(nFields);
    if (fieldCount != null) {
        store.setPlateAcquisitionMaximumFieldCount(fieldCount, 0, 0);
    }
    for (int i = 0; i < getSeriesCount(); i++) {
        int field = i % nFields;
        int well = i / nFields;
        int index = well;
        while (wellNumbers.get(index) == null && index < wellNumbers.size()) {
            index++;
        }
        int wellIndex = wellNumbers.get(index) == null ? index : wellNumbers.get(index) - 1;
        int wellRow = wellIndex / wellColumns;
        int wellCol = wellIndex % wellColumns;
        if (field == 0) {
            store.setWellID(MetadataTools.createLSID("Well", 0, well), 0, well);
            store.setWellColumn(new NonNegativeInteger(wellCol), 0, well);
            store.setWellRow(new NonNegativeInteger(wellRow), 0, well);
        }
        String wellSample = MetadataTools.createLSID("WellSample", 0, well, field);
        store.setWellSampleID(wellSample, 0, well, field);
        store.setWellSampleIndex(new NonNegativeInteger(i), 0, well, field);
        String imageID = MetadataTools.createLSID("Image", i);
        store.setWellSampleImageRef(imageID, 0, well, field);
        store.setImageID(imageID, i);
        String name = "Well " + (well + 1) + ", Field " + (field + 1) + " (Spot " + (i + 1) + ")";
        store.setImageName(name, i);
        store.setPlateAcquisitionWellSampleRef(wellSample, 0, 0, i);
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        for (int i = 0; i < getSeriesCount(); i++) {
            for (int c = 0; c < getSizeC(); c++) {
                store.setChannelName(channelNames.get(c), i, c);
            }
            Length x = FormatTools.getPhysicalSizeX(pixelSize);
            Length y = FormatTools.getPhysicalSizeY(pixelSize);
            if (x != null) {
                store.setPixelsPhysicalSizeX(x, i);
            }
            if (y != null) {
                store.setPixelsPhysicalSizeY(y, i);
            }
            if (fieldPositionX != null && fieldPositionY != null) {
                int field = i % nFields;
                int well = i / nFields;
                final Length posX = fieldPositionX[field];
                final Length posY = fieldPositionY[field];
                store.setWellSamplePositionX(posX, 0, well, field);
                store.setWellSamplePositionY(posY, 0, well, field);
                for (int c = 0; c < getSizeC(); c++) {
                    int image = getIndex(0, c, 0);
                    store.setPlaneTheZ(new NonNegativeInteger(0), i, image);
                    store.setPlaneTheC(new NonNegativeInteger(c), i, image);
                    store.setPlaneTheT(new NonNegativeInteger(0), i, image);
                    store.setPlanePositionX(fieldPositionX[field], i, image);
                    store.setPlanePositionY(fieldPositionY[field], i, image);
                    // exposure time is stored in milliseconds
                    // convert to seconds before populating MetadataStore
                    Double time = exposures.get(c);
                    if (time != null) {
                        time /= 1000;
                        store.setPlaneExposureTime(new Time(time, UNITS.SECOND), i, image);
                    }
                    if (deltaT != null) {
                        store.setPlaneDeltaT(new Time(deltaT, UNITS.SECOND), i, image);
                    }
                }
            }
        }
        String row = wellRows > 26 ? "Number" : "Letter";
        String col = wellRows > 26 ? "Letter" : "Number";
        store.setPlateRowNamingConvention(getNamingConvention(row), 0);
        store.setPlateColumnNamingConvention(getNamingConvention(col), 0);
        store.setPlateName(plateName, 0);
    }
}
Also used : PositiveInteger(ome.xml.model.primitives.PositiveInteger) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) ArrayList(java.util.ArrayList) Time(ome.units.quantity.Time) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) PositiveInteger(ome.xml.model.primitives.PositiveInteger) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) HashMap(java.util.HashMap) Map(java.util.Map) Location(loci.common.Location)

Example 43 with Location

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

the class ScanrReader method isSingleFile.

// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isSingleFile(String) */
@Override
public boolean isSingleFile(String id) throws FormatException, IOException {
    Location file = new Location(id).getAbsoluteFile();
    String name = file.getName();
    if (name.equals(XML_FILE) || name.equals(EXPERIMENT_FILE) || name.equals(ACQUISITION_FILE)) {
        return true;
    }
    Location parent = file.getParentFile();
    if (parent != null) {
        parent = parent.getParentFile();
    }
    return new Location(parent, XML_FILE).exists();
}
Also used : Location(loci.common.Location)

Example 44 with Location

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

the class SPCReader method isThisType.

/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
@Override
public boolean isThisType(String name, boolean open) {
    if (!(checkSuffix(name, "spc") || checkSuffix(name, "set")))
        return false;
    String extension = name.substring(name.lastIndexOf(".") + 1);
    String baseName = name.substring(0, name.lastIndexOf("."));
    if (!new Location(baseName + ".spc").exists())
        return false;
    return new Location(baseName + ".set").exists();
}
Also used : Location(loci.common.Location)

Example 45 with Location

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

the class SPCReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    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 = "";
    }
    String name = tmpFile.getName();
    // generate the name of the two matching files
    String setName = null;
    String spcName = null;
    int pos = name.lastIndexOf(".");
    if (pos != -1) {
        setName = tmpFile.getName().substring(0, pos) + ".set";
        spcName = tmpFile.getName().substring(0, pos) + ".spc";
        for (String l : ls) {
            if (l.equalsIgnoreCase(setName))
                setName = l;
            if (l.equalsIgnoreCase(spcName))
                spcName = l;
        }
    }
    if (setName == null) {
        throw new FormatException("Failed to find a matching .set file!");
    }
    if (spcName == null) {
        throw new FormatException("Failed to find a matching .spc file!");
    }
    frameClockList = new ArrayList<>();
    endOfFrameList = new ArrayList<>();
    allFiles.add(workingDirPath + setName);
    allFiles.add(workingDirPath + spcName);
    in = new RandomAccessInputStream(workingDirPath + setName);
    LOGGER.info("Reading info from .set file");
    in.order(true);
    in.skip(8);
    Integer setuppos = in.readInt();
    Short setupcount = in.readShort();
    String module = "";
    try {
        // Arbitrary length established by trial and error
        String header = in.readString(600);
        int index = header.indexOf("module SPC-");
        module = header.substring(index + 7, index + 14);
    } catch (IOException exc) {
        LOGGER.debug("Failed to read header from .set file!", exc);
    }
    if (!module.equalsIgnoreCase("SPC-134") && !module.equalsIgnoreCase("SPC-144") && !module.equalsIgnoreCase("SPC-154") && !module.equalsIgnoreCase("SPC-830")) {
        throw new FormatException("Failed to find a matching .set file!");
    }
    // goto start of setup information
    in.seek(setuppos);
    String setup = in.readString(setupcount);
    in.close();
    // get the tac range from the setup information
    double tacRange = parseSetup(TAC_RANGE, setup);
    // get the tac range from the setup information
    double tacGain = parseSetup(TAC_GAIN, setup);
    double timeBase;
    if (tacGain != 0.0 && tacRange != 0.0) {
        timeBase = 4095 * tacRange / (tacGain * 4096);
        // convert from s to ps
        timeBase *= 1.000e12;
    } else {
        throw new FormatException("Failed to parse setup file!");
    }
    LOGGER.debug("timeBase = " + Double.toString(timeBase));
    // Now read .spc file
    spcId = workingDirPath + spcName;
    in = new RandomAccessInputStream(spcId);
    in.order(true);
    LOGGER.info("Reading info from .spc file");
    /* The first 3 bytes in the file contain information about the 
     * macro time clock in 0.1 ns units ("500" for 50ns clock)
    */
    in.skip(3);
    /*
     * The 4th byte contains information about the number of 
     * routing channels in bits 3 to 6.
     * Bits 0-2 reserved bit 7 = 1 ("Data invalid")
    */
    byte routing = in.readByte();
    if ((routing & 0x10) != 0) {
        throw new FormatException("Invalid data!");
    }
    nChannels = (routing & 0x78) >> 3;
    currentPixel = 0;
    currentLine = -1;
    currentFrame = -1;
    rawBuf = new byte[bufLength];
    endOfFrameFlag = false;
    nBuffers = 0;
    bufLength = 1024;
    rawBuf = new byte[bufLength];
    int noOfBytes;
    nBuffers = 0;
    byte adcL;
    byte adcLM;
    while ((noOfBytes = in.read(rawBuf)) != -1) {
        for (int bb = 3; bb < noOfBytes; bb += 4) {
            // even nybble adc
            // get upper byte containing ADC data
            adcL = rawBuf[bb];
            // mask out upper 4 bits
            adcLM = (byte) (adcL & 0xF0);
            // at this point only the various clocks are of interest
            switch(adcLM) {
                case (byte) 0x90:
                    invalidAndMarkInit(bb);
                    break;
                case // Invalid, Mark and MTOV all set.
                (byte) 0xd0:
                    // Unsure about this-- Not well documented!
                    invalidAndMarkInit(bb);
                    break;
                default:
                    break;
            }
        // end switch
        }
        // end for
        nBuffers++;
    }
    nTimebins = (0xFFF >> adcResShift) + 1;
    nFrames = currentFrame - 1;
    addGlobalMeta("time bins", nTimebins);
    addGlobalMeta("nChannels", nChannels);
    addGlobalMeta("time base", timeBase);
    LOGGER.info("Populating metadata");
    CoreMetadata m = core.get(0);
    // Duplicates the behaviour of U.Lorenzo's Matlab code.
    if (nLines < 530) {
        // return an image
        lineMode = false;
        m.sizeY = nLines;
    } else {
        LOGGER.info("Single line mode");
        // return a single line
        lineMode = true;
        m.sizeY = 1;
    }
    Integer frameLength;
    Integer maxFrameLength = 0;
    for (int T = 0; T < nFrames; T++) {
        frameLength = (int) (endOfFrameList.get(T + 1) - frameClockList.get(T));
        if (frameLength > maxFrameLength)
            maxFrameLength = frameLength;
    }
    rawBuf = new byte[maxFrameLength];
    m.sizeX = nPixels;
    m.sizeZ = 1;
    m.sizeT = nTimebins * nFrames;
    m.sizeC = nChannels;
    m.dimensionOrder = "XYZTC";
    m.pixelType = FormatTools.UINT16;
    m.rgb = false;
    m.littleEndian = true;
    m.imageCount = m.sizeZ * m.sizeC * m.sizeT;
    m.indexed = false;
    m.falseColor = false;
    m.metadataComplete = true;
    m.moduloT.type = FormatTools.LIFETIME;
    m.moduloT.parentType = FormatTools.SPECTRA;
    m.moduloT.typeDescription = "TCSPC";
    m.moduloT.start = 0;
    m.moduloT.step = timeBase / nTimebins;
    m.moduloT.end = m.moduloT.step * (nTimebins - 1);
    m.moduloT.unit = "ps";
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
}
Also used : IOException(java.io.IOException) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) 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