Search in sources :

Example 6 with ServiceFactory

use of loci.common.services.ServiceFactory in project bioformats by openmicroscopy.

the class VolocityReader method initFile.

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

Example 7 with ServiceFactory

use of loci.common.services.ServiceFactory in project bioformats by openmicroscopy.

the class WlzReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    try {
        ServiceFactory factory = new ServiceFactory();
        wlz = factory.getInstance(WlzService.class);
    } catch (DependencyException e) {
        throw new FormatException(NO_WLZ_MSG, e);
    }
    if (wlz != null) {
        wlz.open(id, "r");
        CoreMetadata md = core.get(0);
        MetadataStore store = makeFilterMetadata();
        md.rgb = wlz.isRGB();
        md.interleaved = false;
        md.indexed = false;
        md.sizeX = wlz.getSizeX();
        md.sizeY = wlz.getSizeY();
        md.sizeZ = wlz.getSizeZ();
        md.sizeC = wlz.getSizeC();
        md.sizeT = wlz.getSizeT();
        md.dimensionOrder = "XYZCT";
        md.imageCount = wlz.getSizeZ();
        md.pixelType = wlz.getPixelType();
        PositiveFloat x = new PositiveFloat(Math.abs(wlz.getVoxSzX()));
        PositiveFloat y = new PositiveFloat(Math.abs(wlz.getVoxSzY()));
        PositiveFloat z = new PositiveFloat(Math.abs(wlz.getVoxSzZ()));
        store.setPixelsPhysicalSizeX(FormatTools.createLength(x, UNITS.MICROMETER), 0);
        store.setPixelsPhysicalSizeY(FormatTools.createLength(y, UNITS.MICROMETER), 0);
        store.setPixelsPhysicalSizeZ(FormatTools.createLength(z, UNITS.MICROMETER), 0);
        store.setStageLabelName(wlz.getWlzOrgLabelName(), 0);
        store.setStageLabelX(new Length(wlz.getOrgX(), UNITS.REFERENCEFRAME), 0);
        store.setStageLabelY(new Length(wlz.getOrgY(), UNITS.REFERENCEFRAME), 0);
        store.setStageLabelZ(new Length(wlz.getOrgZ(), UNITS.REFERENCEFRAME), 0);
        MetadataTools.populatePixels(store, this);
    }
}
Also used : WlzService(loci.formats.services.WlzService) MetadataStore(loci.formats.meta.MetadataStore) ServiceFactory(loci.common.services.ServiceFactory) Length(ome.units.quantity.Length) PositiveFloat(ome.xml.model.primitives.PositiveFloat) DependencyException(loci.common.services.DependencyException) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException)

Example 8 with ServiceFactory

use of loci.common.services.ServiceFactory in project bioformats by openmicroscopy.

the class WlzReader method openBytes.

/**
 * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
 */
@Override
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException {
    FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
    if (wlz != null) {
        buf = wlz.readBytes(no, buf, x, y, w, h);
    } else {
        try {
            ServiceFactory factory = new ServiceFactory();
            wlz = factory.getInstance(WlzService.class);
        } catch (DependencyException e) {
            throw new FormatException(NO_WLZ_MSG, e);
        }
        if (wlz != null) {
            wlz.open(currentId, "r");
            buf = wlz.readBytes(no, buf, x, y, w, h);
        }
    }
    return buf;
}
Also used : WlzService(loci.formats.services.WlzService) ServiceFactory(loci.common.services.ServiceFactory) DependencyException(loci.common.services.DependencyException) FormatException(loci.formats.FormatException)

Example 9 with ServiceFactory

use of loci.common.services.ServiceFactory in project bioformats by openmicroscopy.

