Search in sources :

Example 31 with DependencyException

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

the class CellWorxReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    if (!checkSuffix(id, "htd")) {
        LOGGER.info("Searching for .htd file");
        String base = new Location(id).getAbsolutePath();
        base = base.substring(0, base.lastIndexOf("_"));
        id = base + ".HTD";
        if (!new Location(id).exists()) {
            Location parent = new Location(id).getAbsoluteFile().getParentFile();
            directoryList = parent.list(true);
            for (String f : directoryList) {
                if (checkSuffix(f, "htd")) {
                    id = new Location(parent, f).getAbsolutePath();
                    LOGGER.info("Found .htd file {}", f);
                    break;
                }
            }
        }
    }
    super.initFile(id);
    try {
        ServiceFactory factory = new ServiceFactory();
        service = factory.getInstance(OMEXMLService.class);
    } catch (DependencyException exc) {
        throw new FormatException("Could not create OME-XML store.", exc);
    }
    String plateData = DataTools.readFile(id);
    String[] lines = plateData.split("\n");
    int xWells = 0, yWells = 0;
    int xFields = 0, yFields = 0;
    String[] wavelengths = null;
    int nTimepoints = 1;
    // determine dataset dimensions
    for (String line : lines) {
        int split = line.indexOf("\",");
        if (split < 1)
            continue;
        String key = line.substring(1, split).trim();
        String value = line.substring(split + 2).trim();
        if (key.equals("XWells")) {
            xWells = Integer.parseInt(value);
        } else if (key.equals("YWells")) {
            yWells = Integer.parseInt(value);
            wellFiles = new String[yWells][xWells][];
            logFiles = new String[yWells][xWells];
        } else if (key.startsWith("WellsSelection")) {
            int row = Integer.parseInt(key.substring(14)) - 1;
            String[] mapping = value.split(",");
            for (int col = 0; col < xWells; col++) {
                if (new Boolean(mapping[col].trim()).booleanValue()) {
                    wellFiles[row][col] = new String[1];
                }
            }
        } else if (key.equals("XSites")) {
            xFields = Integer.parseInt(value);
        } else if (key.equals("YSites")) {
            yFields = Integer.parseInt(value);
            fieldMap = new boolean[yFields][xFields];
        } else if (key.equals("TimePoints")) {
            nTimepoints = Integer.parseInt(value);
        } else if (key.startsWith("SiteSelection")) {
            int row = Integer.parseInt(key.substring(13)) - 1;
            String[] mapping = value.split(",");
            for (int col = 0; col < xFields; col++) {
                fieldMap[row][col] = new Boolean(mapping[col].trim()).booleanValue();
            }
        } else if (key.equals("Waves")) {
            doChannels = new Boolean(value.toLowerCase());
        } else if (key.equals("NWavelengths")) {
            wavelengths = new String[Integer.parseInt(value)];
        } else if (key.startsWith("WaveName")) {
            int index = Integer.parseInt(key.substring(8)) - 1;
            wavelengths[index] = value.replaceAll("\"", "");
        }
    }
    for (int row = 0; row < fieldMap.length; row++) {
        for (int col = 0; col < fieldMap[row].length; col++) {
            if (fieldMap[row][col])
                fieldCount++;
        }
    }
    // find pixels files
    String plateName = new Location(id).getAbsolutePath();
    plateName = plateName.substring(0, plateName.lastIndexOf(".")) + "_";
    int wellCount = 0;
    for (int row = 0; row < wellFiles.length; row++) {
        for (int col = 0; col < wellFiles[row].length; col++) {
            if (wellFiles[row][col] != null) {
                wellCount++;
                char rowLetter = (char) (row + 'A');
                String base = plateName + rowLetter + String.format("%02d", col + 1);
                wellFiles[row][col][0] = base + ".pnl";
                logFiles[row][col] = base + "_scan.log";
                if (!new Location(wellFiles[row][col][0]).exists()) {
                    // using TIFF files instead
                    wellFiles[row][col] = getTiffFiles(plateName, rowLetter, col, wavelengths.length, nTimepoints);
                }
            }
        }
    }
    plateLogFile = plateName + "scan.log";
    String serialNumber = null;
    if (new Location(plateLogFile).exists()) {
        String[] f = DataTools.readFile(plateLogFile).split("\n");
        for (String line : f) {
            if (line.trim().startsWith("Z Map File")) {
                String file = line.substring(line.indexOf(':') + 1);
                file = file.substring(file.lastIndexOf("/") + 1).trim();
                String parent = new Location(id).getAbsoluteFile().getParent();
                zMapFile = new Location(parent, file).getAbsolutePath();
            } else if (line.trim().startsWith("Scanner SN")) {
                serialNumber = line.substring(line.indexOf(':') + 1).trim();
            }
        }
    }
    int seriesCount = fieldCount * wellCount;
    int planeIndex = 0;
    int seriesIndex = 0;
    String file = getFile(seriesIndex, planeIndex);
    while (!new Location(file).exists()) {
        if (planeIndex < nTimepoints * wavelengths.length) {
            planeIndex++;
        } else if (seriesIndex < seriesCount - 1) {
            planeIndex = 0;
            seriesIndex++;
        } else {
            break;
        }
        file = getFile(seriesIndex, planeIndex);
    }
    IFormatReader pnl = getReader(file, true);
    core.clear();
    for (int i = 0; i < seriesCount; i++) {
        CoreMetadata ms = new CoreMetadata();
        core.add(ms);
        setSeries(i);
        ms.littleEndian = pnl.isLittleEndian();
        ms.sizeX = pnl.getSizeX();
        ms.sizeY = pnl.getSizeY();
        ms.pixelType = pnl.getPixelType();
        ms.sizeZ = 1;
        ms.sizeT = nTimepoints;
        ms.sizeC = wavelengths.length;
        ms.imageCount = getSizeZ() * getSizeC() * getSizeT();
        ms.dimensionOrder = "XYCZT";
        ms.rgb = false;
        ms.interleaved = pnl.isInterleaved();
    }
    OMEXMLMetadata readerMetadata = (OMEXMLMetadata) pnl.getMetadataStore();
    OMEXMLMetadataRoot root = (OMEXMLMetadataRoot) readerMetadata.getRoot();
    Instrument instrument = root.getInstrument(0);
    List<Image> images = root.copyImageList();
    OMEXMLMetadataRoot convertRoot = new OMEXMLMetadataRoot();
    convertRoot.addInstrument(instrument);
    for (int i = 0; i < core.size() / images.size(); i++) {
        for (Image img : images) {
            convertRoot.addImage(img);
        }
    }
    OMEXMLMetadata convertMetadata;
    try {
        convertMetadata = service.createOMEXMLMetadata();
    } catch (ServiceException exc) {
        throw new FormatException("Could not create OME-XML store.", exc);
    }
    convertMetadata.setRoot(convertRoot);
    pnl.close();
    MetadataStore store = makeFilterMetadata();
    MetadataConverter.convertMetadata(convertMetadata, store);
    MetadataTools.populatePixels(store, this);
    String plateID = MetadataTools.createLSID("Plate", 0);
    Location plate = new Location(id).getAbsoluteFile();
    store.setPlateID(plateID, 0);
    plateName = plate.getName();
    if (plateName.indexOf('.') > 0) {
        plateName = plateName.substring(0, plateName.lastIndexOf('.'));
    }
    store.setPlateName(plateName, 0);
    store.setPlateRows(new PositiveInteger(wellFiles.length), 0);
    store.setPlateColumns(new PositiveInteger(wellFiles[0].length), 0);
    for (int i = 0; i < core.size(); i++) {
        store.setImageID(MetadataTools.createLSID("Image", i), i);
    }
    String plateAcqID = MetadataTools.createLSID("PlateAcquisition", 0, 0);
    store.setPlateAcquisitionID(plateAcqID, 0, 0);
    PositiveInteger fieldCount = FormatTools.getMaxFieldCount(fieldMap.length * fieldMap[0].length);
    if (fieldCount != null) {
        store.setPlateAcquisitionMaximumFieldCount(fieldCount, 0, 0);
    }
    int nextImage = 0;
    for (int row = 0; row < wellFiles.length; row++) {
        for (int col = 0; col < wellFiles[row].length; col++) {
            int wellIndex = row * wellFiles[row].length + col;
            String wellID = MetadataTools.createLSID("Well", 0, wellIndex);
            store.setWellID(wellID, 0, wellIndex);
            store.setWellColumn(new NonNegativeInteger(col), 0, wellIndex);
            store.setWellRow(new NonNegativeInteger(row), 0, wellIndex);
            int fieldIndex = 0;
            for (int fieldRow = 0; fieldRow < fieldMap.length; fieldRow++) {
                for (int fieldCol = 0; fieldCol < fieldMap[fieldRow].length; fieldCol++) {
                    if (fieldMap[fieldRow][fieldCol] && wellFiles[row][col] != null) {
                        String wellSampleID = MetadataTools.createLSID("WellSample", 0, wellIndex, fieldIndex);
                        store.setWellSampleID(wellSampleID, 0, wellIndex, fieldIndex);
                        String imageID = MetadataTools.createLSID("Image", nextImage);
                        store.setWellSampleImageRef(imageID, 0, wellIndex, fieldIndex);
                        store.setWellSampleIndex(new NonNegativeInteger(nextImage), 0, wellIndex, fieldIndex);
                        store.setPlateAcquisitionWellSampleRef(wellSampleID, 0, 0, nextImage);
                        String well = (char) (row + 'A') + String.format("%02d", col + 1);
                        store.setImageName("Well " + well + " Field #" + (fieldIndex + 1), nextImage);
                        nextImage++;
                        fieldIndex++;
                    }
                }
            }
        }
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        if (serialNumber != null) {
            store.setMicroscopeSerialNumber(serialNumber, 0);
        }
        for (int well = 0; well < wellCount; well++) {
            parseWellLogFile(well, store);
        }
        if (timestamps.size() > 0) {
            store.setPlateAcquisitionStartTime(timestamps.get(0), 0, 0);
            store.setPlateAcquisitionEndTime(timestamps.get(timestamps.size() - 1), 0, 0);
        }
        for (int i = 0; i < core.size(); i++) {
            for (int c = 0; c < getSizeC(); c++) {
                if (c < wavelengths.length && wavelengths[c] != null) {
                    store.setChannelName(wavelengths[c], i, c);
                }
            }
        }
    }
}
Also used : PositiveInteger(ome.xml.model.primitives.PositiveInteger) IFormatReader(loci.formats.IFormatReader) ServiceFactory(loci.common.services.ServiceFactory) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) DependencyException(loci.common.services.DependencyException) Image(ome.xml.model.Image) CoreMetadata(loci.formats.CoreMetadata) OMEXMLService(loci.formats.services.OMEXMLService) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) ServiceException(loci.common.services.ServiceException) OMEXMLMetadata(loci.formats.ome.OMEXMLMetadata) OMEXMLMetadataRoot(ome.xml.meta.OMEXMLMetadataRoot) Instrument(ome.xml.model.Instrument) Location(loci.common.Location)

