use of loci.formats.FormatException in project bioformats by openmicroscopy.
the class ZeissCZIReader method checkPALM.
private boolean checkPALM(String xml) throws FormatException, IOException {
Element root = null;
try {
ByteArrayInputStream s = new ByteArrayInputStream(xml.getBytes(Constants.ENCODING));
root = parser.parse(s).getDocumentElement();
s.close();
} catch (SAXException e) {
throw new FormatException(e);
}
if (root == null) {
throw new FormatException("Could not parse the XML metadata.");
}
NodeList customAttributes = root.getElementsByTagName("CustomAttributes");
if (customAttributes != null && customAttributes.getLength() > 0) {
Element attributes = (Element) customAttributes.item(0);
if (attributes != null) {
NodeList lsmTags = attributes.getElementsByTagName("LsmTag");
if (lsmTags != null) {
for (int i = 0; i < lsmTags.getLength(); i++) {
Element tag = (Element) lsmTags.item(i);
String name = tag.getAttribute("Name");
if (name.toLowerCase().startsWith("palm")) {
return true;
}
}
}
}
}
NodeList experiments = root.getElementsByTagName("Experiment");
if (experiments == null || experiments.getLength() == 0) {
return false;
}
Element experimentBlock = getFirstNode((Element) experiments.item(0), "ExperimentBlocks");
Element acquisition = getFirstNode(experimentBlock, "AcquisitionBlock");
if (acquisition == null) {
return false;
}
Element multiTrack = getFirstNode(acquisition, "MultiTrackSetup");
if (multiTrack == null) {
return false;
}
Element trackSetup = getFirstNode(multiTrack, "TrackSetup");
if (trackSetup == null) {
return false;
}
Element palmSlider = getFirstNode(trackSetup, "PalmSlider");
if (palmSlider == null) {
return false;
}
return Boolean.parseBoolean(palmSlider.getTextContent());
}
use of loci.formats.FormatException in project bioformats by openmicroscopy.
the class TillVisionReader method initFile.
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
if (!checkSuffix(id, "vws")) {
Location pst = new Location(id).getAbsoluteFile();
String name = pst.getParentFile().getName();
Location parent = pst.getParentFile().getParentFile();
Location vwsFile = new Location(parent, name.replaceAll(".pst", ".vws"));
if (vwsFile.exists() && !vwsFile.isDirectory()) {
id = vwsFile.getAbsolutePath();
} else if (vwsFile.isDirectory()) {
parent = pst.getParentFile();
String[] list = parent.list(true);
boolean foundVWS = false;
for (String f : list) {
if (checkSuffix(f, "vws")) {
id = new Location(parent, f).getAbsolutePath();
foundVWS = true;
break;
}
}
if (!foundVWS) {
throw new FormatException("Could not find .vws file.");
}
} else
throw new FormatException("Could not find .vws file.");
}
super.initFile(id);
exposureTimes = new HashMap<Integer, Double>();
POIService poi = null;
try {
ServiceFactory factory = new ServiceFactory();
poi = factory.getInstance(POIService.class);
} catch (DependencyException de) {
throw new FormatException("POI library not found", de);
}
poi.initialize(id);
Vector<String> documents = poi.getDocumentList();
int nImages = 0;
final Hashtable<String, Object> tmpSeriesMetadata = new Hashtable<String, Object>();
for (String name : documents) {
LOGGER.debug("Reading {}", name);
if (name.equals("Root Entry" + File.separator + "Contents")) {
RandomAccessInputStream s = poi.getDocumentStream(name);
s.order(true);
boolean specialCImage = false;
int nFound = 0;
Long[] cimages = null;
Location dir = new Location(id).getAbsoluteFile().getParentFile();
String[] list = dir.list(true);
boolean hasPST = false;
for (String f : list) {
if (checkSuffix(f, "pst")) {
hasPST = true;
break;
}
}
if (!hasPST) {
cimages = findImages(s);
nFound = cimages.length;
if (nFound == 0) {
s.seek(13);
int len = s.readShort();
String type = s.readString(len);
if (type.equals("CImage")) {
nFound = 1;
cimages = new Long[] { s.getFilePointer() + 6 };
specialCImage = true;
}
}
embeddedImages = nFound > 0;
}
LOGGER.debug("Images are {}embedded", embeddedImages ? "" : "not ");
if (embeddedImages) {
core.clear();
embeddedOffset = new long[nFound];
for (int i = 0; i < nFound; i++) {
CoreMetadata ms = new CoreMetadata();
core.add(ms);
s.seek(cimages[i]);
int len = s.read();
String imageName = s.readString(len);
imageNames.add(imageName);
if (specialCImage) {
s.seek(1280);
} else {
while (true) {
if (s.readString(2).equals("sB")) {
break;
} else
s.seek(s.getFilePointer() - 1);
}
}
s.skipBytes(20);
ms.sizeX = s.readInt();
ms.sizeY = s.readInt();
ms.sizeZ = s.readInt();
ms.sizeC = s.readInt();
ms.sizeT = s.readInt();
ms.pixelType = convertPixelType(s.readInt());
if (specialCImage) {
embeddedOffset[i] = s.getFilePointer() + 27;
} else {
embeddedOffset[i] = s.getFilePointer() + 31;
}
}
if (in != null)
in.close();
in = poi.getDocumentStream(name);
s.close();
break;
}
s.seek(0);
int lowerBound = 0;
int upperBound = 0x1000;
while (s.getFilePointer() < s.length() - 2) {
LOGGER.debug(" Looking for image at {}", s.getFilePointer());
s.order(false);
int nextOffset = findNextOffset(s);
if (nextOffset < 0 || nextOffset >= s.length())
break;
s.seek(nextOffset);
s.skipBytes(3);
int len = s.readShort();
if (len <= 0)
continue;
imageNames.add(s.readString(len));
if (s.getFilePointer() + 8 >= s.length())
break;
s.skipBytes(6);
s.order(true);
len = s.readShort();
if (nImages == 0 && len > upperBound * 2 && len < upperBound * 4) {
lowerBound = 512;
upperBound = 0x4000;
}
if (len < lowerBound || len > upperBound)
continue;
String description = s.readString(len);
LOGGER.debug("Description: {}", description);
// parse key/value pairs from description
String dateTime = "";
String[] lines = description.split("[\r\n]");
for (String line : lines) {
line = line.trim();
int colon = line.indexOf(':');
if (colon != -1 && !line.startsWith(";")) {
String key = line.substring(0, colon).trim();
String value = line.substring(colon + 1).trim();
String metaKey = "Series " + nImages + " " + key;
addMeta(metaKey, value, tmpSeriesMetadata);
if (key.equals("Start time of experiment")) {
// HH:mm:ss aa OR HH:mm:ss.sss aa
dateTime += " " + value;
} else if (key.equals("Date")) {
// mm/dd/yy ?
dateTime = value + " " + dateTime;
} else if (key.equals("Exposure time [ms]")) {
double exp = Double.parseDouble(value) / 1000;
exposureTimes.put(nImages, exp);
} else if (key.equals("Image type")) {
types.add(value);
}
}
}
dateTime = dateTime.trim();
if (!dateTime.equals("")) {
boolean success = false;
for (String format : DATE_FORMATS) {
try {
dateTime = DateTools.formatDate(dateTime, format, ".");
success = true;
} catch (NullPointerException e) {
}
}
dates.add(success ? dateTime : "");
}
nImages++;
}
s.close();
}
}
Location directory = new Location(currentId).getAbsoluteFile().getParentFile();
String[] pixelsFile = new String[nImages];
if (!embeddedImages) {
if (nImages == 0) {
throw new FormatException("No images found.");
}
// look for appropriate pixels files
String[] files = directory.list(true);
String name = currentId.substring(currentId.lastIndexOf(File.separator) + 1, currentId.lastIndexOf("."));
int nextFile = 0;
for (String f : files) {
if (checkSuffix(f, "pst")) {
Location pst = new Location(directory, f);
if (pst.isDirectory() && f.startsWith(name)) {
String[] subfiles = pst.list(true);
Arrays.sort(subfiles);
for (String q : subfiles) {
if (checkSuffix(q, "pst") && nextFile < nImages) {
pixelsFile[nextFile++] = f + File.separator + q;
}
}
}
}
}
if (nextFile == 0) {
for (String f : files) {
if (checkSuffix(f, "pst")) {
pixelsFile[nextFile++] = new Location(directory, f).getAbsolutePath();
}
}
if (nextFile == 0)
throw new FormatException("No image files found.");
}
}
Arrays.sort(pixelsFile);
int nSeries = core.size();
if (!embeddedImages) {
core.clear();
nSeries = nImages;
}
pixelsFiles = new String[nSeries];
infFiles = new String[nSeries];
Object[] metadataKeys = tmpSeriesMetadata.keySet().toArray();
IniParser parser = new IniParser();
for (int i = 0; i < nSeries; i++) {
CoreMetadata ms;
if (!embeddedImages) {
ms = new CoreMetadata();
core.add(ms);
setSeries(i);
// make sure that pixels file exists
String file = pixelsFile[i];
file = file.replace('/', File.separatorChar);
file = file.replace('\\', File.separatorChar);
String oldFile = file;
Location f = new Location(directory, oldFile);
if (!f.exists()) {
oldFile = oldFile.substring(oldFile.lastIndexOf(File.separator) + 1);
f = new Location(directory, oldFile);
if (!f.exists()) {
throw new FormatException("Could not find pixels file '" + file);
}
}
file = f.getAbsolutePath();
pixelsFiles[i] = file;
// read key/value pairs from .inf files
int dot = file.lastIndexOf(".");
String inf = file.substring(0, dot) + ".inf";
infFiles[i] = inf;
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(inf), Constants.ENCODING));
IniList data = parser.parseINI(reader);
reader.close();
IniTable infoTable = data.getTable("Info");
ms.sizeX = Integer.parseInt(infoTable.get("Width"));
ms.sizeY = Integer.parseInt(infoTable.get("Height"));
ms.sizeC = Integer.parseInt(infoTable.get("Bands"));
ms.sizeZ = Integer.parseInt(infoTable.get("Slices"));
ms.sizeT = Integer.parseInt(infoTable.get("Frames"));
int dataType = Integer.parseInt(infoTable.get("Datatype"));
ms.pixelType = convertPixelType(dataType);
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
HashMap<String, String> iniMap = data.flattenIntoHashMap();
ms.seriesMetadata.putAll(iniMap);
}
} else {
ms = core.get(i);
setSeries(i);
}
ms.imageCount = ms.sizeZ * ms.sizeC * ms.sizeT;
ms.rgb = false;
ms.littleEndian = true;
ms.dimensionOrder = "XYCZT";
ms.seriesMetadata = new Hashtable<String, Object>();
for (Object key : metadataKeys) {
String keyName = key.toString();
if (keyName.startsWith("Series " + i + " ")) {
keyName = keyName.replaceAll("Series " + i + " ", "");
ms.seriesMetadata.put(keyName, tmpSeriesMetadata.get(key));
}
}
}
setSeries(0);
populateMetadataStore();
poi.close();
poi = null;
}
use of loci.formats.FormatException in project bioformats by openmicroscopy.
the class VectraReader method initMetadataStore.
/* @see loci.formats.BaseTiffReader#initMetadataStore() */
@Override
protected void initMetadataStore() throws FormatException {
super.initMetadataStore();
MetadataStore store = makeFilterMetadata();
for (int i = 0; i < getSeriesCount(); i++) {
int coreIndex = seriesToCoreIndex(i);
store.setImageName(getImageName(coreIndex), i);
store.setImageDescription("", i);
int ifdIndex = getIFDIndex(coreIndex, 0);
IFD ifd = ifds.get(ifdIndex);
double x = ifd.getXResolution();
double y = ifd.getYResolution();
store.setPixelsPhysicalSizeX(FormatTools.getPhysicalSizeX(x), i);
store.setPixelsPhysicalSizeY(FormatTools.getPhysicalSizeY(y), i);
}
for (int c = 0; c < getSizeC(); c++) {
String xml = getIFDComment(c);
try {
Element root = XMLTools.parseDOM(xml).getDocumentElement();
NodeList children = root.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
if (!(children.item(i) instanceof Element)) {
continue;
}
Element e = (Element) children.item(i);
String name = e.getNodeName();
String value = e.getTextContent();
if (name.equals("ScanProfile")) {
try {
Document profileRoot = XMLTools.createDocument();
Node tmp = profileRoot.importNode(e, true);
profileRoot.appendChild(tmp);
profileXML = XMLTools.getXML(profileRoot);
// scan profile XML is usually too long to be saved
// when original metadata filtering is enabled, but there
// is an API method below to retrieve it
addGlobalMeta(name, profileXML);
} catch (Exception ex) {
LOGGER.debug("Could not preserve scan profile metadata", ex);
}
} else {
addGlobalMetaList(name, value);
}
if (name.equals("Name")) {
if (hasFlattenedResolutions()) {
for (int series = 0; series < pyramidDepth; series++) {
store.setChannelName(value, series, c);
}
} else {
store.setChannelName(value, 0, c);
}
} else if (name.equals("Color")) {
String[] components = value.split(",");
Color color = new Color(Integer.parseInt(components[0]), Integer.parseInt(components[1]), Integer.parseInt(components[2]), 255);
if (hasFlattenedResolutions()) {
for (int series = 0; series < pyramidDepth; series++) {
store.setChannelColor(color, series, c);
}
} else {
store.setChannelColor(color, 0, c);
}
} else if (name.equals("Objective") && c == 0) {
String instrument = MetadataTools.createLSID("Instrument", 0);
String objective = MetadataTools.createLSID("Objective", 0, 0);
store.setInstrumentID(instrument, 0);
store.setObjectiveID(objective, 0, 0);
store.setObjectiveModel(value, 0, 0);
try {
String mag = value.toLowerCase().replace("x", "");
Double magFactor = DataTools.parseDouble(mag);
store.setObjectiveNominalMagnification(magFactor, 0, 0);
} catch (NumberFormatException ex) {
LOGGER.info("Could not determine magnification: {}", value);
}
for (int series = 0; series < getSeriesCount(); series++) {
store.setImageInstrumentRef(instrument, series);
store.setObjectiveSettingsID(objective, series);
}
} else if (name.equals("ExposureTime")) {
Time exposure = new Time(DataTools.parseDouble(value), UNITS.MICROSECOND);
store.setPlaneExposureTime(exposure, 0, c);
store.setPlaneTheZ(new NonNegativeInteger(0), 0, c);
store.setPlaneTheT(new NonNegativeInteger(0), 0, c);
store.setPlaneTheC(new NonNegativeInteger(c), 0, c);
}
}
} catch (ParserConfigurationException | SAXException | IOException e) {
LOGGER.warn("Could not parse XML for channel {}", c);
LOGGER.debug("", e);
}
}
}
use of loci.formats.FormatException in project bioformats by openmicroscopy.
the class VarianFDFReader method parseFDF.
// -- Helper methods --
private void parseFDF(String file) throws FormatException, IOException {
in = new RandomAccessInputStream(file);
CoreMetadata m = core.get(0);
boolean storedFloats = false;
boolean multifile = false;
String data = in.readString(Character.toString((char) 0x0c));
String[] lines = data.split("\n");
for (String line : lines) {
line = line.trim();
if (line.length() == 0)
break;
if (line.startsWith("#"))
continue;
int space = line.indexOf(' ');
int eq = line.indexOf('=');
String type = line.substring(0, space).trim();
String var = line.substring(space, eq).trim();
String value = line.substring(eq + 1, line.indexOf(';')).trim();
if (var.equals("*storage")) {
storedFloats = value.equals("\"float\"");
}
if (var.equals("bits")) {
m.bitsPerPixel = Integer.parseInt(value);
if (value.equals("8")) {
m.pixelType = FormatTools.UINT8;
} else if (value.equals("16")) {
m.pixelType = FormatTools.UINT16;
} else if (value.equals("32")) {
if (storedFloats) {
m.pixelType = FormatTools.FLOAT;
} else
m.pixelType = FormatTools.UINT32;
} else
throw new FormatException("Unsupported bits: " + value);
} else if (var.equals("matrix[]")) {
String[] values = parseArray(value);
m.sizeX = (int) Double.parseDouble(values[0]);
m.sizeY = (int) Double.parseDouble(values[1]);
if (values.length > 2) {
m.sizeZ = (int) Double.parseDouble(values[2]);
}
} else if (var.equals("slices")) {
m.sizeZ = Integer.parseInt(value);
multifile = true;
} else if (var.equals("echoes")) {
m.sizeT = Integer.parseInt(value);
multifile = true;
} else if (var.equals("span[]")) {
String[] values = parseArray(value);
if (values.length > 0) {
pixelSizeX = computePhysicalSize(getSizeX(), values[0], units[0]);
}
if (values.length > 1) {
pixelSizeY = computePhysicalSize(getSizeY(), values[1], units[1]);
}
if (values.length > 2) {
pixelSizeZ = computePhysicalSize(getSizeZ(), values[2], units[2]);
}
} else if (var.equals("origin[]")) {
String[] values = parseArray(value);
if (values.length > 0) {
final double size = computePhysicalSize(1, values[0], units[0]);
originX = new Length(size, UNITS.REFERENCEFRAME);
addGlobalMeta("X position for position #1", originX);
}
if (values.length > 1) {
final double size = computePhysicalSize(1, values[1], units[1]);
originY = new Length(size, UNITS.REFERENCEFRAME);
addGlobalMeta("Y position for position #1", originY);
}
if (values.length > 2) {
final double size = computePhysicalSize(1, values[2], units[2]);
originZ = new Length(size, UNITS.REFERENCEFRAME);
addGlobalMeta("Z position for position #1", originZ);
}
} else if (var.equals("*abscissa[]")) {
units = parseArray(value);
} else if (var.equals("bigendian")) {
m.littleEndian = value.equals("0");
in.order(isLittleEndian());
}
addGlobalMeta(var, value);
}
if (multifile && files.isEmpty()) {
Location thisFile = new Location(file).getAbsoluteFile();
Location parent = thisFile.getParentFile();
String[] list = parent.list(true);
Arrays.sort(list);
for (String f : list) {
if (checkSuffix(f, "fdf") && f.length() == thisFile.getName().length()) {
files.add(new Location(parent, f).getAbsolutePath());
}
}
}
}
use of loci.formats.FormatException in project bioformats by openmicroscopy.
the class VolocityClippingReader method initFile.
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
CoreMetadata m = core.get(0);
m.littleEndian = in.read() == 'I';
in.order(isLittleEndian());
in.skipBytes(4);
String magicString = in.readString(4);
if (!magicString.equals(CLIPPING_MAGIC_STRING)) {
throw new FormatException("Found invalid magic string: " + magicString);
}
int check = in.readInt();
while (check != 0x208 && check != AISF) {
in.seek(in.getFilePointer() - 3);
check = in.readInt();
}
if (check == AISF) {
m.littleEndian = false;
in.order(isLittleEndian());
in.skipBytes(28);
}
m.sizeX = in.readInt();
m.sizeY = in.readInt();
m.sizeZ = in.readInt();
m.sizeC = 1;
m.sizeT = 1;
m.imageCount = getSizeZ() * getSizeT();
m.dimensionOrder = "XYCZT";
m.pixelType = FormatTools.UINT8;
pixelOffset = in.getFilePointer() + 65;
if (getSizeX() * getSizeY() * 100 >= in.length()) {
while (in.getFilePointer() < in.length()) {
try {
byte[] b = new LZOCodec().decompress(in, null);
if (b.length > 0 && (b.length % (getSizeX() * getSizeY())) == 0) {
int bytes = b.length / (getSizeX() * getSizeY());
m.pixelType = FormatTools.pixelTypeFromBytes(bytes, false, false);
break;
}
} catch (EOFException e) {
}
pixelOffset++;
in.seek(pixelOffset);
}
}
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
}
Aggregations