the class TillVisionReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    if (!checkSuffix(id, "vws")) {
        Location pst = new Location(id).getAbsoluteFile();
        String name = pst.getParentFile().getName();
        Location parent = pst.getParentFile().getParentFile();
        Location vwsFile = new Location(parent, name.replaceAll(".pst", ".vws"));
        if (vwsFile.exists() && !vwsFile.isDirectory()) {
            id = vwsFile.getAbsolutePath();
        } else if (vwsFile.isDirectory()) {
            parent = pst.getParentFile();
            String[] list = parent.list(true);
            boolean foundVWS = false;
            for (String f : list) {
                if (checkSuffix(f, "vws")) {
                    id = new Location(parent, f).getAbsolutePath();
                    foundVWS = true;
                    break;
                }
            }
            if (!foundVWS) {
                throw new FormatException("Could not find .vws file.");
            }
        } else
            throw new FormatException("Could not find .vws file.");
    }
    super.initFile(id);
    exposureTimes = new HashMap<Integer, Double>();
    POIService poi = null;
    try {
        ServiceFactory factory = new ServiceFactory();
        poi = factory.getInstance(POIService.class);
    } catch (DependencyException de) {
        throw new FormatException("POI library not found", de);
    }
    poi.initialize(id);
    Vector<String> documents = poi.getDocumentList();
    int nImages = 0;
    final Hashtable<String, Object> tmpSeriesMetadata = new Hashtable<String, Object>();
    for (String name : documents) {
        LOGGER.debug("Reading {}", name);
        if (name.equals("Root Entry" + File.separator + "Contents")) {
            RandomAccessInputStream s = poi.getDocumentStream(name);
            s.order(true);
            boolean specialCImage = false;
            int nFound = 0;
            Long[] cimages = null;
            Location dir = new Location(id).getAbsoluteFile().getParentFile();
            String[] list = dir.list(true);
            boolean hasPST = false;
            for (String f : list) {
                if (checkSuffix(f, "pst")) {
                    hasPST = true;
                    break;
                }
            }
            if (!hasPST) {
                cimages = findImages(s);
                nFound = cimages.length;
                if (nFound == 0) {
                    s.seek(13);
                    int len = s.readShort();
                    String type = s.readString(len);
                    if (type.equals("CImage")) {
                        nFound = 1;
                        cimages = new Long[] { s.getFilePointer() + 6 };
                        specialCImage = true;
                    }
                }
                embeddedImages = nFound > 0;
            }
            LOGGER.debug("Images are {}embedded", embeddedImages ? "" : "not ");
            if (embeddedImages) {
                core.clear();
                embeddedOffset = new long[nFound];
                for (int i = 0; i < nFound; i++) {
                    CoreMetadata ms = new CoreMetadata();
                    core.add(ms);
                    s.seek(cimages[i]);
                    int len = s.read();
                    String imageName = s.readString(len);
                    imageNames.add(imageName);
                    if (specialCImage) {
                        s.seek(1280);
                    } else {
                        while (true) {
                            if (s.readString(2).equals("sB")) {
                                break;
                            } else
                                s.seek(s.getFilePointer() - 1);
                        }
                    }
                    s.skipBytes(20);
                    ms.sizeX = s.readInt();
                    ms.sizeY = s.readInt();
                    ms.sizeZ = s.readInt();
                    ms.sizeC = s.readInt();
                    ms.sizeT = s.readInt();
                    ms.pixelType = convertPixelType(s.readInt());
                    if (specialCImage) {
                        embeddedOffset[i] = s.getFilePointer() + 27;
                    } else {
                        embeddedOffset[i] = s.getFilePointer() + 31;
                    }
                }
                if (in != null)
                    in.close();
                in = poi.getDocumentStream(name);
                s.close();
                break;
            }
            s.seek(0);
            int lowerBound = 0;
            int upperBound = 0x1000;
            while (s.getFilePointer() < s.length() - 2) {
                LOGGER.debug("  Looking for image at {}", s.getFilePointer());
                s.order(false);
                int nextOffset = findNextOffset(s);
                if (nextOffset < 0 || nextOffset >= s.length())
                    break;
                s.seek(nextOffset);
                s.skipBytes(3);
                int len = s.readShort();
                if (len <= 0)
                    continue;
                imageNames.add(s.readString(len));
                if (s.getFilePointer() + 8 >= s.length())
                    break;
                s.skipBytes(6);
                s.order(true);
                len = s.readShort();
                if (nImages == 0 && len > upperBound * 2 && len < upperBound * 4) {
                    lowerBound = 512;
                    upperBound = 0x4000;
                }
                if (len < lowerBound || len > upperBound)
                    continue;
                String description = s.readString(len);
                LOGGER.debug("Description: {}", description);
                // parse key/value pairs from description
                String dateTime = "";
                String[] lines = description.split("[\r\n]");
                for (String line : lines) {
                    line = line.trim();
                    int colon = line.indexOf(':');
                    if (colon != -1 && !line.startsWith(";")) {
                        String key = line.substring(0, colon).trim();
                        String value = line.substring(colon + 1).trim();
                        String metaKey = "Series " + nImages + " " + key;
                        addMeta(metaKey, value, tmpSeriesMetadata);
                        if (key.equals("Start time of experiment")) {
                            // HH:mm:ss aa OR HH:mm:ss.sss aa
                            dateTime += " " + value;
                        } else if (key.equals("Date")) {
                            // mm/dd/yy ?
                            dateTime = value + " " + dateTime;
                        } else if (key.equals("Exposure time [ms]")) {
                            double exp = Double.parseDouble(value) / 1000;
                            exposureTimes.put(nImages, exp);
                        } else if (key.equals("Image type")) {
                            types.add(value);
                        }
                    }
                }
                dateTime = dateTime.trim();
                if (!dateTime.equals("")) {
                    boolean success = false;
                    for (String format : DATE_FORMATS) {
                        try {
                            dateTime = DateTools.formatDate(dateTime, format, ".");
                            success = true;
                        } catch (NullPointerException e) {
                        }
                    }
                    dates.add(success ? dateTime : "");
                }
                nImages++;
            }
            s.close();
        }
    }
    Location directory = new Location(currentId).getAbsoluteFile().getParentFile();
    String[] pixelsFile = new String[nImages];
    if (!embeddedImages) {
        if (nImages == 0) {
            throw new FormatException("No images found.");
        }
        // look for appropriate pixels files
        String[] files = directory.list(true);
        String name = currentId.substring(currentId.lastIndexOf(File.separator) + 1, currentId.lastIndexOf("."));
        int nextFile = 0;
        for (String f : files) {
            if (checkSuffix(f, "pst")) {
                Location pst = new Location(directory, f);
                if (pst.isDirectory() && f.startsWith(name)) {
                    String[] subfiles = pst.list(true);
                    Arrays.sort(subfiles);
                    for (String q : subfiles) {
                        if (checkSuffix(q, "pst") && nextFile < nImages) {
                            pixelsFile[nextFile++] = f + File.separator + q;
                        }
                    }
                }
            }
        }
        if (nextFile == 0) {
            for (String f : files) {
                if (checkSuffix(f, "pst")) {
                    pixelsFile[nextFile++] = new Location(directory, f).getAbsolutePath();
                }
            }
            if (nextFile == 0)
                throw new FormatException("No image files found.");
        }
    }
    Arrays.sort(pixelsFile);
    int nSeries = core.size();
    if (!embeddedImages) {
        core.clear();
        nSeries = nImages;
    }
    pixelsFiles = new String[nSeries];
    infFiles = new String[nSeries];
    Object[] metadataKeys = tmpSeriesMetadata.keySet().toArray();
    IniParser parser = new IniParser();
    for (int i = 0; i < nSeries; i++) {
        CoreMetadata ms;
        if (!embeddedImages) {
            ms = new CoreMetadata();
            core.add(ms);
            setSeries(i);
            // make sure that pixels file exists
            String file = pixelsFile[i];
            file = file.replace('/', File.separatorChar);
            file = file.replace('\\', File.separatorChar);
            String oldFile = file;
            Location f = new Location(directory, oldFile);
            if (!f.exists()) {
                oldFile = oldFile.substring(oldFile.lastIndexOf(File.separator) + 1);
                f = new Location(directory, oldFile);
                if (!f.exists()) {
                    throw new FormatException("Could not find pixels file '" + file);
                }
            }
            file = f.getAbsolutePath();
            pixelsFiles[i] = file;
            // read key/value pairs from .inf files
            int dot = file.lastIndexOf(".");
            String inf = file.substring(0, dot) + ".inf";
            infFiles[i] = inf;
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(inf), Constants.ENCODING));
            IniList data = parser.parseINI(reader);
            reader.close();
            IniTable infoTable = data.getTable("Info");
            ms.sizeX = Integer.parseInt(infoTable.get("Width"));
            ms.sizeY = Integer.parseInt(infoTable.get("Height"));
            ms.sizeC = Integer.parseInt(infoTable.get("Bands"));
            ms.sizeZ = Integer.parseInt(infoTable.get("Slices"));
            ms.sizeT = Integer.parseInt(infoTable.get("Frames"));
            int dataType = Integer.parseInt(infoTable.get("Datatype"));
            ms.pixelType = convertPixelType(dataType);
            if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
                HashMap<String, String> iniMap = data.flattenIntoHashMap();
                ms.seriesMetadata.putAll(iniMap);
            }
        } else {
            ms = core.get(i);
            setSeries(i);
        }
        ms.imageCount = ms.sizeZ * ms.sizeC * ms.sizeT;
        ms.rgb = false;
        ms.littleEndian = true;
        ms.dimensionOrder = "XYCZT";
        ms.seriesMetadata = new Hashtable<String, Object>();
        for (Object key : metadataKeys) {
            String keyName = key.toString();
            if (keyName.startsWith("Series " + i + " ")) {
                keyName = keyName.replaceAll("Series " + i + " ", "");
                ms.seriesMetadata.put(keyName, tmpSeriesMetadata.get(key));
            }
        }
    }
    setSeries(0);
    populateMetadataStore();
    poi.close();
    poi = null;
}
Also used : IniParser(loci.common.IniParser) ServiceFactory(loci.common.services.ServiceFactory) IniList(loci.common.IniList) InputStreamReader(java.io.InputStreamReader) Hashtable(java.util.Hashtable) POIService(loci.formats.services.POIService) DependencyException(loci.common.services.DependencyException) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) FileInputStream(java.io.FileInputStream) IniTable(loci.common.IniTable) BufferedReader(java.io.BufferedReader) RandomAccessInputStream(loci.common.RandomAccessInputStream) Location(loci.common.Location)

