Search in sources :

Example 46 with DependencyException

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

the class MakeTestOmeTiff method createWriter.

private OMETiffWriter createWriter(final String name, final CoreMetadata info, final String id) throws FormatException, IOException {
    final OMETiffWriter out = new OMETiffWriter();
    try {
        out.setMetadataRetrieve(createMetadata(name, info));
    } catch (final DependencyException e) {
        throw new FormatException(e);
    } catch (final ServiceException e) {
        throw new FormatException(e);
    } catch (final EnumerationException e) {
        throw new FormatException(e);
    }
    ensureNonExisting(id);
    out.setId(id);
    return out;
}
Also used : OMETiffWriter(loci.formats.out.OMETiffWriter) ServiceException(loci.common.services.ServiceException) DependencyException(loci.common.services.DependencyException) EnumerationException(ome.xml.model.enums.EnumerationException) FormatException(loci.formats.FormatException)

Example 47 with DependencyException

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

the class EightBitLosslessJPEG2000Test method setUp.

@BeforeMethod
public void setUp() throws Exception {
    for (byte v = Byte.MIN_VALUE; v < Byte.MAX_VALUE; v++) {
        int index = v + Byte.MAX_VALUE + 1;
        pixels[index][0] = v;
        String file = index + ".jp2";
        File tempFile = File.createTempFile("test", ".jp2");
        tempFile.deleteOnExit();
        Location.mapId(file, tempFile.getAbsolutePath());
        files.add(file);
        IMetadata metadata;
        try {
            ServiceFactory factory = new ServiceFactory();
            OMEXMLService service = factory.getInstance(OMEXMLService.class);
            metadata = 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(metadata, 0, "foo", false, "XYCZT", "uint8", 1, 1, 1, 1, 1, 1);
        IFormatWriter writer = new JPEG2000Writer();
        writer.setMetadataRetrieve(metadata);
        writer.setId(file);
        writer.saveBytes(0, pixels[index]);
        writer.close();
    }
}
Also used : IFormatWriter(loci.formats.IFormatWriter) JPEG2000Writer(loci.formats.out.JPEG2000Writer) IMetadata(loci.formats.meta.IMetadata) ServiceException(loci.common.services.ServiceException) ServiceFactory(loci.common.services.ServiceFactory) DependencyException(loci.common.services.DependencyException) File(java.io.File) OMEXMLService(loci.formats.services.OMEXMLService) FormatException(loci.formats.FormatException) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 48 with DependencyException

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

the class LIFReader method initMetadata.

// -- Helper methods --
/**
 * Parses a string of XML and puts the values in a Hashtable.
 */
private void initMetadata(String xml) throws FormatException, IOException {
    try {
        ServiceFactory factory = new ServiceFactory();
        OMEXMLService service = factory.getInstance(OMEXMLService.class);
        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);
    }
    MetadataStore store = makeFilterMetadata();
    // the XML blocks stored in a LIF file are invalid,
    // because they don't have a root node
    xml = "<?xml version=\"1.0\" encoding=\"" + ENCODING + "\"?><LEICA>" + xml + "</LEICA>";
    xml = XMLTools.sanitizeXML(xml);
    LOGGER.trace(xml);
    translateMetadata(getMetadataRoot(xml));
    for (int i = 0; i < imageNames.length; i++) {
        setSeries(i);
        addSeriesMeta("Image name", imageNames[i]);
    }
    setSeries(0);
    // set up mapping to rearrange channels
    // for instance, the green channel may be #0, and the red channel may be #1
    realChannel = new int[tileCount.length][];
    int nextLut = 0;
    for (int i = 0; i < core.size(); i++) {
        int index = getTileIndex(i);
        if (realChannel[index] != null) {
            continue;
        }
        CoreMetadata ms = core.get(i);
        realChannel[index] = new int[ms.sizeC];
        for (int q = 0; q < ms.sizeC; q++) {
            String lut = "";
            if (nextLut < lutNames.size()) {
                lut = lutNames.get(nextLut++).toLowerCase();
            }
            if (!CHANNEL_PRIORITIES.containsKey(lut))
                lut = "";
            realChannel[index][q] = CHANNEL_PRIORITIES.get(lut).intValue();
        }
        int[] sorted = new int[ms.sizeC];
        Arrays.fill(sorted, -1);
        for (int q = 0; q < sorted.length; q++) {
            int min = Integer.MAX_VALUE;
            int minIndex = -1;
            for (int n = 0; n < ms.sizeC; n++) {
                if (realChannel[index][n] < min && !DataTools.containsValue(sorted, n)) {
                    min = realChannel[index][n];
                    minIndex = n;
                }
            }
            sorted[q] = minIndex;
        }
    }
    MetadataTools.populatePixels(store, this, true, false);
    int roiCount = 0;
    for (int i = 0; i < getSeriesCount(); i++) {
        setSeries(i);
        String instrumentID = MetadataTools.createLSID("Instrument", i);
        store.setInstrumentID(instrumentID, i);
        int index = getTileIndex(i);
        store.setMicroscopeModel(microscopeModels[index], i);
        store.setMicroscopeType(getMicroscopeType("Other"), i);
        String objectiveID = MetadataTools.createLSID("Objective", i, 0);
        store.setObjectiveID(objectiveID, i, 0);
        store.setObjectiveLensNA(lensNA[index], i, 0);
        store.setObjectiveSerialNumber(serialNumber[index], i, 0);
        if (magnification[index] != null) {
            store.setObjectiveNominalMagnification(magnification[index], i, 0);
        }
        store.setObjectiveImmersion(getImmersion(immersions[index]), i, 0);
        store.setObjectiveCorrection(getCorrection(corrections[index]), i, 0);
        store.setObjectiveModel(objectiveModels[index], i, 0);
        if (cutIns[index] != null && filterModels[index] != null) {
            int channel = 0;
            if (cutIns[index].size() >= filterModels[index].size() * 2) {
                int diff = cutIns[index].size() - filterModels[index].size();
                for (int q = 0; q < diff; q++) {
                    cutIns[index].remove(filterModels[index].size());
                }
            }
            for (int filter = 0; filter < cutIns[index].size(); filter++) {
                String filterID = MetadataTools.createLSID("Filter", i, filter);
                store.setFilterID(filterID, i, filter);
                if (filterModels[index] != null && filter < filterModels[index].size()) {
                    store.setFilterModel((String) filterModels[index].get(filter), i, filter);
                }
                store.setTransmittanceRangeCutIn((Length) cutIns[index].get(filter), i, filter);
                store.setTransmittanceRangeCutOut((Length) cutOuts[index].get(filter), i, filter);
            }
        }
        final List<Double> lasers = laserWavelength[index];
        final List<Double> laserIntensities = laserIntensity[index];
        final List<Boolean> active = laserActive[index];
        final List<Boolean> frap = laserFrap[index];
        int nextChannel = 0;
        if (lasers != null) {
            int laserIndex = 0;
            while (laserIndex < lasers.size()) {
                if ((Double) lasers.get(laserIndex) == 0) {
                    lasers.remove(laserIndex);
                } else {
                    laserIndex++;
                }
            }
            for (int laser = 0; laser < lasers.size(); laser++) {
                String id = MetadataTools.createLSID("LightSource", i, laser);
                store.setLaserID(id, i, laser);
                store.setLaserType(LaserType.OTHER, i, laser);
                store.setLaserLaserMedium(LaserMedium.OTHER, i, laser);
                Double wavelength = (Double) lasers.get(laser);
                Length wave = FormatTools.getWavelength(wavelength);
                if (wave != null) {
                    store.setLaserWavelength(wave, i, laser);
                }
            }
            Set<Integer> ignoredChannels = new HashSet<Integer>();
            final List<Integer> validIntensities = new ArrayList<Integer>();
            int size = lasers.size();
            int channel = 0;
            Set<Integer> channels = new HashSet<Integer>();
            for (int laser = 0; laser < laserIntensities.size(); laser++) {
                double intensity = (Double) laserIntensities.get(laser);
                channel = laser / size;
                if (intensity < 100) {
                    validIntensities.add(laser);
                    channels.add(channel);
                }
                ignoredChannels.add(channel);
            }
            // remove channels w/o valid intensities
            ignoredChannels.removeAll(channels);
            // remove entries if channel has 2 wavelengths
            // e.g. 30% 458 70% 633
            int s = validIntensities.size();
            int jj;
            Set<Integer> toRemove = new HashSet<Integer>();
            int as = active.size();
            for (int j = 0; j < s; j++) {
                if (j < as && !(Boolean) active.get(j)) {
                    toRemove.add(validIntensities.get(j));
                }
                jj = j + 1;
                if (jj < s) {
                    int v = validIntensities.get(j) / size;
                    int vv = validIntensities.get(jj) / size;
                    if (vv == v) {
                        // do not consider that channel.
                        toRemove.add(validIntensities.get(j));
                        toRemove.add(validIntensities.get(jj));
                        ignoredChannels.add(j);
                    }
                }
            }
            if (toRemove.size() > 0) {
                validIntensities.removeAll(toRemove);
            }
            boolean noNames = true;
            if (channelNames[index] != null) {
                for (String name : channelNames[index]) {
                    if (name != null && !name.equals("")) {
                        noNames = false;
                        break;
                    }
                }
            }
            if (!noNames && frap != null) {
                // only use name for frap.
                for (int k = 0; k < frap.size(); k++) {
                    if (!frap.get(k)) {
                        noNames = true;
                        break;
                    }
                }
            }
            int nextFilter = 0;
            // int nextFilter = cutIns[i].size() - getEffectiveSizeC();
            for (int k = 0; k < validIntensities.size(); k++, nextChannel++) {
                int laserArrayIndex = validIntensities.get(k);
                double intensity = (Double) laserIntensities.get(laserArrayIndex);
                int laser = laserArrayIndex % lasers.size();
                Double wavelength = (Double) lasers.get(laser);
                if (wavelength != 0) {
                    while (ignoredChannels.contains(nextChannel)) {
                        nextChannel++;
                    }
                    while (channelNames != null && nextChannel < getEffectiveSizeC() && channelNames[index] != null && ((channelNames[index][nextChannel] == null || channelNames[index][nextChannel].equals("")) && !noNames)) {
                        nextChannel++;
                    }
                    if (nextChannel < getEffectiveSizeC()) {
                        String id = MetadataTools.createLSID("LightSource", i, laser);
                        store.setChannelLightSourceSettingsID(id, i, nextChannel);
                        store.setChannelLightSourceSettingsAttenuation(new PercentFraction((float) intensity / 100f), i, nextChannel);
                        Length ex = FormatTools.getExcitationWavelength(wavelength);
                        if (ex != null) {
                            store.setChannelExcitationWavelength(ex, i, nextChannel);
                        }
                        if (wavelength > 0) {
                            if (cutIns[index] == null || nextFilter >= cutIns[index].size()) {
                                continue;
                            }
                            Double cutIn = ((Length) cutIns[index].get(nextFilter)).value(UNITS.NANOMETER).doubleValue();
                            while (cutIn - wavelength > 20) {
                                nextFilter++;
                                if (nextFilter < cutIns[index].size()) {
                                    cutIn = ((Length) cutIns[index].get(nextFilter)).value(UNITS.NANOMETER).doubleValue();
                                } else {
                                    break;
                                }
                            }
                            if (nextFilter < cutIns[index].size()) {
                                String fid = MetadataTools.createLSID("Filter", i, nextFilter);
                                // store.setLightPathEmissionFilterRef(fid, i, nextChannel, 0);
                                nextFilter++;
                            }
                        }
                    }
                }
            }
        }
        store.setImageInstrumentRef(instrumentID, i);
        store.setObjectiveSettingsID(objectiveID, i);
        store.setObjectiveSettingsRefractiveIndex(refractiveIndex[index], i);
        store.setImageDescription(descriptions[index], i);
        if (acquiredDate[index] > 0) {
            store.setImageAcquisitionDate(new Timestamp(DateTools.convertDate((long) (acquiredDate[index] * 1000), DateTools.COBOL, DateTools.ISO8601_FORMAT, false)), i);
        }
        store.setImageName(imageNames[index].trim(), i);
        Length sizeX = FormatTools.getPhysicalSizeX(physicalSizeXs.get(index));
        Length sizeY = FormatTools.getPhysicalSizeY(physicalSizeYs.get(index));
        Length sizeZ = FormatTools.getPhysicalSizeZ(zSteps[index]);
        if (sizeX != null) {
            store.setPixelsPhysicalSizeX(sizeX, i);
        }
        if (sizeY != null) {
            store.setPixelsPhysicalSizeY(sizeY, i);
        }
        if (sizeZ != null) {
            store.setPixelsPhysicalSizeZ(sizeZ, i);
        }
        if (tSteps[index] != null) {
            store.setPixelsTimeIncrement(new Time(tSteps[index], UNITS.SECOND), i);
        }
        final List<String> detectors = detectorModels[index];
        if (detectors != null) {
            nextChannel = 0;
            int start = detectors.size() - getEffectiveSizeC();
            if (start < 0) {
                start = 0;
            }
            for (int detector = start; detector < detectors.size(); detector++) {
                int dIndex = detector - start;
                String detectorID = MetadataTools.createLSID("Detector", i, dIndex);
                store.setDetectorID(detectorID, i, dIndex);
                store.setDetectorModel((String) detectors.get(detector), i, dIndex);
                store.setDetectorZoom(zooms[index], i, dIndex);
                store.setDetectorType(DetectorType.PMT, i, dIndex);
                if (activeDetector[index] != null) {
                    int detectorIndex = activeDetector[index].size() - getEffectiveSizeC() + dIndex;
                    if (detectorIndex >= 0 && detectorIndex < activeDetector[index].size() && (Boolean) activeDetector[index].get(detectorIndex) && detectorOffsets[index] != null && nextChannel < detectorOffsets[index].length) {
                        store.setDetectorOffset(detectorOffsets[index][nextChannel++], i, dIndex);
                    }
                }
            }
        }
        final List<Boolean> activeDetectors = activeDetector[index];
        int firstDetector = activeDetectors == null ? 0 : activeDetectors.size() - getEffectiveSizeC();
        int nextDetector = firstDetector;
        int nextFilter = 0;
        int nextFilterDetector = 0;
        if (activeDetectors != null && activeDetectors.size() > cutIns[index].size() && (Boolean) activeDetectors.get(activeDetectors.size() - 1) && (Boolean) activeDetectors.get(activeDetectors.size() - 2)) {
            nextFilterDetector = activeDetectors.size() - cutIns[index].size();
            if (cutIns[index].size() > filterModels[index].size()) {
                nextFilterDetector += filterModels[index].size();
                nextFilter += filterModels[index].size();
            }
        }
        for (int c = 0; c < getEffectiveSizeC(); c++) {
            if (activeDetectors != null) {
                while (nextDetector >= 0 && nextDetector < activeDetectors.size() && !(Boolean) activeDetectors.get(nextDetector)) {
                    nextDetector++;
                }
                if (nextDetector < activeDetectors.size() && detectors != null && nextDetector - firstDetector < detectors.size()) {
                    String detectorID = MetadataTools.createLSID("Detector", i, nextDetector - firstDetector);
                    store.setDetectorSettingsID(detectorID, i, c);
                    nextDetector++;
                    if (detectorOffsets[index] != null && c < detectorOffsets[index].length) {
                        store.setDetectorSettingsOffset(detectorOffsets[index][c], i, c);
                    }
                    if (gains[index] != null) {
                        store.setDetectorSettingsGain(gains[index][c], i, c);
                    }
                }
            }
            if (channelNames[index] != null) {
                store.setChannelName(channelNames[index][c], i, c);
            }
            if (pinholes[index] != null) {
                store.setChannelPinholeSize(new Length(pinholes[index], UNITS.MICROMETER), i, c);
            }
            if (exWaves[index] != null) {
                if (exWaves[index][c] != null && exWaves[index][c] > 1) {
                    Length ex = FormatTools.getExcitationWavelength(exWaves[index][c]);
                    if (ex != null) {
                        store.setChannelExcitationWavelength(ex, i, c);
                    }
                }
            }
            // channel coloring is implicit if the image is stored as RGB
            Color channelColor = getChannelColor(realChannel[index][c]);
            if (!isRGB()) {
                store.setChannelColor(channelColor, i, c);
            }
            if (channelColor.getValue() != -1 && nextFilter >= 0) {
                if (nextDetector - firstDetector != getSizeC() && cutIns[index] != null && nextDetector >= cutIns[index].size()) {
                    while (nextFilterDetector < firstDetector) {
                        String filterID = MetadataTools.createLSID("Filter", i, nextFilter);
                        store.setFilterID(filterID, i, nextFilter);
                        nextFilterDetector++;
                        nextFilter++;
                    }
                }
                while (activeDetectors != null && nextFilterDetector < activeDetectors.size() && !(Boolean) activeDetectors.get(nextFilterDetector)) {
                    String filterID = MetadataTools.createLSID("Filter", i, nextFilter);
                    store.setFilterID(filterID, i, nextFilter);
                    nextFilterDetector++;
                    nextFilter++;
                }
                String filterID = MetadataTools.createLSID("Filter", i, nextFilter);
                store.setFilterID(filterID, i, nextFilter);
                store.setLightPathEmissionFilterRef(filterID, i, c, 0);
                nextFilterDetector++;
                nextFilter++;
            }
        }
        for (int image = 0; image < getImageCount(); image++) {
            Length xPos = posX[index];
            Length yPos = posY[index];
            if (i < fieldPosX.size() && fieldPosX.get(i) != null) {
                xPos = fieldPosX.get(i);
            }
            if (i < fieldPosY.size() && fieldPosY.get(i) != null) {
                yPos = fieldPosY.get(i);
            }
            if (xPos != null) {
                store.setPlanePositionX(xPos, i, image);
            }
            if (yPos != null) {
                store.setPlanePositionY(yPos, i, image);
            }
            store.setPlanePositionZ(posZ[index], i, image);
            if (timestamps[index] != null) {
                if (timestamps[index][image] != null) {
                    double timestamp = timestamps[index][image];
                    if (timestamps[index][0] == acquiredDate[index]) {
                        timestamp -= acquiredDate[index];
                    } else if (timestamp == acquiredDate[index] && image > 0) {
                        timestamp = timestamps[index][0];
                    }
                    store.setPlaneDeltaT(new Time(timestamp, UNITS.SECOND), i, image);
                }
            }
            if (expTimes[index] != null) {
                int c = getZCTCoords(image)[1];
                if (expTimes[index][c] != null) {
                    store.setPlaneExposureTime(new Time(expTimes[index][c], UNITS.SECOND), i, image);
                }
            }
        }
        if (imageROIs[index] != null) {
            for (int roi = 0; roi < imageROIs[index].length; roi++) {
                if (imageROIs[index][roi] != null) {
                    imageROIs[index][roi].storeROI(store, i, roiCount++, roi);
                }
            }
        }
    }
}
Also used : ServiceFactory(loci.common.services.ServiceFactory) ArrayList(java.util.ArrayList) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp) OMEXMLService(loci.formats.services.OMEXMLService) HashSet(java.util.HashSet) Color(ome.xml.model.primitives.Color) DependencyException(loci.common.services.DependencyException) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) ServiceException(loci.common.services.ServiceException) Length(ome.units.quantity.Length) PercentFraction(ome.xml.model.primitives.PercentFraction)

