Search in sources :

Example 1 with SbmlException

use of org.vcell.sbml.SbmlException in project vcell by virtualcell.

the class SEDMLExporter method translateBioModelToSedML.

private void translateBioModelToSedML(String savePath) {
    sbmlFilePathStrAbsoluteList.clear();
    // models
    try {
        SimulationContext[] simContexts = vcBioModel.getSimulationContexts();
        cbit.vcell.model.Model vcModel = vcBioModel.getModel();
        // "urn:sedml:language:sbml";
        String sbmlLanguageURN = SUPPORTED_LANGUAGE.SBML_GENERIC.getURN();
        String bioModelName = TokenMangler.mangleToSName(vcBioModel.getName());
        // String usrHomeDirPath = ResourceUtil.getUserHomeDir().getAbsolutePath();
        // to get Xpath string for variables.
        SBMLSupport sbmlSupport = new SBMLSupport();
        // for model count, task subcount
        int simContextCnt = 0;
        // for dtaGenerator count.
        int varCount = 0;
        boolean bSpeciesAddedAsDataGens = false;
        String sedmlNotesStr = "";
        for (SimulationContext simContext : simContexts) {
            String simContextName = simContext.getName();
            // export all applications that are not spatial stochastic
            if (!(simContext.getGeometry().getDimension() > 0 && simContext.isStoch())) {
                // to compute and set the sizes of the remaining structures.
                if (!simContext.getGeometryContext().isAllSizeSpecifiedPositive()) {
                    Structure structure = simContext.getModel().getStructure(0);
                    double structureSize = 1.0;
                    StructureMapping structMapping = simContext.getGeometryContext().getStructureMapping(structure);
                    StructureSizeSolver.updateAbsoluteStructureSizes(simContext, structure, structureSize, structMapping.getSizeParameter().getUnitDefinition());
                }
                // Export the application itself to SBML, with default overrides
                String sbmlString = null;
                int level = 2;
                int version = 4;
                boolean isSpatial = simContext.getGeometry().getDimension() > 0 ? true : false;
                SimulationJob simJob = null;
                // if (simContext.getGeometry().getDimension() > 0) {
                // sbmlString = XmlHelper.exportSBML(vcBioModel, 2, 4, 0, true, simContext, null);
                // } else {
                // sbmlString = XmlHelper.exportSBML(vcBioModel, 2, 4, 0, false, simContext, null);
                // }
                // 
                // TODO: we need to salvage from the SBMLExporter info about the fate of local parameters
                // some of them may stay as locals, some others may become globals
                // Any of these, if used in a repeated task or change or whatever, needs to be used in a consistent way,
                // that is, if a param becomes a global in SBML, we need to refer at it in SEDML as the same global
                // 
                // We'll use:
                // Map<Pair <String reaction, String param>, String global>		- if local converted to global
                // Set<Pair <String reaction, String param>>	(if needed?)	- if local stays local
                // 
                // local to global translation map
                Map<Pair<String, String>, String> l2gMap = null;
                if (vcBioModel instanceof BioModel) {
                    try {
                        // check if model to be exported to SBML has units compatible with SBML default units (default units in SBML can be assumed only until SBML Level2)
                        ModelUnitSystem forcedModelUnitSystem = simContext.getModel().getUnitSystem();
                        if (level < 3 && !ModelUnitSystem.isCompatibleWithDefaultSBMLLevel2Units(forcedModelUnitSystem)) {
                            forcedModelUnitSystem = ModelUnitSystem.createDefaultSBMLLevel2Units();
                        }
                        // create new Biomodel with new (SBML compatible)  unit system
                        BioModel modifiedBiomodel = ModelUnitConverter.createBioModelWithNewUnitSystem(simContext.getBioModel(), forcedModelUnitSystem);
                        // extract the simContext from new Biomodel. Apply overrides to *this* modified simContext
                        SimulationContext simContextFromModifiedBioModel = modifiedBiomodel.getSimulationContext(simContext.getName());
                        SBMLExporter sbmlExporter = new SBMLExporter(modifiedBiomodel, level, version, isSpatial);
                        sbmlExporter.setSelectedSimContext(simContextFromModifiedBioModel);
                        // no sim job
                        sbmlExporter.setSelectedSimulationJob(null);
                        sbmlString = sbmlExporter.getSBMLFile();
                        l2gMap = sbmlExporter.getLocalToGlobalTranslationMap();
                    } catch (ExpressionException | SbmlException e) {
                        e.printStackTrace(System.out);
                        throw new XmlParseException(e);
                    }
                } else {
                    throw new RuntimeException("unsupported Document Type " + vcBioModel.getClass().getName() + " for SBML export");
                }
                String sbmlFilePathStrAbsolute = savePath + FileUtils.WINDOWS_SEPARATOR + bioModelName + "_" + simContextName + ".xml";
                String sbmlFilePathStrRelative = bioModelName + "_" + simContextName + ".xml";
                XmlUtil.writeXMLStringToFile(sbmlString, sbmlFilePathStrAbsolute, true);
                sbmlFilePathStrAbsoluteList.add(sbmlFilePathStrRelative);
                String simContextId = TokenMangler.mangleToSName(simContextName);
                sedmlModel.addModel(new Model(simContextId, simContextName, sbmlLanguageURN, sbmlFilePathStrRelative));
                // required for mathOverrides, if any
                MathMapping mathMapping = simContext.createNewMathMapping();
                MathSymbolMapping mathSymbolMapping = mathMapping.getMathSymbolMapping();
                // create sedml simulation objects and tasks (mapping each sim with current simContext)
                int simCount = 0;
                String taskRef = null;
                int overrideCount = 0;
                for (Simulation vcSimulation : simContext.getSimulations()) {
                    List<DataGenerator> dataGeneratorsOfSim = new ArrayList<DataGenerator>();
                    // if simContext is non-spatial stochastic, check if sim is histogram
                    SolverTaskDescription simTaskDesc = vcSimulation.getSolverTaskDescription();
                    if (simContext.getGeometry().getDimension() == 0 && simContext.isStoch()) {
                        long numOfTrials = simTaskDesc.getStochOpt().getNumOfTrials();
                        if (numOfTrials > 1) {
                            String msg = "\n\t" + simContextName + " ( " + vcSimulation.getName() + " ) : export of non-spatial stochastic simulation with histogram option to SEDML not supported at this time.";
                            sedmlNotesStr += msg;
                            continue;
                        }
                    }
                    // create Algorithm and sedmlSimulation (UniformtimeCourse)
                    SolverDescription vcSolverDesc = simTaskDesc.getSolverDescription();
                    // String kiSAOIdStr = getKiSAOIdFromSimulation(vcSolverDesc);	// old way of doing it, going directly to the web site
                    String kiSAOIdStr = vcSolverDesc.getKisao();
                    Algorithm sedmlAlgorithm = new Algorithm(kiSAOIdStr);
                    TimeBounds vcSimTimeBounds = simTaskDesc.getTimeBounds();
                    double startingTime = vcSimTimeBounds.getStartingTime();
                    String simName = vcSimulation.getName();
                    UniformTimeCourse utcSim = new UniformTimeCourse(TokenMangler.mangleToSName(simName), simName, startingTime, startingTime, vcSimTimeBounds.getEndingTime(), (int) simTaskDesc.getExpectedNumTimePoints(), sedmlAlgorithm);
                    // if solver is not CVODE, add a note to utcSim to indicate actual solver name
                    if (!vcSolverDesc.equals(SolverDescription.CVODE)) {
                        String simNotesStr = "Actual Solver Name : '" + vcSolverDesc.getDisplayLabel() + "'.";
                        utcSim.addNote(createNotesElement(simNotesStr));
                    }
                    sedmlModel.addSimulation(utcSim);
                    // add SEDML tasks (map simulation to model:simContext)
                    // repeated tasks
                    MathOverrides mathOverrides = vcSimulation.getMathOverrides();
                    if (mathOverrides != null && mathOverrides.hasOverrides()) {
                        String[] overridenConstantNames = mathOverrides.getOverridenConstantNames();
                        String[] scannedConstantsNames = mathOverrides.getScannedConstantNames();
                        HashMap<String, String> scannedParamHash = new HashMap<String, String>();
                        HashMap<String, String> unscannedParamHash = new HashMap<String, String>();
                        for (String name : scannedConstantsNames) {
                            scannedParamHash.put(name, name);
                        }
                        for (String name : overridenConstantNames) {
                            if (!scannedParamHash.containsKey(name)) {
                                unscannedParamHash.put(name, name);
                            }
                        }
                        if (!unscannedParamHash.isEmpty() && scannedParamHash.isEmpty()) {
                            // only parameters with simple overrides (numeric/expression) no scans
                            // create new model with change for each parameter that has override; add simple task
                            String overriddenSimContextId = simContextId + "_" + overrideCount;
                            String overriddenSimContextName = simContextName + " modified";
                            Model sedModel = new Model(overriddenSimContextId, overriddenSimContextName, sbmlLanguageURN, simContextId);
                            overrideCount++;
                            for (String unscannedParamName : unscannedParamHash.values()) {
                                SymbolTableEntry ste = getSymbolTableEntryForModelEntity(mathSymbolMapping, unscannedParamName);
                                Expression unscannedParamExpr = mathOverrides.getActualExpression(unscannedParamName, 0);
                                if (unscannedParamExpr.isNumeric()) {
                                    // if expression is numeric, add ChangeAttribute to model created above
                                    XPathTarget targetXpath = getTargetAttributeXPath(ste, l2gMap);
                                    ChangeAttribute changeAttribute = new ChangeAttribute(targetXpath, unscannedParamExpr.infix());
                                    sedModel.addChange(changeAttribute);
                                } else {
                                    // non-numeric expression : add 'computeChange' to modified model
                                    ASTNode math = Libsedml.parseFormulaString(unscannedParamExpr.infix());
                                    XPathTarget targetXpath = getTargetXPath(ste, l2gMap);
                                    ComputeChange computeChange = new ComputeChange(targetXpath, math);
                                    String[] exprSymbols = unscannedParamExpr.getSymbols();
                                    for (String symbol : exprSymbols) {
                                        String symbolName = TokenMangler.mangleToSName(symbol);
                                        SymbolTableEntry ste1 = vcModel.getEntry(symbol);
                                        if (ste != null) {
                                            if (ste1 instanceof SpeciesContext || ste1 instanceof Structure || ste1 instanceof ModelParameter) {
                                                XPathTarget ste1_XPath = getTargetXPath(ste1, l2gMap);
                                                org.jlibsedml.Variable sedmlVar = new org.jlibsedml.Variable(symbolName, symbolName, taskRef, ste1_XPath.getTargetAsString());
                                                computeChange.addVariable(sedmlVar);
                                            } else {
                                                double doubleValue = 0.0;
                                                if (ste1 instanceof ReservedSymbol) {
                                                    doubleValue = getReservedSymbolValue(ste1);
                                                }
                                                Parameter sedmlParameter = new Parameter(symbolName, symbolName, doubleValue);
                                                computeChange.addParameter(sedmlParameter);
                                            }
                                        } else {
                                            throw new RuntimeException("Symbol '" + symbol + "' used in expression for '" + unscannedParamName + "' not found in model.");
                                        }
                                    }
                                    sedModel.addChange(computeChange);
                                }
                            }
                            sedmlModel.addModel(sedModel);
                            String taskId = "tsk_" + simContextCnt + "_" + simCount;
                            Task sedmlTask = new Task(taskId, taskId, sedModel.getId(), utcSim.getId());
                            sedmlModel.addTask(sedmlTask);
                            // to be used later to add dataGenerators : one set of DGs per model (simContext).
                            taskRef = taskId;
                        } else if (!scannedParamHash.isEmpty() && unscannedParamHash.isEmpty()) {
                            // only parameters with scans : only add 1 Task and 1 RepeatedTask
                            String taskId = "tsk_" + simContextCnt + "_" + simCount;
                            Task sedmlTask = new Task(taskId, taskId, simContextId, utcSim.getId());
                            sedmlModel.addTask(sedmlTask);
                            String repeatedTaskId = "repTsk_" + simContextCnt + "_" + simCount;
                            // TODO: temporary solution - we use as range here the first range
                            String scn = scannedConstantsNames[0];
                            String rId = "range_" + simContextCnt + "_" + simCount + "_" + scn;
                            RepeatedTask rt = new RepeatedTask(repeatedTaskId, repeatedTaskId, true, rId);
                            // to be used later to add dataGenerators - in our case it has to be the repeated task
                            taskRef = repeatedTaskId;
                            SubTask subTask = new SubTask("0", taskId);
                            rt.addSubtask(subTask);
                            for (String scannedConstName : scannedConstantsNames) {
                                ConstantArraySpec constantArraySpec = mathOverrides.getConstantArraySpec(scannedConstName);
                                String rangeId = "range_" + simContextCnt + "_" + simCount + "_" + scannedConstName;
                                // list of Ranges, if sim is parameter scan.
                                if (constantArraySpec != null) {
                                    Range r = null;
                                    System.out.println("     " + constantArraySpec.toString());
                                    if (constantArraySpec.getType() == ConstantArraySpec.TYPE_INTERVAL) {
                                        // ------ Uniform Range
                                        r = new UniformRange(rangeId, constantArraySpec.getMinValue(), constantArraySpec.getMaxValue(), constantArraySpec.getNumValues());
                                        rt.addRange(r);
                                    } else {
                                        // ----- Vector Range
                                        cbit.vcell.math.Constant[] cs = constantArraySpec.getConstants();
                                        ArrayList<Double> values = new ArrayList<Double>();
                                        for (int i = 0; i < cs.length; i++) {
                                            String value = cs[i].getExpression().infix();
                                            values.add(Double.parseDouble(value));
                                        }
                                        r = new VectorRange(rangeId, values);
                                        rt.addRange(r);
                                    }
                                    // list of Changes
                                    SymbolTableEntry ste = getSymbolTableEntryForModelEntity(mathSymbolMapping, scannedConstName);
                                    XPathTarget target = getTargetXPath(ste, l2gMap);
                                    // ASTNode math1 = new ASTCi(r.getId());		// was scannedConstName
                                    ASTNode math1 = Libsedml.parseFormulaString(r.getId());
                                    SetValue setValue = new SetValue(target, r.getId(), simContextId);
                                    setValue.setMath(math1);
                                    rt.addChange(setValue);
                                } else {
                                    throw new RuntimeException("No scan ranges found for scanned parameter : '" + scannedConstName + "'.");
                                }
                            }
                            sedmlModel.addTask(rt);
                        } else {
                            // both scanned and simple parameters : create new model with change for each simple override; add RepeatedTask
                            // create new model with change for each unscanned parameter that has override
                            String overriddenSimContextId = simContextId + "_" + overrideCount;
                            String overriddenSimContextName = simContextName + " modified";
                            Model sedModel = new Model(overriddenSimContextId, overriddenSimContextName, sbmlLanguageURN, simContextId);
                            overrideCount++;
                            String taskId = "tsk_" + simContextCnt + "_" + simCount;
                            Task sedmlTask = new Task(taskId, taskId, overriddenSimContextId, utcSim.getId());
                            sedmlModel.addTask(sedmlTask);
                            // scanned parameters
                            String repeatedTaskId = "repTsk_" + simContextCnt + "_" + simCount;
                            // TODO: temporary solution - we use as range here the first range
                            String scn = scannedConstantsNames[0];
                            String rId = "range_" + simContextCnt + "_" + simCount + "_" + scn;
                            RepeatedTask rt = new RepeatedTask(repeatedTaskId, repeatedTaskId, true, rId);
                            // to be used later to add dataGenerators - in our case it has to be the repeated task
                            taskRef = repeatedTaskId;
                            SubTask subTask = new SubTask("0", taskId);
                            rt.addSubtask(subTask);
                            for (String scannedConstName : scannedConstantsNames) {
                                ConstantArraySpec constantArraySpec = mathOverrides.getConstantArraySpec(scannedConstName);
                                String rangeId = "range_" + simContextCnt + "_" + simCount + "_" + scannedConstName;
                                // list of Ranges, if sim is parameter scan.
                                if (constantArraySpec != null) {
                                    Range r = null;
                                    System.out.println("     " + constantArraySpec.toString());
                                    if (constantArraySpec.getType() == ConstantArraySpec.TYPE_INTERVAL) {
                                        // ------ Uniform Range
                                        r = new UniformRange(rangeId, constantArraySpec.getMinValue(), constantArraySpec.getMaxValue(), constantArraySpec.getNumValues());
                                        rt.addRange(r);
                                    } else {
                                        // ----- Vector Range
                                        cbit.vcell.math.Constant[] cs = constantArraySpec.getConstants();
                                        ArrayList<Double> values = new ArrayList<Double>();
                                        for (int i = 0; i < cs.length; i++) {
                                            String value = cs[i].getExpression().infix() + ", ";
                                            values.add(Double.parseDouble(value));
                                        }
                                        r = new VectorRange(rangeId, values);
                                        rt.addRange(r);
                                    }
                                    // use scannedParamHash to store rangeId for that param, since it might be needed if unscanned param has a scanned param in expr.
                                    if (scannedParamHash.get(scannedConstName).equals(scannedConstName)) {
                                        // the hash was originally populated as <scannedParamName, scannedParamName>. Replace 'value' with rangeId for scannedParam
                                        scannedParamHash.put(scannedConstName, r.getId());
                                    }
                                    // create setValue for scannedConstName
                                    SymbolTableEntry ste2 = getSymbolTableEntryForModelEntity(mathSymbolMapping, scannedConstName);
                                    XPathTarget target1 = getTargetXPath(ste2, l2gMap);
                                    ASTNode math1 = new ASTCi(scannedConstName);
                                    SetValue setValue1 = new SetValue(target1, r.getId(), sedModel.getId());
                                    setValue1.setMath(math1);
                                    rt.addChange(setValue1);
                                } else {
                                    throw new RuntimeException("No scan ranges found for scanned parameter : '" + scannedConstName + "'.");
                                }
                            }
                            // for unscanned parameter overrides
                            for (String unscannedParamName : unscannedParamHash.values()) {
                                SymbolTableEntry ste = getSymbolTableEntryForModelEntity(mathSymbolMapping, unscannedParamName);
                                Expression unscannedParamExpr = mathOverrides.getActualExpression(unscannedParamName, 0);
                                if (unscannedParamExpr.isNumeric()) {
                                    // if expression is numeric, add ChangeAttribute to model created above
                                    XPathTarget targetXpath = getTargetAttributeXPath(ste, l2gMap);
                                    ChangeAttribute changeAttribute = new ChangeAttribute(targetXpath, unscannedParamExpr.infix());
                                    sedModel.addChange(changeAttribute);
                                } else {
                                    // check for any scanned parameter in unscanned parameter expression
                                    ASTNode math = Libsedml.parseFormulaString(unscannedParamExpr.infix());
                                    String[] exprSymbols = unscannedParamExpr.getSymbols();
                                    boolean bHasScannedParameter = false;
                                    String scannedParamNameInUnscannedParamExp = null;
                                    for (String symbol : exprSymbols) {
                                        if (scannedParamHash.get(symbol) != null) {
                                            bHasScannedParameter = true;
                                            scannedParamNameInUnscannedParamExp = new String(symbol);
                                            // @TODO check for multiple scannedParameters in expression.
                                            break;
                                        }
                                    }
                                    // (scanned parameter in expr) ? (add setValue for unscanned param in repeatedTask) : (add computeChange to modifiedModel)
                                    if (bHasScannedParameter && scannedParamNameInUnscannedParamExp != null) {
                                        // create setValue for unscannedParamName (which contains a scanned param in its expression)
                                        SymbolTableEntry entry = getSymbolTableEntryForModelEntity(mathSymbolMapping, unscannedParamName);
                                        XPathTarget target = getTargetXPath(entry, l2gMap);
                                        String rangeId = scannedParamHash.get(scannedParamNameInUnscannedParamExp);
                                        // @TODO: we have no range??
                                        SetValue setValue = new SetValue(target, rangeId, sedModel.getId());
                                        setValue.setMath(math);
                                        rt.addChange(setValue);
                                    } else {
                                        // non-numeric expression : add 'computeChange' to modified model
                                        XPathTarget targetXpath = getTargetXPath(ste, l2gMap);
                                        ComputeChange computeChange = new ComputeChange(targetXpath, math);
                                        for (String symbol : exprSymbols) {
                                            String symbolName = TokenMangler.mangleToSName(symbol);
                                            SymbolTableEntry ste1 = vcModel.getEntry(symbol);
                                            // ste1 could be a math parameter, hence the above could return null
                                            if (ste1 == null) {
                                                ste1 = simContext.getMathDescription().getEntry(symbol);
                                            }
                                            if (ste1 != null) {
                                                if (ste1 instanceof SpeciesContext || ste1 instanceof Structure || ste1 instanceof ModelParameter) {
                                                    XPathTarget ste1_XPath = getTargetXPath(ste1, l2gMap);
                                                    org.jlibsedml.Variable sedmlVar = new org.jlibsedml.Variable(symbolName, symbolName, taskRef, ste1_XPath.getTargetAsString());
                                                    computeChange.addVariable(sedmlVar);
                                                } else {
                                                    double doubleValue = 0.0;
                                                    if (ste1 instanceof ReservedSymbol) {
                                                        doubleValue = getReservedSymbolValue(ste1);
                                                    } else if (ste instanceof Function) {
                                                        try {
                                                            doubleValue = ste.getExpression().evaluateConstant();
                                                        } catch (Exception e) {
                                                            e.printStackTrace(System.out);
                                                            throw new RuntimeException("Unable to evaluate function '" + ste.getName() + "' used in '" + unscannedParamName + "' expression : ", e);
                                                        }
                                                    } else {
                                                        doubleValue = ste.getConstantValue();
                                                    }
                                                    // TODO: shouldn't be s1_init_uM which is a math symbol, should be s0 (so use the ste-something from above)
                                                    // TODO: revert to Variable, not Parameter
                                                    Parameter sedmlParameter = new Parameter(symbolName, symbolName, doubleValue);
                                                    computeChange.addParameter(sedmlParameter);
                                                }
                                            } else {
                                                throw new RuntimeException("Symbol '" + symbol + "' used in expression for '" + unscannedParamName + "' not found in model.");
                                            }
                                        }
                                        sedModel.addChange(computeChange);
                                    }
                                }
                            }
                            sedmlModel.addModel(sedModel);
                            sedmlModel.addTask(rt);
                        }
                    } else {
                        // no math overrides, add basic task.
                        String taskId = "tsk_" + simContextCnt + "_" + simCount;
                        Task sedmlTask = new Task(taskId, taskId, simContextId, utcSim.getId());
                        sedmlModel.addTask(sedmlTask);
                        // to be used later to add dataGenerators : one set of DGs per model (simContext).
                        taskRef = taskId;
                    }
                    // add one dataGenerator for 'time' for entire SEDML model.
                    // (using the id of the first task in model for 'taskRef' field of var since
                    String timeDataGenPrefix = DATAGENERATOR_TIME_NAME + "_" + taskRef;
                    DataGenerator timeDataGen = sedmlModel.getDataGeneratorWithId(timeDataGenPrefix);
                    if (timeDataGen == null) {
                        // org.jlibsedml.Variable timeVar = new org.jlibsedml.Variable(DATAGENERATOR_TIME_SYMBOL, DATAGENERATOR_TIME_SYMBOL, sedmlModel.getTasks().get(0).getId(), VariableSymbol.TIME);
                        org.jlibsedml.Variable timeVar = new org.jlibsedml.Variable(DATAGENERATOR_TIME_SYMBOL, DATAGENERATOR_TIME_SYMBOL, taskRef, VariableSymbol.TIME);
                        ASTNode math = Libsedml.parseFormulaString(DATAGENERATOR_TIME_SYMBOL);
                        timeDataGen = new DataGenerator(timeDataGenPrefix, timeDataGenPrefix, math);
                        timeDataGen.addVariable(timeVar);
                        sedmlModel.addDataGenerator(timeDataGen);
                        dataGeneratorsOfSim.add(timeDataGen);
                    }
                    // add dataGenerators for species
                    // get species list from SBML model.
                    String dataGenIdPrefix = "dataGen_" + taskRef;
                    String[] varNamesList = SimSpec.fromSBML(sbmlString).getVarsList();
                    for (String varName : varNamesList) {
                        org.jlibsedml.Variable sedmlVar = new org.jlibsedml.Variable(varName, varName, taskRef, sbmlSupport.getXPathForSpecies(varName));
                        ASTNode varMath = Libsedml.parseFormulaString(varName);
                        // "dataGen_" + varCount; - old code
                        String dataGenId = dataGenIdPrefix + "_" + TokenMangler.mangleToSName(varName);
                        DataGenerator dataGen = new DataGenerator(dataGenId, dataGenId, varMath);
                        dataGen.addVariable(sedmlVar);
                        sedmlModel.addDataGenerator(dataGen);
                        dataGeneratorsOfSim.add(dataGen);
                        varCount++;
                    }
                    // add DataGenerators for output functions here
                    ArrayList<AnnotatedFunction> outputFunctions = simContext.getOutputFunctionContext().getOutputFunctionsList();
                    for (AnnotatedFunction annotatedFunction : outputFunctions) {
                        Expression functionExpr = annotatedFunction.getExpression();
                        ASTNode funcMath = Libsedml.parseFormulaString(functionExpr.infix());
                        // "dataGen_" + varCount; - old code
                        String dataGenId = dataGenIdPrefix + "_" + TokenMangler.mangleToSName(annotatedFunction.getName());
                        DataGenerator dataGen = new DataGenerator(dataGenId, dataGenId, funcMath);
                        String[] functionSymbols = functionExpr.getSymbols();
                        for (String symbol : functionSymbols) {
                            String symbolName = TokenMangler.mangleToSName(symbol);
                            // try to get symbol from model, if null, try simContext.mathDesc
                            SymbolTableEntry ste = vcModel.getEntry(symbol);
                            if (ste == null) {
                                ste = simContext.getMathDescription().getEntry(symbol);
                            }
                            if (ste instanceof SpeciesContext || ste instanceof Structure || ste instanceof ModelParameter) {
                                XPathTarget targetXPath = getTargetXPath(ste, l2gMap);
                                org.jlibsedml.Variable sedmlVar = new org.jlibsedml.Variable(symbolName, symbolName, taskRef, targetXPath.getTargetAsString());
                                dataGen.addVariable(sedmlVar);
                            } else {
                                double value = 0.0;
                                if (ste instanceof Function) {
                                    try {
                                        value = ste.getExpression().evaluateConstant();
                                    } catch (Exception e) {
                                        e.printStackTrace(System.out);
                                        throw new RuntimeException("Unable to evaluate function '" + ste.getName() + "' for output function '" + annotatedFunction.getName() + "'.", e);
                                    }
                                } else {
                                    value = ste.getConstantValue();
                                }
                                Parameter sedmlParameter = new Parameter(symbolName, symbolName, value);
                                dataGen.addParameter(sedmlParameter);
                            }
                        }
                        sedmlModel.addDataGenerator(dataGen);
                        dataGeneratorsOfSim.add(dataGen);
                        varCount++;
                    }
                    simCount++;
                    // ignoring output for spatial deterministic (spatial stochastic is not exported to SEDML) and non-spatial stochastic applications with histogram
                    if (!(simContext.getGeometry().getDimension() > 0)) {
                        // ignore Output (Plot2d)  for non-spatial stochastic simulation with histogram.
                        boolean bSimHasHistogram = false;
                        if (simContext.isStoch()) {
                            long numOfTrials = simTaskDesc.getStochOpt().getNumOfTrials();
                            if (numOfTrials > 1) {
                                // not histogram {
                                bSimHasHistogram = true;
                            }
                        }
                        if (!bSimHasHistogram) {
                            String plot2dId = "plot2d_" + TokenMangler.mangleToSName(vcSimulation.getName());
                            Plot2D sedmlPlot2d = new Plot2D(plot2dId, simContext.getName() + "plots");
                            sedmlPlot2d.addNote(createNotesElement("Plot of all variables and output functions from application '" + simContext.getName() + "' ; simulation '" + vcSimulation.getName() + "' in VCell model"));
                            List<DataGenerator> dataGenerators = sedmlModel.getDataGenerators();
                            String xDataRef = sedmlModel.getDataGeneratorWithId(DATAGENERATOR_TIME_NAME + "_" + taskRef).getId();
                            // add a curve for each dataGenerator in SEDML model
                            int curveCnt = 0;
                            for (DataGenerator dataGenerator : dataGeneratorsOfSim) {
                                // no curve for time, since time is xDateReference
                                if (dataGenerator.getId().equals(xDataRef)) {
                                    continue;
                                }
                                String curveId = "curve_" + curveCnt++;
                                Curve curve = new Curve(curveId, curveId, false, false, xDataRef, dataGenerator.getId());
                                sedmlPlot2d.addCurve(curve);
                            }
                            sedmlModel.addOutput(sedmlPlot2d);
                        }
                    }
                }
            // end - for 'sims'
            } else {
                // end if (!(simContext.getGeometry().getDimension() > 0 && simContext.isStoch()))
                String msg = "\n\t" + simContextName + " : export of spatial stochastic (Smoldyn solver) applications to SEDML not supported at this time.";
                sedmlNotesStr += msg;
            }
            // end : if-else simContext is not spatial stochastic
            simContextCnt++;
        }
        // if sedmlNotesStr is not null, there were some applications that could not be exported to SEDML (eg., spatial stochastic). Create a notes element and add it to sedml Model.
        if (sedmlNotesStr.length() > 0) {
            sedmlNotesStr = "\n\tThe following applications in the VCell model were not exported to VCell : " + sedmlNotesStr;
            sedmlModel.addNote(createNotesElement(sedmlNotesStr));
        }
        // error check : if there are no non-spatial deterministic applications (=> no models in SEDML document), complain.
        if (sedmlModel.getModels().isEmpty()) {
            throw new RuntimeException("No applications in biomodel to export to Sedml.");
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new RuntimeException("Error adding model to SEDML document : " + e.getMessage());
    }
}
Also used : Task(org.jlibsedml.Task) SubTask(org.jlibsedml.SubTask) RepeatedTask(org.jlibsedml.RepeatedTask) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SpeciesContext(cbit.vcell.model.SpeciesContext) ConstantArraySpec(cbit.vcell.solver.ConstantArraySpec) ExpressionException(cbit.vcell.parser.ExpressionException) ChangeAttribute(org.jlibsedml.ChangeAttribute) ComputeChange(org.jlibsedml.ComputeChange) SolverTaskDescription(cbit.vcell.solver.SolverTaskDescription) SubTask(org.jlibsedml.SubTask) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) Curve(org.jlibsedml.Curve) SBMLExporter(org.vcell.sbml.vcell.SBMLExporter) XmlParseException(cbit.vcell.xml.XmlParseException) VectorRange(org.jlibsedml.VectorRange) UniformRange(org.jlibsedml.UniformRange) Range(org.jlibsedml.Range) Algorithm(org.jlibsedml.Algorithm) MathOverrides(cbit.vcell.solver.MathOverrides) ModelParameter(cbit.vcell.model.Model.ModelParameter) DataGenerator(org.jlibsedml.DataGenerator) MathMapping(cbit.vcell.mapping.MathMapping) UniformTimeCourse(org.jlibsedml.UniformTimeCourse) Plot2D(org.jlibsedml.Plot2D) SbmlException(org.vcell.sbml.SbmlException) VectorRange(org.jlibsedml.VectorRange) SolverDescription(cbit.vcell.solver.SolverDescription) ReservedSymbol(cbit.vcell.model.Model.ReservedSymbol) StructureMapping(cbit.vcell.mapping.StructureMapping) TimeBounds(cbit.vcell.solver.TimeBounds) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) Function(cbit.vcell.math.Function) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) ASTCi(org.jmathml.ASTCi) RepeatedTask(org.jlibsedml.RepeatedTask) ASTNode(org.jmathml.ASTNode) Structure(cbit.vcell.model.Structure) SimulationJob(cbit.vcell.solver.SimulationJob) Pair(org.vcell.util.Pair) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem) SimulationContext(cbit.vcell.mapping.SimulationContext) MathSymbolMapping(cbit.vcell.mapping.MathSymbolMapping) SbmlException(org.vcell.sbml.SbmlException) TransformerException(javax.xml.transform.TransformerException) XmlParseException(cbit.vcell.xml.XmlParseException) IOException(java.io.IOException) ExpressionException(cbit.vcell.parser.ExpressionException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SBMLSupport(org.jlibsedml.modelsupport.SBMLSupport) Simulation(cbit.vcell.solver.Simulation) Expression(cbit.vcell.parser.Expression) BioModel(cbit.vcell.biomodel.BioModel) UniformRange(org.jlibsedml.UniformRange) BioModel(cbit.vcell.biomodel.BioModel) Model(org.jlibsedml.Model) StructureMappingParameter(cbit.vcell.mapping.StructureMapping.StructureMappingParameter) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) ProxyParameter(cbit.vcell.model.ProxyParameter) Parameter(org.jlibsedml.Parameter) XPathTarget(org.jlibsedml.XPathTarget) SetValue(org.jlibsedml.SetValue)

