Search in sources :

Example 1 with VCellModel

use of org.vcell.imagej.common.vcell.VCellModel 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)

Example 2 with VCellModel

use of org.vcell.imagej.common.vcell.VCellModel 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 3 with VCellModel

use of org.vcell.imagej.common.vcell.VCellModel in project vcell by virtualcell.

the class MainController method addActionListenersToView.

private void addActionListenersToView() {
    view.addNewListener(event -> {
        model.setProject(new Project("New project"));
    });
    view.addOpenListener(event -> {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fileChooser.showOpenDialog(view);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            Task<Project, String> loadTask = projectService.load(fileChooser.getSelectedFile());
            loadTask.addPropertyChangeListener(propertyChangeEvent -> {
                if (propertyChangeEvent.getPropertyName().equals(Task.STATE) && loadTask.getState() == SwingWorker.StateValue.DONE) {
                    try {
                        model.setProject(loadTask.get());
                    } catch (InterruptedException | ExecutionException e) {
                        e.printStackTrace();
                    }
                }
            });
            try {
                executeTaskWithProgressDialog(loadTask, view, "Loading...", false);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    });
    view.addSaveListener(event -> {
        Task<Void, String> saveTask = projectService.save(model.getProject());
        try {
            executeTaskWithProgressDialog(saveTask, view, "Saving...", false);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    });
    view.addSaveAsListener(event -> {
        JFileChooser fileChooser = new JFileChooser();
        int returnVal = fileChooser.showSaveDialog(view);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            model.setProjectTitle(file.getName());
            Task<Void, String> saveAsTask = projectService.saveAs(model.getProject(), file);
            try {
                executeTaskWithProgressDialog(saveAsTask, view, "Saving...", false);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    });
    view.addImportDataListener(event -> {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        if (presentOpenFileChooser(fileChooser)) {
            Dataset dataset = getDatasetFromFile(fileChooser.getSelectedFile());
            model.addData(dataset);
        }
    });
    view.addImportGeometryListener(event -> {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        if (presentOpenFileChooser(fileChooser)) {
            Dataset dataset = getDatasetFromFile(fileChooser.getSelectedFile());
            model.addGeometry(dataset);
        }
    });
    view.addImportResultsSingleListener(event -> {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        if (presentOpenFileChooser(fileChooser)) {
            Dataset dataset = getDatasetFromFile(fileChooser.getSelectedFile());
            model.addResult(dataset);
        }
    });
    view.addImportResultsTimeSeriesListener(event -> {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (presentOpenFileChooser(fileChooser)) {
            try {
                Dataset dataset = vCellResultService.importCsv(fileChooser.getSelectedFile());
                model.addResult(dataset);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    });
    view.addExportListener(event -> {
        Dataset dataset = view.getSelectedDataset();
        if (dataset == null) {
            JOptionPane.showMessageDialog(view, "Please select a dataset to export.", "No dataset selected", JOptionPane.PLAIN_MESSAGE);
            return;
        }
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setSelectedFile(new File(dataset.getName()));
        int returnVal = fileChooser.showSaveDialog(view);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                datasetIOService.save(dataset.duplicate(), fileChooser.getSelectedFile().getPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    view.addChangeAxesListener(event -> {
        Dataset dataset = view.getSelectedDataset();
        if (dataset == null) {
            JOptionPane.showMessageDialog(view, "Please select a dataset to edit.", "No dataset selected", JOptionPane.PLAIN_MESSAGE);
            return;
        }
        ChangeAxesPanel panel = new ChangeAxesPanel(dataset);
        int returnVal = JOptionPane.showConfirmDialog(view, panel, "Change Axes", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        if (returnVal == JOptionPane.OK_OPTION) {
            model.changeAxes(dataset, panel.getSelectedAxisTypes());
        }
    });
    view.addDeleteListener(event -> {
        Dataset dataset = view.getSelectedDataset();
        if (dataset == null) {
            JOptionPane.showMessageDialog(view, "Please select a dataset to delete.", "No dataset selected", JOptionPane.PLAIN_MESSAGE);
            return;
        }
        int result = JOptionPane.showConfirmDialog(view, "Are you sure you want to delete \"" + dataset.getName() + "\"?", "Delete", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            model.delete(dataset);
        }
    });
    view.addCompareDatasetsListener(event -> {
        List<Dataset> datasetList = model.getProject().getData();
        datasetList.addAll(model.getProject().getGeometry());
        datasetList.addAll(model.getProject().getResults());
        Dataset[] datasetArray = datasetList.toArray(new Dataset[datasetList.size()]);
        DatasetSelectionPanel panel = new DatasetSelectionPanel();
        String descriptionA = "Dataset A:";
        String descriptionB = "Dataset B:";
        panel.addComboBox(datasetArray, descriptionA);
        panel.addComboBox(datasetArray, descriptionB);
        int returnVal = JOptionPane.showConfirmDialog(view, panel, "Select datasets to compare", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        if (returnVal == JOptionPane.OK_OPTION) {
            ArrayList<Dataset> datasets = new ArrayList<>();
            datasets.add(panel.getSelectedDatasetForDescription(descriptionA));
            datasets.add(panel.getSelectedDatasetForDescription(descriptionB));
            if (!Datasets.areSameSize(datasets.toArray(new Dataset[datasets.size()]), 0, 1)) {
                JOptionPane.showMessageDialog(view, "The selected datasets are not the same size.", "Incompatible datasets", JOptionPane.ERROR_MESSAGE);
                return;
            }
            CompareView compareView = new CompareView(datasets);
            new CompareController(compareView, model, context);
            compareView.setVisible(true);
            for (Dataset dataset : datasets) {
                inFrameDisplayService.displayDataset(dataset, compareView);
            }
        }
    });
    view.addConstructTIRFGeometryListener(event -> {
        List<Dataset> dataList = model.getProject().getData();
        Dataset[] dataArray = dataList.toArray(new Dataset[dataList.size()]);
        ConstructTIRFGeometryInputPanel panel = new ConstructTIRFGeometryInputPanel(dataArray);
        int returnVal = JOptionPane.showConfirmDialog(view, panel, "Construct TIRF Geometry", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        if (returnVal == JOptionPane.OK_OPTION) {
            Dataset dataset = panel.getData();
            int sliceIndex = panel.getSliceIndex();
            double wavelength = panel.getWavelength();
            double angle = panel.getAngle();
            double zSpacing = panel.getZSpacing();
            Dataset geometry = (Dataset) opService.run("constructTIRFGeometry", dataset, sliceIndex, wavelength, angle, zSpacing);
            String baseName = FilenameUtils.getBaseName(dataset.getName());
            String extension = FilenameUtils.getExtension(dataset.getName());
            geometry.setName(baseName + "_geometry." + extension);
            model.addGeometry(geometry);
        }
    });
    view.addConstructTIRFImageListener(event -> {
        List<Dataset> geometry = model.getProject().getGeometry();
        List<Dataset> results = model.getProject().getResults();
        Dataset[] geometryArray = geometry.toArray(new Dataset[geometry.size()]);
        Dataset[] resultsArray = results.toArray(new Dataset[results.size()]);
        ConstructTIRFImageInputPanel panel = new ConstructTIRFImageInputPanel(geometryArray, resultsArray);
        int returnVal = JOptionPane.showConfirmDialog(view, panel, "Construct TIRF Image", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        if (returnVal == JOptionPane.OK_OPTION) {
            Dataset selectedGeometry = panel.getGeometry();
            Dataset selectedMembraneResults = panel.getMembraneResults();
            Dataset selectedVolumeResults = panel.getVolumeResults();
            double wavelength = panel.getWavelength();
            double angle = panel.getAngle();
            double zSpacing = panel.getZSpacing();
            double xySpacing = panel.getXSpacing() * panel.getYSpacing();
            Dataset result = (Dataset) opService.run("constructTIRFImage", selectedGeometry, selectedMembraneResults, selectedVolumeResults, wavelength, angle, zSpacing, xySpacing);
            String baseName = FilenameUtils.getBaseName(selectedGeometry.getName());
            if (baseName.endsWith("_geometry")) {
                baseName = baseName.substring(0, baseName.length() - "_geometry".length());
            }
            String extension = FilenameUtils.getExtension(selectedGeometry.getName());
            result.setName(baseName + "_constructed_TIRF." + extension);
            model.addResult(result);
        }
    });
    view.addNewModelListener(event -> {
        Task<List<VCellModel>, String> loadTask = vCellModelService.getModels(vCellService);
        try {
            List<VCellModel> models = executeTaskWithProgressDialog(loadTask, view, "Loading models...", false);
            VCellModelSelectionDialog dialog = new VCellModelSelectionDialog(view, vCellModelService);
            dialog.setModels(models);
            int resultVal = dialog.display();
            if (resultVal == JOptionPane.OK_OPTION) {
                VCellModel selectedModel = dialog.getSelectedModel();
                if (selectedModel != null) {
                    model.addModel(selectedModel);
                }
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    });
    view.addSimulateModelListener(event -> {
        VCellModel vCellModel = view.getSelectedModel();
        if (vCellModel == null) {
            JOptionPane.showMessageDialog(view, "Please select a model to simulate.", "No model selected", JOptionPane.PLAIN_MESSAGE);
            return;
        } else if (vCellModel.getSimulationState() == SimulationState.running) {
            JOptionPane.showMessageDialog(view, "This simulation is currently in progress", "Simulation in progress", JOptionPane.PLAIN_MESSAGE);
            return;
        }
        SimulateModelPanel panel = new SimulateModelPanel(vCellModel);
        int returnVal = JOptionPane.showConfirmDialog(view, panel, "Simulate model", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        if (returnVal == JOptionPane.OK_OPTION) {
            // Update parameters of model from user input
            HashMap<Parameter, ASTNode> parameterMathMap = panel.getParameterMathMap();
            Model sbmlModel = vCellModel.getSbmlDocument().getModel();
            for (Parameter parameter : parameterMathMap.keySet()) {
                sbmlModel.getParameter(parameter.getId()).setValue(parameter.getValue());
                ASTNode math = parameterMathMap.get(parameter);
                if (math != null) {
                    ExplicitRule rule = sbmlModel.getRuleByVariable(parameter.getId());
                    if (rule != null) {
                        rule.setMath(math);
                    }
                }
            }
            SimulationSpec simSpec = new SimulationSpec();
            simSpec.setOutputTimeStep(panel.getTimeStep());
            simSpec.setTotalTime(panel.getTotalTime());
            Task<List<Dataset>, SimulationState> task = vCellService.runSimulation(vCellModel, simSpec, panel.getSelectedSpecies(), panel.getShouldCreateIndividualDatasets());
            task.addPropertyChangeListener(propertyChangeEvent -> {
                if (propertyChangeEvent.getPropertyName().equals(Task.SUBTASK)) {
                    model.setSimulationStateForVCellModel(task.getSubtask(), vCellModel);
                }
            });
            task.addDoneListener(propertyChangeEvent -> {
                try {
                    List<Dataset> results = task.get();
                    for (Dataset result : results) {
                        model.addResult(result);
                    }
                    System.out.println(results.toString());
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            });
            task.execute();
        }
    });
    view.addTabbedPaneChangeListener(event -> {
        view.clearListSelection();
    });
    view.addListSelectionListener(event -> {
        if (!event.getValueIsAdjusting()) {
            Object selected = ((JList<?>) event.getSource()).getSelectedValue();
            if (Dataset.class.isInstance(selected)) {
                view.displayDataset((Dataset) selected);
            } else if (VCellModel.class.isInstance(selected)) {
                view.displayModel((VCellModel) selected);
            }
        }
    });
}
Also used : ExplicitRule(org.sbml.jsbml.ExplicitRule) SimulateModelPanel(org.vcell.imagej.common.vcell.SimulateModelPanel) FileNotFoundException(java.io.FileNotFoundException) ArrayList(java.util.ArrayList) SimulationSpec(org.vcell.vcellij.api.SimulationSpec) ASTNode(org.sbml.jsbml.ASTNode) ArrayList(java.util.ArrayList) JList(javax.swing.JList) List(java.util.List) VCellModelSelectionDialog(org.vcell.imagej.common.vcell.VCellModelSelectionDialog) ExecutionException(java.util.concurrent.ExecutionException) Dataset(net.imagej.Dataset) IOException(java.io.IOException) JFileChooser(javax.swing.JFileChooser) VCellModel(org.vcell.imagej.common.vcell.VCellModel) Model(org.sbml.jsbml.Model) VCellModel(org.vcell.imagej.common.vcell.VCellModel) Parameter(org.sbml.jsbml.Parameter) SimulationState(org.vcell.vcellij.api.SimulationState) ChangeAxesPanel(org.vcell.imagej.common.gui.ChangeAxesPanel) File(java.io.File) JList(javax.swing.JList)

Aggregations

IOException (java.io.IOException)3 Dataset (net.imagej.Dataset)3 VCellModel (org.vcell.imagej.common.vcell.VCellModel)3 File (java.io.File)2 List (java.util.List)2 Task (org.vcell.imagej.common.gui.Task)2 BufferedImage (java.awt.image.BufferedImage)1 FileNotFoundException (java.io.FileNotFoundException)1 Path (java.nio.file.Path)1 ArrayList (java.util.ArrayList)1 ExecutionException (java.util.concurrent.ExecutionException)1 JFileChooser (javax.swing.JFileChooser)1 JList (javax.swing.JList)1 ImgPlus (net.imagej.ImgPlus)1 FinalInterval (net.imglib2.FinalInterval)1 Img (net.imglib2.img.Img)1 BitType (net.imglib2.type.logic.BitType)1 UnsignedByteType (net.imglib2.type.numeric.integer.UnsignedByteType)1 ASTNode (org.sbml.jsbml.ASTNode)1 ExplicitRule (org.sbml.jsbml.ExplicitRule)1