Search in sources :

Example 26 with Length

use of ome.units.quantity.Length in project bioformats by openmicroscopy.

the class InveonReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    if (!checkSuffix(id, "hdr")) {
        id += ".hdr";
    }
    super.initFile(id);
    String headerData = DataTools.readFile(id);
    String[] lines = headerData.split("\n");
    String date = null;
    String institution = null, investigator = null;
    String model = null;
    String description = null;
    Double pixelSizeX = null;
    Double pixelSizeY = null;
    Double pixelSizeZ = null;
    int frames = 0;
    for (String line : lines) {
        line = line.trim();
        if (!line.startsWith("#")) {
            int space = line.indexOf(' ');
            if (space < 0) {
                continue;
            }
            String key = line.substring(0, space);
            String value = line.substring(space + 1);
            if (key.equals("institution")) {
                institution = value;
            } else if (key.equals("investigator")) {
                investigator = value;
            } else if (key.equals("study")) {
                description = value;
            } else if (key.equals("model")) {
                value = transformModel(value);
                model = value;
            } else if (key.equals("modality")) {
                value = transformModality(value);
            } else if (key.equals("modality_configuration")) {
                value = transformModalityConfiguration(value);
            } else if (key.equals("file_type")) {
                value = transformFileType(value);
            } else if (key.equals("acquisition_mode")) {
                value = transformAcquisitionMode(value);
            } else if (key.equals("bed_control")) {
                value = transformBedControl(value);
            } else if (key.equals("bed_motion")) {
                value = transformBedMotion(value);
            } else if (key.equals("registration_available")) {
                value = transformRegistrationAvailable(value);
            } else if (key.equals("normalization_applied")) {
                value = transformNormalizationApplied(value);
            } else if (key.equals("recon_algorithm")) {
                value = transformReconAlgorithm(value);
            } else if (key.equals("x_filter")) {
                value = transformFilter(value);
            } else if (key.equals("y_filter")) {
                value = transformFilter(value);
            } else if (key.equals("z_filter")) {
                value = transformFilter(value);
            } else if (key.equals("subject_orientation")) {
                value = transformSubjectOrientation(value);
            } else if (key.equals("subject_length_units")) {
                value = transformSubjectLengthUnits(value);
            } else if (key.equals("subject_weight_units")) {
                value = transformSubjectWeightUnits(value);
            } else if (key.equals("gantry_rotation")) {
                value = transformGantryRotation(value);
            } else if (key.equals("rotation_direction")) {
                value = transformRotationDirection(value);
            } else if (key.equals("ct_warping")) {
                value = transformCTWarping(value);
            } else if (key.equals("ct_projection_interpolation")) {
                value = transformCTProjectionInterpolation(value);
            } else if (key.equals("event_type")) {
                value = transformEventType(value);
            } else if (key.equals("projection") || key.equals("ct_projection_center_offset") || key.equals("ct_projection_horizontal_bed_offset")) {
                space = value.indexOf(' ');
                int index = Integer.parseInt(value.substring(0, space));
                value = value.substring(space + 1);
                key += " " + index;
            } else if (key.equals("user")) {
                space = value.indexOf(' ');
                key = value.substring(0, space);
                value = value.substring(space + 1);
            } else if (key.equals("file_name")) {
                // remove path from stored file name, if present
                value = value.replace('/', File.separatorChar);
                value = value.replace('\\', File.separatorChar);
                value = value.substring(value.lastIndexOf(File.separator) + 1);
                Location header = new Location(currentId).getAbsoluteFile();
                datFile = new Location(header.getParent(), value).getAbsolutePath();
            } else if (key.equals("time_frames")) {
                int sizeT = Integer.parseInt(value);
                for (int i = 0; i < core.size(); i++) {
                    core.get(i).sizeT = sizeT;
                }
            } else if (key.equals("total_frames")) {
                frames = Integer.parseInt(value);
            } else if (key.equals("number_of_bed_positions")) {
                int nPos = (int) Math.min(frames, Integer.parseInt(value));
                if (nPos > 1) {
                    CoreMetadata original = core.get(0);
                    core.clear();
                    for (int i = 0; i < nPos; i++) {
                        core.add(original);
                    }
                }
            } else if (key.equals("data_type")) {
                setDataType(value);
            } else if (key.equals("x_dimension")) {
                int sizeX = Integer.parseInt(value);
                for (int i = 0; i < core.size(); i++) {
                    core.get(i).sizeX = sizeX;
                }
            } else if (key.equals("y_dimension")) {
                int sizeY = Integer.parseInt(value);
                for (int i = 0; i < core.size(); i++) {
                    core.get(i).sizeY = sizeY;
                }
            } else if (key.equals("z_dimension")) {
                int sizeZ = Integer.parseInt(value);
                for (int i = 0; i < core.size(); i++) {
                    core.get(i).sizeZ = sizeZ;
                }
            } else if (key.equals("scan_time")) {
                date = value;
            } else if (key.equals("data_file_pointer")) {
                String[] values = value.split(" ");
                int[] ints = new int[values.length];
                for (int i = 0; i < ints.length; i++) {
                    ints[i] = Integer.parseInt(values[i]);
                }
                byte[] b = DataTools.intsToBytes(ints, false);
                dataPointers.add(DataTools.bytesToLong(b, false));
            } else // pixel sizes stored in mm
            if (key.equals("pixel_size_x")) {
                pixelSizeX = new Double(value) * 1000;
            } else if (key.equals("pixel_size_y")) {
                pixelSizeY = new Double(value) * 1000;
            } else if (key.equals("pixel_size_z")) {
                pixelSizeZ = new Double(value) * 1000;
            }
            addGlobalMeta(key, value);
        }
    }
    for (int i = 0; i < core.size(); i++) {
        CoreMetadata ms = core.get(i);
        if (ms.sizeZ == 0) {
            ms.sizeZ = 1;
        }
        if (ms.sizeT == 0) {
            ms.sizeT = 1;
        }
        ms.sizeC = 1;
        ms.rgb = false;
        ms.interleaved = false;
        ms.indexed = false;
        ms.dimensionOrder = "XYZCT";
        ms.imageCount = ms.sizeZ * ms.sizeC * ms.sizeT;
    }
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
    String experimenter = null, instrument = null;
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        experimenter = MetadataTools.createLSID("Experimenter", 0);
        store.setExperimenterID(experimenter, 0);
        store.setExperimenterUserName(investigator, 0);
        store.setExperimenterInstitution(institution, 0);
        instrument = MetadataTools.createLSID("Instrument", 0);
        store.setInstrumentID(instrument, 0);
        store.setMicroscopeModel(model, 0);
    }
    for (int i = 0; i < core.size(); i++) {
        if (date != null) {
            String newDate = DateTools.formatDate(date, "EEE MMM dd HH:mm:ss yyyy");
            if (newDate != null) {
                store.setImageAcquisitionDate(new Timestamp(newDate), i);
            }
        }
        if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
            if (experimenter != null) {
                store.setImageExperimenterRef(experimenter, i);
            }
            if (instrument != null) {
                store.setImageInstrumentRef(instrument, i);
            }
            store.setImageDescription(description, i);
            Length sizeX = FormatTools.getPhysicalSizeX(pixelSizeX);
            Length sizeY = FormatTools.getPhysicalSizeY(pixelSizeY);
            Length sizeZ = FormatTools.getPhysicalSizeZ(pixelSizeZ);
            if (sizeX != null) {
                store.setPixelsPhysicalSizeX(sizeX, i);
            }
            if (sizeY != null) {
                store.setPixelsPhysicalSizeY(sizeY, i);
            }
            if (sizeZ != null) {
                store.setPixelsPhysicalSizeZ(sizeZ, i);
            }
        }
    }
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) CoreMetadata(loci.formats.CoreMetadata) Timestamp(ome.xml.model.primitives.Timestamp) Location(loci.common.Location)