Example 2 with SbmlException

use of org.vcell.sbml.SbmlException in project vcell by virtualcell.

the class XmlHelper method exportSBML.

/**
 * Exports VCML format to another supported format (currently: SBML or CellML). It allows
 *	 choosing a specific Simulation Spec to export.
 * Creation date: (4/8/2003 12:30:27 PM)
 * @return java.lang.String
 */
public static String exportSBML(VCDocument vcDoc, int level, int version, int pkgVersion, boolean isSpatial, SimulationContext simContext, SimulationJob simJob) throws XmlParseException {
    if (vcDoc == null) {
        throw new XmlParseException("Invalid arguments for exporting SBML.");
    }
    if (vcDoc instanceof BioModel) {
        try {
            // clone BioModel
            BioModel clonedBioModel = cloneBioModel(simContext.getBioModel());
            // extract the simContext from new Biomodel. Apply overrides to *this* modified simContext
            SimulationContext simContextFromClonedBioModel = clonedBioModel.getSimulationContext(simContext.getName());
            SimulationContext clonedSimContext = applyOverridesForSBML(clonedBioModel, simContextFromClonedBioModel, simJob);
            // extract sim (in simJob) from modified Biomodel, if not null
            SimulationJob modifiedSimJob = null;
            if (simJob != null) {
                Simulation simFromClonedBiomodel = clonedSimContext.getSimulation(simJob.getSimulation().getName());
                modifiedSimJob = new SimulationJob(simFromClonedBiomodel, simJob.getJobIndex(), null);
            }
            SBMLExporter sbmlExporter = new SBMLExporter(clonedBioModel, level, version, isSpatial);
            sbmlExporter.setSelectedSimContext(clonedSimContext);
            sbmlExporter.setSelectedSimulationJob(modifiedSimJob);
            String sbmlSTring = sbmlExporter.getSBMLString();
            // cleanup the string of all the "sameAs" statements
            sbmlSTring = SBMLAnnotationUtil.postProcessCleanup(sbmlSTring);
            return sbmlSTring;
        } catch (SbmlException | SBMLException | XMLStreamException e) {
            e.printStackTrace(System.out);
            throw new XmlParseException(e);
        }
    } else if (vcDoc instanceof MathModel) {
        try {
            return MathModel_SBMLExporter.getSBMLString((MathModel) vcDoc, level, version);
        } catch (ExpressionException | IOException | SBMLException | XMLStreamException e) {
            e.printStackTrace(System.out);
            throw new XmlParseException(e);
        }
    } else {
        throw new RuntimeException("unsupported Document Type " + vcDoc.getClass().getName() + " for SBML export");
    }
}
Also used : SBMLException(org.sbml.jsbml.SBMLException) MathModel(cbit.vcell.mathmodel.MathModel) MathModel_SBMLExporter(org.vcell.sbml.vcell.MathModel_SBMLExporter) SBMLExporter(org.vcell.sbml.vcell.SBMLExporter) SimulationContext(cbit.vcell.mapping.SimulationContext) XMLStreamException(javax.xml.stream.XMLStreamException) BioModel(cbit.vcell.biomodel.BioModel) SbmlException(org.vcell.sbml.SbmlException)