Example 32 with DependencyException

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

the class PlugInBioFormatsImporter method readImage.

public void readImage() {
    final ViewUserInterface mipav = ViewUserInterface.getReference();
    // prompt user to choose a file
    if (chooser == null) {
        chooser = GUITools.buildFileChooser(reader);
        chooser.setCurrentDirectory(new File(Preferences.getImageDirectory()));
    }
    JFrame parent = mipav.getMainFrame();
    int rval = chooser.showOpenDialog(parent);
    // user canceled
    if (rval != JFileChooser.APPROVE_OPTION)
        return;
    final File file = chooser.getSelectedFile();
    // load the image in a separate thread
    Thread importerThread = new Thread("BioFormats-Importer") {

        public void run() {
            String name = file.getName();
            String dir = file.getParent();
            // open file using Bio-Formats
            setMessage(mipav, "Importing " + name + "...", true);
            String id = file.getPath();
            try {
                long tic = System.currentTimeMillis();
                IMetadata store;
                try {
                    ServiceFactory factory = new ServiceFactory();
                    OMEXMLService service = factory.getInstance(OMEXMLService.class);
                    store = service.createOMEXMLMetadata();
                } catch (DependencyException exc) {
                    throw new FormatException("Could not create OME-XML store.", exc);
                } catch (ServiceException exc) {
                    throw new FormatException("Could not create OME-XML store.", exc);
                }
                reader.setMetadataStore(store);
                reader.setId(id);
                // MIPAV assumes 4-D data in XYZT order
                reader.setOutputOrder("XYZTC");
                // harvest some core metadata
                int imageCount = reader.getImageCount();
                boolean little = reader.isLittleEndian();
                int pixelType = reader.getPixelType();
                int bpp = FormatTools.getBytesPerPixel(pixelType);
                boolean floating = FormatTools.isFloatingPoint(pixelType);
                int sizeX = reader.getSizeX();
                int sizeY = reader.getSizeY();
                int sizeZ = reader.getSizeZ();
                int sizeT = reader.getSizeT();
                int sizeC = reader.getSizeC();
                String imageName = store.getImageName(0);
                if (sizeC > 1) {
                    throw new FormatException("Multichannel data is unsupported at the moment");
                }
                // compute MIPAV buffer type
                int mipavType;
                switch(pixelType) {
                    case FormatTools.INT8:
                        mipavType = ModelStorageBase.BYTE;
                        break;
                    case FormatTools.UINT8:
                        mipavType = ModelStorageBase.UBYTE;
                        break;
                    case FormatTools.INT16:
                        mipavType = ModelStorageBase.SHORT;
                        break;
                    case FormatTools.UINT16:
                        mipavType = ModelStorageBase.USHORT;
                        break;
                    case FormatTools.INT32:
                        mipavType = ModelStorageBase.INTEGER;
                        break;
                    case FormatTools.UINT32:
                        mipavType = ModelStorageBase.UINTEGER;
                        break;
                    case FormatTools.FLOAT:
                        mipavType = ModelStorageBase.FLOAT;
                        break;
                    case FormatTools.DOUBLE:
                        mipavType = ModelStorageBase.DOUBLE;
                        break;
                    default:
                        throw new FormatException("Unsupported pixel type: " + pixelType);
                }
                // harvest physical resolution
                Length dimPhysSizeX = store.getPixelsPhysicalSizeX(0);
                Length dimPhysSizeY = store.getPixelsPhysicalSizeY(0);
                Length dimPhysSizeZ = store.getPixelsPhysicalSizeZ(0);
                Time dimTimeInc = store.getPixelsTimeIncrement(0);
                float physSizeX = dimPhysSizeX == null ? 1.0f : dimPhysSizeX.value(UNITS.MICROMETER).floatValue();
                float physSizeY = dimPhysSizeY == null ? 1.0f : dimPhysSizeY.value(UNITS.MICROMETER).floatValue();
                float physSizeZ = dimPhysSizeZ == null ? 1.0f : dimPhysSizeZ.value(UNITS.MICROMETER).floatValue();
                float timeInc = dimTimeInc == null ? 1.0f : dimTimeInc.value(UNITS.SECOND).floatValue();
                // compute dimensional extents
                int[] dimExtents = { sizeX, sizeY, sizeZ, sizeT };
                float[] res = { physSizeX, physSizeY, physSizeZ, timeInc };
                int[] units = { FileInfoBase.MICROMETERS, FileInfoBase.MICROMETERS, FileInfoBase.MICROMETERS, FileInfoBase.SECONDS };
                // create MIPAV image object
                ModelImage modelImage = new ModelImage(mipavType, dimExtents, imageName);
                // import planes into MIPAV image
                byte[] buf = new byte[bpp * sizeX * sizeY];
                for (int i = 0; i < imageCount; i++) {
                    setMessage(mipav, "Reading plane #" + (i + 1) + "/" + imageCount, false);
                    reader.openBytes(i, buf);
                    // convert byte array to appropriate primitive type
                    int offset = i * buf.length;
                    Object array = DataTools.makeDataArray(buf, bpp, floating, little);
                    // assign data to MIPAV image object
                    switch(mipavType) {
                        case ModelStorageBase.BYTE:
                        case ModelStorageBase.UBYTE:
                            modelImage.importData(offset, (byte[]) array, false);
                            break;
                        case ModelStorageBase.SHORT:
                        case ModelStorageBase.USHORT:
                            modelImage.importData(offset, (short[]) array, false);
                            break;
                        case ModelStorageBase.INTEGER:
                        case ModelStorageBase.UINTEGER:
                            modelImage.importData(offset, (int[]) array, false);
                            break;
                        case ModelStorageBase.FLOAT:
                            modelImage.importData(offset, (float[]) array, false);
                            break;
                        case ModelStorageBase.DOUBLE:
                            modelImage.importData(offset, (double[]) array, false);
                            break;
                        default:
                            throw new FormatException("Unknown buffer type: " + mipavType);
                    }
                }
                setMessage(mipav, "Finishing import...", true);
                // create a FileInfo object for each image plane
                FileInfoBase[] fileInfo = new FileInfoBase[imageCount];
                for (int i = 0; i < imageCount; i++) {
                    // HACK: Use FileInfoImageXML since FileInfoBase is abstract.
                    fileInfo[i] = new FileInfoImageXML(name, dir, FileUtility.XML);
                    fileInfo[i].setExtents(dimExtents);
                    fileInfo[i].setResolutions(res);
                    fileInfo[i].setUnitsOfMeasure(units);
                    fileInfo[i].setDataType(mipavType);
                }
                modelImage.setFileInfo(fileInfo);
                // scale color range and display MIPAV image
                modelImage.calcMinMax();
                new ViewJFrameImage(modelImage);
                long toc = System.currentTimeMillis();
                long time = toc - tic;
                long avg = time / imageCount;
                setMessage(mipav, name + ": Read " + imageCount + " planes in " + (time / 1000f) + " seconds (" + avg + " ms/plane)", true);
            } catch (FormatException exc) {
                exc.printStackTrace();
                MipavUtil.displayError("An error occurred parsing the file: " + exc.getMessage());
            } catch (IOException exc) {
                exc.printStackTrace();
                MipavUtil.displayError("An I/O error occurred reading the file: " + exc.getMessage());
            }
        }
    };
    importerThread.start();
}
Also used : ModelImage(gov.nih.mipav.model.structures.ModelImage) ServiceFactory(loci.common.services.ServiceFactory) Time(ome.units.quantity.Time) OMEXMLService(loci.formats.services.OMEXMLService) FileInfoBase(gov.nih.mipav.model.file.FileInfoBase) IMetadata(loci.formats.meta.IMetadata) JFrame(javax.swing.JFrame) ViewUserInterface(gov.nih.mipav.view.ViewUserInterface) FileInfoImageXML(gov.nih.mipav.model.file.FileInfoImageXML) IOException(java.io.IOException) DependencyException(loci.common.services.DependencyException) FormatException(loci.formats.FormatException) ServiceException(loci.common.services.ServiceException) ViewJFrameImage(gov.nih.mipav.view.ViewJFrameImage) Length(ome.units.quantity.Length) File(java.io.File) PlugInFile(gov.nih.mipav.plugins.PlugInFile)

