use of loci.common.Location in project bioformats by openmicroscopy.
the class ImagePlusReader method constructImageTitle.
private String constructImageTitle(IFormatReader r, String file, String seriesName, boolean groupFiles) {
String[] used = r.getUsedFiles();
String title = file.substring(file.lastIndexOf(File.separator) + 1);
if (used.length > 1 && groupFiles) {
FilePattern fp = new FilePattern(new Location(file));
title = fp.getPattern();
if (title == null) {
title = file;
if (title.indexOf('.') != -1) {
title = title.substring(0, title.lastIndexOf("."));
}
}
title = title.substring(title.lastIndexOf(File.separator) + 1);
}
if (seriesName != null && !file.endsWith(seriesName) && r.getSeriesCount() > 1) {
title += " - " + seriesName;
}
if (title.length() > 128) {
String a = title.substring(0, 62);
String b = title.substring(title.length() - 62);
title = a + "..." + b;
}
return title;
}
use of loci.common.Location in project bioformats by openmicroscopy.
the class LeicaReader method parseFilenames.
private void parseFilenames(int seriesIndex) throws IOException {
int maxPlanes = 0;
final List<String> f = new ArrayList<String>();
int tempImages = in.readInt();
if (((long) tempImages * nameLength) > in.length()) {
in.order(!isLittleEndian());
tempImages = in.readInt();
in.order(isLittleEndian());
}
CoreMetadata ms = core.get(seriesIndex);
ms.sizeX = in.readInt();
ms.sizeY = in.readInt();
in.skipBytes(4);
int samplesPerPixel = in.readInt();
ms.rgb = samplesPerPixel > 1;
ms.sizeC = samplesPerPixel;
boolean tiffsExist = false;
String dirPrefix = new Location(currentId).getAbsoluteFile().getParent();
if (!dirPrefix.endsWith(File.separator))
dirPrefix += File.separator;
String prefix = "";
for (int j = 0; j < tempImages; j++) {
// read in each filename
prefix = getString(nameLength);
f.add(dirPrefix + prefix);
// test to make sure the path is valid
Location test = new Location(f.get(f.size() - 1)).getAbsoluteFile();
LOGGER.debug("Expected to find TIFF file {}", test.getAbsolutePath());
if (!test.exists()) {
LOGGER.debug(" file does not exist");
}
if (!tiffsExist)
tiffsExist = test.exists();
}
if (!tiffsExist) {
// Strategy for handling renamed files:
// 1) Assume that files for each series follow a pattern.
// 2) Assign each file group to the first series with the correct count.
LOGGER.info("Handling renamed TIFF files");
String[] listing = getTIFFList();
// grab the file patterns
final List<String> filePatterns = new ArrayList<String>();
for (String q : listing) {
Location l = new Location(q).getAbsoluteFile();
if (!l.exists()) {
l = new Location(dirPrefix, q).getAbsoluteFile();
}
FilePattern pattern = new FilePattern(l);
if (!pattern.isValid())
continue;
AxisGuesser guess = new AxisGuesser(pattern, "XYZCT", 1, 1, 1, false);
String fp = pattern.getPattern();
if (guess.getAxisCountS() >= 1) {
String pre = pattern.getPrefix(guess.getAxisCountS());
final List<String> fileList = new ArrayList<String>();
for (int n = 0; n < listing.length; n++) {
Location p = new Location(dirPrefix, listing[n]);
if (p.getAbsolutePath().startsWith(pre)) {
fileList.add(listing[n]);
}
}
fp = FilePattern.findPattern(l.getAbsolutePath(), dirPrefix, fileList.toArray(new String[fileList.size()]));
}
if (fp != null && !filePatterns.contains(fp)) {
filePatterns.add(fp);
}
}
for (String q : filePatterns) {
String[] pattern = new FilePattern(q).getFiles();
if (pattern.length == tempImages) {
// make sure that this pattern hasn't already been used
boolean validPattern = true;
for (int n = 0; n < seriesIndex; n++) {
if (files[n] == null)
continue;
if (files[n].contains(pattern[0])) {
validPattern = false;
break;
}
}
if (validPattern) {
files[seriesIndex] = new ArrayList<String>();
files[seriesIndex].addAll(Arrays.asList(pattern));
}
}
}
} else {
files[seriesIndex] = f;
for (int s = 0; s < seriesIndex; s++) {
if (files[s] != null) {
if (files[s].get(0).equals(f.get(0))) {
valid[s] = false;
files[s] = null;
}
}
}
}
if (files[seriesIndex] == null)
valid[seriesIndex] = false;
else {
ms.imageCount = files[seriesIndex].size();
maxPlanes = (int) Math.max(maxPlanes, ms.imageCount);
}
}
use of loci.common.Location in project bioformats by openmicroscopy.
the class LeicaReader 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);
lastPlane = no;
int fileIndex = no < files[getSeries()].size() ? no : 0;
int planeIndex = no < files[getSeries()].size() ? 0 : no;
String filename = (String) files[getSeries()].get(fileIndex);
if (new Location(filename).exists()) {
if (checkSuffix(filename, TiffReader.TIFF_SUFFIXES)) {
tiff.setId(filename);
return tiff.openBytes(planeIndex, buf, x, y, w, h);
} else {
RandomAccessInputStream s = new RandomAccessInputStream(filename);
s.seek(planeIndex * FormatTools.getPlaneSize(this));
readPlane(s, x, y, w, h, buf);
s.close();
}
}
// appropriate TIFF file is missing
return buf;
}
use of loci.common.Location in project bioformats by openmicroscopy.
the class LeicaReader method initFile.
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
close();
String leiFile = findLEIFile(id);
if (leiFile == null || leiFile.trim().length() == 0 || new Location(leiFile).isDirectory()) {
if (checkSuffix(id, TiffReader.TIFF_SUFFIXES)) {
super.initFile(id);
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();
files = new List[] { new ArrayList<String>() };
files[0].add(id);
tiff = new MinimalTiffReader();
return;
} else {
throw new FormatException("LEI file not found.");
}
}
// parse the LEI file
super.initFile(leiFile);
leiFilename = new File(leiFile).exists() ? new Location(leiFile).getAbsolutePath() : id;
in = new RandomAccessInputStream(leiFile);
byte[] data = null;
try {
data = new byte[(int) in.length()];
in.read(data);
} finally {
in.close();
}
in = new RandomAccessInputStream(data);
MetadataLevel metadataLevel = metadataOptions.getMetadataLevel();
seriesNames = new ArrayList<String>();
byte[] fourBytes = new byte[4];
in.read(fourBytes);
core.get(0).littleEndian = (fourBytes[0] == TiffConstants.LITTLE && fourBytes[1] == TiffConstants.LITTLE && fourBytes[2] == TiffConstants.LITTLE && fourBytes[3] == TiffConstants.LITTLE);
boolean realLittleEndian = isLittleEndian();
in.order(isLittleEndian());
LOGGER.info("Reading metadata blocks");
in.skipBytes(8);
int addr = in.readInt();
headerIFDs = new IFDList();
while (addr != 0) {
IFD ifd = new IFD();
headerIFDs.add(ifd);
in.seek(addr + 4);
int tag = in.readInt();
while (tag != 0) {
// create the IFD structure
int offset = in.readInt();
long pos = in.getFilePointer();
in.seek(offset + 12);
int size = in.readInt();
ifd.putIFDValue(tag, in.getFilePointer());
in.seek(pos);
tag = in.readInt();
}
addr = in.readInt();
}
numSeries = headerIFDs.size();
tileWidth = new int[numSeries];
tileHeight = new int[numSeries];
core.clear();
for (int i = 0; i < numSeries; i++) {
core.add(new CoreMetadata());
}
files = new List[numSeries];
channelNames = new List[getSeriesCount()];
emWaves = new List[getSeriesCount()];
exWaves = new List[getSeriesCount()];
cutInPopulated = new boolean[getSeriesCount()][];
cutOutPopulated = new boolean[getSeriesCount()][];
filterRefPopulated = new boolean[getSeriesCount()][];
for (int i = 0; i < getSeriesCount(); i++) {
channelNames[i] = new ArrayList();
emWaves[i] = new ArrayList();
exWaves[i] = new ArrayList();
}
// determine the length of a filename
LOGGER.info("Parsing metadata blocks");
core.get(0).littleEndian = !isLittleEndian();
int seriesIndex = 0;
int invalidCount = 0;
valid = new boolean[numSeries];
timestamps = new String[headerIFDs.size()][];
for (int i = 0; i < headerIFDs.size(); i++) {
IFD ifd = headerIFDs.get(i);
valid[i] = true;
if (ifd.get(SERIES) != null) {
long offset = ((Long) ifd.get(SERIES)).longValue();
in.seek(offset + 8);
nameLength = in.readInt() * 2;
}
in.seek(((Long) ifd.get(IMAGES)).longValue());
parseFilenames(i);
if (!valid[i])
invalidCount++;
}
numSeries -= invalidCount;
if (numSeries <= 0) {
throw new FormatException("TIFF files not found");
}
int[] count = new int[getSeriesCount()];
for (int i = 0; i < getSeriesCount(); i++) {
count[i] = core.get(i).imageCount;
}
final List<String>[] tempFiles = files;
IFDList tempIFDs = headerIFDs;
core = new ArrayList<CoreMetadata>(numSeries);
files = new List[numSeries];
headerIFDs = new IFDList();
int index = 0;
core.clear();
for (int i = 0; i < numSeries; i++) {
CoreMetadata ms = new CoreMetadata();
while (index < valid.length && !valid[index]) index++;
if (index >= valid.length) {
break;
}
ms.imageCount = count[index];
files[i] = tempFiles[index];
Collections.sort(files[i]);
headerIFDs.add(tempIFDs.get(index));
index++;
core.add(ms);
}
tiff = new MinimalTiffReader();
LOGGER.info("Populating metadata");
if (headerIFDs == null)
headerIFDs = ifds;
seriesDescriptions = new ArrayList<String>();
physicalSizes = new double[headerIFDs.size()][5];
pinhole = new double[headerIFDs.size()];
exposureTime = new double[headerIFDs.size()];
channelColor = new Color[headerIFDs.size()][];
for (int i = 0; i < headerIFDs.size(); i++) {
IFD ifd = headerIFDs.get(i);
CoreMetadata ms = core.get(i);
ms.littleEndian = isLittleEndian();
setSeries(i);
Integer[] keys = ifd.keySet().toArray(new Integer[ifd.size()]);
Arrays.sort(keys);
for (Integer key : keys) {
long offset = ((Long) ifd.get(key)).longValue();
in.seek(offset);
if (key.equals(SERIES)) {
parseSeriesTag();
} else if (key.equals(IMAGES)) {
parseImageTag(i);
} else if (key.equals(DIMDESCR)) {
parseDimensionTag(i);
} else if (key.equals(TIMEINFO) && metadataLevel != MetadataLevel.MINIMUM) {
parseTimeTag(i);
} else if (key.equals(EXPERIMENT) && metadataLevel != MetadataLevel.MINIMUM) {
parseExperimentTag();
} else if (key.equals(LUTDESC)) {
parseLUT(i);
} else if (key.equals(CHANDESC) && metadataLevel != MetadataLevel.MINIMUM) {
parseChannelTag();
}
}
ms.orderCertain = true;
ms.littleEndian = isLittleEndian();
ms.falseColor = true;
ms.metadataComplete = true;
ms.interleaved = false;
String filename = (String) files[i].get(0);
if (checkSuffix(filename, TiffReader.TIFF_SUFFIXES)) {
RandomAccessInputStream s = new RandomAccessInputStream(filename, 16);
try {
TiffParser parser = new TiffParser(s);
parser.setDoCaching(false);
IFD firstIFD = parser.getFirstIFD();
parser.fillInIFD(firstIFD);
ms.sizeX = (int) firstIFD.getImageWidth();
ms.sizeY = (int) firstIFD.getImageLength();
// override the .lei pixel type, in case a TIFF file was overwritten
ms.pixelType = firstIFD.getPixelType();
// won't affect the pixel data
if (FormatTools.getBytesPerPixel(ms.pixelType) > 1) {
ms.littleEndian = firstIFD.isLittleEndian();
} else {
ms.littleEndian = realLittleEndian;
}
tileWidth[i] = (int) firstIFD.getTileWidth();
tileHeight[i] = (int) firstIFD.getTileLength();
} finally {
s.close();
}
} else {
ms.littleEndian = realLittleEndian;
}
}
for (int i = 0; i < getSeriesCount(); i++) {
setSeries(i);
CoreMetadata ms = core.get(i);
if (getSizeZ() == 0)
ms.sizeZ = 1;
if (getSizeT() == 0)
ms.sizeT = 1;
if (getSizeC() == 0)
ms.sizeC = 1;
if (getImageCount() == 0)
ms.imageCount = 1;
if (getImageCount() == 1 && getSizeZ() * getSizeT() > 1) {
ms.sizeZ = 1;
ms.sizeT = 1;
}
if (getSizeY() == 1 || getSizeY() == getSizeZ() || getSizeY() == getSizeT()) {
// XZ or XT scan
if (getSizeZ() > 1 && getImageCount() == getSizeC() * getSizeT()) {
ms.sizeY = getSizeZ();
ms.sizeZ = 1;
} else if (getSizeT() > 1 && getImageCount() == getSizeC() * getSizeZ()) {
ms.sizeY = getSizeT();
ms.sizeT = 1;
}
}
if (isRGB())
ms.indexed = false;
ms.dimensionOrder = MetadataTools.makeSaneDimensionOrder(getDimensionOrder());
}
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
// minimum metadata level.
for (int i = 0; i < getSeriesCount(); i++) {
store.setImageName(seriesNames.get(i), i);
}
if (metadataLevel == MetadataLevel.MINIMUM)
return;
for (int i = 0; i < getSeriesCount(); i++) {
CoreMetadata ms = core.get(i);
IFD ifd = headerIFDs.get(i);
long firstPlane = 0;
if (i < timestamps.length && timestamps[i] != null && timestamps[i].length > 0) {
firstPlane = DateTools.getTime(timestamps[i][0], DATE_FORMAT, ":");
String date = DateTools.formatDate(timestamps[i][0], DATE_FORMAT);
if (date != null) {
store.setImageAcquisitionDate(new Timestamp(date), i);
}
}
store.setImageDescription(seriesDescriptions.get(i), i);
String instrumentID = MetadataTools.createLSID("Instrument", i);
store.setInstrumentID(instrumentID, i);
// parse instrument data
nextDetector = 0;
nextChannel = 0;
detectors.clear();
cutInPopulated[i] = new boolean[ms.sizeC];
cutOutPopulated[i] = new boolean[ms.sizeC];
filterRefPopulated[i] = new boolean[ms.sizeC];
Integer[] keys = ifd.keySet().toArray(new Integer[ifd.size()]);
Arrays.sort(keys);
int nextInstrumentBlock = 1;
sequential = DataTools.indexOf(keys, SEQ_SCANNERSET) != -1;
for (Integer key : keys) {
if (key.equals(FILTERSET) || key.equals(SCANNERSET) || key.equals(SEQ_SCANNERSET) || key.equals(SEQ_FILTERSET) || (key > SEQ_SCANNERSET && key < SEQ_SCANNERSET_END) || (key > SEQ_FILTERSET && key < SEQ_FILTERSET_END)) {
if (sequential && (key.equals(FILTERSET) || key.equals(SCANNERSET))) {
continue;
}
long offset = ((Long) ifd.get(key)).longValue();
in.seek(offset);
setSeries(i);
parseInstrumentData(store, nextInstrumentBlock++);
}
}
activeChannelIndices.clear();
// link Instrument and Image
store.setImageInstrumentRef(instrumentID, i);
Length sizeX = FormatTools.getPhysicalSizeX(physicalSizes[i][0]);
Length sizeY = FormatTools.getPhysicalSizeY(physicalSizes[i][1]);
Length sizeZ = FormatTools.getPhysicalSizeZ(physicalSizes[i][2]);
if (sizeX != null) {
store.setPixelsPhysicalSizeX(sizeX, i);
}
if (sizeY != null) {
store.setPixelsPhysicalSizeY(sizeY, i);
}
if (sizeZ != null) {
store.setPixelsPhysicalSizeZ(sizeZ, i);
}
if ((int) physicalSizes[i][4] > 0) {
store.setPixelsTimeIncrement(new Time(physicalSizes[i][4], UNITS.SECOND), i);
}
for (int j = 0; j < ms.imageCount; j++) {
if (timestamps[i] != null && j < timestamps[i].length) {
long time = DateTools.getTime(timestamps[i][j], DATE_FORMAT, ":");
double elapsedTime = (double) (time - firstPlane) / 1000;
store.setPlaneDeltaT(new Time(elapsedTime, UNITS.SECOND), i, j);
if (exposureTime[i] > 0) {
store.setPlaneExposureTime(new Time(exposureTime[i], UNITS.SECOND), i, j);
}
}
}
}
setSeries(0);
}
use of loci.common.Location in project bioformats by openmicroscopy.
the class LeicaReader method isThisType.
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
@Override
public boolean isThisType(String name, boolean open) {
if (checkSuffix(name, LEI_SUFFIX))
return true;
if (!checkSuffix(name, TiffReader.TIFF_SUFFIXES) && !checkSuffix(name, "raw")) {
return false;
}
// not allowed to touch the file system
if (!open)
return false;
// check for that there is an .lei file in the same directory
String prefix = name;
if (prefix.indexOf('.') != -1) {
prefix = prefix.substring(0, prefix.lastIndexOf("."));
}
Location lei = new Location(prefix + ".lei");
if (!lei.exists()) {
lei = new Location(prefix + ".LEI");
while (!lei.exists() && prefix.indexOf('_') != -1) {
prefix = prefix.substring(0, prefix.lastIndexOf("_"));
lei = new Location(prefix + ".lei");
if (!lei.exists())
lei = new Location(prefix + ".LEI");
}
}
return lei.exists();
}
Aggregations