Example 3 with SbmlException

use of org.vcell.sbml.SbmlException in project vcell by virtualcell.

the class SBMLImporter method addGeometry.

protected void addGeometry() {
    // get a Geometry object via SpatialModelPlugin object.
    org.sbml.jsbml.ext.spatial.Geometry sbmlGeometry = getSbmlGeometry();
    if (sbmlGeometry == null) {
        return;
    }
    int dimension = 0;
    Origin vcOrigin = null;
    Extent vcExtent = null;
    {
        // local code block
        // get a CoordComponent object via the Geometry object.
        ListOf<CoordinateComponent> listOfCoordComps = sbmlGeometry.getListOfCoordinateComponents();
        if (listOfCoordComps == null) {
            throw new RuntimeException("Cannot have 0 coordinate compartments in geometry");
        }
        // coord component
        double ox = 0.0;
        double oy = 0.0;
        double oz = 0.0;
        double ex = 1.0;
        double ey = 1.0;
        double ez = 1.0;
        for (CoordinateComponent coordComponent : listOfCoordComps) {
            double minValue = coordComponent.getBoundaryMinimum().getValue();
            double maxValue = coordComponent.getBoundaryMaximum().getValue();
            switch(coordComponent.getType()) {
                case cartesianX:
                    {
                        ox = minValue;
                        ex = maxValue - minValue;
                        break;
                    }
                case cartesianY:
                    {
                        oy = minValue;
                        ey = maxValue - minValue;
                        break;
                    }
                case cartesianZ:
                    {
                        oz = minValue;
                        ez = maxValue - minValue;
                        break;
                    }
            }
            dimension++;
        }
        vcOrigin = new Origin(ox, oy, oz);
        vcExtent = new Extent(ex, ey, ez);
    }
    // from geometry definition, find out which type of geometry : image or
    // analytic or CSG
    AnalyticGeometry analyticGeometryDefinition = null;
    CSGeometry csGeometry = null;
    SampledFieldGeometry segmentedSampledFieldGeometry = null;
    SampledFieldGeometry distanceMapSampledFieldGeometry = null;
    ParametricGeometry parametricGeometry = null;
    for (int i = 0; i < sbmlGeometry.getListOfGeometryDefinitions().size(); i++) {
        GeometryDefinition gd_temp = sbmlGeometry.getListOfGeometryDefinitions().get(i);
        if (!gd_temp.isSetIsActive()) {
            continue;
        }
        if (gd_temp instanceof AnalyticGeometry) {
            analyticGeometryDefinition = (AnalyticGeometry) gd_temp;
        } else if (gd_temp instanceof SampledFieldGeometry) {
            SampledFieldGeometry sfg = (SampledFieldGeometry) gd_temp;
            String sfn = sfg.getSampledField();
            ListOf<SampledField> sampledFields = sbmlGeometry.getListOfSampledFields();
            if (sampledFields.size() > 1) {
                throw new RuntimeException("only one sampled field supported");
            }
            InterpolationKind ik = sampledFields.get(0).getInterpolationType();
            switch(ik) {
                case linear:
                    distanceMapSampledFieldGeometry = sfg;
                    break;
                case nearestNeighbor:
                    segmentedSampledFieldGeometry = sfg;
                    break;
                default:
                    lg.warn("Unsupported " + sampledFields.get(0).getName() + " interpolation type " + ik);
            }
        } else if (gd_temp instanceof CSGeometry) {
            csGeometry = (CSGeometry) gd_temp;
        } else if (gd_temp instanceof ParametricGeometry) {
            parametricGeometry = (ParametricGeometry) gd_temp;
        } else {
            throw new RuntimeException("unsupported geometry definition type " + gd_temp.getClass().getSimpleName());
        }
    }
    if (analyticGeometryDefinition == null && segmentedSampledFieldGeometry == null && distanceMapSampledFieldGeometry == null && csGeometry == null) {
        throw new SBMLImportException("VCell supports only Analytic, Image based (segmentd or distance map) or Constructed Solid Geometry at this time.");
    }
    GeometryDefinition selectedGeometryDefinition = null;
    if (csGeometry != null) {
        selectedGeometryDefinition = csGeometry;
    } else if (analyticGeometryDefinition != null) {
        selectedGeometryDefinition = analyticGeometryDefinition;
    } else if (segmentedSampledFieldGeometry != null) {
        selectedGeometryDefinition = segmentedSampledFieldGeometry;
    } else if (distanceMapSampledFieldGeometry != null) {
        selectedGeometryDefinition = distanceMapSampledFieldGeometry;
    } else if (parametricGeometry != null) {
        selectedGeometryDefinition = parametricGeometry;
    } else {
        throw new SBMLImportException("no geometry definition found");
    }
    Geometry vcGeometry = null;
    if (selectedGeometryDefinition == analyticGeometryDefinition || selectedGeometryDefinition == csGeometry) {
        vcGeometry = new Geometry("spatialGeom", dimension);
    } else if (selectedGeometryDefinition == distanceMapSampledFieldGeometry || selectedGeometryDefinition == segmentedSampledFieldGeometry) {
        SampledFieldGeometry sfg = (SampledFieldGeometry) selectedGeometryDefinition;
        // get image from sampledFieldGeometry
        // get a sampledVol object via the listOfSampledVol (from
        // SampledGeometry) object.
        // gcw gcw gcw
        String sfn = sfg.getSampledField();
        SampledField sf = null;
        for (SampledField sampledField : sbmlGeometry.getListOfSampledFields()) {
            if (sampledField.getSpatialId().equals(sfn)) {
                sf = sampledField;
            }
        }
        int numX = sf.getNumSamples1();
        int numY = sf.getNumSamples2();
        int numZ = sf.getNumSamples3();
        int[] samples = new int[sf.getSamplesLength()];
        StringTokenizer tokens = new StringTokenizer(sf.getSamples(), " ");
        int count = 0;
        while (tokens.hasMoreTokens()) {
            int sample = Integer.parseInt(tokens.nextToken());
            samples[count++] = sample;
        }
        byte[] imageInBytes = new byte[samples.length];
        if (selectedGeometryDefinition == distanceMapSampledFieldGeometry) {
            // 
            for (int i = 0; i < imageInBytes.length; i++) {
                // if (interpolation(samples[i])<0){
                if (samples[i] < 0) {
                    imageInBytes[i] = -1;
                } else {
                    imageInBytes[i] = 1;
                }
            }
        } else {
            for (int i = 0; i < imageInBytes.length; i++) {
                imageInBytes[i] = (byte) samples[i];
            }
        }
        try {
            // System.out.println("ident " + sf.getId() + " " + sf.getName());
            VCImage vcImage = null;
            CompressionKind ck = sf.getCompression();
            DataKind dk = sf.getDataType();
            if (ck == CompressionKind.deflated) {
                vcImage = new VCImageCompressed(null, imageInBytes, vcExtent, numX, numY, numZ);
            } else {
                switch(dk) {
                    case UINT8:
                    case UINT16:
                    case UINT32:
                        vcImage = new VCImageUncompressed(null, imageInBytes, vcExtent, numX, numY, numZ);
                    default:
                }
            }
            if (vcImage == null) {
                throw new SbmlException("Unsupported type combination " + ck + ", " + dk + " for sampled field " + sf.getName());
            }
            vcImage.setName(sf.getId());
            ListOf<SampledVolume> sampledVolumes = sfg.getListOfSampledVolumes();
            final int numSampledVols = sampledVolumes.size();
            if (numSampledVols == 0) {
                throw new RuntimeException("Cannot have 0 sampled volumes in sampledField (image_based) geometry");
            }
            // check to see if values are uniquely integer , add set up scaling if necessary
            double scaleFactor = checkPixelScaling(sampledVolumes, 1);
            if (scaleFactor != 1) {
                double checkScaleFactor = checkPixelScaling(sampledVolumes, scaleFactor);
                VCAssert.assertTrue(checkScaleFactor != scaleFactor, "Scale factor check failed");
            }
            VCPixelClass[] vcpixelClasses = new VCPixelClass[numSampledVols];
            // get pixel classes for geometry
            for (int i = 0; i < numSampledVols; i++) {
                SampledVolume sVol = sampledVolumes.get(i);
                // from subVolume, get pixelClass?
                final int scaled = (int) (scaleFactor * sVol.getSampledValue());
                vcpixelClasses[i] = new VCPixelClass(null, sVol.getDomainType(), scaled);
            }
            vcImage.setPixelClasses(vcpixelClasses);
            // now create image geometry
            vcGeometry = new Geometry("spatialGeom", vcImage);
        } catch (Exception e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Unable to create image from SampledFieldGeometry : " + e.getMessage());
        }
    }
    GeometrySpec vcGeometrySpec = vcGeometry.getGeometrySpec();
    vcGeometrySpec.setOrigin(vcOrigin);
    try {
        vcGeometrySpec.setExtent(vcExtent);
    } catch (PropertyVetoException e) {
        e.printStackTrace(System.out);
        throw new SBMLImportException("Unable to set extent on VC geometry : " + e.getMessage(), e);
    }
    // get listOfDomainTypes via the Geometry object.
    ListOf<DomainType> listOfDomainTypes = sbmlGeometry.getListOfDomainTypes();
    if (listOfDomainTypes == null || listOfDomainTypes.size() < 1) {
        throw new SBMLImportException("Cannot have 0 domainTypes in geometry");
    }
    // get a listOfDomains via the Geometry object.
    ListOf<Domain> listOfDomains = sbmlGeometry.getListOfDomains();
    if (listOfDomains == null || listOfDomains.size() < 1) {
        throw new SBMLImportException("Cannot have 0 domains in geometry");
    }
    // ListOfGeometryDefinitions listOfGeomDefns =
    // sbmlGeometry.getListOfGeometryDefinitions();
    // if ((listOfGeomDefns == null) ||
    // (sbmlGeometry.getNumGeometryDefinitions() > 1)) {
    // throw new
    // RuntimeException("Can have only 1 geometry definition in geometry");
    // }
    // use the boolean bAnalytic to create the right kind of subvolume.
    // First match the somVol=domainTypes for spDim=3. Deal witl spDim=2
    // afterwards.
    GeometrySurfaceDescription vcGsd = vcGeometry.getGeometrySurfaceDescription();
    Vector<DomainType> surfaceClassDomainTypesVector = new Vector<DomainType>();
    try {
        for (DomainType dt : listOfDomainTypes) {
            if (dt.getSpatialDimensions() == 3) {
                // subvolume
                if (selectedGeometryDefinition == analyticGeometryDefinition) {
                    // will set expression later - when reading in Analytic
                    // Volumes in GeometryDefinition
                    vcGeometrySpec.addSubVolume(new AnalyticSubVolume(dt.getId(), new Expression(1.0)));
                } else {
                // add SubVolumes later for CSG and Image-based
                }
            } else if (dt.getSpatialDimensions() == 2) {
                surfaceClassDomainTypesVector.add(dt);
            }
        }
        // analytic vol is needed to get the expression for subVols
        if (selectedGeometryDefinition == analyticGeometryDefinition) {
            // get an analyticVol object via the listOfAnalyticVol (from
            // AnalyticGeometry) object.
            ListOf<AnalyticVolume> aVolumes = analyticGeometryDefinition.getListOfAnalyticVolumes();
            if (aVolumes.size() < 1) {
                throw new SBMLImportException("Cannot have 0 Analytic volumes in analytic geometry");
            }
            for (AnalyticVolume analyticVol : aVolumes) {
                // get subVol from VC geometry using analyticVol spatialId;
                // set its expr using analyticVol's math.
                SubVolume vcSubvolume = vcGeometrySpec.getSubVolume(analyticVol.getDomainType());
                CastInfo<AnalyticSubVolume> ci = BeanUtils.attemptCast(AnalyticSubVolume.class, vcSubvolume);
                if (!ci.isGood()) {
                    throw new RuntimeException("analytic volume '" + analyticVol.getId() + "' does not map to any VC subvolume.");
                }
                AnalyticSubVolume asv = ci.get();
                try {
                    Expression subVolExpr = getExpressionFromFormula(analyticVol.getMath());
                    asv.setExpression(subVolExpr);
                } catch (ExpressionException e) {
                    e.printStackTrace(System.out);
                    throw new SBMLImportException("Unable to set expression on subVolume '" + asv.getName() + "'. " + e.getMessage(), e);
                }
            }
        }
        SampledFieldGeometry sfg = BeanUtils.downcast(SampledFieldGeometry.class, selectedGeometryDefinition);
        if (sfg != null) {
            ListOf<SampledVolume> sampledVolumes = sfg.getListOfSampledVolumes();
            int numSampledVols = sampledVolumes.size();
            if (numSampledVols == 0) {
                throw new SBMLImportException("Cannot have 0 sampled volumes in sampledField (image_based) geometry");
            }
            VCPixelClass[] vcpixelClasses = new VCPixelClass[numSampledVols];
            ImageSubVolume[] vcImageSubVols = new ImageSubVolume[numSampledVols];
            // get pixel classes for geometry
            int idx = 0;
            for (SampledVolume sVol : sampledVolumes) {
                // from subVolume, get pixelClass?
                final String name = sVol.getDomainType();
                final int pixelValue = SBMLUtils.ignoreZeroFraction(sVol.getSampledValue());
                VCPixelClass pc = new VCPixelClass(null, name, pixelValue);
                vcpixelClasses[idx] = pc;
                // Create the new Image SubVolume - use index of this for
                // loop as 'handle' for ImageSubVol?
                ImageSubVolume isv = new ImageSubVolume(null, pc, idx);
                isv.setName(name);
                vcImageSubVols[idx++] = isv;
            }
            vcGeometry.getGeometrySpec().setSubVolumes(vcImageSubVols);
        }
        if (selectedGeometryDefinition == csGeometry) {
            ListOf<org.sbml.jsbml.ext.spatial.CSGObject> listOfcsgObjs = csGeometry.getListOfCSGObjects();
            ArrayList<org.sbml.jsbml.ext.spatial.CSGObject> sbmlCSGs = new ArrayList<org.sbml.jsbml.ext.spatial.CSGObject>(listOfcsgObjs);
            // we want the CSGObj with highest ordinal to be the first
            // element in the CSG subvols array.
            Collections.sort(sbmlCSGs, new Comparator<org.sbml.jsbml.ext.spatial.CSGObject>() {

                @Override
                public int compare(org.sbml.jsbml.ext.spatial.CSGObject lhs, org.sbml.jsbml.ext.spatial.CSGObject rhs) {
                    // minus one to reverse sort
                    return -1 * Integer.compare(lhs.getOrdinal(), rhs.getOrdinal());
                }
            });
            int n = sbmlCSGs.size();
            CSGObject[] vcCSGSubVolumes = new CSGObject[n];
            for (int i = 0; i < n; i++) {
                org.sbml.jsbml.ext.spatial.CSGObject sbmlCSGObject = sbmlCSGs.get(i);
                CSGObject vcellCSGObject = new CSGObject(null, sbmlCSGObject.getDomainType(), i);
                vcellCSGObject.setRoot(getVCellCSGNode(sbmlCSGObject.getCSGNode()));
            }
            vcGeometry.getGeometrySpec().setSubVolumes(vcCSGSubVolumes);
        }
        // Call geom.geomSurfDesc.updateAll() to automatically generate
        // surface classes.
        // vcGsd.updateAll();
        vcGeometry.precomputeAll(new GeometryThumbnailImageFactoryAWT(), true, true);
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new SBMLImportException("Unable to create VC subVolumes from SBML domainTypes : " + e.getMessage(), e);
    }
    // should now map each SBML domain to right VC geometric region.
    GeometricRegion[] vcGeomRegions = vcGsd.getGeometricRegions();
    ISize sampleSize = vcGsd.getVolumeSampleSize();
    RegionInfo[] regionInfos = vcGsd.getRegionImage().getRegionInfos();
    int numX = sampleSize.getX();
    int numY = sampleSize.getY();
    int numZ = sampleSize.getZ();
    double ox = vcOrigin.getX();
    double oy = vcOrigin.getY();
    double oz = vcOrigin.getZ();
    for (Domain domain : listOfDomains) {
        String domainType = domain.getDomainType();
        InteriorPoint interiorPt = domain.getListOfInteriorPoints().get(0);
        if (interiorPt == null) {
            DomainType currDomainType = null;
            for (DomainType dt : sbmlGeometry.getListOfDomainTypes()) {
                if (dt.getSpatialId().equals(domainType)) {
                    currDomainType = dt;
                }
            }
            if (currDomainType.getSpatialDimensions() == 2) {
                continue;
            }
        }
        Coordinate sbmlInteriorPtCoord = new Coordinate(interiorPt.getCoord1(), interiorPt.getCoord2(), interiorPt.getCoord3());
        for (int j = 0; j < vcGeomRegions.length; j++) {
            if (vcGeomRegions[j] instanceof VolumeGeometricRegion) {
                int regionID = ((VolumeGeometricRegion) vcGeomRegions[j]).getRegionID();
                for (int k = 0; k < regionInfos.length; k++) {
                    // (using gemoRegion regionID).
                    if (regionInfos[k].getRegionIndex() == regionID) {
                        int volIndx = 0;
                        Coordinate nearestPtCoord = null;
                        double minDistance = Double.MAX_VALUE;
                        // represented by SBML 'domain[i]'.
                        for (int z = 0; z < numZ; z++) {
                            for (int y = 0; y < numY; y++) {
                                for (int x = 0; x < numX; x++) {
                                    if (regionInfos[k].isIndexInRegion(volIndx)) {
                                        double unit_z = (numZ > 1) ? ((double) z) / (numZ - 1) : 0.5;
                                        double coordZ = oz + vcExtent.getZ() * unit_z;
                                        double unit_y = (numY > 1) ? ((double) y) / (numY - 1) : 0.5;
                                        double coordY = oy + vcExtent.getY() * unit_y;
                                        double unit_x = (numX > 1) ? ((double) x) / (numX - 1) : 0.5;
                                        double coordX = ox + vcExtent.getX() * unit_x;
                                        // for now, find the shortest dist
                                        // coord. Can refine algo later.
                                        Coordinate vcCoord = new Coordinate(coordX, coordY, coordZ);
                                        double distance = sbmlInteriorPtCoord.distanceTo(vcCoord);
                                        if (distance < minDistance) {
                                            minDistance = distance;
                                            nearestPtCoord = vcCoord;
                                        }
                                    }
                                    volIndx++;
                                }
                            // end - for x
                            }
                        // end - for y
                        }
                        // with domain name
                        if (nearestPtCoord != null) {
                            GeometryClass geomClassSBML = vcGeometry.getGeometryClass(domainType);
                            // we know vcGeometryReg[j] is a VolGeomRegion
                            GeometryClass geomClassVC = ((VolumeGeometricRegion) vcGeomRegions[j]).getSubVolume();
                            if (geomClassSBML.compareEqual(geomClassVC)) {
                                vcGeomRegions[j].setName(domain.getId());
                            }
                        }
                    }
                // end if (regInfoIndx = regId)
                }
            // end - for regInfo
            }
        }
    // end for - vcGeomRegions
    }
    // deal with surfaceClass:spDim2-domainTypes
    for (int i = 0; i < surfaceClassDomainTypesVector.size(); i++) {
        DomainType surfaceClassDomainType = surfaceClassDomainTypesVector.elementAt(i);
        // 'surfaceClassDomainType'
        for (Domain d : listOfDomains) {
            if (d.getDomainType().equals(surfaceClassDomainType.getId())) {
                // get the adjacent domains of this 'surface' domain
                // (surface domain + its 2 adj vol domains)
                Set<Domain> adjacentDomainsSet = getAssociatedAdjacentDomains(sbmlGeometry, d);
                // get the domain types of the adjacent domains in SBML and
                // store the corresponding subVol counterparts from VC for
                // adj vol domains
                Vector<SubVolume> adjacentSubVolumesVector = new Vector<SubVolume>();
                Vector<VolumeGeometricRegion> adjVolGeomRegionsVector = new Vector<VolumeGeometricRegion>();
                Iterator<Domain> iterator = adjacentDomainsSet.iterator();
                while (iterator.hasNext()) {
                    Domain dom = iterator.next();
                    DomainType dt = getBySpatialID(sbmlGeometry.getListOfDomainTypes(), dom.getDomainType());
                    if (dt.getSpatialDimensions() == 3) {
                        // for domain type with sp. dim = 3, get
                        // correspoinding subVol from VC geometry.
                        GeometryClass gc = vcGeometry.getGeometryClass(dt.getId());
                        adjacentSubVolumesVector.add((SubVolume) gc);
                        // store volGeomRegions corresponding to this (vol)
                        // geomClass in adjVolGeomRegionsVector : this
                        // should return ONLY 1 region for subVol.
                        GeometricRegion[] geomRegion = vcGsd.getGeometricRegions(gc);
                        adjVolGeomRegionsVector.add((VolumeGeometricRegion) geomRegion[0]);
                    }
                }
                // there should be only 2 subVols in this vector
                if (adjacentSubVolumesVector.size() != 2) {
                    throw new RuntimeException("Cannot have more or less than 2 subvolumes that are adjacent to surface (membrane) '" + d.getId() + "'");
                }
                // get the surface class with these 2 adj subVols. Set its
                // name to that of 'surfaceClassDomainType'
                SurfaceClass surfacClass = vcGsd.getSurfaceClass(adjacentSubVolumesVector.get(0), adjacentSubVolumesVector.get(1));
                surfacClass.setName(surfaceClassDomainType.getSpatialId());
                // get surfaceGeometricRegion that has adjVolGeomRegions as
                // its adjacent vol geom regions and set its name from
                // domain 'd'
                SurfaceGeometricRegion surfaceGeomRegion = getAssociatedSurfaceGeometricRegion(vcGsd, adjVolGeomRegionsVector);
                if (surfaceGeomRegion != null) {
                    surfaceGeomRegion.setName(d.getId());
                }
            }
        // end if - domain.domainType == surfaceClassDomainType
        }
    // end for - numDomains
    }
    // structureMappings in VC from compartmentMappings in SBML
    try {
        // set geometry first and then set structureMappings?
        vcBioModel.getSimulationContext(0).setGeometry(vcGeometry);
        // update simContextName ...
        vcBioModel.getSimulationContext(0).setName(vcBioModel.getSimulationContext(0).getName() + "_" + vcGeometry.getName());
        Model vcModel = vcBioModel.getSimulationContext(0).getModel();
        ModelUnitSystem vcModelUnitSystem = vcModel.getUnitSystem();
        Vector<StructureMapping> structMappingsVector = new Vector<StructureMapping>();
        SpatialCompartmentPlugin cplugin = null;
        for (int i = 0; i < sbmlModel.getNumCompartments(); i++) {
            Compartment c = sbmlModel.getCompartment(i);
            String cname = c.getName();
            cplugin = (SpatialCompartmentPlugin) c.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
            CompartmentMapping compMapping = cplugin.getCompartmentMapping();
            if (compMapping != null) {
                // final String id = compMapping.getId();
                // final String name = compMapping.getName();
                CastInfo<Structure> ci = SBMLHelper.getTypedStructure(Structure.class, vcModel, cname);
                if (ci.isGood()) {
                    Structure struct = ci.get();
                    String domainType = compMapping.getDomainType();
                    GeometryClass geometryClass = vcGeometry.getGeometryClass(domainType);
                    double unitSize = compMapping.getUnitSize();
                    Feature feat = BeanUtils.downcast(Feature.class, struct);
                    if (feat != null) {
                        FeatureMapping featureMapping = new FeatureMapping(feat, vcBioModel.getSimulationContext(0), vcModelUnitSystem);
                        featureMapping.setGeometryClass(geometryClass);
                        if (geometryClass instanceof SubVolume) {
                            featureMapping.getVolumePerUnitVolumeParameter().setExpression(new Expression(unitSize));
                        } else if (geometryClass instanceof SurfaceClass) {
                            featureMapping.getVolumePerUnitAreaParameter().setExpression(new Expression(unitSize));
                        }
                        structMappingsVector.add(featureMapping);
                    } else if (struct instanceof Membrane) {
                        MembraneMapping membraneMapping = new MembraneMapping((Membrane) struct, vcBioModel.getSimulationContext(0), vcModelUnitSystem);
                        membraneMapping.setGeometryClass(geometryClass);
                        if (geometryClass instanceof SubVolume) {
                            membraneMapping.getAreaPerUnitVolumeParameter().setExpression(new Expression(unitSize));
                        } else if (geometryClass instanceof SurfaceClass) {
                            membraneMapping.getAreaPerUnitAreaParameter().setExpression(new Expression(unitSize));
                        }
                        structMappingsVector.add(membraneMapping);
                    }
                }
            }
        }
        StructureMapping[] structMappings = structMappingsVector.toArray(new StructureMapping[0]);
        vcBioModel.getSimulationContext(0).getGeometryContext().setStructureMappings(structMappings);
        // if type from SBML parameter Boundary Condn is not the same as the
        // boundary type of the
        // structureMapping of structure of paramSpContext, set the boundary
        // condn type of the structureMapping
        // to the value of 'type' from SBML parameter Boundary Condn.
        ListOf<Parameter> listOfGlobalParams = sbmlModel.getListOfParameters();
        for (Parameter sbmlGlobalParam : sbmlModel.getListOfParameters()) {
            SpatialParameterPlugin spplugin = (SpatialParameterPlugin) sbmlGlobalParam.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
            ParameterType paramType = spplugin.getParamType();
            if (!(paramType instanceof BoundaryCondition)) {
                continue;
            }
            BoundaryCondition bCondn = (BoundaryCondition) paramType;
            if (bCondn.isSetVariable()) {
                // get the var of boundaryCondn; find appropriate spContext
                // in vcell;
                SpeciesContext paramSpContext = vcBioModel.getSimulationContext(0).getModel().getSpeciesContext(bCondn.getVariable());
                if (paramSpContext != null) {
                    Structure s = paramSpContext.getStructure();
                    StructureMapping sm = vcBioModel.getSimulationContext(0).getGeometryContext().getStructureMapping(s);
                    if (sm != null) {
                        BoundaryConditionType bct = null;
                        switch(bCondn.getType()) {
                            case Dirichlet:
                                {
                                    bct = BoundaryConditionType.DIRICHLET;
                                    break;
                                }
                            case Neumann:
                                {
                                    bct = BoundaryConditionType.NEUMANN;
                                    break;
                                }
                            case Robin_inwardNormalGradientCoefficient:
                            case Robin_sum:
                            case Robin_valueCoefficient:
                            default:
                                throw new RuntimeException("boundary condition type " + bCondn.getType().name() + " not supported");
                        }
                        for (CoordinateComponent coordComp : getSbmlGeometry().getListOfCoordinateComponents()) {
                            if (bCondn.getSpatialRef().equals(coordComp.getBoundaryMinimum().getSpatialId())) {
                                switch(coordComp.getType()) {
                                    case cartesianX:
                                        {
                                            sm.setBoundaryConditionTypeXm(bct);
                                        }
                                    case cartesianY:
                                        {
                                            sm.setBoundaryConditionTypeYm(bct);
                                        }
                                    case cartesianZ:
                                        {
                                            sm.setBoundaryConditionTypeZm(bct);
                                        }
                                }
                            }
                            if (bCondn.getSpatialRef().equals(coordComp.getBoundaryMaximum().getSpatialId())) {
                                switch(coordComp.getType()) {
                                    case cartesianX:
                                        {
                                            sm.setBoundaryConditionTypeXm(bct);
                                        }
                                    case cartesianY:
                                        {
                                            sm.setBoundaryConditionTypeYm(bct);
                                        }
                                    case cartesianZ:
                                        {
                                            sm.setBoundaryConditionTypeZm(bct);
                                        }
                                }
                            }
                        }
                    } else // sm != null
                    {
                        logger.sendMessage(VCLogger.Priority.MediumPriority, VCLogger.ErrorType.OverallWarning, "No structure " + s.getName() + " requested by species context " + paramSpContext.getName());
                    }
                }
            // end if (paramSpContext != null)
            }
        // end if (bCondn.isSetVar())
        }
        // end for (sbmlModel.numParams)
        vcBioModel.getSimulationContext(0).getGeometryContext().refreshStructureMappings();
        vcBioModel.getSimulationContext(0).refreshSpatialObjects();
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new SBMLImportException("Unable to create VC structureMappings from SBML compartment mappings : " + e.getMessage(), e);
    }
}
Also used : Origin(org.vcell.util.Origin) VCPixelClass(cbit.image.VCPixelClass) MembraneMapping(cbit.vcell.mapping.MembraneMapping) DataKind(org.sbml.jsbml.ext.spatial.DataKind) ArrayList(java.util.ArrayList) BoundaryConditionType(cbit.vcell.math.BoundaryConditionType) SpeciesContext(cbit.vcell.model.SpeciesContext) Feature(cbit.vcell.model.Feature) GeometryDefinition(org.sbml.jsbml.ext.spatial.GeometryDefinition) SubVolume(cbit.vcell.geometry.SubVolume) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) CompartmentSubVolume(cbit.vcell.geometry.CompartmentSubVolume) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) Vector(java.util.Vector) CoordinateComponent(org.sbml.jsbml.ext.spatial.CoordinateComponent) SimulationContext(cbit.vcell.mapping.SimulationContext) SpeciesContext(cbit.vcell.model.SpeciesContext) GeometryContext(cbit.vcell.mapping.GeometryContext) IssueContext(org.vcell.util.IssueContext) ReactionContext(cbit.vcell.mapping.ReactionContext) CompressionKind(org.sbml.jsbml.ext.spatial.CompressionKind) VolumeGeometricRegion(cbit.vcell.geometry.surface.VolumeGeometricRegion) PropertyVetoException(java.beans.PropertyVetoException) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) Coordinate(org.vcell.util.Coordinate) BoundaryCondition(org.sbml.jsbml.ext.spatial.BoundaryCondition) SbmlException(org.vcell.sbml.SbmlException) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) SurfaceClass(cbit.vcell.geometry.SurfaceClass) CSGeometry(org.sbml.jsbml.ext.spatial.CSGeometry) VCImage(cbit.image.VCImage) StructureMapping(cbit.vcell.mapping.StructureMapping) GeometryThumbnailImageFactoryAWT(cbit.vcell.geometry.GeometryThumbnailImageFactoryAWT) FeatureMapping(cbit.vcell.mapping.FeatureMapping) Structure(cbit.vcell.model.Structure) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem) ParameterType(org.sbml.jsbml.ext.spatial.ParameterType) BioEventParameterType(cbit.vcell.mapping.BioEvent.BioEventParameterType) SampledFieldGeometry(org.sbml.jsbml.ext.spatial.SampledFieldGeometry) Geometry(cbit.vcell.geometry.Geometry) SampledFieldGeometry(org.sbml.jsbml.ext.spatial.SampledFieldGeometry) AnalyticGeometry(org.sbml.jsbml.ext.spatial.AnalyticGeometry) ParametricGeometry(org.sbml.jsbml.ext.spatial.ParametricGeometry) CSGeometry(org.sbml.jsbml.ext.spatial.CSGeometry) StringTokenizer(java.util.StringTokenizer) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) InterpolationKind(org.sbml.jsbml.ext.spatial.InterpolationKind) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) Parameter(org.sbml.jsbml.Parameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) LocalParameter(org.sbml.jsbml.LocalParameter) KineticsProxyParameter(cbit.vcell.model.Kinetics.KineticsProxyParameter) UnresolvedParameter(cbit.vcell.model.Kinetics.UnresolvedParameter) CompartmentMapping(org.sbml.jsbml.ext.spatial.CompartmentMapping) Compartment(org.sbml.jsbml.Compartment) SpatialParameterPlugin(org.sbml.jsbml.ext.spatial.SpatialParameterPlugin) AnalyticGeometry(org.sbml.jsbml.ext.spatial.AnalyticGeometry) ExpressionException(cbit.vcell.parser.ExpressionException) GeometrySpec(cbit.vcell.geometry.GeometrySpec) DomainType(org.sbml.jsbml.ext.spatial.DomainType) SampledVolume(org.sbml.jsbml.ext.spatial.SampledVolume) ListOf(org.sbml.jsbml.ListOf) SpatialCompartmentPlugin(org.sbml.jsbml.ext.spatial.SpatialCompartmentPlugin) VCImageCompressed(cbit.image.VCImageCompressed) SurfaceGeometricRegion(cbit.vcell.geometry.surface.SurfaceGeometricRegion) VolumeGeometricRegion(cbit.vcell.geometry.surface.VolumeGeometricRegion) GeometricRegion(cbit.vcell.geometry.surface.GeometricRegion) AnalyticVolume(org.sbml.jsbml.ext.spatial.AnalyticVolume) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) ParametricGeometry(org.sbml.jsbml.ext.spatial.ParametricGeometry) SampledField(org.sbml.jsbml.ext.spatial.SampledField) Domain(org.sbml.jsbml.ext.spatial.Domain) GeometryClass(cbit.vcell.geometry.GeometryClass) GeometrySurfaceDescription(cbit.vcell.geometry.surface.GeometrySurfaceDescription) Extent(org.vcell.util.Extent) ISize(org.vcell.util.ISize) RegionInfo(cbit.vcell.geometry.RegionImage.RegionInfo) Membrane(cbit.vcell.model.Membrane) CSGObject(cbit.vcell.geometry.CSGObject) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) SurfaceGeometricRegion(cbit.vcell.geometry.surface.SurfaceGeometricRegion) VCImageUncompressed(cbit.image.VCImageUncompressed) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) XmlParseException(cbit.vcell.xml.XmlParseException) IOException(java.io.IOException) PropertyVetoException(java.beans.PropertyVetoException) DivideByZeroException(cbit.vcell.parser.DivideByZeroException) SBMLException(org.sbml.jsbml.SBMLException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) ExpressionException(cbit.vcell.parser.ExpressionException)

