use of loci.common.services.ServiceFactory 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);
}
}
}
}
}
use of loci.common.services.ServiceFactory 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()));
}
use of loci.common.services.ServiceFactory in project bioformats by openmicroscopy.
the class TiffWriterTest method parse.
@Parameters({ "id" })
@BeforeClass
public void parse(String id) throws Exception {
ServiceFactory factory = new ServiceFactory();
service = factory.getInstance(OMEXMLService.class);
metadata = service.createOMEXMLMetadata();
reader = new ImageReader();
reader.setMetadataStore(metadata);
reader.setId(id);
}
use of loci.common.services.ServiceFactory in project bioformats by openmicroscopy.
the class ReadWriteInMemory method main.
public static void main(String[] args) throws DependencyException, FormatException, IOException, ServiceException {
if (args.length < 1) {
System.out.println("Please specify a (small) image file.");
System.exit(1);
}
String path = args[0];
/* file-read-start */
// read in entire file
System.out.println("Reading file into memory from disk...");
File inputFile = new File(path);
int fileSize = (int) inputFile.length();
DataInputStream in = new DataInputStream(new FileInputStream(inputFile));
byte[] inBytes = new byte[fileSize];
in.readFully(inBytes);
System.out.println(fileSize + " bytes read.");
/* file-read-end */
/* mapping-start */
// determine input file suffix
String fileName = inputFile.getName();
int dot = fileName.lastIndexOf(".");
String suffix = dot < 0 ? "" : fileName.substring(dot);
// map input id string to input byte array
String inId = "inBytes" + suffix;
Location.mapFile(inId, new ByteArrayHandle(inBytes));
/* mapping-end */
// read data from byte array using ImageReader
System.out.println();
System.out.println("Reading image data from memory...");
/* read-start */
ServiceFactory factory = new ServiceFactory();
OMEXMLService service = factory.getInstance(OMEXMLService.class);
IMetadata omeMeta = service.createOMEXMLMetadata();
ImageReader reader = new ImageReader();
reader.setMetadataStore(omeMeta);
reader.setId(inId);
/* read-end */
int seriesCount = reader.getSeriesCount();
int imageCount = reader.getImageCount();
int sizeX = reader.getSizeX();
int sizeY = reader.getSizeY();
int sizeZ = reader.getSizeZ();
int sizeC = reader.getSizeC();
int sizeT = reader.getSizeT();
// output some details
System.out.println("Series count: " + seriesCount);
System.out.println("First series:");
System.out.println("\tImage count = " + imageCount);
System.out.println("\tSizeX = " + sizeX);
System.out.println("\tSizeY = " + sizeY);
System.out.println("\tSizeZ = " + sizeZ);
System.out.println("\tSizeC = " + sizeC);
System.out.println("\tSizeT = " + sizeT);
/* out—mapping-start */
// map output id string to output byte array
String outId = fileName + ".ome.tif";
ByteArrayHandle outputFile = new ByteArrayHandle();
Location.mapFile(outId, outputFile);
/* out—mapping-end */
/* write—init-start */
// write data to byte array using ImageWriter
System.out.println();
System.out.print("Writing planes to destination in memory: ");
ImageWriter writer = new ImageWriter();
writer.setMetadataRetrieve(omeMeta);
writer.setId(outId);
/* write—init-end */
/* write-start */
byte[] plane = null;
for (int i = 0; i < imageCount; i++) {
if (plane == null) {
// allow reader to allocate a new byte array
plane = reader.openBytes(i);
} else {
// reuse previously allocated byte array
reader.openBytes(i, plane);
}
writer.saveBytes(i, plane);
System.out.print(".");
}
reader.close();
writer.close();
System.out.println();
byte[] outBytes = outputFile.getBytes();
outputFile.close();
/* write-end */
/* flush-start */
// flush output byte array to disk
System.out.println();
System.out.println("Flushing image data to disk...");
File outFile = new File(fileName + ".ome.tif");
DataOutputStream out = new DataOutputStream(new FileOutputStream(outFile));
out.write(outBytes);
out.close();
/* flush-end */
}
use of loci.common.services.ServiceFactory in project bioformats by openmicroscopy.
the class TiledReaderWriter method initialize.
/**
* Set up the file reader and writer, ensuring that the input file is
* associated with the reader and the output file is associated with the
* writer.
*
* @return true if the reader and writer were successfully set up, or false
* if an error occurred
* @throws DependencyException thrown if failed to create an OMEXMLService
* @throws IOException thrown if unable to setup input or output stream for reader or writer
* @throws FormatException thrown if invalid ID set for reader or writer or invalid tile size set
* @throws ServiceException thrown if unable to create OME-XML meta data
*/
private void initialize() throws DependencyException, FormatException, IOException, ServiceException {
// construct the object that stores OME-XML metadata
ServiceFactory factory = new ServiceFactory();
OMEXMLService service = factory.getInstance(OMEXMLService.class);
IMetadata omexml = service.createOMEXMLMetadata();
// set up the reader and associate it with the input file
reader = new ImageReader();
reader.setMetadataStore(omexml);
reader.setId(inputFile);
// set up the writer and associate it with the output file
writer = new OMETiffWriter();
writer.setMetadataRetrieve(omexml);
writer.setInterleaved(reader.isInterleaved());
// set the tile size height and width for writing
this.tileSizeX = writer.setTileSizeX(tileSizeX);
this.tileSizeY = writer.setTileSizeY(tileSizeY);
writer.setId(outputFile);
}
Aggregations