Search in sources :

Example 1 with Img

use of net.imglib2.img.Img in project vcell by virtualcell.

the class DeconstructGeometryCommand method run.

@Override
public void run() {
    // Crop to get a z-stack over time (remove channel dimension)
    long maxX = fluorData.max(fluorData.dimensionIndex(Axes.X));
    long maxY = fluorData.max(fluorData.dimensionIndex(Axes.Y));
    long maxZ = fluorData.max(fluorData.dimensionIndex(Axes.Z));
    long maxTime = fluorData.max(fluorData.dimensionIndex(Axes.TIME));
    Img fluorImg = fluorData.getImgPlus().getImg();
    FinalInterval intervals = Intervals.createMinMax(0, 0, 0, 0, 0, maxX, maxY, maxZ, 0, maxTime);
    RandomAccessibleInterval fluorImgCropped = ops.transform().crop(fluorImg, intervals, true);
    // Calculate scale factors
    double[] scaleFactors = { 1, 1, 1, 1 };
    for (int i = 0; i < geomData.numDimensions(); i++) {
        scaleFactors[i] = geomData.dimension(i) / (double) fluorImgCropped.dimension(i);
    }
    // Scale the fluorescence dataset to match the geometry
    NLinearInterpolatorFactory interpolatorFactory = new NLinearInterpolatorFactory();
    RandomAccessibleInterval fluorScaled = ops.transform().scale(fluorImgCropped, scaleFactors, interpolatorFactory);
    // Crop out the first slice of each z-stack in time series
    intervals = Intervals.createMinMax(0, 0, 0, 0, fluorScaled.dimension(0) - 1, fluorScaled.dimension(1) - 1, 0, fluorScaled.dimension(3) - 1);
    IntervalView fluorXYT = (IntervalView) ops.transform().crop(fluorScaled, intervals, true);
    // Create a blank image of the same X-Y-Time dimensions
    long[] dimensions = { fluorXYT.dimension(0), fluorXYT.dimension(1), fluorXYT.dimension(2) };
    Img<DoubleType> result = ops.create().img(dimensions);
    // Calculate constant d in TIRF exponential decay function
    theta = theta * 2 * Math.PI / 360;
    double n1 = 1.52;
    double n2 = 1.38;
    double d = lambda * Math.pow((Math.pow(n1, 2) * Math.pow(Math.sin(theta), 2) - Math.pow(n2, 2)), -0.5) / (4 * Math.PI);
    // Iterate through each time point, using 3D geometry to generate 2D intensities
    Cursor<DoubleType> cursor = fluorXYT.localizingCursor();
    RandomAccess fluorRA = fluorScaled.randomAccess();
    RandomAccess<RealType<?>> geomRA = geomData.randomAccess();
    RandomAccess<DoubleType> resultRA = result.randomAccess();
    maxZ = geomData.dimension(2) - 1;
    while (cursor.hasNext()) {
        cursor.fwd();
        int[] positionXYZ = { cursor.getIntPosition(0), cursor.getIntPosition(1), (int) maxZ - 1 };
        int[] positionXYZT = { cursor.getIntPosition(0), cursor.getIntPosition(1), (int) maxZ - 1, cursor.getIntPosition(2) };
        resultRA.setPosition(cursor);
        geomRA.setPosition(positionXYZ);
        double sum = 0.0;
        while (positionXYZ[2] >= 0 && geomRA.get().getRealDouble() != 0.0) {
            fluorRA.setPosition(positionXYZT);
            geomRA.setPosition(positionXYZ);
            sum += geomRA.get().getRealDouble() * Math.exp(-zSpacing * positionXYZ[2] / d);
            positionXYZ[2]--;
        }
        resultRA.get().set(sum);
    }
    System.out.println("done");
    displayService.createDisplay(result);
}
Also used : Img(net.imglib2.img.Img) NLinearInterpolatorFactory(net.imglib2.interpolation.randomaccess.NLinearInterpolatorFactory) RandomAccess(net.imglib2.RandomAccess) RealType(net.imglib2.type.numeric.RealType) IntervalView(net.imglib2.view.IntervalView) RandomAccessibleInterval(net.imglib2.RandomAccessibleInterval) DoubleType(net.imglib2.type.numeric.real.DoubleType) FinalInterval(net.imglib2.FinalInterval)