Example 4 with SbmlException

use of org.vcell.sbml.SbmlException in project vcell by virtualcell.

the class SBMLImporter method translateSBMLModel.

/**
 * translateSBMLModel:
 */
private void translateSBMLModel() {
    // Add Function Definitions (Lambda functions).
    addFunctionDefinitions();
    // Check for SBML features not supported in VCell; stop import process if present.
    try {
        checkForUnsupportedVCellFeaturesAndApplyDefaults();
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new SBMLImportException(e.getMessage(), e);
    }
    // Create Virtual Cell Model with species, compartment, etc. and read in the 'values' from the SBML model
    // Add compartmentTypes (not handled in VCell)
    addCompartmentTypes();
    // Add spciesTypes (not handled in VCell)
    addSpeciesTypes();
    // when sbml non-spatial model uses a vCell reserved symbols x,y,z as
    Map<String, String> vcToSbmlNameMap = new HashMap<>();
    // species or reaction name (ex: in the BMDB database), we rename it
    Map<String, String> sbmlToVcNameMap = new HashMap<>();
    // could be defined by assignment rules
    try {
        // we just read and place them in a hash
        parseAssignmentRules();
    } catch (SBMLImportException sie) {
        throw sie;
    } catch (Exception ee) {
        ee.printStackTrace(System.out);
        throw new SBMLImportException(ee.getMessage(), ee);
    }
    // Add features/compartments
    VCMetaData vcMetaData = vcBioModel.getVCMetaData();
    Map<String, Expression> deferredStructureExpression = new HashMap<>();
    addCompartments(vcMetaData, deferredStructureExpression);
    // Add species/speciesContexts
    addSpecies(vcMetaData, vcToSbmlNameMap, sbmlToVcNameMap);
    // Add Parameters
    try {
        addParameters(vcToSbmlNameMap, sbmlToVcNameMap);
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new SBMLImportException(e.getMessage(), e);
    }
    // If species variables were renamed from x,y,z, apply corrections to the hash
    try {
        readAssignmentRules(sbmlToVcNameMap);
    } catch (ExpressionException | PropertyVetoException e) {
        e.printStackTrace();
        throw new SBMLImportException(e.getMessage(), e);
    }
    // Set initial conditions on species
    // assignment rules must be present already because initConc set by an assignment rule
    // takes precedence over initConc value set on species
    setSpeciesInitialConditions(vcToSbmlNameMap);
    // Add InitialAssignments
    addInitialAssignments(deferredStructureExpression, sbmlToVcNameMap);
    // Add constraints (not handled in VCell)
    addConstraints();
    // Add Reactions
    addReactions(vcMetaData, vcToSbmlNameMap, sbmlToVcNameMap);
    // Check if we found and renamed successfully any reserved symbols used as species or reaction name
    for (Map.Entry<String, String> entry : sbmlToVcNameMap.entrySet()) {
        String sbmlName = entry.getKey();
        String vcName = entry.getValue();
        localIssueList.add(new Issue(vcBioModel, issueContext, IssueCategory.SBMLImport_ReservedSymbolUsed, "Reserved vCell symbol '" + sbmlName + "' found and replaced with '" + vcName + "' during import. Please check for correctness.", Issue.Severity.WARNING));
    }
    // for those vars can be read in).
    try {
        readRateRules(sbmlToVcNameMap);
        processParameters();
        processAssignmentRules();
        processRateRules();
    } catch (ExpressionException | SBMLException | XMLStreamException | PropertyVetoException e) {
        e.printStackTrace(System.out);
        throw new SBMLImportException(e.getMessage(), e);
    }
    // now that we have the parameters loaded, we can bind
    // TODO: use BMDB model Whitcomb to test comp size initialized with expression
    finalizeCompartments(deferredStructureExpression);
    // Sort VCell-model Structures in structure array according to reaction
    // adjacency and parentCompartment.
    Structure[] sortedStructures = StructureSorter.sortStructures(vcBioModel.getSimulationContext(0).getModel());
    try {
        vcBioModel.getSimulationContext(0).getModel().setStructures(sortedStructures);
    } catch (PropertyVetoException e1) {
        e1.printStackTrace(System.out);
        throw new SBMLImportException("Error while sorting compartments: " + e1.getMessage(), e1);
    }
    // Add Events
    addEvents(sbmlToVcNameMap);
    // (say, > 64), if so give warning.
    try {
        checkIdentifiersNameLength();
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new SBMLImportException(e.getMessage(), e);
    }
    // Add geometry, if sbml model is spatial
    if (bSpatial) {
        addGeometry();
    }
    // post processing
    finalizeAssignmentRules();
    finalizeRateRules();
    postProcessing();
}
Also used : SBMLException(org.sbml.jsbml.SBMLException) Issue(org.vcell.util.Issue) HashMap(java.util.HashMap) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) XmlParseException(cbit.vcell.xml.XmlParseException) IOException(java.io.IOException) PropertyVetoException(java.beans.PropertyVetoException) DivideByZeroException(cbit.vcell.parser.DivideByZeroException) SBMLException(org.sbml.jsbml.SBMLException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) ExpressionException(cbit.vcell.parser.ExpressionException) ExpressionException(cbit.vcell.parser.ExpressionException) PropertyVetoException(java.beans.PropertyVetoException) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) VCMetaData(cbit.vcell.biomodel.meta.VCMetaData) XMLStreamException(javax.xml.stream.XMLStreamException) Expression(cbit.vcell.parser.Expression) Structure(cbit.vcell.model.Structure) Map(java.util.Map) HashMap(java.util.HashMap)

