Search in sources :

Example 1 with Model

use of org.sbml.jsbml.Model in project vcell by virtualcell.

the class MathModel_SBMLExporter method getSBMLString.

/**
 * Insert the method's description here.
 * Creation date: (4/11/2006 11:38:26 AM)
 * @return org.sbml.libsbml.Model
 * @param mathModel cbit.vcell.mathmodel.MathModel
 * @throws XMLStreamException
 * @throws SBMLException
 */
public static String getSBMLString(cbit.vcell.mathmodel.MathModel mathModel, long level, long version) throws cbit.vcell.parser.ExpressionException, java.io.IOException, SBMLException, XMLStreamException {
    if (mathModel.getMathDescription().isSpatial()) {
        throw new RuntimeException("spatial models export to SBML not supported");
    }
    if (mathModel.getMathDescription().hasFastSystems()) {
        throw new RuntimeException("math models with fast systems cannot be exported to SBML");
    }
    if (mathModel.getMathDescription().isNonSpatialStoch()) {
        throw new RuntimeException("stochastic math models cannot be exported to SBML");
    }
    if (!mathModel.getMathDescription().isValid()) {
        throw new RuntimeException("math model has an invalid Math Description, cannot export to SBML");
    }
    String dummyID = "ID_0";
    String compartmentId = "compartment";
    SBMLDocument sbmlDocument = new SBMLDocument((int) level, (int) version);
    Model sbmlModel = sbmlDocument.createModel();
    sbmlModel.setId("MathModel_" + TokenMangler.mangleToSName(mathModel.getName()));
    if (mathModel.getMathDescription().isSpatial()) {
        addGeometry(sbmlModel, mathModel);
    }
    Compartment compartment = sbmlModel.createCompartment();
    compartment.setId(compartmentId);
    // ------ For spatial SBML when implemented -----
    // if (vcMathModel.getMathDescription().isSpatial()){
    // // for spatial model, compartment(s) created in addGeometry(), based on number of subVolumes/surfaceClasses.
    // addGeometry();
    // } else {
    // // for non-spatial mathmodel, only 1 compartment; create it here.
    // String compartmentId = "compartment";
    // org.sbml.libsbml.Compartment compartment = sbmlModel.createCompartment();
    // compartment.setId(compartmentId);
    // }
    MathDescription mathDesc = mathModel.getMathDescription();
    Enumeration<Variable> enumVars = mathDesc.getVariables();
    while (enumVars.hasMoreElements()) {
        Variable vcVar = (Variable) enumVars.nextElement();
        // 
        if (vcVar instanceof cbit.vcell.math.VolVariable) {
        // 
        // skip for now, define later when defining ODEEquations.
        // 
        // org.sbml.libsbml.Species species = model.createSpecies();
        // species.setId(vcVar.getName());
        // species.setCompartment(compartmentId);
        } else if (vcVar instanceof cbit.vcell.math.Constant && ((cbit.vcell.math.Constant) vcVar).getExpression().isNumeric()) {
            Parameter param = sbmlModel.createParameter();
            param.setId(TokenMangler.mangleToSName(vcVar.getName()));
            param.setConstant(true);
            param.setValue(vcVar.getExpression().evaluateConstant());
        } else if (vcVar instanceof cbit.vcell.math.Constant || vcVar instanceof cbit.vcell.math.Function) {
            Parameter param = sbmlModel.createParameter();
            param.setId(TokenMangler.mangleToSName(vcVar.getName()));
            param.setConstant(false);
            // 
            // Function or Constant with expressions - create assignment rule and add to model.
            // 
            ASTNode mathNode = getFormulaFromExpression(vcVar.getExpression(), MathType.REAL);
            AssignmentRule assignmentRule = sbmlModel.createAssignmentRule();
            dummyID = TokenMangler.getNextEnumeratedToken(dummyID);
            assignmentRule.setId(dummyID);
            assignmentRule.setVariable(TokenMangler.mangleToSName(vcVar.getName()));
            assignmentRule.setMath(mathNode);
        // Create a parameter for this function/non-numeric constant, set its value to be 'not-constant',
        // add to model.
        }
    }
    cbit.vcell.math.CompartmentSubDomain subDomain = (cbit.vcell.math.CompartmentSubDomain) mathDesc.getSubDomains().nextElement();
    // System.out.println(model.toSBML());
    Enumeration<Equation> enumEqu = subDomain.getEquations();
    while (enumEqu.hasMoreElements()) {
        cbit.vcell.math.Equation equ = (cbit.vcell.math.Equation) enumEqu.nextElement();
        if (equ instanceof cbit.vcell.math.OdeEquation) {
            // For ODE equations, add the ode variable as a parameter, add rate as a rate rule and init condition as an initial assignment rule.
            Parameter param = sbmlModel.createParameter();
            param.setId(TokenMangler.mangleToSName(equ.getVariable().getName()));
            param.setConstant(false);
            // try to obtain the constant to which the init expression evaluates.
            RateRule rateRule = sbmlModel.createRateRule();
            rateRule.setVariable(TokenMangler.mangleToSName(equ.getVariable().getName()));
            rateRule.setMath(getFormulaFromExpression(equ.getRateExpression(), MathType.REAL));
            InitialAssignment initialAssignment = sbmlModel.createInitialAssignment();
            dummyID = TokenMangler.getNextEnumeratedToken(dummyID);
            initialAssignment.setId(dummyID);
            initialAssignment.setMath(getFormulaFromExpression(equ.getInitialExpression(), MathType.REAL));
            initialAssignment.setVariable(TokenMangler.mangleToSName(equ.getVariable().getName()));
        } else {
            throw new RuntimeException("equation type " + equ.getClass().getName() + " not supported");
        }
    }
    Iterator<Event> vcellEvents = mathDesc.getEvents();
    while (vcellEvents.hasNext()) {
        Event vcellEvent = vcellEvents.next();
        addSbmlEvent(sbmlModel, vcellEvent);
    }
    System.out.println(new SBMLWriter().writeSBMLToString(sbmlDocument));
    // validate the sbml document
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.GENERAL_CONSISTENCY, true);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.IDENTIFIER_CONSISTENCY, true);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.MATHML_CONSISTENCY, true);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.MODELING_PRACTICE, false);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.OVERDETERMINED_MODEL, true);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.SBO_CONSISTENCY, false);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.UNITS_CONSISTENCY, false);
    sbmlDocument.checkConsistency();
    // sbmlDocument.checkConsistencyOffline();
    long internalErrCount = sbmlDocument.getNumErrors();
    if (internalErrCount > 0) {
        StringBuffer sbmlErrbuf = new StringBuffer();
        for (int i = 0; i < internalErrCount; i++) {
            SBMLError sbmlErr = sbmlDocument.getError(i);
            if (sbmlErr.isError() || sbmlErr.isFatal()) {
                sbmlErrbuf.append(sbmlErr.getCategory() + " :: " + sbmlErr.getSeverity() + " :: " + sbmlErr.getMessage() + "\n");
            }
        }
        if (sbmlErrbuf.length() > 0) {
            throw new RuntimeException("SBML Internal consistency checks failed: \n" + sbmlErrbuf.toString());
        }
    }
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.GENERAL_CONSISTENCY, true);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.IDENTIFIER_CONSISTENCY, true);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.UNITS_CONSISTENCY, false);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.MATHML_CONSISTENCY, true);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.SBO_CONSISTENCY, false);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.OVERDETERMINED_MODEL, true);
    sbmlDocument.setConsistencyChecks(CHECK_CATEGORY.MODELING_PRACTICE, false);
    sbmlDocument.checkConsistency();
    // sbmlDocument.checkConsistencyOffline();
    long errCount = sbmlDocument.getNumErrors();
    if (errCount > 0) {
        StringBuffer sbmlErrbuf = new StringBuffer();
        for (int i = 0; i < errCount; i++) {
            SBMLError sbmlErr = sbmlDocument.getError(i);
            if (sbmlErr.isError() || sbmlErr.isFatal()) {
                sbmlErrbuf.append(sbmlErr.getCategory() + " :: " + sbmlErr.getSeverity() + " :: " + sbmlErr.getMessage() + "\n");
            }
        }
        if (sbmlErrbuf.length() > 0) {
            throw new RuntimeException("SBML validation failed: \n" + sbmlErrbuf.toString());
        }
    }
    // end of validation
    // start writing
    SBMLWriter sbmlWriter = new SBMLWriter();
    String sbmlStr = sbmlWriter.writeSBMLToString(sbmlDocument);
    // Error check - use libSBML's document.printError to print to outputstream
    System.out.println("\n\nSBML Export Error Report");
    sbmlDocument.printErrors(System.out);
    return sbmlStr;
}
Also used : ReservedVariable(cbit.vcell.math.ReservedVariable) Variable(cbit.vcell.math.Variable) SBMLDocument(org.sbml.jsbml.SBMLDocument) MathDescription(cbit.vcell.math.MathDescription) Compartment(org.sbml.jsbml.Compartment) SBMLError(org.sbml.jsbml.SBMLError) ASTNode(org.sbml.jsbml.ASTNode) RateRule(org.sbml.jsbml.RateRule) AssignmentRule(org.sbml.jsbml.AssignmentRule) Equation(cbit.vcell.math.Equation) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) InitialAssignment(org.sbml.jsbml.InitialAssignment) SBMLWriter(org.sbml.jsbml.SBMLWriter) Model(org.sbml.jsbml.Model) MathModel(cbit.vcell.mathmodel.MathModel) Parameter(org.sbml.jsbml.Parameter) Event(cbit.vcell.math.Event) Equation(cbit.vcell.math.Equation)