Example 10 with ServiceFactory

use of loci.common.services.ServiceFactory in project bioformats by openmicroscopy.

the class MDBServiceTest method setUp.

@BeforeMethod
public void setUp() throws DependencyException, IOException {
    ServiceFactory sf = new ServiceFactory();
    service = sf.getInstance(MDBService.class);
    URL file = this.getClass().getResource(TEST_FILE);
    service.initialize(file.getPath());
}
Also used : MDBService(loci.formats.services.MDBService) ServiceFactory(loci.common.services.ServiceFactory) URL(java.net.URL) BeforeMethod(org.testng.annotations.BeforeMethod)

Aggregations

ServiceFactory (loci.common.services.ServiceFactory)94 OMEXMLService (loci.formats.services.OMEXMLService)73 DependencyException (loci.common.services.DependencyException)49 FormatException (loci.formats.FormatException)38 IMetadata (loci.formats.meta.IMetadata)35 ServiceException (loci.common.services.ServiceException)30 ImageReader (loci.formats.ImageReader)23 MissingLibraryException (loci.formats.MissingLibraryException)15 BeforeMethod (org.testng.annotations.BeforeMethod)15 MetadataStore (loci.formats.meta.MetadataStore)14 PositiveInteger (ome.xml.model.primitives.PositiveInteger)14 IOException (java.io.IOException)13 CoreMetadata (loci.formats.CoreMetadata)13 Length (ome.units.quantity.Length)12 Location (loci.common.Location)11 OMEXMLMetadata (loci.formats.ome.OMEXMLMetadata)10 InputStream (java.io.InputStream)9 ArrayList (java.util.ArrayList)8 MetadataRetrieve (loci.formats.meta.MetadataRetrieve)8 BeforeClass (org.testng.annotations.BeforeClass)8