Example 27 with Length

use of ome.units.quantity.Length in project bioformats by openmicroscopy.

the class L2DReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    if (!checkSuffix(id, "l2d") && isGroupFiles()) {
        // find the corresponding .l2d file
        Location parent = new Location(id).getAbsoluteFile().getParentFile();
        parent = parent.getParentFile();
        String[] list = parent.list();
        for (String file : list) {
            if (checkSuffix(file, "l2d")) {
                initFile(new Location(parent, file).getAbsolutePath());
                return;
            }
        }
        throw new FormatException("Could not find .l2d file");
    } else if (!isGroupFiles()) {
        super.initFile(id);
        tiffs = new String[][] { { 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();
        reader = new MinimalTiffReader();
        return;
    }
    super.initFile(id);
    String[] scans = getScanNames();
    Location parent = new Location(id).getAbsoluteFile().getParentFile();
    // remove scan names that do not correspond to existing directories
    final List<String> validScans = new ArrayList<String>();
    for (String s : scans) {
        Location scanDir = new Location(parent, s);
        if (scanDir.exists() && scanDir.isDirectory())
            validScans.add(s);
    }
    scans = validScans.toArray(new String[validScans.size()]);
    // read metadata from each scan
    tiffs = new String[scans.length][];
    metadataFiles = new List[scans.length];
    core = new ArrayList<CoreMetadata>(scans.length);
    String[] comments = new String[scans.length];
    String[] wavelengths = new String[scans.length];
    String[] dates = new String[scans.length];
    String model = null;
    tileWidth = new int[scans.length];
    tileHeight = new int[scans.length];
    core.clear();
    for (int i = 0; i < scans.length; i++) {
        CoreMetadata ms = new CoreMetadata();
        core.add(ms);
        setSeries(i);
        metadataFiles[i] = new ArrayList<String>();
        String scanName = scans[i] + ".scn";
        Location scanDir = new Location(parent, scans[i]);
        // read .scn file from each scan
        String scanPath = new Location(scanDir, scanName).getAbsolutePath();
        addDirectory(scanDir.getAbsolutePath(), i);
        String scanData = DataTools.readFile(scanPath);
        String[] lines = scanData.split("\n");
        for (String line : lines) {
            if (!line.startsWith("#")) {
                String key = line.substring(0, line.indexOf('='));
                String value = line.substring(line.indexOf('=') + 1);
                addSeriesMeta(key, value);
                if (key.equals("ExperimentNames")) {
                // TODO : parse experiment metadata - this is typically a list of
                // overlay shapes, or analysis data
                } else if (key.equals("ImageNames")) {
                    tiffs[i] = value.split(",");
                    for (int t = 0; t < tiffs[i].length; t++) {
                        tiffs[i][t] = new Location(scanDir, tiffs[i][t].trim()).getAbsolutePath();
                    }
                } else if (key.equals("Comments")) {
                    comments[i] = value;
                } else if (key.equals("ScanDate")) {
                    dates[i] = value;
                } else if (key.equals("ScannerName")) {
                    model = value;
                } else if (key.equals("ScanChannels")) {
                    wavelengths[i] = value;
                }
            }
        }
    }
    setSeries(0);
    reader = new MinimalTiffReader();
    MetadataStore store = makeFilterMetadata();
    for (int i = 0; i < getSeriesCount(); i++) {
        CoreMetadata ms = core.get(i);
        ms.imageCount = tiffs[i].length;
        ms.sizeC = tiffs[i].length;
        ms.sizeT = 1;
        ms.sizeZ = 1;
        ms.dimensionOrder = "XYCZT";
        reader.setId(tiffs[i][0]);
        ms.sizeX = reader.getSizeX();
        ms.sizeY = reader.getSizeY();
        ms.sizeC *= reader.getSizeC();
        ms.rgb = reader.isRGB();
        ms.indexed = reader.isIndexed();
        ms.littleEndian = reader.isLittleEndian();
        ms.pixelType = reader.getPixelType();
        tileWidth[i] = reader.getOptimalTileWidth();
        tileHeight[i] = reader.getOptimalTileHeight();
    }
    MetadataTools.populatePixels(store, this);
    for (int i = 0; i < getSeriesCount(); i++) {
        store.setImageName(scans[i], i);
        if (dates[i] != null) {
            dates[i] = DateTools.formatDate(dates[i], DATE_FORMAT);
            if (dates[i] != null) {
                store.setImageAcquisitionDate(new Timestamp(dates[i]), i);
            }
        }
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        String instrumentID = MetadataTools.createLSID("Instrument", 0);
        store.setInstrumentID(instrumentID, 0);
        for (int i = 0; i < getSeriesCount(); i++) {
            store.setImageInstrumentRef(instrumentID, i);
            store.setImageDescription(comments[i], i);
            if (wavelengths[i] != null) {
                String[] waves = wavelengths[i].split("[, ]");
                if (waves.length < getEffectiveSizeC()) {
                    LOGGER.debug("Expected {} wavelengths; got {} wavelengths.", getEffectiveSizeC(), waves.length);
                }
                for (int q = 0; q < waves.length; q++) {
                    String laser = MetadataTools.createLSID("LightSource", 0, q);
                    store.setLaserID(laser, 0, q);
                    Double wave = new Double(waves[q].trim());
                    Length wavelength = FormatTools.getWavelength(wave);
                    if (wavelength != null) {
                        store.setLaserWavelength(wavelength, 0, q);
                    }
                    store.setLaserType(getLaserType("Other"), 0, q);
                    store.setLaserLaserMedium(getLaserMedium("Other"), 0, q);
                    store.setChannelLightSourceSettingsID(laser, i, q);
                }
            }
        }
        store.setMicroscopeModel(model, 0);
        store.setMicroscopeType(getMicroscopeType("Other"), 0);
    }
}
Also used : ArrayList(java.util.ArrayList) CoreMetadata(loci.formats.CoreMetadata) Timestamp(ome.xml.model.primitives.Timestamp) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) Map(java.util.Map) Location(loci.common.Location)