Example 2 with Model

use of org.sbml.jsbml.Model in project vcell by virtualcell.

the class SBMLUnitTranslatorTest method testSBMLtoVCell.

@Test
public void testSBMLtoVCell() throws XMLStreamException, IOException, SbmlException {
    File[] sbmlFiles = getBiomodelsCuratedSBMLFiles();
    // };
    for (File sbmlFile : sbmlFiles) {
        if (sbmlFile.getName().equals("BIOMD0000000539.xml")) {
            System.err.println("skipping this model, seems like a bug in jsbml  RenderParser.processEndDocument() ... line 403 ... wrong constant for extension name");
            continue;
        }
        SBMLDocument doc = SBMLReader.read(sbmlFile);
        BioModel bioModel = new BioModel(null);
        VCUnitSystem unitSystem = bioModel.getModel().getUnitSystem();
        Model sbmlModel = doc.getModel();
        ListOf<UnitDefinition> listOfUnitDefinitions = sbmlModel.getListOfUnitDefinitions();
        for (UnitDefinition sbmlUnitDef : listOfUnitDefinitions) {
            VCUnitDefinition vcUnit = SBMLUnitTranslator.getVCUnitDefinition(sbmlUnitDef, unitSystem);
            UnitDefinition new_sbmlUnitDef = SBMLUnitTranslator.getSBMLUnitDefinition(vcUnit, 3, 1, unitSystem);
            VCUnitDefinition new_vcUnit = SBMLUnitTranslator.getVCUnitDefinition(new_sbmlUnitDef, unitSystem);
            if (!vcUnit.getSymbol().equals(new_vcUnit.getSymbol())) {
                System.err.println("orig vcUnit '" + vcUnit.getSymbol() + "' doesn't match new vcUnit '" + new_vcUnit.getSymbol() + "'");
            }
            // System.out.println("sbmlUnit = "+sbmlUnitDef.toString()+", vcUnit = "+vcUnit.getSymbol());
            System.out.println("sbmlUnit(" + sbmlUnitDef.getClass().getName() + ", builtin=" + sbmlUnitDef.isVariantOfSubstance() + ") = " + sbmlUnitDef.toString() + ", id=" + sbmlUnitDef.getId() + ",  name=" + sbmlUnitDef.getName() + ",   vcUnit = " + vcUnit.getSymbol());
            if (sbmlUnitDef.getNumUnits() > 1) {
                System.out.println("vcUnit = " + vcUnit.getSymbol());
                for (Unit unit : sbmlUnitDef.getListOfUnits()) {
                    try {
                        // VCUnitDefinition vcUnit = unitSystem.getInstance(unit.getKind().getName());
                        System.out.println("    vcUnit = " + unit);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("found bigger unit, " + sbmlUnitDef);
            }
        }
        if (sbmlFile == sbmlFiles[0]) {
            System.out.println("sbml length unit = " + sbmlModel.getLengthUnitsInstance() + ", idref=" + sbmlModel.getLengthUnits());
            System.out.println("sbml area unit = " + sbmlModel.getAreaUnitsInstance() + ", idref=" + sbmlModel.getAreaUnits());
            System.out.println("sbml volume unit = " + sbmlModel.getVolumeUnitsInstance() + ", idref=" + sbmlModel.getVolumeUnits());
            System.out.println("sbml time unit = " + sbmlModel.getTimeUnitsInstance() + ", idref=" + sbmlModel.getTimeUnits());
            System.out.println("sbml extent unit = " + sbmlModel.getExtentUnitsInstance() + ", idref=" + sbmlModel.getExtentUnits());
            System.out.println("sbml substance unit = " + sbmlModel.getSubstanceUnitsInstance() + ", idref=" + sbmlModel.getSubstanceUnits());
            for (UnitDefinition sbmlUnitDef : sbmlModel.getListOfPredefinedUnitDefinitions()) {
                if (sbmlUnitDef.getNumUnits() == 1 && sbmlUnitDef.getUnit(0).isAvogadro()) {
                    continue;
                }
                if (sbmlUnitDef.getNumUnits() == 1 && sbmlUnitDef.getUnit(0).isKatal()) {
                    continue;
                }
                VCUnitDefinition vcUnit = SBMLUnitTranslator.getVCUnitDefinition(sbmlUnitDef, unitSystem);
                // System.out.println("sbmlUnit = "+sbmlUnitDef.toString()+", vcUnit = "+vcUnit.getSymbol());
                System.out.println("sbmlUnit(" + sbmlUnitDef.getClass().getName() + ", builtin=" + sbmlUnitDef.isVariantOfSubstance() + ") = " + sbmlUnitDef.toString() + ", id=" + sbmlUnitDef.getId() + ",  name=" + sbmlUnitDef.getName() + ",   vcUnit = " + vcUnit.getSymbol());
            // for (Unit unit : sbmlUnitDef.getListOfUnits()){
            // try {
            // VCUnitDefinition vcUnit = unitSystem.getInstance(unit.getKind().getName());
            // System.out.println("    vcUnit = "+vcUnit.getSymbol());
            // }catch (Exception e){
            // e.printStackTrace();
            // }
            // }
            }
        }
    }
}
Also used : VCUnitSystem(cbit.vcell.units.VCUnitSystem) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) SBMLDocument(org.sbml.jsbml.SBMLDocument) BioModel(cbit.vcell.biomodel.BioModel) Model(org.sbml.jsbml.Model) BioModel(cbit.vcell.biomodel.BioModel) Unit(org.sbml.jsbml.Unit) File(java.io.File) UnitDefinition(org.sbml.jsbml.UnitDefinition) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) IOException(java.io.IOException) XMLStreamException(javax.xml.stream.XMLStreamException) Test(org.junit.Test)