Example 49 with DependencyException

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

the class IPWReader method initPOIService.

private void initPOIService() throws FormatException, IOException {
    try {
        ServiceFactory factory = new ServiceFactory();
        poi = factory.getInstance(POIService.class);
    } catch (DependencyException de) {
        throw new MissingLibraryException("POI library not found", de);
    }
    poi.initialize(Location.getMappedId(getCurrentFile()));
}
Also used : ServiceFactory(loci.common.services.ServiceFactory) POIService(loci.formats.services.POIService) MissingLibraryException(loci.formats.MissingLibraryException) DependencyException(loci.common.services.DependencyException)

Example 50 with DependencyException

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

the class TiledExportExample method main.

public static void main(String[] args) throws Exception {
    if (args.length < 2) {
        System.out.println("Usage: java TiledExportExample <infile> <outfile>");
        System.exit(1);
    }
    ImageReader reader = new ImageReader();
    ImageWriter writer = new ImageWriter();
    IMetadata meta;
    try {
        ServiceFactory factory = new ServiceFactory();
        OMEXMLService service = factory.getInstance(OMEXMLService.class);
        meta = 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(meta);
    reader.setId(args[0]);
    writer.setMetadataRetrieve(meta);
    writer.setId(args[1]);
    for (int series = 0; series < reader.getSeriesCount(); series++) {
        reader.setSeries(series);
        writer.setSeries(series);
        for (int image = 0; image < reader.getImageCount(); image++) {
            for (int row = 0; row < 2; row++) {
                for (int col = 0; col < 2; col++) {
                    int w = reader.getSizeX() / 2;
                    int h = reader.getSizeY() / 2;
                    int x = col * w;
                    int y = row * h;
                    /* debug */
                    System.out.println("[" + x + ", " + y + ", " + w + ", " + h + "]");
                    byte[] buf = reader.openBytes(image, x, y, w, h);
                    writer.saveBytes(image, buf, x, y, w, h);
                }
            }
        }
    }
    reader.close();
    writer.close();
}
Also used : IMetadata(loci.formats.meta.IMetadata) ServiceException(loci.common.services.ServiceException) ServiceFactory(loci.common.services.ServiceFactory) ImageWriter(loci.formats.ImageWriter) ImageReader(loci.formats.ImageReader) DependencyException(loci.common.services.DependencyException) OMEXMLService(loci.formats.services.OMEXMLService) FormatException(loci.formats.FormatException)

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