Example 28 with Length

use of ome.units.quantity.Length in project bioformats by openmicroscopy.

the class SBIGReader 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);
    Double sizeX = null, sizeY = null;
    String date = null, description = null;
    String[] lines = DataTools.readFile(currentId).split("\n");
    for (String line : lines) {
        line = line.trim();
        int eq = line.indexOf('=');
        if (eq != -1) {
            String key = line.substring(0, eq).trim();
            String value = line.substring(eq + 1).trim();
            addGlobalMeta(key, value);
            if (key.equals("Width")) {
                m.sizeX = Integer.parseInt(value);
            } else if (key.equals("Height")) {
                m.sizeY = Integer.parseInt(value);
            } else if (key.equals("Note")) {
                description = value;
            } else if (key.equals("X_pixel_size")) {
                sizeX = new Double(value) * 1000;
            } else if (key.equals("Y_pixel_size")) {
                sizeY = new Double(value) * 1000;
            } else if (key.equals("Date")) {
                date = value;
            } else if (key.equals("Time")) {
                date += " " + value;
            }
        } else if (line.indexOf("Compressed") != -1) {
            compressed = true;
        } else if (line.equals("End"))
            break;
    }
    m.pixelType = FormatTools.UINT16;
    m.littleEndian = true;
    m.rgb = false;
    m.sizeZ = 1;
    m.sizeC = 1;
    m.sizeT = 1;
    m.imageCount = 1;
    m.dimensionOrder = "XYZCT";
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
    if (date != null) {
        date = DateTools.formatDate(date, DATE_FORMAT);
        if (date != null) {
            store.setImageAcquisitionDate(new Timestamp(date), 0);
        }
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        Length x = FormatTools.getPhysicalSizeX(sizeX);
        Length y = FormatTools.getPhysicalSizeY(sizeY);
        if (x != null) {
            store.setPixelsPhysicalSizeX(x, 0);
        }
        if (y != null) {
            store.setPixelsPhysicalSizeY(y, 0);
        }
        store.setImageDescription(description, 0);
    }
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) RandomAccessInputStream(loci.common.RandomAccessInputStream) CoreMetadata(loci.formats.CoreMetadata) Timestamp(ome.xml.model.primitives.Timestamp)