Example 2 with Img

use of net.imglib2.img.Img in project vcell by virtualcell.

the class VCellResultService method importCsv.

public Dataset importCsv(File directory) throws FileNotFoundException {
    File[] files = directory.listFiles();
    // TODO: Better handling
    if (files == null)
        return null;
    ArrayList<ArrayList<Float>> timeSeries = new ArrayList<>(files.length);
    Scanner scanner;
    int dataSize = 0;
    for (File file : files) {
        scanner = new Scanner(file);
        scanner.useDelimiter("[,\n]");
        while (scanner.hasNext() && !scanner.hasNextDouble()) {
            scanner.next();
        }
        if (!scanner.hasNextDouble()) {
            scanner.close();
            return null;
        }
        ArrayList<Float> data = new ArrayList<>();
        while (scanner.hasNextDouble()) {
            data.add(scanner.nextFloat());
        }
        scanner.close();
        timeSeries.add(data);
        dataSize = data.size();
    }
    int[] dimensions = { dataSize, timeSeries.size() };
    Img<FloatType> img = new ArrayImgFactory<FloatType>().create(dimensions, new FloatType());
    Cursor<FloatType> cursor = img.localizingCursor();
    while (cursor.hasNext()) {
        cursor.next();
        int xPos = cursor.getIntPosition(0);
        int tPos = cursor.getIntPosition(1);
        Float val = timeSeries.get(tPos).get(xPos);
        cursor.get().set(val);
    }
    Dataset dataset = datasetService.create(img);
    // Drop single dimensions
    @SuppressWarnings("unchecked") ImgPlus<FloatType> imgPlus = (ImgPlus<FloatType>) dataset.getImgPlus();
    FinalInterval interval = Intervals.createMinMax(0, 0, imgPlus.dimension(0) - 1, imgPlus.dimension(1) - 1);
    ImgPlus<FloatType> cropped = ops.transform().crop(imgPlus, interval, true);
    dataset.setImgPlus(cropped);
    System.out.println(dataset.numDimensions());
    dataset.setName(directory.getName());
    return dataset;
}
Also used : Scanner(java.util.Scanner) ImgPlus(net.imagej.ImgPlus) Dataset(net.imagej.Dataset) ArrayList(java.util.ArrayList) FloatType(net.imglib2.type.numeric.real.FloatType) FinalInterval(net.imglib2.FinalInterval) File(java.io.File)

Example 3 with Img

use of net.imglib2.img.Img in project vcell by virtualcell.

the class ImportSBMLCommand method run.

@Override
public void run() {
    // Read SBML document
    SBMLDocument document = null;
    try {
        document = SBMLReader.read(file);
    } catch (XMLStreamException | IOException e) {
        e.printStackTrace();
    }
    // Get SBML geometry
    SpatialModelPlugin modelPlugin = (SpatialModelPlugin) document.getModel().getPlugin("spatial");
    Geometry geometry = modelPlugin.getGeometry();
    SampledField sampledField = geometry.getListOfSampledFields().get(0);
    // Parse pixel values to int
    String[] imgStringArray = sampledField.getSamples().split(" ");
    int[] imgArray = new int[imgStringArray.length];
    for (int i = 0; i < imgStringArray.length; i++) {
        imgArray[i] = Integer.parseInt(imgStringArray[i]);
    }
    // Create the image and display
    int width = sampledField.getNumSamples1();
    int height = sampledField.getNumSamples2();
    ArrayImg<UnsignedIntType, IntArray> img = ArrayImgs.unsignedInts(imgArray, width, height);
    displayService.createDisplay(img);
}
Also used : SBMLDocument(org.sbml.jsbml.SBMLDocument) SpatialModelPlugin(org.sbml.jsbml.ext.spatial.SpatialModelPlugin) IOException(java.io.IOException) Geometry(org.sbml.jsbml.ext.spatial.Geometry) XMLStreamException(javax.xml.stream.XMLStreamException) IntArray(net.imglib2.img.basictypeaccess.array.IntArray) SampledField(org.sbml.jsbml.ext.spatial.SampledField) UnsignedIntType(net.imglib2.type.numeric.integer.UnsignedIntType)