Example 3 with Model

use of org.sbml.jsbml.Model in project vcell by virtualcell.

the class VCellModel method parseValueStringForParameter.

public ASTNode parseValueStringForParameter(Parameter parameter, String value) {
    Model model = sbmlDocument.getModel();
    ExplicitRule rule = model.getRuleByVariable(parameter.getId());
    if (rule != null) {
        try {
            return ASTNode.parseFormula(value);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    return null;
}
Also used : ExplicitRule(org.sbml.jsbml.ExplicitRule) Model(org.sbml.jsbml.Model) ParseException(org.sbml.jsbml.text.parser.ParseException)

Example 4 with Model

use of org.sbml.jsbml.Model in project vcell by virtualcell.

the class VCellModel method getValueStringForParameter.

public String getValueStringForParameter(Parameter parameter) {
    Model model = sbmlDocument.getModel();
    ExplicitRule rule = model.getRuleByVariable(parameter.getId());
    if (rule == null) {
        return Double.toString(parameter.getValue());
    }
    return ASTNode.formulaToString(rule.getMath());
}
Also used : ExplicitRule(org.sbml.jsbml.ExplicitRule) Model(org.sbml.jsbml.Model)

Example 5 with Model

use of org.sbml.jsbml.Model 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

Model (org.sbml.jsbml.Model)5 ExplicitRule (org.sbml.jsbml.ExplicitRule)3 File (java.io.File)2 IOException (java.io.IOException)2 ASTNode (org.sbml.jsbml.ASTNode)2 Parameter (org.sbml.jsbml.Parameter)2 SBMLDocument (org.sbml.jsbml.SBMLDocument)2 BioModel (cbit.vcell.biomodel.BioModel)1 Equation (cbit.vcell.math.Equation)1 Event (cbit.vcell.math.Event)1 MathDescription (cbit.vcell.math.MathDescription)1 ReservedVariable (cbit.vcell.math.ReservedVariable)1 Variable (cbit.vcell.math.Variable)1 MathModel (cbit.vcell.mathmodel.MathModel)1 VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)1 VCUnitSystem (cbit.vcell.units.VCUnitSystem)1 FileNotFoundException (java.io.FileNotFoundException)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 ExecutionException (java.util.concurrent.ExecutionException)1