Example 29 with Length

use of ome.units.quantity.Length in project bioformats by openmicroscopy.

the class VolocityReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    if (!checkSuffix(id, "mvd2")) {
        Location file = new Location(id).getAbsoluteFile();
        Location parent = file.getParentFile().getParentFile();
        String[] files = parent.list(true);
        for (String f : files) {
            if (checkSuffix(f, "mvd2")) {
                id = new Location(parent, f).getAbsolutePath();
                break;
            }
        }
    }
    super.initFile(id);
    stacks = new ArrayList<Stack>();
    extraFiles = new ArrayList<String>();
    Location file = new Location(id).getAbsoluteFile();
    extraFiles.add(file.getAbsolutePath());
    Location parentDir = file.getParentFile();
    dir = new Location(parentDir, DATA_DIR);
    if (dir.exists()) {
        String[] files = dir.list(true);
        for (String f : files) {
            if (!checkSuffix(f, "aisf") && !checkSuffix(f, "atsf")) {
                extraFiles.add(new Location(dir, f).getAbsolutePath());
            }
        }
    }
    try {
        ServiceFactory factory = new ServiceFactory();
        MetakitService reader = factory.getInstance(MetakitService.class);
        reader.initialize(id);
        sampleTable = reader.getTableData(1);
        stringTable = reader.getTableData(2);
        reader.close();
    } catch (DependencyException e) {
        throw new MissingLibraryException("Could not find Metakit library", e);
    }
    ArrayList<String> stackNames = new ArrayList<String>();
    ArrayList<Integer> parentIDs = new ArrayList<Integer>();
    for (int i = 0; i < sampleTable.length; i++) {
        Integer stringID = (Integer) sampleTable[i][11];
        String name = getString(stringID);
        int channelIndex = getChildIndex((Integer) sampleTable[i][0], "Channels");
        if (i > 0 && (Integer) sampleTable[i][2] == 1 && (channelIndex >= 0 || (sampleTable[i][14] != null && !sampleTable[i][14].equals(0)) || ((byte[]) sampleTable[i][13]).length > 21)) {
            if (channelIndex < 0) {
                RandomAccessInputStream s = getStream(i);
                s.seek(0);
                if (s.read() != 'I') {
                    s.order(false);
                }
                s.seek(22);
                int x = s.readInt();
                int y = s.readInt();
                int z = s.readInt();
                if (x * y * z > 0 && x * y * z < (s.length() * 3)) {
                    stackNames.add(name);
                    parentIDs.add((Integer) sampleTable[i][0]);
                }
                s.close();
            } else {
                stackNames.add(name);
                parentIDs.add((Integer) sampleTable[i][0]);
            }
        }
    }
    for (int i = 0; i < parentIDs.size(); i++) {
        Stack stack = new Stack();
        stack.core = new CoreMetadata();
        Integer parent = parentIDs.get(i);
        int channelIndex = getChildIndex(parent, "Channels");
        if (channelIndex >= 0) {
            Integer[] channels = getAllChildren((Integer) sampleTable[channelIndex][0]);
            stack.core.sizeC = channels.length;
            stack.pixelsFiles = new String[stack.core.sizeC];
            stack.channelNames = new String[channels.length];
            for (int c = 0; c < channels.length; c++) {
                stack.channelNames[c] = getString((Integer) sampleTable[channels[c]][11]);
                RandomAccessInputStream data = getStream(channels[c]);
                if (data.length() > 22) {
                    data.seek(22);
                    int stackID = data.readInt();
                    Location f = new Location(dir, stackID + ".aisf");
                    if (!f.exists()) {
                        f = new Location(dir, DataTools.swap(stackID) + ".aisf");
                    }
                    stack.pixelsFiles[c] = f.getAbsolutePath();
                } else {
                    Integer child = getAllChildren((Integer) sampleTable[channels[c]][0])[0];
                    stack.pixelsFiles[c] = getFile((Integer) sampleTable[child][0], dir);
                }
                data.close();
            }
        } else {
            stack.pixelsFiles = new String[1];
            stack.pixelsFiles[0] = getFile(parent, dir);
            if (stack.pixelsFiles[0] == null || !new Location(stack.pixelsFiles[0]).exists()) {
                int row = -1;
                for (int r = 0; r < sampleTable.length; r++) {
                    if (sampleTable[r][0].equals(parent)) {
                        row = r;
                        break;
                    }
                }
                stack.pixelsFiles[0] = EMBEDDED_STREAM;
                IRandomAccess data = new ByteArrayHandle((byte[]) sampleTable[row][13]);
                Location.mapFile(stack.pixelsFiles[0], data);
            }
        }
        RandomAccessInputStream data = null;
        int timestampIndex = getChildIndex(parent, "Timepoint times stream");
        if (timestampIndex >= 0) {
            data = getStream(timestampIndex);
            data.seek(22);
            int timestampID = data.readInt();
            Location f = new Location(dir, timestampID + ".atsf");
            if (!f.exists()) {
                f = new Location(dir, DataTools.swap(timestampID) + ".atsf");
            }
            stack.timestampFile = f.getAbsolutePath();
            data.close();
        }
        int xIndex = getChildIndex(parent, "um/pixel (X)");
        if (xIndex >= 0) {
            data = getStream(xIndex);
            data.seek(SIGNATURE_SIZE);
            stack.physicalX = data.readDouble();
            data.close();
        }
        int yIndex = getChildIndex(parent, "um/pixel (Y)");
        if (yIndex >= 0) {
            data = getStream(yIndex);
            data.seek(SIGNATURE_SIZE);
            stack.physicalY = data.readDouble();
            data.close();
        }
        int zIndex = getChildIndex(parent, "um/pixel (Z)");
        if (zIndex >= 0) {
            data = getStream(zIndex);
            data.seek(SIGNATURE_SIZE);
            stack.physicalZ = data.readDouble();
            data.close();
        }
        timestampIndex = getChildIndex(parent, "TimepointTimes");
        if (timestampIndex >= 0) {
            data = getStream(timestampIndex);
            data.seek(SIGNATURE_SIZE);
            data.close();
        }
        int objectiveIndex = getChildIndex(parent, "Microscope Objective");
        if (objectiveIndex >= 0) {
            data = getStream(objectiveIndex);
            data.seek(SIGNATURE_SIZE);
            stack.magnification = data.readDouble();
            data.close();
        }
        int detectorIndex = getChildIndex(parent, "Camera/Detector");
        if (detectorIndex >= 0) {
            data = getStream(detectorIndex);
            data.seek(SIGNATURE_SIZE);
            int len = data.readInt();
            stack.detector = data.readString(len);
            data.close();
        }
        int descriptionIndex = getChildIndex(parent, "Experiment Description");
        if (descriptionIndex >= 0) {
            data = getStream(descriptionIndex);
            data.seek(SIGNATURE_SIZE);
            int len = data.readInt();
            stack.description = data.readString(len);
            data.close();
        }
        int xLocationIndex = getChildIndex(parent, "X Location");
        if (xLocationIndex >= 0) {
            data = getStream(xLocationIndex);
            data.seek(SIGNATURE_SIZE);
            stack.xLocation = data.readDouble();
            data.close();
        }
        int yLocationIndex = getChildIndex(parent, "Y Location");
        if (yLocationIndex >= 0) {
            data = getStream(yLocationIndex);
            data.seek(SIGNATURE_SIZE);
            stack.yLocation = data.readDouble();
            data.close();
        }
        int zLocationIndex = getChildIndex(parent, "Z Location");
        if (zLocationIndex >= 0) {
            data = getStream(zLocationIndex);
            data.seek(SIGNATURE_SIZE);
            stack.zLocation = data.readDouble();
            data.close();
        }
        stacks.add(stack);
    }
    for (int i = 0; i < stacks.size(); i++) {
        Stack stack = stacks.get(i);
        if (!new Location(stack.pixelsFiles[0]).exists()) {
            stacks.remove(i);
            i--;
            continue;
        }
        RandomAccessInputStream base = new RandomAccessInputStream(stack.pixelsFiles[0]);
        long baseLength = base.length();
        base.close();
        for (int q = 1; q < stack.pixelsFiles.length; q++) {
            if (!new Location(stack.pixelsFiles[q]).exists()) {
                continue;
            }
            base = new RandomAccessInputStream(stack.pixelsFiles[q]);
            long length = base.length();
            base.close();
            if (length > baseLength) {
                // split the stack
                Stack newStack = new Stack();
                newStack.timestampFile = stack.timestampFile;
                newStack.core = new CoreMetadata();
                newStack.physicalX = stack.physicalX;
                newStack.physicalY = stack.physicalY;
                newStack.physicalZ = stack.physicalZ;
                newStack.magnification = stack.magnification;
                newStack.detector = stack.detector;
                newStack.description = stack.description;
                newStack.xLocation = stack.xLocation;
                newStack.yLocation = stack.yLocation;
                newStack.zLocation = stack.zLocation;
                String[] pixels = stack.pixelsFiles;
                newStack.pixelsFiles = new String[pixels.length - q];
                System.arraycopy(pixels, q, newStack.pixelsFiles, 0, newStack.pixelsFiles.length);
                stack.pixelsFiles = new String[q];
                System.arraycopy(pixels, 0, stack.pixelsFiles, 0, q);
                String[] channels = stack.channelNames;
                newStack.channelNames = new String[channels.length - q];
                System.arraycopy(channels, q, newStack.channelNames, 0, newStack.channelNames.length);
                stack.channelNames = new String[q];
                System.arraycopy(channels, 0, stack.channelNames, 0, q);
                newStack.core.sizeC = newStack.channelNames.length;
                stack.core.sizeC = stack.channelNames.length;
                stacks.add(i + 1, newStack);
                stackNames.add(i + 1, stackNames.get(i));
            }
        }
    }
    int seriesCount = stacks.size();
    core.clear();
    for (int i = 0; i < seriesCount; i++) {
        Stack stack = stacks.get(i);
        CoreMetadata ms = stack.core;
        core.add(ms);
        setSeries(i);
        ms.littleEndian = true;
        if (stack.timestampFile != null) {
            RandomAccessInputStream s = new RandomAccessInputStream(stack.timestampFile);
            s.seek(0);
            if (s.read() != 'I') {
                ms.littleEndian = false;
            }
            s.seek(17);
            s.order(isLittleEndian());
            ms.sizeT = s.readInt();
            Double firstStamp = null;
            Double[] stamps = new Double[ms.sizeT];
            for (int t = 0; t < ms.sizeT; t++) {
                // timestamps are stored in microseconds
                double timestamp = s.readLong() / 1000000.0;
                if (firstStamp == null) {
                    firstStamp = timestamp;
                }
                stamps[t] = timestamp - firstStamp;
            }
            timestamps.add(stamps);
            s.close();
        } else {
            ms.sizeT = 1;
        }
        ms.rgb = false;
        ms.interleaved = true;
        ms.dimensionOrder = "XYCZT";
        RandomAccessInputStream s = new RandomAccessInputStream(stack.pixelsFiles[0]);
        s.order(isLittleEndian());
        if (checkSuffix(stack.pixelsFiles[0], "aisf")) {
            s.seek(18);
            stack.blockSize = s.readShort() * 256;
            s.skipBytes(5);
            int x = s.readInt();
            int y = s.readInt();
            int zStart = s.readInt();
            int w = s.readInt();
            int h = s.readInt();
            if (w - x < 0 || h - y < 0 || (w - x) * (h - y) < 0) {
                ms.littleEndian = !isLittleEndian();
                s.order(isLittleEndian());
                s.seek(s.getFilePointer() - 20);
                x = s.readInt();
                y = s.readInt();
                zStart = s.readInt();
                w = s.readInt();
                h = s.readInt();
            }
            ms.sizeX = w - x;
            ms.sizeY = h - y;
            ms.sizeZ = s.readInt() - zStart;
            ms.imageCount = getSizeZ() * getSizeC() * getSizeT();
            ms.pixelType = FormatTools.INT8;
            int planesPerFile = getSizeZ() * getSizeT();
            int planeSize = FormatTools.getPlaneSize(this);
            int bytesPerPlane = (int) ((s.length() - stack.blockSize) / planesPerFile);
            int bytesPerPixel = 0;
            while (bytesPerPlane >= planeSize) {
                bytesPerPixel++;
                bytesPerPlane -= planeSize;
            }
            if ((bytesPerPixel % 3) == 0) {
                ms.sizeC *= 3;
                ms.rgb = true;
                bytesPerPixel /= 3;
            }
            ms.pixelType = FormatTools.pixelTypeFromBytes(bytesPerPixel, false, bytesPerPixel > 2);
            // full timepoints are padded to have a multiple of 256 bytes
            int timepoint = FormatTools.getPlaneSize(this) * getSizeZ();
            stack.planePadding = stack.blockSize - (timepoint % stack.blockSize);
            if (stack.planePadding == stack.blockSize) {
                stack.planePadding = 0;
            }
        } else {
            boolean embedded = Location.getMappedFile(EMBEDDED_STREAM) != null;
            s.seek(0);
            if (s.read() != 'I') {
                ms.littleEndian = false;
                s.order(false);
            }
            s.seek(22);
            ms.sizeX = s.readInt();
            ms.sizeY = s.readInt();
            ms.sizeZ = s.readInt();
            ms.sizeC = embedded ? 1 : 4;
            ms.imageCount = getSizeZ() * getSizeT();
            ms.rgb = ms.sizeC > 1;
            ms.pixelType = FormatTools.UINT8;
            stack.blockSize = embedded ? (int) s.getFilePointer() : 99;
            stack.planePadding = 0;
            if (s.length() > ms.sizeX * ms.sizeY * ms.sizeZ * 6) {
                ms.pixelType = FormatTools.UINT16;
                ms.sizeC = 3;
                ms.rgb = true;
            }
            if (s.length() < (ms.sizeX * ms.sizeY * ms.sizeZ * ms.sizeC)) {
                ms.rgb = false;
                ms.sizeC = 1;
                long pixels = ms.sizeX * ms.sizeY * ms.sizeZ;
                double approximateBytes = (double) s.length() / pixels;
                int bytes = (int) Math.ceil(approximateBytes);
                if (bytes == 0) {
                    bytes = 1;
                } else if (bytes == 3) {
                    bytes = 2;
                }
                ms.pixelType = FormatTools.pixelTypeFromBytes(bytes, false, false);
                s.seek(70);
                stack.blockSize = s.readInt();
                stack.clippingData = true;
            }
        }
        s.close();
    }
    setSeries(0);
    for (int i = 0; i < getSeriesCount(); i++) {
        setSeries(i);
        Stack stack = stacks.get(i);
        addSeriesMeta("Name", stackNames.get(i));
        addSeriesMeta("Pixel width (in microns)", stack.physicalX);
        addSeriesMeta("Pixel height (in microns)", stack.physicalY);
        addSeriesMeta("Z step (in microns)", stack.physicalZ);
        addSeriesMeta("Objective magnification", stack.magnification);
        addSeriesMeta("Camera/Detector", stack.detector);
        addSeriesMeta("Description", stack.description);
        addSeriesMeta("X Location", stack.xLocation);
        addSeriesMeta("Y Location", stack.yLocation);
        addSeriesMeta("Z Location", stack.zLocation);
        if (stack.channelNames != null) {
            for (int c = 0; c < stack.channelNames.length; c++) {
                addSeriesMetaList("Channel", stack.channelNames[c]);
            }
        }
    }
    setSeries(0);
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);
    String instrument = MetadataTools.createLSID("Instrument", 0);
    store.setInstrumentID(instrument, 0);
    for (int i = 0; i < getSeriesCount(); i++) {
        store.setImageInstrumentRef(instrument, i);
        setSeries(i);
        Stack stack = stacks.get(i);
        store.setImageName(stackNames.get(i), i);
        store.setImageDescription(stack.description, i);
        if (stack.channelNames != null) {
            for (int c = 0; c < getEffectiveSizeC(); c++) {
                store.setChannelName(stack.channelNames[c], i, c);
            }
        }
        Length sizeX = FormatTools.getPhysicalSizeX(stack.physicalX);
        Length sizeY = FormatTools.getPhysicalSizeY(stack.physicalY);
        Length sizeZ = FormatTools.getPhysicalSizeZ(stack.physicalZ);
        if (sizeX != null) {
            store.setPixelsPhysicalSizeX(sizeX, i);
        }
        if (sizeY != null) {
            store.setPixelsPhysicalSizeY(sizeY, i);
        }
        if (sizeZ != null) {
            store.setPixelsPhysicalSizeZ(sizeZ, i);
        }
        String objective = MetadataTools.createLSID("Objective", 0, i);
        store.setObjectiveID(objective, 0, i);
        store.setObjectiveNominalMagnification(stack.magnification, 0, i);
        store.setObjectiveCorrection(getCorrection("Other"), 0, i);
        store.setObjectiveImmersion(getImmersion("Other"), 0, i);
        store.setObjectiveSettingsID(objective, i);
        String detectorID = MetadataTools.createLSID("Detector", 0, i);
        store.setDetectorID(detectorID, 0, i);
        store.setDetectorModel(stack.detector, 0, i);
        for (int c = 0; c < getEffectiveSizeC(); c++) {
            store.setDetectorSettingsID(detectorID, i, c);
        }
        for (int img = 0; img < getImageCount(); img++) {
            int[] coords = getZCTCoords(img);
            int z = coords[0];
            final Length xLoc = new Length(stack.xLocation, UNITS.REFERENCEFRAME);
            final Length yLoc = new Length(stack.yLocation, UNITS.REFERENCEFRAME);
            store.setPlanePositionX(xLoc, i, img);
            store.setPlanePositionY(yLoc, i, img);
            if (stack.physicalZ != null) {
                final double zLocNumber = stack.zLocation + z * stack.physicalZ;
                final Length zLoc = new Length(zLocNumber, UNITS.REFERENCEFRAME);
                store.setPlanePositionZ(zLoc, i, img);
            }
            if (i < timestamps.size() && coords[2] < timestamps.get(i).length && timestamps.get(i)[coords[2]] != null) {
                store.setPlaneDeltaT(new Time(timestamps.get(i)[coords[2]], UNITS.SECOND), i, img);
            }
        }
    }
    setSeries(0);
}
Also used : ServiceFactory(loci.common.services.ServiceFactory) ArrayList(java.util.ArrayList) Time(ome.units.quantity.Time) IRandomAccess(loci.common.IRandomAccess) DependencyException(loci.common.services.DependencyException) CoreMetadata(loci.formats.CoreMetadata) MetadataStore(loci.formats.meta.MetadataStore) MetakitService(loci.formats.services.MetakitService) Length(ome.units.quantity.Length) MissingLibraryException(loci.formats.MissingLibraryException) RandomAccessInputStream(loci.common.RandomAccessInputStream) ByteArrayHandle(loci.common.ByteArrayHandle) Location(loci.common.Location)

