Search in sources :

Example 1 with Task

use of org.vcell.imagej.common.gui.Task in project vcell by virtualcell.

the class VCellModelService method getVCellImageForModel.

public Task<BufferedImage, Void> getVCellImageForModel(VCellModel vCellModel) {
    Task<BufferedImage, Void> task = new Task<BufferedImage, Void>() {

        @Override
        protected BufferedImage doInBackground() throws Exception {
            try {
                BufferedImage img = ImageIO.read(new URL("https://" + HOST + ":" + PORT + "/biomodel/" + vCellModel.getBiomodelKey() + "/diagram"));
                System.out.println("read " + img.toString());
                return img;
            } catch (IOException e) {
                System.out.println("Could not load image for: " + vCellModel.getName());
            }
            return null;
        }
    };
    return task;
}
Also used : Task(org.vcell.imagej.common.gui.Task) IOException(java.io.IOException) BufferedImage(java.awt.image.BufferedImage) URL(java.net.URL)

Example 2 with Task

use of org.vcell.imagej.common.gui.Task in project vcell by virtualcell.

the class VCellModelService method getModels.

public Task<List<VCellModel>, String> getModels(VCellService vCellService) {
    final Task<List<VCellModel>, String> task = new Task<List<VCellModel>, String>() {

        @Override
        protected List<VCellModel> doInBackground() throws Exception {
            boolean bIgnoreCertProblems = true;
            boolean bIgnoreHostMismatch = true;
            VCellApiClient vCellApiClient = null;
            List<VCellModel> vCellModels = new ArrayList<VCellModel>();
            try {
                vCellApiClient = new VCellApiClient(HOST, PORT, bIgnoreCertProblems, bIgnoreHostMismatch);
                vCellApiClient.authenticate("ImageJ", "richarddberlin", false);
                BioModelsQuerySpec querySpec = new BioModelsQuerySpec();
                querySpec.owner = "tutorial";
                final BiomodelRepresentation[] biomodelReps = vCellApiClient.getBioModels(querySpec);
                final int modelsToLoad = biomodelReps.length;
                int modelsLoaded = 0;
                for (BiomodelRepresentation biomodelRep : biomodelReps) {
                    setSubtask(biomodelRep.getName());
                    ApplicationRepresentation[] applicationReps = biomodelRep.getApplications();
                    if (applicationReps.length > 0) {
                        String vcml = getVCML(biomodelRep);
                        if (vcml != null) {
                            SBMLDocument sbml = vCellService.getSBML(vcml, applicationReps[0].getName());
                            VCellModel vCellModel = new VCellModel(biomodelRep.getName(), biomodelRep.getBmKey(), sbml);
                            vCellModels.add(vCellModel);
                            modelsLoaded++;
                            setProgress(modelsLoaded * 100 / modelsToLoad);
                        } else {
                            System.err.println("failed to return VCML for " + biomodelRep.bmKey);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace(System.out);
            }
            return vCellModels;
        }
    };
    return task;
}
Also used : BiomodelRepresentation(org.vcell.api.common.BiomodelRepresentation) Task(org.vcell.imagej.common.gui.Task) SBMLDocument(org.sbml.jsbml.SBMLDocument) ArrayList(java.util.ArrayList) VCellApiClient(org.vcell.api.client.VCellApiClient) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ApplicationRepresentation(org.vcell.api.common.ApplicationRepresentation) ArrayList(java.util.ArrayList) List(java.util.List) BioModelsQuerySpec(org.vcell.api.client.query.BioModelsQuerySpec)

Example 3 with Task

use of org.vcell.imagej.common.gui.Task 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(sbmlSpatialFile);
            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 4 with Task

use of org.vcell.imagej.common.gui.Task 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 5 with Task

use of org.vcell.imagej.common.gui.Task in project vcell by virtualcell.

the class ProjectService method saveAs.

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

        @Override
        protected Void doInBackground() throws Exception {
            int numToSave = project.getData().size() + project.getGeometry().size() + project.getModels().size() + project.getResults().size();
            int numSaved = 0;
            String rootPath = root.getAbsolutePath();
            Path dataPath = Paths.get(rootPath, "data");
            Path geometryPath = Paths.get(rootPath, "geometry");
            Path modelsPath = Paths.get(rootPath, "models");
            Path resultsPath = Paths.get(rootPath, "results");
            try {
                // Save data
                Files.createDirectories(dataPath);
                FileUtils.cleanDirectory(dataPath.toFile());
                for (Dataset dataset : project.getData()) {
                    setSubtask(dataset.getName());
                    saveDataset(dataset, dataPath);
                    numSaved++;
                    setProgress(numSaved * 100 / numToSave);
                }
                // Save geometry
                Files.createDirectories(geometryPath);
                FileUtils.cleanDirectory(geometryPath.toFile());
                for (Dataset dataset : project.getGeometry()) {
                    setSubtask(dataset.getName());
                    saveDataset(dataset, geometryPath);
                    numSaved++;
                    setProgress(numSaved * 100 / numToSave);
                }
                // Save models
                Files.createDirectories(modelsPath);
                FileUtils.cleanDirectory(modelsPath.toFile());
                for (VCellModel model : project.getModels()) {
                    setSubtask(model.getName());
                    saveModel(model, modelsPath);
                    numSaved++;
                    setProgress(numSaved * 100 / numToSave);
                }
                // Save results
                Files.createDirectories(resultsPath);
                FileUtils.cleanDirectory(resultsPath.toFile());
                for (Dataset dataset : project.getResults()) {
                    setSubtask(dataset.getName());
                    saveDataset(dataset, resultsPath);
                    numSaved++;
                    setProgress(numSaved * 100 / numToSave);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            currentProjectRoot = root;
            return null;
        }

        @Override
        protected void process(List<String> chunks) {
            super.process(chunks);
        }
    };
    return task;
}
Also used : Path(java.nio.file.Path) Task(org.vcell.imagej.common.gui.Task) Dataset(net.imagej.Dataset) VCellModel(org.vcell.imagej.common.vcell.VCellModel) List(java.util.List) IOException(java.io.IOException)

Aggregations

Task (org.vcell.imagej.common.gui.Task)5 IOException (java.io.IOException)4 List (java.util.List)3 Dataset (net.imagej.Dataset)3 BufferedImage (java.awt.image.BufferedImage)2 File (java.io.File)2 ArrayList (java.util.ArrayList)2 Img (net.imglib2.img.Img)2 SBMLDocument (org.sbml.jsbml.SBMLDocument)2 VCellModel (org.vcell.imagej.common.vcell.VCellModel)2 URL (java.net.URL)1 Path (java.nio.file.Path)1 KeyManagementException (java.security.KeyManagementException)1 KeyStoreException (java.security.KeyStoreException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 ImgPlus (net.imagej.ImgPlus)1 FinalInterval (net.imglib2.FinalInterval)1 BitType (net.imglib2.type.logic.BitType)1 UnsignedByteType (net.imglib2.type.numeric.integer.UnsignedByteType)1 DoubleType (net.imglib2.type.numeric.real.DoubleType)1