Example 4 with Img

use of net.imglib2.img.Img in project vcell by virtualcell.

the class ConstructTIRFGeometry method run.

@Override
public void run() {
    // Calculate constant d in TIRF exponential decay function
    // Angle of incidence in radians
    theta = theta * 2 * Math.PI / 360;
    // Refractive index of glass
    final double n1 = 1.52;
    // Refractive index of cytosol
    final double n2 = 1.38;
    final double d = lambda * Math.pow((Math.pow(n1, 2) * Math.pow(Math.sin(theta), 2) - Math.pow(n2, 2)), -0.5) / (4 * Math.PI);
    System.out.println("d: " + d);
    final double fluorPerMolecule = 250;
    // Get frame of interest to define geometry
    long maxX = data.dimension(0) - 1;
    long maxY = data.dimension(1) - 1;
    Interval interval = Intervals.createMinMax(0, 0, sliceIndex, maxX, maxY, sliceIndex);
    RandomAccessibleInterval<T> croppedRAI = ops.transform().crop(data, interval, true);
    // Subtract lowest pixel value
    IterableInterval<T> dataII = Views.iterable(croppedRAI);
    double min = ops.stats().min(dataII).getRealDouble();
    Cursor<T> dataCursor = dataII.cursor();
    while (dataCursor.hasNext()) {
        double val = dataCursor.next().getRealDouble();
        dataCursor.get().setReal(val - min);
    }
    // Perform Gaussian blur
    RandomAccessibleInterval<T> blurredRAI = ops.filter().gauss(croppedRAI, 2);
    IterableInterval<T> blurredII = Views.iterable(blurredRAI);
    // Segment slice by threshold and fill holes
    IterableInterval<BitType> thresholded = ops.threshold().huang(blurredII);
    Img<BitType> thresholdedImg = ops.convert().bit(thresholded);
    RandomAccessibleInterval<BitType> thresholdedRAI = ops.morphology().fillHoles(thresholdedImg);
    // Get the largest region
    RandomAccessibleInterval<LabelingType<ByteType>> labeling = ops.labeling().cca(thresholdedRAI, ConnectedComponents.StructuringElement.EIGHT_CONNECTED);
    LabelRegions<ByteType> labelRegions = new LabelRegions<>(labeling);
    Iterator<LabelRegion<ByteType>> iterator = labelRegions.iterator();
    LabelRegion<ByteType> maxRegion = iterator.next();
    while (iterator.hasNext()) {
        LabelRegion<ByteType> currRegion = iterator.next();
        if (currRegion.size() > maxRegion.size()) {
            maxRegion = currRegion;
        }
    }
    // Generate z index map
    double iMax = ops.stats().max(dataII).getRealDouble();
    Img<UnsignedShortType> dataImg = ops.convert().uint16(dataII);
    Img<UnsignedShortType> zMap = ops.convert().uint16(ops.create().img(dataII));
    LabelRegionCursor cursor = maxRegion.localizingCursor();
    RandomAccess<UnsignedShortType> zMapRA = zMap.randomAccess();
    RandomAccess<UnsignedShortType> dataRA = dataImg.randomAccess();
    while (cursor.hasNext()) {
        cursor.fwd();
        zMapRA.setPosition(cursor);
        dataRA.setPosition(cursor);
        double val = dataRA.get().getRealDouble();
        // Log of 0 is undefined
        if (val < 1) {
            val = 1;
        }
        int z = (int) Math.round(-d * Math.log(val / iMax) / zRes);
        zMapRA.get().set(z);
    }
    System.out.println("6");
    // Use map to construct 3D geometry
    // Add 5 slices of padding on top
    int maxZ = (int) ops.stats().max(zMap).getRealDouble() + 5;
    long[] resultDimensions = { maxX + 1, maxY + 1, maxZ };
    Img<BitType> result = new ArrayImgFactory<BitType>().create(resultDimensions, new BitType());
    RandomAccess<BitType> resultRA = result.randomAccess();
    System.out.println(maxZ);
    cursor.reset();
    while (cursor.hasNext()) {
        cursor.fwd();
        zMapRA.setPosition(cursor);
        int zIndex = zMapRA.get().get();
        int[] position = { cursor.getIntPosition(0), cursor.getIntPosition(1), zIndex };
        while (position[2] < maxZ) {
            resultRA.setPosition(position);
            resultRA.get().set(true);
            position[2]++;
        }
    }
    output = datasetService.create(result);
    CalibratedAxis[] axes = new DefaultLinearAxis[] { new DefaultLinearAxis(Axes.X), new DefaultLinearAxis(Axes.Y), new DefaultLinearAxis(Axes.Z) };
    output.setAxes(axes);
    System.out.println("Done constructing geometry");
}
Also used : ByteType(net.imglib2.type.numeric.integer.ByteType) DefaultLinearAxis(net.imagej.axis.DefaultLinearAxis) BitType(net.imglib2.type.logic.BitType) LabelRegionCursor(net.imglib2.roi.labeling.LabelRegionCursor) LabelingType(net.imglib2.roi.labeling.LabelingType) UnsignedShortType(net.imglib2.type.numeric.integer.UnsignedShortType) LabelRegion(net.imglib2.roi.labeling.LabelRegion) CalibratedAxis(net.imagej.axis.CalibratedAxis) LabelRegions(net.imglib2.roi.labeling.LabelRegions) RandomAccessibleInterval(net.imglib2.RandomAccessibleInterval) Interval(net.imglib2.Interval) IterableInterval(net.imglib2.IterableInterval)

