Search in sources :

Example 1 with SimulationState

use of org.vcell.vcellij.api.SimulationState in project vcell by virtualcell.

the class VCellService method runSimulation.

public Task<List<Dataset>, SimulationState> runSimulation(final VCellModel model, final SimulationSpec simSpec, final List<Species> outputSpecies, final boolean shouldCreateIndividualDatasets) {
    try {
        final SimulationServiceImpl client = new SimulationServiceImpl();
        final Task<List<Dataset>, SimulationState> task = runSimulation(client, model, simSpec, outputSpecies, shouldCreateIndividualDatasets, opService, datasetService);
        return task;
    } catch (final Throwable e) {
        e.printStackTrace();
    }
    return null;
}
Also used : SimulationServiceImpl(org.vcell.vcellij.SimulationServiceImpl) SimulationState(org.vcell.vcellij.api.SimulationState) ArrayList(java.util.ArrayList) List(java.util.List)

Example 2 with SimulationState

use of org.vcell.vcellij.api.SimulationState 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 3 with SimulationState

use of org.vcell.vcellij.api.SimulationState 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

ArrayList (java.util.ArrayList)3 List (java.util.List)3 SimulationState (org.vcell.vcellij.api.SimulationState)3 File (java.io.File)2 Dataset (net.imagej.Dataset)2 FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 ExecutionException (java.util.concurrent.ExecutionException)1 JFileChooser (javax.swing.JFileChooser)1 JList (javax.swing.JList)1 Img (net.imglib2.img.Img)1 DoubleType (net.imglib2.type.numeric.real.DoubleType)1 ASTNode (org.sbml.jsbml.ASTNode)1 ExplicitRule (org.sbml.jsbml.ExplicitRule)1 Model (org.sbml.jsbml.Model)1 Parameter (org.sbml.jsbml.Parameter)1 SBMLWriter (org.sbml.jsbml.SBMLWriter)1 ChangeAxesPanel (org.vcell.imagej.common.gui.ChangeAxesPanel)1 Task (org.vcell.imagej.common.gui.Task)1 SimulateModelPanel (org.vcell.imagej.common.vcell.SimulateModelPanel)1