use of loci.formats.FormatException in project bioformats by openmicroscopy.
the class ScanrReader method initFile.
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
if (metadataFiles.size() > 0) {
// this dataset has already been initialized
return;
}
// make sure we have the .xml file
if (!checkSuffix(id, "xml") && isGroupFiles()) {
Location parent = new Location(id).getAbsoluteFile().getParentFile();
if (checkSuffix(id, "tif") && parent.getName().equalsIgnoreCase("Data")) {
parent = parent.getParentFile();
}
String[] list = parent.list();
for (String file : list) {
if (file.equals(XML_FILE)) {
id = new Location(parent, file).getAbsolutePath();
super.initFile(id);
break;
}
}
if (!checkSuffix(id, "xml")) {
throw new FormatException("Could not find " + XML_FILE + " in " + parent.getAbsolutePath());
}
} else if (!isGroupFiles() && checkSuffix(id, "tif")) {
TiffReader r = new TiffReader();
r.setMetadataStore(getMetadataStore());
r.setId(id);
core = new ArrayList<CoreMetadata>(r.getCoreMetadataList());
metadataStore = r.getMetadataStore();
final Map<String, Object> globalMetadata = r.getGlobalMetadata();
for (final Map.Entry<String, Object> entry : globalMetadata.entrySet()) {
addGlobalMeta(entry.getKey(), entry.getValue());
}
r.close();
tiffs = new String[] { id };
reader = new MinimalTiffReader();
return;
}
Location dir = new Location(id).getAbsoluteFile().getParentFile();
String[] list = dir.list(true);
for (String file : list) {
Location f = new Location(dir, file);
if (checkSuffix(file, METADATA_SUFFIXES) && !f.isDirectory()) {
metadataFiles.add(f.getAbsolutePath());
}
}
// parse XML metadata
String xml = DataTools.readFile(id).trim();
if (xml.startsWith("<?")) {
xml = xml.substring(xml.indexOf("?>") + 2);
}
xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + xml;
XMLTools.parseXML(xml, new ScanrHandler());
final List<String> uniqueRows = new ArrayList<String>();
final List<String> uniqueColumns = new ArrayList<String>();
if (wellRows == 0 || wellColumns == 0) {
for (String well : wellLabels.keySet()) {
if (!Character.isLetter(well.charAt(0)))
continue;
String row = well.substring(0, 1).trim();
String column = well.substring(1).trim();
if (!uniqueRows.contains(row) && row.length() > 0)
uniqueRows.add(row);
if (!uniqueColumns.contains(column) && column.length() > 0) {
uniqueColumns.add(column);
}
}
wellRows = uniqueRows.size();
wellColumns = uniqueColumns.size();
if (wellRows * wellColumns != wellCount) {
adjustWellDimensions();
}
}
int nChannels = getSizeC() == 0 ? channelNames.size() : (int) Math.min(channelNames.size(), getSizeC());
if (nChannels == 0)
nChannels = 1;
int nSlices = getSizeZ() == 0 ? 1 : getSizeZ();
int nTimepoints = getSizeT();
int nWells = wellCount;
int nPos = 0;
if (foundPositions)
nPos = fieldPositionX.length;
else
nPos = fieldRows * fieldColumns;
if (nPos == 0)
nPos = 1;
// get list of TIFF files
Location dataDir = new Location(dir, "data");
list = dataDir.list(true);
if (list == null) {
// try to find the TIFFs in the current directory
list = dir.list(true);
} else
dir = dataDir;
if (nTimepoints == 0 || list.length < nTimepoints * nChannels * nSlices * nWells * nPos) {
nTimepoints = list.length / (nChannels * nWells * nPos * nSlices);
if (nTimepoints == 0)
nTimepoints = 1;
}
tiffs = new String[nChannels * nWells * nPos * nTimepoints * nSlices];
Arrays.sort(list, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
int lastSeparator1 = s1.lastIndexOf(File.separator) + 1;
int lastSeparator2 = s2.lastIndexOf(File.separator) + 1;
String dir1 = s1.substring(0, lastSeparator1);
String dir2 = s2.substring(0, lastSeparator2);
if (!dir1.equals(dir2)) {
return dir1.compareTo(dir2);
}
int dash1 = s1.indexOf("-", lastSeparator1);
int dash2 = s2.indexOf("-", lastSeparator2);
String label1 = dash1 < 0 ? "" : s1.substring(lastSeparator1, dash1);
String label2 = dash2 < 0 ? "" : s2.substring(lastSeparator2, dash2);
if (label1.equals(label2)) {
String remainder1 = dash1 < 0 ? s1 : s1.substring(dash1);
String remainder2 = dash2 < 0 ? s2 : s2.substring(dash2);
return remainder1.compareTo(remainder2);
}
Integer index1 = wellLabels.get(label1);
Integer index2 = wellLabels.get(label2);
if (index1 == null && index2 != null) {
return 1;
} else if (index1 != null && index2 == null) {
return -1;
}
return index1.compareTo(index2);
}
});
int lastListIndex = 0;
int next = 0;
String[] keys = wellLabels.keySet().toArray(new String[wellLabels.size()]);
Arrays.sort(keys, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
char row1 = s1.charAt(0);
char row2 = s2.charAt(0);
final Integer col1 = new Integer(s1.substring(1));
final Integer col2 = new Integer(s2.substring(1));
if (row1 < row2) {
return -1;
} else if (row1 > row2) {
return 1;
}
return col1.compareTo(col2);
}
});
int realPosCount = 0;
for (int well = 0; well < nWells; well++) {
int missingWellFiles = 0;
int wellIndex = wellNumbers.get(well);
String wellPos = getBlock(wellIndex, "W");
int originalIndex = next;
for (int pos = 0; pos < nPos; pos++) {
String posPos = getBlock(pos + 1, "P");
int posIndex = next;
for (int z = 0; z < nSlices; z++) {
String zPos = getBlock(z, "Z");
for (int t = 0; t < nTimepoints; t++) {
String tPos = getBlock(t, "T");
for (int c = 0; c < nChannels; c++) {
for (int i = lastListIndex; i < list.length; i++) {
String file = list[i];
if (file.indexOf(wellPos) != -1 && file.indexOf(zPos) != -1 && file.indexOf(posPos) != -1 && file.indexOf(tPos) != -1 && file.indexOf(channelNames.get(c)) != -1) {
tiffs[next++] = new Location(dir, file).getAbsolutePath();
if (c == nChannels - 1) {
lastListIndex = i;
}
break;
}
}
if (next == originalIndex) {
missingWellFiles++;
}
}
}
}
if (posIndex != next)
realPosCount++;
}
if (next == originalIndex && well < keys.length) {
wellLabels.remove(keys[well]);
}
if (next == originalIndex && missingWellFiles == nSlices * nTimepoints * nChannels * nPos) {
wellNumbers.remove(well);
}
}
nWells = wellNumbers.size();
if (wellLabels.size() > 0 && wellLabels.size() != nWells) {
uniqueRows.clear();
uniqueColumns.clear();
for (String well : wellLabels.keySet()) {
if (!Character.isLetter(well.charAt(0)))
continue;
String row = well.substring(0, 1).trim();
String column = well.substring(1).trim();
if (!uniqueRows.contains(row) && row.length() > 0)
uniqueRows.add(row);
if (!uniqueColumns.contains(column) && column.length() > 0) {
uniqueColumns.add(column);
}
}
nWells = uniqueRows.size() * uniqueColumns.size();
adjustWellDimensions();
}
if (realPosCount < nPos) {
nPos = realPosCount;
}
reader = new MinimalTiffReader();
reader.setId(tiffs[0]);
int sizeX = reader.getSizeX();
int sizeY = reader.getSizeY();
int pixelType = reader.getPixelType();
tileWidth = reader.getOptimalTileWidth();
tileHeight = reader.getOptimalTileHeight();
switch(pixelType) {
case FormatTools.INT8:
pixelType = FormatTools.UINT8;
break;
case FormatTools.INT16:
pixelType = FormatTools.UINT16;
break;
}
boolean rgb = reader.isRGB();
boolean interleaved = reader.isInterleaved();
boolean indexed = reader.isIndexed();
boolean littleEndian = reader.isLittleEndian();
reader.close();
int seriesCount = nWells * nPos;
core.clear();
for (int i = 0; i < seriesCount; i++) {
CoreMetadata ms = new CoreMetadata();
core.add(ms);
ms.sizeC = nChannels;
ms.sizeZ = nSlices;
ms.sizeT = nTimepoints;
ms.sizeX = sizeX;
ms.sizeY = sizeY;
ms.pixelType = pixelType;
ms.rgb = rgb;
ms.interleaved = interleaved;
ms.indexed = indexed;
ms.littleEndian = littleEndian;
ms.dimensionOrder = "XYCTZ";
ms.imageCount = nSlices * nTimepoints * nChannels;
ms.bitsPerPixel = 12;
}
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
store.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
store.setPlateColumns(new PositiveInteger(wellColumns), 0);
store.setPlateRows(new PositiveInteger(wellRows), 0);
String plateAcqID = MetadataTools.createLSID("PlateAcquisition", 0, 0);
store.setPlateAcquisitionID(plateAcqID, 0, 0);
int nFields = 0;
if (foundPositions) {
nFields = fieldPositionX.length;
} else {
nFields = fieldRows * fieldColumns;
}
PositiveInteger fieldCount = FormatTools.getMaxFieldCount(nFields);
if (fieldCount != null) {
store.setPlateAcquisitionMaximumFieldCount(fieldCount, 0, 0);
}
for (int i = 0; i < getSeriesCount(); i++) {
int field = i % nFields;
int well = i / nFields;
int index = well;
while (wellNumbers.get(index) == null && index < wellNumbers.size()) {
index++;
}
int wellIndex = wellNumbers.get(index) == null ? index : wellNumbers.get(index) - 1;
int wellRow = wellIndex / wellColumns;
int wellCol = wellIndex % wellColumns;
if (field == 0) {
store.setWellID(MetadataTools.createLSID("Well", 0, well), 0, well);
store.setWellColumn(new NonNegativeInteger(wellCol), 0, well);
store.setWellRow(new NonNegativeInteger(wellRow), 0, well);
}
String wellSample = MetadataTools.createLSID("WellSample", 0, well, field);
store.setWellSampleID(wellSample, 0, well, field);
store.setWellSampleIndex(new NonNegativeInteger(i), 0, well, field);
String imageID = MetadataTools.createLSID("Image", i);
store.setWellSampleImageRef(imageID, 0, well, field);
store.setImageID(imageID, i);
String name = "Well " + (well + 1) + ", Field " + (field + 1) + " (Spot " + (i + 1) + ")";
store.setImageName(name, i);
store.setPlateAcquisitionWellSampleRef(wellSample, 0, 0, i);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
for (int i = 0; i < getSeriesCount(); i++) {
for (int c = 0; c < getSizeC(); c++) {
store.setChannelName(channelNames.get(c), i, c);
}
Length x = FormatTools.getPhysicalSizeX(pixelSize);
Length y = FormatTools.getPhysicalSizeY(pixelSize);
if (x != null) {
store.setPixelsPhysicalSizeX(x, i);
}
if (y != null) {
store.setPixelsPhysicalSizeY(y, i);
}
if (fieldPositionX != null && fieldPositionY != null) {
int field = i % nFields;
int well = i / nFields;
final Length posX = fieldPositionX[field];
final Length posY = fieldPositionY[field];
store.setWellSamplePositionX(posX, 0, well, field);
store.setWellSamplePositionY(posY, 0, well, field);
for (int c = 0; c < getSizeC(); c++) {
int image = getIndex(0, c, 0);
store.setPlaneTheZ(new NonNegativeInteger(0), i, image);
store.setPlaneTheC(new NonNegativeInteger(c), i, image);
store.setPlaneTheT(new NonNegativeInteger(0), i, image);
store.setPlanePositionX(fieldPositionX[field], i, image);
store.setPlanePositionY(fieldPositionY[field], i, image);
// exposure time is stored in milliseconds
// convert to seconds before populating MetadataStore
Double time = exposures.get(c);
if (time != null) {
time /= 1000;
store.setPlaneExposureTime(new Time(time, UNITS.SECOND), i, image);
}
if (deltaT != null) {
store.setPlaneDeltaT(new Time(deltaT, UNITS.SECOND), i, image);
}
}
}
}
String row = wellRows > 26 ? "Number" : "Letter";
String col = wellRows > 26 ? "Letter" : "Number";
store.setPlateRowNamingConvention(getNamingConvention(row), 0);
store.setPlateColumnNamingConvention(getNamingConvention(col), 0);
store.setPlateName(plateName, 0);
}
}
use of loci.formats.FormatException in project bioformats by openmicroscopy.
the class ScanrReader method openBytes.
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
@Override
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException {
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
int index = getSeries() * getImageCount() + no;
if (index < tiffs.length && tiffs[index] != null) {
try {
reader.setId(tiffs[index]);
reader.openBytes(0, buf, x, y, w, h);
reader.close();
} catch (FormatException e) {
reader.close();
Arrays.fill(buf, (byte) 0);
return buf;
}
// mask out the sign bit
ByteArrayHandle pixels = new ByteArrayHandle(buf);
pixels.setOrder(isLittleEndian() ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
for (int i = 0; i < buf.length; i += 2) {
pixels.seek(i);
short value = pixels.readShort();
value = (short) (value & 0xfff);
pixels.seek(i);
pixels.writeShort(value);
}
buf = pixels.getBytes();
pixels.close();
}
return buf;
}
use of loci.formats.FormatException in project bioformats by openmicroscopy.
the class SPCReader method initFile.
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
allFiles = new ArrayList<String>();
// get the working directory
Location tmpFile = new Location(id).getAbsoluteFile();
Location workingDir = tmpFile.getParentFile();
if (workingDir == null)
workingDir = new Location(".");
String workingDirPath = workingDir.getPath();
if (!workingDirPath.equals(""))
workingDirPath += File.separator;
String[] ls = workingDir.list(true);
if (!new Location(id).exists()) {
ls = Location.getIdMap().keySet().toArray(new String[0]);
workingDirPath = "";
}
String name = tmpFile.getName();
// generate the name of the two matching files
String setName = null;
String spcName = null;
int pos = name.lastIndexOf(".");
if (pos != -1) {
setName = tmpFile.getName().substring(0, pos) + ".set";
spcName = tmpFile.getName().substring(0, pos) + ".spc";
for (String l : ls) {
if (l.equalsIgnoreCase(setName))
setName = l;
if (l.equalsIgnoreCase(spcName))
spcName = l;
}
}
if (setName == null) {
throw new FormatException("Failed to find a matching .set file!");
}
if (spcName == null) {
throw new FormatException("Failed to find a matching .spc file!");
}
frameClockList = new ArrayList<>();
endOfFrameList = new ArrayList<>();
allFiles.add(workingDirPath + setName);
allFiles.add(workingDirPath + spcName);
in = new RandomAccessInputStream(workingDirPath + setName);
LOGGER.info("Reading info from .set file");
in.order(true);
in.skip(8);
Integer setuppos = in.readInt();
Short setupcount = in.readShort();
String module = "";
try {
// Arbitrary length established by trial and error
String header = in.readString(600);
int index = header.indexOf("module SPC-");
module = header.substring(index + 7, index + 14);
} catch (IOException exc) {
LOGGER.debug("Failed to read header from .set file!", exc);
}
if (!module.equalsIgnoreCase("SPC-134") && !module.equalsIgnoreCase("SPC-144") && !module.equalsIgnoreCase("SPC-154") && !module.equalsIgnoreCase("SPC-830")) {
throw new FormatException("Failed to find a matching .set file!");
}
// goto start of setup information
in.seek(setuppos);
String setup = in.readString(setupcount);
in.close();
// get the tac range from the setup information
double tacRange = parseSetup(TAC_RANGE, setup);
// get the tac range from the setup information
double tacGain = parseSetup(TAC_GAIN, setup);
double timeBase;
if (tacGain != 0.0 && tacRange != 0.0) {
timeBase = 4095 * tacRange / (tacGain * 4096);
// convert from s to ps
timeBase *= 1.000e12;
} else {
throw new FormatException("Failed to parse setup file!");
}
LOGGER.debug("timeBase = " + Double.toString(timeBase));
// Now read .spc file
spcId = workingDirPath + spcName;
in = new RandomAccessInputStream(spcId);
in.order(true);
LOGGER.info("Reading info from .spc file");
/* The first 3 bytes in the file contain information about the
* macro time clock in 0.1 ns units ("500" for 50ns clock)
*/
in.skip(3);
/*
* The 4th byte contains information about the number of
* routing channels in bits 3 to 6.
* Bits 0-2 reserved bit 7 = 1 ("Data invalid")
*/
byte routing = in.readByte();
if ((routing & 0x10) != 0) {
throw new FormatException("Invalid data!");
}
nChannels = (routing & 0x78) >> 3;
currentPixel = 0;
currentLine = -1;
currentFrame = -1;
rawBuf = new byte[bufLength];
endOfFrameFlag = false;
nBuffers = 0;
bufLength = 1024;
rawBuf = new byte[bufLength];
int noOfBytes;
nBuffers = 0;
byte adcL;
byte adcLM;
while ((noOfBytes = in.read(rawBuf)) != -1) {
for (int bb = 3; bb < noOfBytes; bb += 4) {
// even nybble adc
// get upper byte containing ADC data
adcL = rawBuf[bb];
// mask out upper 4 bits
adcLM = (byte) (adcL & 0xF0);
// at this point only the various clocks are of interest
switch(adcLM) {
case (byte) 0x90:
invalidAndMarkInit(bb);
break;
case // Invalid, Mark and MTOV all set.
(byte) 0xd0:
// Unsure about this-- Not well documented!
invalidAndMarkInit(bb);
break;
default:
break;
}
// end switch
}
// end for
nBuffers++;
}
nTimebins = (0xFFF >> adcResShift) + 1;
nFrames = currentFrame - 1;
addGlobalMeta("time bins", nTimebins);
addGlobalMeta("nChannels", nChannels);
addGlobalMeta("time base", timeBase);
LOGGER.info("Populating metadata");
CoreMetadata m = core.get(0);
// Duplicates the behaviour of U.Lorenzo's Matlab code.
if (nLines < 530) {
// return an image
lineMode = false;
m.sizeY = nLines;
} else {
LOGGER.info("Single line mode");
// return a single line
lineMode = true;
m.sizeY = 1;
}
Integer frameLength;
Integer maxFrameLength = 0;
for (int T = 0; T < nFrames; T++) {
frameLength = (int) (endOfFrameList.get(T + 1) - frameClockList.get(T));
if (frameLength > maxFrameLength)
maxFrameLength = frameLength;
}
rawBuf = new byte[maxFrameLength];
m.sizeX = nPixels;
m.sizeZ = 1;
m.sizeT = nTimebins * nFrames;
m.sizeC = nChannels;
m.dimensionOrder = "XYZTC";
m.pixelType = FormatTools.UINT16;
m.rgb = false;
m.littleEndian = true;
m.imageCount = m.sizeZ * m.sizeC * m.sizeT;
m.indexed = false;
m.falseColor = false;
m.metadataComplete = true;
m.moduloT.type = FormatTools.LIFETIME;
m.moduloT.parentType = FormatTools.SPECTRA;
m.moduloT.typeDescription = "TCSPC";
m.moduloT.start = 0;
m.moduloT.step = timeBase / nTimebins;
m.moduloT.end = m.moduloT.step * (nTimebins - 1);
m.moduloT.unit = "ps";
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
}
use of loci.formats.FormatException in project bioformats by openmicroscopy.
the class SimplePCITiffReader method initStandardMetadata.
// -- Internal BaseTiffReader API methods --
/* @see BaseTiffReader#initStandardMetadata() */
@Override
protected void initStandardMetadata() throws FormatException, IOException {
super.initStandardMetadata();
delegate = new MinimalTiffReader();
delegate.setId(currentId);
exposureTimes = new ArrayList<Double>();
String data = ifds.get(0).getComment();
// remove magic string
data = data.substring(data.indexOf("\n") + 1);
date = data.substring(0, data.indexOf("\n"));
data = data.substring(data.indexOf("\n") + 1);
data = data.replaceAll("ReadFromDoc", "");
IniParser parser = new IniParser();
parser.setCommentDelimiter(";");
IniList ini = parser.parseINI(new BufferedReader(new StringReader(data)));
IniTable microscopeTable = ini.getTable(" MICROSCOPE ");
if (microscopeTable != null) {
String objective = microscopeTable.get("Objective");
int space = objective.indexOf(' ');
if (space != -1) {
magnification = new Double(objective.substring(0, space - 1));
immersion = objective.substring(space + 1);
}
}
CoreMetadata m = core.get(0);
IniTable cameraTable = ini.getTable(" CAPTURE DEVICE ");
binning = cameraTable.get("Binning") + "x" + cameraTable.get("Binning");
cameraType = cameraTable.get("Camera Type");
cameraName = cameraTable.get("Camera Name");
String displayDepth = cameraTable.get("Display Depth");
if (displayDepth != null) {
m.bitsPerPixel = Integer.parseInt(displayDepth);
} else {
String bitDepth = cameraTable.get("Bit Depth");
if (bitDepth != null && bitDepth.length() > "-bit".length()) {
bitDepth = bitDepth.substring(0, bitDepth.length() - "-bit".length());
m.bitsPerPixel = Integer.parseInt(bitDepth);
} else {
throw new FormatException("Could not find bits per pixels");
}
}
IniTable captureTable = ini.getTable(" CAPTURE ");
if (captureTable != null) {
int index = 1;
for (int i = 0; i < getSizeC(); i++) {
if (captureTable.get("c_Filter" + index) != null) {
exposureTimes.add(new Double(captureTable.get("c_Expos" + index)));
}
index++;
}
}
IniTable calibrationTable = ini.getTable(" CALIBRATION ");
String units = calibrationTable.get("units");
scaling = Double.parseDouble(calibrationTable.get("factor"));
m.imageCount *= getSizeC();
m.rgb = false;
if (ifds.get(0).containsKey(CUSTOM_BITS)) {
m.bitsPerPixel = ifds.get(0).getIFDIntValue(CUSTOM_BITS);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
HashMap<String, String> iniMap = ini.flattenIntoHashMap();
metadata.putAll(iniMap);
}
}
use of loci.formats.FormatException in project bioformats by openmicroscopy.
the class ZeissZVIReader method initPOIService.
private void initPOIService() throws FormatException, IOException {
try {
ServiceFactory factory = new ServiceFactory();
poi = factory.getInstance(POIService.class);
} catch (DependencyException de) {
throw new FormatException("POI library not found", de);
}
poi.initialize(Location.getMappedId(getCurrentFile()));
}
Aggregations