use of loci.formats.IFormatReader in project bioformats by openmicroscopy.
the class GUITools method buildFileFilters.
// -- File chooser --
/**
* Constructs a list of file filters for the given file format handler.
*/
public static FileFilter[] buildFileFilters(IFormatHandler handler) {
FileFilter[] filters = null;
// unwrap reader
while (true) {
if (handler instanceof ReaderWrapper) {
handler = ((ReaderWrapper) handler).getReader();
} else if (handler instanceof FileStitcher) {
handler = ((FileStitcher) handler).getReader();
} else if (handler instanceof WriterWrapper) {
handler = ((WriterWrapper) handler).getWriter();
} else
break;
}
// handle special cases of ImageReader and ImageWriter
if (handler instanceof ImageReader) {
ImageReader imageReader = (ImageReader) handler;
IFormatReader[] readers = imageReader.getReaders();
Vector filterList = new Vector();
Vector comboList = new Vector();
for (int i = 0; i < readers.length; i++) {
filterList.add(new FormatFileFilter(readers[i]));
// NB: Some readers need to open a file to determine if it is the
// proper type, when the extension alone is insufficient to
// distinguish. This behavior is fine for individual filters, but not
// for ImageReader's combination filter, because it makes the combo
// filter too slow. So rather than composing the combo filter from
// FormatFileFilters, we use faster but less accurate
// ExtensionFileFilters instead.
String[] suffixes = readers[i].getSuffixes();
String format = readers[i].getFormat();
comboList.add(new ExtensionFileFilter(suffixes, format));
}
comboList.add(new NoExtensionFileFilter());
FileFilter combo = makeComboFilter(sortFilters(comboList));
if (combo != null)
filterList.add(combo);
filters = sortFilters(filterList);
} else if (handler instanceof ImageWriter) {
IFormatWriter[] writers = ((ImageWriter) handler).getWriters();
Vector filterList = new Vector();
for (int i = 0; i < writers.length; i++) {
String[] suffixes = writers[i].getSuffixes();
String format = writers[i].getFormat();
filterList.add(new ExtensionFileFilter(suffixes, format));
}
filters = sortFilters(filterList);
} else // handle default reader and writer cases
if (handler instanceof IFormatReader) {
IFormatReader reader = (IFormatReader) handler;
filters = new FileFilter[] { new FormatFileFilter(reader) };
} else {
String[] suffixes = handler.getSuffixes();
String format = handler.getFormat();
filters = new FileFilter[] { new ExtensionFileFilter(suffixes, format) };
}
return filters;
}
use of loci.formats.IFormatReader 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);
}
}
}
}
}
use of loci.formats.IFormatReader in project bioformats by openmicroscopy.
the class CellSensReader method decodeTile.
private byte[] decodeTile(int no, int row, int col) throws FormatException, IOException {
if (tileMap.get(getCoreIndex()) == null) {
return new byte[getTileSize()];
}
int[] zct = getZCTCoords(no);
TileCoordinate t = new TileCoordinate(nDimensions.get(getCoreIndex()));
t.coordinate[0] = col;
t.coordinate[1] = row;
int resIndex = getResolution();
int pyramidIndex = getSeries();
if (hasFlattenedResolutions()) {
int index = 0;
pyramidIndex = 0;
for (int i = 0; i < core.size(); ) {
if (index + core.get(i).resolutionCount <= getSeries()) {
index += core.get(i).resolutionCount;
i += core.get(i).resolutionCount;
pyramidIndex++;
} else {
resIndex = getSeries() - index;
break;
}
}
}
Pyramid pyramid = pyramids.get(pyramidIndex);
for (String dim : pyramid.dimensionOrdering.keySet()) {
int index = pyramid.dimensionOrdering.get(dim) + 2;
if (dim.equals("Z")) {
t.coordinate[index] = zct[0];
} else if (dim.equals("C")) {
t.coordinate[index] = zct[1];
} else if (dim.equals("T")) {
t.coordinate[index] = zct[2];
}
}
if (resIndex > 0) {
t.coordinate[t.coordinate.length - 1] = resIndex;
}
ArrayList<TileCoordinate> map = tileMap.get(getCoreIndex());
Integer index = map.indexOf(t);
if (index == null || index < 0) {
// fill in the tile with the stored background color
// usually this is either black or white
byte[] tile = new byte[getTileSize()];
byte[] color = backgroundColor.get(getCoreIndex());
if (color != null) {
for (int q = 0; q < getTileSize(); q += color.length) {
for (int i = 0; i < color.length; i++) {
tile[q + i] = color[i];
}
}
}
return tile;
}
Long offset = tileOffsets.get(getCoreIndex())[index];
RandomAccessInputStream ets = new RandomAccessInputStream(fileMap.get(getCoreIndex()));
ets.seek(offset);
CodecOptions options = new CodecOptions();
options.interleaved = isInterleaved();
options.littleEndian = isLittleEndian();
int tileSize = getTileSize();
if (tileSize == 0) {
tileSize = tileX.get(getCoreIndex()) * tileY.get(getCoreIndex()) * 10;
}
options.maxBytes = (int) (offset + tileSize);
byte[] buf = null;
long end = index < tileOffsets.get(getCoreIndex()).length - 1 ? tileOffsets.get(getCoreIndex())[index + 1] : ets.length();
IFormatReader reader = null;
String file = null;
switch(compressionType.get(getCoreIndex())) {
case RAW:
buf = new byte[tileSize];
ets.read(buf);
break;
case JPEG:
Codec codec = new JPEGCodec();
buf = codec.decompress(ets, options);
break;
case JPEG_2000:
codec = new JPEG2000Codec();
buf = codec.decompress(ets, options);
break;
case JPEG_LOSSLESS:
codec = new LosslessJPEGCodec();
buf = codec.decompress(ets, options);
break;
case PNG:
file = "tile.png";
reader = new APNGReader();
case BMP:
if (reader == null) {
file = "tile.bmp";
reader = new BMPReader();
}
byte[] b = new byte[(int) (end - offset)];
ets.read(b);
Location.mapFile(file, new ByteArrayHandle(b));
reader.setId(file);
buf = reader.openBytes(0);
Location.mapFile(file, null);
break;
}
if (reader != null) {
reader.close();
}
ets.close();
return buf;
}
use of loci.formats.IFormatReader in project bioformats by openmicroscopy.
the class ReaderEqualityTest method createEqualWrappers.
@DataProvider(name = "equalWrappers")
public Object[][] createEqualWrappers() {
Location.mapId(TEST_FILE_A, TEST_FILE_A);
Location.mapId(TEST_FILE_B, TEST_FILE_B);
Object[][] wrappers = new Object[][] { { new ImageReader(), new ImageReader() }, { new ImageReader(), new ImageReader() }, { new MinMaxCalculator(new ChannelSeparator(new ChannelFiller())), new MinMaxCalculator(new ChannelSeparator(new ChannelFiller())) }, { new DimensionSwapper(new ChannelMerger()), new DimensionSwapper(new ChannelMerger()) } };
for (int i = 1; i < wrappers.length; i++) {
IFormatReader readerA = (IFormatReader) wrappers[i][0];
IFormatReader readerB = (IFormatReader) wrappers[i][1];
try {
readerA.setId(TEST_FILE_A);
readerB.setId(TEST_FILE_B);
} catch (FormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return wrappers;
}
use of loci.formats.IFormatReader in project bioformats by openmicroscopy.
the class ReaderEqualityTest method createUnequalWrappers.
@DataProvider(name = "unequalWrappers")
public Object[][] createUnequalWrappers() {
Object[][] wrappers = new Object[][] { { new ImageReader(), new ImageReader() }, { new ImageReader(), new ImageReader() }, { new MinMaxCalculator(new ChannelSeparator(new ChannelFiller())), new MinMaxCalculator(new ChannelSeparator()) }, { new DimensionSwapper(new ChannelMerger()), new DimensionSwapper(new ChannelMerger()) } };
for (int i = 0; i < wrappers.length; i++) {
IFormatReader readerA = (IFormatReader) wrappers[i][0];
IFormatReader readerB = (IFormatReader) wrappers[i][1];
try {
if (i != 1) {
readerA.setId(TEST_FILE_A);
} else {
readerA.setId(TEST_FILE_B);
}
if (i > 1) {
readerB.setId(TEST_FILE_B);
} else if (i == 1) {
readerB.setId(TEST_FILE_A);
}
} catch (FormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return wrappers;
}
Aggregations