Example 5 with Img

use of net.imglib2.img.Img in project vcell by virtualcell.

the class ProjectService method load.

public Task<Project, String> load(File root) {
    final Task<Project, String> task = new Task<Project, String>() {

        @Override
        protected Project doInBackground() throws Exception {
            Project project = new Project(root.getName());
            String rootPath = root.getAbsolutePath();
            File[] dataFiles = Paths.get(rootPath, "data").toFile().listFiles();
            File[] geometryFiles = Paths.get(rootPath, "geometry").toFile().listFiles();
            File[] modelDirectories = Paths.get(rootPath, "models").toFile().listFiles();
            File[] resultsFiles = Paths.get(rootPath, "results").toFile().listFiles();
            int numFiles = dataFiles.length + geometryFiles.length + modelDirectories.length + resultsFiles.length;
            int numLoaded = 0;
            if (dataFiles != null) {
                for (File dataFile : dataFiles) {
                    try {
                        setSubtask(dataFile.getName());
                        Dataset data = datasetIOService.open(dataFile.getAbsolutePath());
                        project.getData().add(data);
                        numLoaded++;
                        setProgress(numLoaded * 100 / numFiles);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (geometryFiles != null) {
                for (File geometryFile : geometryFiles) {
                    try {
                        setSubtask(geometryFile.getName());
                        Dataset geometry = datasetIOService.open(geometryFile.getAbsolutePath());
                        // Geometry datasets are saved as 8-bit images so we must convert back to 1-bit
                        if (geometry.firstElement() instanceof UnsignedByteType) {
                            @SuppressWarnings("unchecked") Img<UnsignedByteType> img = (Img<UnsignedByteType>) geometry.getImgPlus().getImg();
                            Img<BitType> converted = opService.convert().bit(img);
                            ImgPlus<BitType> convertedImgPlus = new ImgPlus<>(converted, geometry.getName());
                            geometry.setImgPlus(convertedImgPlus);
                        }
                        project.getGeometry().add(geometry);
                        numLoaded++;
                        setProgress(numLoaded * 100 / numFiles);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (modelDirectories != null) {
                for (File modelDirectory : modelDirectories) {
                    setSubtask(modelDirectory.getName());
                    SBMLDocument sbmlDocument = null;
                    BufferedImage image = null;
                    File[] modelFiles = modelDirectory.listFiles();
                    System.out.println(modelFiles.length);
                    // Invalid model directory
                    if (modelFiles.length > 2)
                        continue;
                    for (File modelFile : modelFiles) {
                        System.out.println(modelFile.getName());
                        if (FilenameUtils.getExtension(modelFile.getName()).equals("xml")) {
                            sbmlDocument = new SBMLReader().readSBML(modelFile);
                            System.out.println("Loaded sbml");
                        } else if (FilenameUtils.getExtension(modelFile.getName()).equals("png")) {
                            image = ImageIO.read(modelFile);
                            System.out.println("Loaded image");
                        }
                    }
                    if (sbmlDocument != null) {
                        VCellModel vCellModel = new VCellModel(modelDirectory.getName(), null, sbmlDocument);
                        vCellModel.setImage(image);
                        project.getModels().add(vCellModel);
                        System.out.println("Added model");
                    }
                    numLoaded++;
                    setProgress(numLoaded * 100 / numFiles);
                }
            }
            if (resultsFiles != null) {
                for (File resultsFile : resultsFiles) {
                    try {
                        setSubtask(resultsFile.getName());
                        Dataset results = datasetIOService.open(resultsFile.getAbsolutePath());
                        // Loading 1-dimensional tif images adds a dimension
                        // so must crop out empty dimensions
                        @SuppressWarnings("unchecked") ImgPlus<T> imgPlus = (ImgPlus<T>) results.getImgPlus();
                        int numDimensions = imgPlus.numDimensions();
                        long[] dimensions = new long[2 * imgPlus.numDimensions()];
                        for (int i = 0; i < numDimensions; i++) {
                            dimensions[i] = 0;
                            dimensions[i + numDimensions] = imgPlus.dimension(i) - 1;
                        }
                        FinalInterval interval = Intervals.createMinMax(dimensions);
                        ImgPlus<T> cropped = opService.transform().crop(imgPlus, interval, true);
                        results.setImgPlus(cropped);
                        project.getResults().add(results);
                        numLoaded++;
                        setProgress(numLoaded * 100 / numFiles);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            currentProjectRoot = root;
            return project;
        }
    };
    return task;
}
Also used : Task(org.vcell.imagej.common.gui.Task) SBMLDocument(org.sbml.jsbml.SBMLDocument) UnsignedByteType(net.imglib2.type.numeric.integer.UnsignedByteType) BufferedImage(java.awt.image.BufferedImage) BitType(net.imglib2.type.logic.BitType) Img(net.imglib2.img.Img) SBMLReader(org.sbml.jsbml.SBMLReader) ImgPlus(net.imagej.ImgPlus) Dataset(net.imagej.Dataset) IOException(java.io.IOException) VCellModel(org.vcell.imagej.common.vcell.VCellModel) FinalInterval(net.imglib2.FinalInterval) File(java.io.File)

Aggregations

Dataset (net.imagej.Dataset)4 Img (net.imglib2.img.Img)4 File (java.io.File)3 ImgPlus (net.imagej.ImgPlus)3 FinalInterval (net.imglib2.FinalInterval)3 BitType (net.imglib2.type.logic.BitType)3 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 RandomAccessibleInterval (net.imglib2.RandomAccessibleInterval)2 UnsignedByteType (net.imglib2.type.numeric.integer.UnsignedByteType)2 DoubleType (net.imglib2.type.numeric.real.DoubleType)2 SBMLDocument (org.sbml.jsbml.SBMLDocument)2 Task (org.vcell.imagej.common.gui.Task)2 BufferedImage (java.awt.image.BufferedImage)1 Path (java.nio.file.Path)1 List (java.util.List)1 Scanner (java.util.Scanner)1 XMLStreamException (javax.xml.stream.XMLStreamException)1 CalibratedAxis (net.imagej.axis.CalibratedAxis)1 DefaultLinearAxis (net.imagej.axis.DefaultLinearAxis)1