Example 5 with SbmlException

use of org.vcell.sbml.SbmlException in project vcell by virtualcell.

the class SimulationServiceImpl method getSBML.

public String getSBML(String vcml, String applicationName) throws ThriftDataAccessException, TException {
    try {
        BioModel bioModel = XmlHelper.XMLToBioModel(new XMLSource(vcml));
        SimulationContext simContext = bioModel.getSimulationContext(applicationName);
        SBMLExporter exporter = new SBMLExporter(simContext, 3, 1, simContext.getGeometry().getDimension() > 0);
        VCellSBMLDoc sbmlDoc = exporter.convertToSBML();
        return sbmlDoc.xmlString;
    } catch (SBMLException | XmlParseException | SbmlException | XMLStreamException e) {
        e.printStackTrace();
        throw new ThriftDataAccessException("failed to generate SBML document: " + e.getMessage());
    }
}
Also used : SBMLException(org.sbml.jsbml.SBMLException) XMLStreamException(javax.xml.stream.XMLStreamException) BioModel(cbit.vcell.biomodel.BioModel) VCellSBMLDoc(org.vcell.sbml.vcell.SBMLExporter.VCellSBMLDoc) ThriftDataAccessException(org.vcell.vcellij.api.ThriftDataAccessException) SBMLExporter(org.vcell.sbml.vcell.SBMLExporter) XmlParseException(cbit.vcell.xml.XmlParseException) SbmlException(org.vcell.sbml.SbmlException) SimulationContext(cbit.vcell.mapping.SimulationContext) XMLSource(cbit.vcell.xml.XMLSource)

Aggregations

SbmlException (org.vcell.sbml.SbmlException)10 BioModel (cbit.vcell.biomodel.BioModel)8 XmlParseException (cbit.vcell.xml.XmlParseException)8 XMLStreamException (javax.xml.stream.XMLStreamException)8 SimulationContext (cbit.vcell.mapping.SimulationContext)7 IOException (java.io.IOException)6 SBMLException (org.sbml.jsbml.SBMLException)6 Expression (cbit.vcell.parser.Expression)5 ExpressionException (cbit.vcell.parser.ExpressionException)5 StructureMapping (cbit.vcell.mapping.StructureMapping)4 Model (cbit.vcell.model.Model)4 SpeciesContext (cbit.vcell.model.SpeciesContext)4 PropertyVetoException (java.beans.PropertyVetoException)4 Structure (cbit.vcell.model.Structure)3 SolverException (cbit.vcell.solver.SolverException)3 ODESolverResultSet (cbit.vcell.solver.ode.ODESolverResultSet)3 XMLSource (cbit.vcell.xml.XMLSource)3 File (java.io.File)3 PrintWriter (java.io.PrintWriter)3 SBMLImportException (org.vcell.sbml.vcell.SBMLImportException)3