Example 33 with DependencyException

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

the class SixteenBitLosslessJPEG2000Test method testLosslessPixels.

@Test
public void testLosslessPixels() throws Exception {
    int failureCount = 0;
    for (int v = Short.MIN_VALUE; v < Short.MAX_VALUE; v += increment) {
        int index = v + Short.MAX_VALUE + 1;
        byte[] pixels = DataTools.shortToBytes((short) v, false);
        String file = index + ".jp2";
        ByteArrayHandle tmpFile = new ByteArrayHandle(1);
        Location.mapFile(file, tmpFile);
        IMetadata metadata16;
        try {
            ServiceFactory factory = new ServiceFactory();
            OMEXMLService service = factory.getInstance(OMEXMLService.class);
            metadata16 = service.createOMEXMLMetadata();
        } catch (DependencyException exc) {
            throw new FormatException("Could not create OME-XML store.", exc);
        } catch (ServiceException exc) {
            throw new FormatException("Could not create OME-XML store.", exc);
        }
        MetadataTools.populateMetadata(metadata16, 0, "foo", false, "XYCZT", "uint16", 1, 1, 1, 1, 1, 1);
        IFormatWriter writer16 = new JPEG2000Writer();
        writer16.setMetadataRetrieve(metadata16);
        writer16.setId(file);
        writer16.saveBytes(0, pixels);
        writer16.close();
        byte[] buf = tmpFile.getBytes();
        byte[] realData = new byte[(int) tmpFile.length()];
        System.arraycopy(buf, 0, realData, 0, realData.length);
        tmpFile.close();
        tmpFile = new ByteArrayHandle(realData);
        Location.mapFile(file, tmpFile);
        ImageReader reader = new ImageReader();
        reader.setId(file);
        byte[] plane = reader.openBytes(0);
        for (int q = 0; q < plane.length; q++) {
            if (plane[q] != pixels[q]) {
                LOGGER.debug("FAILED on {}", DataTools.bytesToShort(pixels, false));
                failureCount++;
                break;
            }
        }
        reader.close();
        tmpFile.close();
        Location.mapFile(file, null);
    }
    assertEquals(failureCount, 0);
}
Also used : JPEG2000Writer(loci.formats.out.JPEG2000Writer) ServiceFactory(loci.common.services.ServiceFactory) DependencyException(loci.common.services.DependencyException) OMEXMLService(loci.formats.services.OMEXMLService) FormatException(loci.formats.FormatException) IFormatWriter(loci.formats.IFormatWriter) IMetadata(loci.formats.meta.IMetadata) ServiceException(loci.common.services.ServiceException) ByteArrayHandle(loci.common.ByteArrayHandle) ImageReader(loci.formats.ImageReader) Test(org.testng.annotations.Test)

