Search in sources :

Example 21 with Dimensions

use of net.imglib2.Dimensions 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)

Example 22 with Dimensions

use of net.imglib2.Dimensions in project vcell by virtualcell.

the class ImageStatsForPlotting method computeMean.

/**
 * Computes the mean of each XY slice along the 3rd dimension
 * TODO: Currently assumes only 3 dimensions, must handle time series of z stacks and multiple channels
 * @param data
 * @return Pair containing A) the 3rd dimension index, and B) the mean value of the XY slice
 */
private Pair<double[], double[]> computeMean(RandomAccessibleInterval<T> data, IterableInterval<BitType> mask) {
    double[] indices = new double[(int) data.dimension(2)];
    double[] means = new double[indices.length];
    for (int z = 0; z < indices.length; z++) {
        FinalInterval interval = Intervals.createMinMax(0, 0, z, data.dimension(0) - 1, data.dimension(1) - 1, z);
        double mean = 0.0;
        RandomAccessibleInterval<T> cropped = ops.transform().crop(data, interval);
        if (mask == null) {
            mean = ops.stats().mean(Views.iterable(cropped)).getRealDouble();
        } else {
            Cursor<BitType> maskCursor = mask.localizingCursor();
            RandomAccess<T> dataRA = cropped.randomAccess();
            RealSum sum = new RealSum();
            int size = 0;
            maskCursor.reset();
            while (maskCursor.hasNext()) {
                maskCursor.fwd();
                if (maskCursor.get().get()) {
                    dataRA.setPosition(maskCursor);
                    sum.add(dataRA.get().getRealDouble());
                    size++;
                }
            }
            mean = sum.getSum() / size;
        }
        indices[z] = z;
        means[z] = mean;
    }
    return new ValuePair<double[], double[]>(indices, means);
}
Also used : BitType(net.imglib2.type.logic.BitType) ValuePair(net.imglib2.util.ValuePair) FinalInterval(net.imglib2.FinalInterval) RealSum(net.imglib2.util.RealSum)

Example 23 with Dimensions

use of net.imglib2.Dimensions in project vcell by virtualcell.

the class VCellService method runSimulation.