Example 30 with Length

use of ome.units.quantity.Length in project bioformats by openmicroscopy.

the class WATOPReader 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 = true;
    in.order(isLittleEndian());
    String comment = null;
    MetadataLevel level = getMetadataOptions().getMetadataLevel();
    if (level != MetadataLevel.MINIMUM) {
        in.seek(49);
        comment = in.readString(33);
    }
    in.seek(211);
    int year = in.readInt();
    int month = in.readInt();
    int day = in.readInt();
    int hour = in.readInt();
    int min = in.readInt();
    String date = year + "-" + month + "-" + day + "T" + hour + ":" + min;
    date = DateTools.formatDate(date, "yyyy-MM-dd'T'HH:mm");
    in.skipBytes(8);
    double xSize = in.readInt() / 100d;
    double ySize = in.readInt() / 100d;
    double zSize = in.readInt() / 100d;
    m.sizeX = in.readInt();
    m.sizeY = in.readInt();
    if (level != MetadataLevel.MINIMUM) {
        double tunnelCurrent = in.readInt() / 1000d;
        double sampleVolts = in.readInt() / 1000d;
        in.skipBytes(180);
        int originalZMax = in.readInt();
        int originalZMin = in.readInt();
        int zMax = in.readInt();
        int zMin = in.readInt();
        addGlobalMeta("Comment", comment);
        addGlobalMeta("X size (in um)", xSize);
        addGlobalMeta("Y size (in um)", ySize);
        addGlobalMeta("Z size (in um)", zSize);
        addGlobalMeta("Tunnel current (in amps)", tunnelCurrent);
        addGlobalMeta("Sample volts", sampleVolts);
        addGlobalMeta("Acquisition date", date);
    }
    m.pixelType = FormatTools.INT16;
    m.sizeC = 1;
    m.sizeZ = 1;
    m.sizeT = 1;
    m.imageCount = 1;
    m.dimensionOrder = "XYZCT";
    m.rgb = false;
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
    if (date != null) {
        store.setImageAcquisitionDate(new Timestamp(date), 0);
    }
    if (level != MetadataLevel.MINIMUM) {
        store.setImageDescription(comment, 0);
        Length sizeX = FormatTools.getPhysicalSizeX((double) xSize / getSizeX());
        Length sizeY = FormatTools.getPhysicalSizeY((double) ySize / getSizeY());
        if (sizeX != null) {
            store.setPixelsPhysicalSizeX(sizeX, 0);
        }
        if (sizeY != null) {
            store.setPixelsPhysicalSizeY(sizeY, 0);
        }
    }
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) RandomAccessInputStream(loci.common.RandomAccessInputStream) CoreMetadata(loci.formats.CoreMetadata) Timestamp(ome.xml.model.primitives.Timestamp)

Aggregations

Length (ome.units.quantity.Length)154 MetadataStore (loci.formats.meta.MetadataStore)82 CoreMetadata (loci.formats.CoreMetadata)74 Timestamp (ome.xml.model.primitives.Timestamp)52 RandomAccessInputStream (loci.common.RandomAccessInputStream)48 Time (ome.units.quantity.Time)46 FormatException (loci.formats.FormatException)39 Location (loci.common.Location)34 ArrayList (java.util.ArrayList)29 IMetadata (loci.formats.meta.IMetadata)13 NonNegativeInteger (ome.xml.model.primitives.NonNegativeInteger)13 ServiceFactory (loci.common.services.ServiceFactory)12 IOException (java.io.IOException)11 DependencyException (loci.common.services.DependencyException)11 PositiveInteger (ome.xml.model.primitives.PositiveInteger)11 MetadataRetrieve (loci.formats.meta.MetadataRetrieve)10 ElectricPotential (ome.units.quantity.ElectricPotential)9 Test (org.testng.annotations.Test)9 Element (org.w3c.dom.Element)9 NodeList (org.w3c.dom.NodeList)9