Example 34 with DependencyException

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

the class JPEGXRCodec method initialize.

// -- Helper methods --
/**
 * Initializes the JPEG-XR dependency service. This is called at the
 * beginning of the {@link #decompress} method to avoid having the
 * constructor's method definition contain a checked exception.
 *
 * @throws FormatException If there is an error initializing JPEG-XR
 * services.
 */
private void initialize() throws FormatException {
    if (service != null)
        return;
    try {
        ServiceFactory factory = new ServiceFactory();
        service = factory.getInstance(JPEGXRService.class);
    } catch (DependencyException e) {
        throw new MissingLibraryException("JPEG-XR library not available", e);
    }
}
Also used : ServiceFactory(loci.common.services.ServiceFactory) MissingLibraryException(loci.formats.MissingLibraryException) JPEGXRService(loci.formats.services.JPEGXRService) DependencyException(loci.common.services.DependencyException)

Example 35 with DependencyException

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

the class APLReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    LOGGER.debug("Initializing {}", id);
    // find the corresponding .mtb file
    if (!checkSuffix(id, "mtb")) {
        if (checkSuffix(id, METADATA_SUFFIXES)) {
            int separator = id.lastIndexOf(File.separator);
            if (separator < 0)
                separator = 0;
            int underscore = id.lastIndexOf("_");
            if (underscore < separator || checkSuffix(id, "apl")) {
                underscore = id.lastIndexOf(".");
            }
            String mtbFile = id.substring(0, underscore) + "_d.mtb";
            if (!new Location(mtbFile).exists()) {
                throw new FormatException(".mtb file not found");
            }
            currentId = new Location(mtbFile).getAbsolutePath();
        } else {
            Location parent = new Location(id).getAbsoluteFile().getParentFile();
            parent = parent.getParentFile();
            String[] list = parent.list(true);
            for (String f : list) {
                if (checkSuffix(f, "mtb")) {
                    currentId = new Location(parent, f).getAbsolutePath();
                    break;
                }
            }
            if (!checkSuffix(currentId, "mtb")) {
                throw new FormatException(".mtb file not found");
            }
        }
    }
    String mtb = new Location(currentId).getAbsolutePath();
    LOGGER.debug("Reading .mtb file '{}'", mtb);
    MDBService mdb = null;
    try {
        ServiceFactory factory = new ServiceFactory();
        mdb = factory.getInstance(MDBService.class);
    } catch (DependencyException de) {
        throw new FormatException("MDB Tools Java library not found", de);
    }
    String[] columnNames = null;
    List<String[]> rows = null;
    try {
        mdb.initialize(mtb);
        rows = mdb.parseDatabase().get(0);
        columnNames = rows.get(0);
        String[] tmpNames = columnNames;
        columnNames = new String[tmpNames.length - 1];
        System.arraycopy(tmpNames, 1, columnNames, 0, columnNames.length);
    } finally {
        mdb.close();
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        for (int i = 1; i < rows.size(); i++) {
            String[] row = rows.get(i);
            for (int q = 0; q < row.length; q++) {
                addGlobalMetaList(columnNames[q], row[q]);
            }
        }
    }
    used = new ArrayList<String>();
    used.add(mtb);
    String tnb = mtb.substring(0, mtb.lastIndexOf("."));
    if (tnb.lastIndexOf("_") > tnb.lastIndexOf(File.separator)) {
        tnb = tnb.substring(0, tnb.lastIndexOf("_"));
    }
    used.add(tnb + "_1.tnb");
    used.add(tnb + ".apl");
    String idPath = new Location(id).getAbsolutePath();
    if (!used.contains(idPath) && checkSuffix(idPath, METADATA_SUFFIXES)) {
        used.add(idPath);
    }
    // calculate indexes to relevant metadata
    int calibrationUnit = DataTools.indexOf(columnNames, "Calibration Unit");
    int colorChannels = DataTools.indexOf(columnNames, "Color Channels");
    int frames = DataTools.indexOf(columnNames, "Frames");
    int calibratedHeight = DataTools.indexOf(columnNames, "Height");
    int calibratedWidth = DataTools.indexOf(columnNames, "Width");
    int path = DataTools.indexOf(columnNames, "Image Path");
    if (path == -1) {
        path = DataTools.indexOf(columnNames, "Path");
    }
    int filename = DataTools.indexOf(columnNames, "File Name");
    int magnification = DataTools.indexOf(columnNames, "Magnification");
    int width = DataTools.indexOf(columnNames, "X-Resolution");
    int height = DataTools.indexOf(columnNames, "Y-Resolution");
    int imageType = DataTools.indexOf(columnNames, "Image Type");
    int imageName = DataTools.indexOf(columnNames, "Image Name");
    int zLayers = DataTools.indexOf(columnNames, "Z-Layers");
    String parentDirectory = mtb.substring(0, mtb.lastIndexOf(File.separator));
    // look for the directory that contains TIFF and XML files
    LOGGER.debug("Searching {} for a directory with TIFFs", parentDirectory);
    Location dir = new Location(parentDirectory);
    String topDirectory = null;
    int index = 2;
    String pathName = rows.get(index++)[path].trim();
    while (pathName.equals("") && index < rows.size()) {
        pathName = rows.get(index++)[path].trim();
    }
    pathName = pathName.replace('\\', File.separatorChar);
    pathName = pathName.replaceAll("/", File.separator);
    String[] dirs = pathName.split(File.separatorChar == '\\' ? "\\\\" : File.separator);
    for (int i = dirs.length - 1; i >= 0; i--) {
        if (dirs[i].indexOf("_DocumentFiles") > 0) {
            Location file = new Location(dir, dirs[i]);
            if (file.exists()) {
                topDirectory = file.getAbsolutePath();
                break;
            }
        }
    }
    if (topDirectory == null) {
        String[] list = dir.list();
        for (String f : list) {
            LOGGER.debug("  '{}'", f);
            Location file = new Location(dir, f);
            if (file.isDirectory() && f.indexOf("_DocumentFiles") > 0) {
                topDirectory = file.getAbsolutePath();
                LOGGER.debug("Found {}", topDirectory);
                break;
            }
        }
    }
    if (topDirectory == null) {
        throw new FormatException("Could not find a directory with TIFF files.");
    }
    final List<Integer> seriesIndexes = new ArrayList<Integer>();
    for (int i = 1; i < rows.size(); i++) {
        String file = parseFilename(rows.get(i), filename, path);
        if (file.equals(""))
            continue;
        file = topDirectory + File.separator + file;
        if (new Location(file).exists() && checkSuffix(file, "tif")) {
            seriesIndexes.add(i);
        }
    }
    int seriesCount = seriesIndexes.size();
    core.clear();
    tiffFiles = new String[seriesCount];
    xmlFiles = new String[seriesCount];
    parser = new TiffParser[seriesCount];
    ifds = new IFDList[seriesCount];
    for (int i = 0; i < seriesCount; i++) {
        CoreMetadata ms = new CoreMetadata();
        core.add(ms);
        int secondRow = seriesIndexes.get(i);
        int firstRow = secondRow - 1;
        String[] row2 = rows.get(firstRow);
        String[] row3 = rows.get(secondRow);
        if (frames > -1) {
            ms.sizeT = parseDimension(row3[frames]);
        }
        if (zLayers > -1) {
            ms.sizeZ = parseDimension(row3[zLayers]);
        }
        if (colorChannels > -1) {
            ms.sizeC = parseDimension(row3[colorChannels]);
        } else if (imageType > -1) {
            if (row3[imageType] != null && row3[imageType].equals("RGB")) {
                ms.sizeC = 3;
            }
        }
        ms.dimensionOrder = "XYCZT";
        if (ms.sizeZ == 0)
            ms.sizeZ = 1;
        if (ms.sizeC == 0)
            ms.sizeC = 1;
        if (ms.sizeT == 0)
            ms.sizeT = 1;
        xmlFiles[i] = topDirectory + File.separator + parseFilename(row2, filename, path);
        tiffFiles[i] = topDirectory + File.separator + parseFilename(row3, filename, path);
        parser[i] = new TiffParser(tiffFiles[i]);
        parser[i].setDoCaching(false);
        ifds[i] = parser[i].getIFDs();
        for (IFD ifd : ifds[i]) {
            parser[i].fillInIFD(ifd);
        }
        // get core metadata from TIFF file
        IFD ifd = ifds[i].get(0);
        PhotoInterp photo = ifd.getPhotometricInterpretation();
        int samples = ifd.getSamplesPerPixel();
        ms.sizeX = (int) ifd.getImageWidth();
        ms.sizeY = (int) ifd.getImageLength();
        ms.rgb = samples > 1 || photo == PhotoInterp.RGB;
        ms.pixelType = ifd.getPixelType();
        ms.littleEndian = ifd.isLittleEndian();
        ms.indexed = photo == PhotoInterp.RGB_PALETTE && ifd.containsKey(IFD.COLOR_MAP);
        ms.imageCount = ifds[i].size();
        if (ms.sizeZ * ms.sizeT * (ms.rgb ? 1 : ms.sizeC) != ms.imageCount) {
            ms.sizeT = ms.imageCount / (ms.rgb ? 1 : ms.sizeC);
            ms.sizeZ = 1;
        }
    }
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
    for (int i = 0; i < seriesCount; i++) {
        String[] row = rows.get(seriesIndexes.get(i));
        // populate Image data
        MetadataTools.setDefaultCreationDate(store, mtb, i);
        store.setImageName(row[imageName].trim(), i);
        if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
            // populate Dimensions data
            // calculate physical X and Y sizes
            double realWidth = Double.parseDouble(row[calibratedWidth]);
            double realHeight = Double.parseDouble(row[calibratedHeight]);
            String units = row[calibrationUnit];
            CoreMetadata ms = core.get(i);
            double px = realWidth / ms.sizeX;
            double py = realHeight / ms.sizeY;
            Length physicalSizeX = FormatTools.getPhysicalSizeX(px, units);
            Length physicalSizeY = FormatTools.getPhysicalSizeY(py, units);
            if (physicalSizeX != null) {
                store.setPixelsPhysicalSizeX(physicalSizeX, i);
            }
            if (physicalSizeY != null) {
                store.setPixelsPhysicalSizeY(physicalSizeY, i);
            }
        }
    }
    setSeries(0);
}
Also used : MDBService(loci.formats.services.MDBService) ServiceFactory(loci.common.services.ServiceFactory) IFD(loci.formats.tiff.IFD) ArrayList(java.util.ArrayList) PhotoInterp(loci.formats.tiff.PhotoInterp) DependencyException(loci.common.services.DependencyException) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) TiffParser(loci.formats.tiff.TiffParser) Location(loci.common.Location)

Aggregations

DependencyException (loci.common.services.DependencyException)51 ServiceFactory (loci.common.services.ServiceFactory)49 FormatException (loci.formats.FormatException)39 ServiceException (loci.common.services.ServiceException)32 OMEXMLService (loci.formats.services.OMEXMLService)32 MissingLibraryException (loci.formats.MissingLibraryException)15 MetadataStore (loci.formats.meta.MetadataStore)14 CoreMetadata (loci.formats.CoreMetadata)13 IMetadata (loci.formats.meta.IMetadata)13 IOException (java.io.IOException)12 Location (loci.common.Location)10 ImageReader (loci.formats.ImageReader)10 Length (ome.units.quantity.Length)10 PositiveInteger (ome.xml.model.primitives.PositiveInteger)9 OMEXMLMetadata (loci.formats.ome.OMEXMLMetadata)8 ArrayList (java.util.ArrayList)7 MetadataRetrieve (loci.formats.meta.MetadataRetrieve)6 EnumerationException (ome.xml.model.enums.EnumerationException)6 File (java.io.File)5 IFormatWriter (loci.formats.IFormatWriter)5