private static Task<List<Dataset>, SimulationState> runSimulation(final SimulationServiceImpl client, final VCellModel vCellModel, final SimulationSpec simSpec, final List<Species> outputSpecies, final boolean shouldCreateIndividualDatasets, final OpService opService, final DatasetService datasetService) throws IOException, XMLStreamException {
    final Task<List<Dataset>, SimulationState> task = new Task<List<Dataset>, SimulationState>() {

        @Override
        protected List<Dataset> doInBackground() throws Exception {
            setSubtask(SimulationState.notRun);
            final File sbmlSpatialFile = new File(vCellModel.getName() + ".xml");
            new SBMLWriter().write(vCellModel.getSbmlDocument(), sbmlSpatialFile);
            final SBMLModel model = new SBMLModel();
            model.setFilepath(sbmlSpatialFile.getAbsolutePath());
            final SimulationInfo simulationInfo = client.computeModel(model, simSpec);
            try {
                Thread.sleep(500);
            } catch (final InterruptedException e) {
                e.printStackTrace();
            }
            setSubtask(SimulationState.running);
            while (client.getStatus(simulationInfo).getSimState() == SimulationState.running) {
                System.out.println("waiting for simulation results");
                try {
                    Thread.sleep(500);
                } catch (final InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (client.getStatus(simulationInfo).getSimState() == SimulationState.failed) {
                setSubtask(SimulationState.failed);
                return null;
            }
            final List<Dataset> results = new ArrayList<>();
            final List<VariableInfo> vars = client.getVariableList(simulationInfo);
            final List<Double> times = client.getTimePoints(simulationInfo);
            for (final VariableInfo var : vars) {
                if (outputSpecies.stream().anyMatch(species -> species.getId().equals(var.getVariableVtuName()))) {
                    // Get data for first time point and determine dimensions
                    List<Double> data = client.getData(simulationInfo, var, 0);
                    final int[] dimensions = getDimensions(data, times);
                    final Img<DoubleType> img = opService.create().img(dimensions);
                    final RandomAccess<DoubleType> imgRA = img.randomAccess();
                    // Copy data to the ImgLib2 Img
                    for (int t = 0; t < times.size(); t++) {
                        data = client.getData(simulationInfo, var, t);
                        for (int d = 0; d < data.size(); d++) {
                            imgRA.setPosition(new int[] { d, t });
                            imgRA.get().set(data.get(d));
                        }
                    }
                    // Create ImageJ Dataset and add to results
                    final Dataset dataset = datasetService.create(img);
                    dataset.setName(var.getVariableVtuName());
                    results.add(dataset);
                }
            }
            // If desired, add all datasets with the same dimensions
            if (!shouldCreateIndividualDatasets && !results.isEmpty()) {
                // First, group datasets according to dimensions
                final List<List<Dataset>> datasetGroups = new ArrayList<>();
                final List<Dataset> initialGroup = new ArrayList<>();
                initialGroup.add(results.get(0));
                datasetGroups.add(initialGroup);
                for (int i = 1; i < results.size(); i++) {
                    final Dataset result = results.get(i);
                    for (final List<Dataset> datasetGroup : datasetGroups) {
                        final Dataset[] datasets = new Dataset[] { datasetGroup.get(0), result };
                        if (Datasets.areSameSize(datasets, 0, 1)) {
                            datasetGroup.add(result);
                        } else {
                            final List<Dataset> newGroup = new ArrayList<>();
                            newGroup.add(result);
                            datasetGroups.add(newGroup);
                        }
                    }
                }
                final List<Dataset> summedResults = new ArrayList<>();
                for (final List<Dataset> datasetGroup : datasetGroups) {
                    final Img<DoubleType> sum = opService.create().img(datasetGroup.get(0));
                    for (final Dataset dataset : datasetGroup) {
                        @SuppressWarnings("unchecked") final RandomAccessibleInterval<DoubleType> current = (Img<DoubleType>) dataset.getImgPlus().getImg();
                        opService.math().add(sum, sum, current);
                    }
                    final Dataset result = datasetService.create(sum);
                    result.setName(datasetGroup.stream().map(d -> d.getName()).collect(Collectors.joining("+")));
                    summedResults.add(result);
                }
                return summedResults;
            }
            setSubtask(SimulationState.done);
            return results;
        }
    };
    return task;
}
Also used : Task(org.vcell.imagej.common.gui.Task) SBMLModel(org.vcell.vcellij.api.SBMLModel) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) Img(net.imglib2.img.Img) Dataset(net.imagej.Dataset) VariableInfo(org.vcell.vcellij.api.VariableInfo) SBMLWriter(org.sbml.jsbml.SBMLWriter) DoubleType(net.imglib2.type.numeric.real.DoubleType) SimulationState(org.vcell.vcellij.api.SimulationState) File(java.io.File) SimulationInfo(org.vcell.vcellij.api.SimulationInfo)

Example 24 with Dimensions

use of net.imglib2.Dimensions in project imagej-ops by imagej.

the class MapTest method testIIAndIIInplace.

@Test
public void testIIAndIIInplace() {
    final Img<ByteType> first = generateByteArrayTestImg(true, 10, 10);
    final Img<ByteType> firstCopy = first.copy();
    final Img<ByteType> second = generateByteArrayTestImg(false, 10, 10);
    for (final ByteType px : second) px.set((byte) 1);
    final Img<ByteType> secondCopy = second.copy();
    final Img<ByteType> secondDiffDims = generateByteArrayTestImg(false, 10, 10, 2);
    sub = Inplaces.binary(ops, Ops.Math.Subtract.class, ByteType.class);
    final BinaryInplaceOp<? super Img<ByteType>, Img<ByteType>> map = Inplaces.binary(ops, MapIIAndIIInplace.class, firstCopy, second, sub);
    map.run(firstCopy, second, firstCopy);
    map.run(first, secondCopy, secondCopy);
    assertImgSubEquals(first, second, firstCopy);
    assertImgSubEquals(first, second, secondCopy);
    // Expect exception when in2 has different dimensions
    thrown.expect(IllegalArgumentException.class);
    ops.op(MapIIAndIIInplace.class, first, secondDiffDims, sub);
}
Also used : Img(net.imglib2.img.Img) Ops(net.imagej.ops.Ops) ByteType(net.imglib2.type.numeric.integer.ByteType) AbstractOpTest(net.imagej.ops.AbstractOpTest) Test(org.junit.Test)

Example 25 with Dimensions

use of net.imglib2.Dimensions in project imagej-ops by imagej.

the class Outline method neighbourhoodInterval.

/**
 * Creates a view that spans from (x-1, y-1, ... i-1) to (x+1, y+1, ... i+1)
 * around the given coordinates
 *
 * @param interval the space of the coordinates
 * @param coordinates coordinates (x, y, ... i)
 * @return a view of a neighbourhood in the space
 */
private IntervalView<B> neighbourhoodInterval(final ExtendedRandomAccessibleInterval<B, RandomAccessibleInterval<B>> interval, final long[] coordinates) {
    final int dimensions = interval.numDimensions();
    final BoundingBox box = new BoundingBox(dimensions);
    final long[] minBounds = Arrays.stream(coordinates).map(c -> c - 1).toArray();
    final long[] maxBounds = Arrays.stream(coordinates).map(c -> c + 1).toArray();
    box.update(minBounds);
    box.update(maxBounds);
    return Views.offsetInterval(interval, box);
}
Also used : BitType(net.imglib2.type.logic.BitType) RandomAccess(net.imglib2.RandomAccess) Arrays(java.util.Arrays) OutOfBounds(net.imglib2.outofbounds.OutOfBounds) BoundingBox(net.imglib2.roi.labeling.BoundingBox) Util(net.imglib2.util.Util) IntervalView(net.imglib2.view.IntervalView) Plugin(org.scijava.plugin.Plugin) AbstractBinaryHybridCF(net.imagej.ops.special.hybrid.AbstractBinaryHybridCF) Cursor(net.imglib2.Cursor) FinalDimensions(net.imglib2.FinalDimensions) RandomAccessibleInterval(net.imglib2.RandomAccessibleInterval) BooleanType(net.imglib2.type.BooleanType) Ops(net.imagej.ops.Ops) Views(net.imglib2.view.Views) ExtendedRandomAccessibleInterval(net.imglib2.view.ExtendedRandomAccessibleInterval) BoundingBox(net.imglib2.roi.labeling.BoundingBox)

Aggregations

AbstractOpTest (net.imagej.ops.AbstractOpTest)14 Img (net.imglib2.img.Img)14 Test (org.junit.Test)14 DoubleType (net.imglib2.type.numeric.real.DoubleType)13 FinalDimensions (net.imglib2.FinalDimensions)12 Dimensions (net.imglib2.Dimensions)10 RandomAccessibleInterval (net.imglib2.RandomAccessibleInterval)9 FinalInterval (net.imglib2.FinalInterval)8 FloatType (net.imglib2.type.numeric.real.FloatType)8 Ops (net.imagej.ops.Ops)6 CreateImgFromImg (net.imagej.ops.create.img.CreateImgFromImg)5 BitType (net.imglib2.type.logic.BitType)5 ArrayList (java.util.ArrayList)4 Random (java.util.Random)4 CreateImgFromDimsAndType (net.imagej.ops.create.img.CreateImgFromDimsAndType)4 File (java.io.File)3 Dataset (net.imagej.Dataset)3 IntegralCursor (net.imagej.ops.image.integral.IntegralCursor)3 ByteType (net.imglib2.type.numeric.integer.ByteType)3 UnsignedByteType (net.imglib2.type.numeric.integer.UnsignedByteType)3