Search in sources :

Example 36 with BioModel

use of cbit.vcell.biomodel.BioModel in project vcell by virtualcell.

the class BNGExecutorServiceMultipass method preprocessInput.

// parse the compartmental bngl file and produce the "trick"
// where each molecule has an extra Site with the compartments as possible States
// a reserved name will be used for this Site
// 
private String preprocessInput(String cBngInputString) throws ParseException, PropertyVetoException, ExpressionBindingException {
    // take the cBNGL file (as string), parse it to recover the rules (we'll need them later)
    // and create the bngl string with the extra, fake site for the compartments
    BioModel bioModel = new BioModel(null);
    bioModel.setName("BngBioModel");
    model = new Model("model");
    bioModel.setModel(model);
    model.createFeature();
    simContext = bioModel.addNewSimulationContext("BioNetGen app", SimulationContext.Application.NETWORK_DETERMINISTIC);
    List<SimulationContext> appList = new ArrayList<SimulationContext>();
    appList.add(simContext);
    // set convention for initial conditions in generated application for seed species (concentration or count)
    BngUnitSystem bngUnitSystem = new BngUnitSystem(BngUnitOrigin.DEFAULT);
    InputStream is = new ByteArrayInputStream(cBngInputString.getBytes());
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    ASTModel astModel = RbmUtils.importBnglFile(br);
    if (astModel.hasCompartments()) {
        Structure struct = model.getStructure(0);
        if (struct != null) {
            try {
                model.removeStructure(struct);
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }
        }
    }
    BnglObjectConstructionVisitor constructionVisitor = null;
    constructionVisitor = new BnglObjectConstructionVisitor(model, appList, bngUnitSystem, true);
    astModel.jjtAccept(constructionVisitor, model.getRbmModelContainer());
    int numCompartments = model.getStructures().length;
    if (numCompartments == 0) {
        throw new RuntimeException("No structure present in the bngl file.");
    } else if (numCompartments == 1) {
        // for single compartment we don't need the 'trick'
        compartmentMode = CompartmentMode.hide;
    } else {
        compartmentMode = CompartmentMode.asSite;
    }
    // extract all polymer observables for special treatment at the end
    for (RbmObservable oo : model.getRbmModelContainer().getObservableList()) {
        if (oo.getSequence() == RbmObservable.Sequence.PolymerLengthEqual) {
            polymerEqualObservables.add(oo);
        } else if (oo.getSequence() == RbmObservable.Sequence.PolymerLengthGreater) {
            polymerGreaterObservables.add(oo);
        }
    }
    for (RbmObservable oo : polymerEqualObservables) {
        model.getRbmModelContainer().removeObservable(oo);
    }
    for (RbmObservable oo : polymerGreaterObservables) {
        model.getRbmModelContainer().removeObservable(oo);
    }
    // replace all reversible rules with 2 direct rules
    List<ReactionRule> newRRList = new ArrayList<>();
    for (ReactionRule rr : model.getRbmModelContainer().getReactionRuleList()) {
        if (rr.isReversible()) {
            ReactionRule rr1 = ReactionRule.deriveDirectRule(rr);
            newRRList.add(rr1);
            ReactionRule rr2 = ReactionRule.deriveInverseRule(rr);
            newRRList.add(rr2);
        } else {
            newRRList.add(rr);
        }
        model.getRbmModelContainer().removeReactionRule(rr);
    }
    // model.getRbmModelContainer().getReactionRuleList().clear();
    model.getRbmModelContainer().setReactionRules(newRRList);
    StringWriter bnglStringWriter = new StringWriter();
    PrintWriter writer = new PrintWriter(bnglStringWriter);
    writer.println(RbmNetworkGenerator.BEGIN_MODEL);
    writer.println();
    // RbmNetworkGenerator.writeCompartments(writer, model, null);
    RbmNetworkGenerator.writeParameters(writer, model.getRbmModelContainer(), false);
    RbmNetworkGenerator.writeMolecularTypes(writer, model, compartmentMode);
    RbmNetworkGenerator.writeSpeciesSortedAlphabetically(writer, model, simContext, compartmentMode);
    RbmNetworkGenerator.writeObservables(writer, model.getRbmModelContainer(), compartmentMode);
    // RbmNetworkGenerator.writeFunctions(writer, rbmModelContainer, ignoreFunctions);
    RbmNetworkGenerator.writeReactions(writer, model.getRbmModelContainer(), null, false, compartmentMode);
    writer.println(RbmNetworkGenerator.END_MODEL);
    writer.println();
    // we parse the real numbers from the bngl file provided by the caller, the nc in the simContext has the default ones
    NetworkConstraints realNC = extractNetworkConstraints(cBngInputString);
    simContext.getNetworkConstraints().setMaxMoleculesPerSpecies(realNC.getMaxMoleculesPerSpecies());
    simContext.getNetworkConstraints().setMaxIteration(realNC.getMaxIteration());
    RbmNetworkGenerator.generateNetworkEx(1, simContext.getNetworkConstraints().getMaxMoleculesPerSpecies(), writer, model.getRbmModelContainer(), simContext, NetworkGenerationRequirements.AllowTruncatedStandardTimeout);
    String sInputString = bnglStringWriter.toString();
    return sInputString;
}
Also used : InputStreamReader(java.io.InputStreamReader) ReactionRule(cbit.vcell.model.ReactionRule) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) RbmObservable(cbit.vcell.model.RbmObservable) ArrayList(java.util.ArrayList) SimulationContext(cbit.vcell.mapping.SimulationContext) PropertyVetoException(java.beans.PropertyVetoException) BngUnitSystem(org.vcell.model.bngl.BngUnitSystem) BnglObjectConstructionVisitor(org.vcell.model.rbm.RbmUtils.BnglObjectConstructionVisitor) StringWriter(java.io.StringWriter) ByteArrayInputStream(java.io.ByteArrayInputStream) BioModel(cbit.vcell.biomodel.BioModel) ASTModel(org.vcell.model.bngl.ASTModel) BioModel(cbit.vcell.biomodel.BioModel) Model(cbit.vcell.model.Model) BufferedReader(java.io.BufferedReader) Structure(cbit.vcell.model.Structure) ASTModel(org.vcell.model.bngl.ASTModel) PrintWriter(java.io.PrintWriter) NetworkConstraints(org.vcell.model.rbm.NetworkConstraints)

Example 37 with BioModel

use of cbit.vcell.biomodel.BioModel in project vcell by virtualcell.

the class XmlHelper method applyOverridesForSBML.

/**
 * applyOverrides: private method to apply overrides from the simulation in 'simJob' to simContext, if any.
 * 				Start off by cloning biomodel, since all the references are required in cloned simContext and is
 * 				best retained by cloning biomodel.
 * @param bm - biomodel to be cloned
 * @param sc - simulationContext to be cloned and overridden using math overrides in simulation
 * @param simJob - simulationJob from where simulation with overrides is obtained.
 * @return
 */
public static SimulationContext applyOverridesForSBML(BioModel bm, SimulationContext sc, SimulationJob simJob) {
    SimulationContext overriddenSimContext = sc;
    if (simJob != null) {
        Simulation sim = simJob.getSimulation();
        // need to clone Biomodel, simContext, etc. only if simulation has override(s)
        try {
            if (sim != null && sim.getMathOverrides().hasOverrides()) {
                // BioModel clonedBM = (BioModel)BeanUtils.cloneSerializable(bm);
                BioModel clonedBM = XMLToBioModel(new XMLSource(bioModelToXML(bm)));
                clonedBM.refreshDependencies();
                // get the simContext in cloned Biomodel that corresponds to 'sc'
                SimulationContext[] simContexts = clonedBM.getSimulationContexts();
                for (int i = 0; i < simContexts.length; i++) {
                    if (simContexts[i].getName().equals(sc.getName())) {
                        overriddenSimContext = simContexts[i];
                        break;
                    }
                }
                // 
                overriddenSimContext.getModel().refreshDependencies();
                overriddenSimContext.refreshDependencies();
                MathMapping mathMapping = overriddenSimContext.createNewMathMapping();
                MathSymbolMapping msm = mathMapping.getMathSymbolMapping();
                MathOverrides mathOverrides = sim.getMathOverrides();
                String[] moConstNames = mathOverrides.getOverridenConstantNames();
                for (int i = 0; i < moConstNames.length; i++) {
                    cbit.vcell.math.Constant overriddenConstant = mathOverrides.getConstant(moConstNames[i]);
                    // Expression overriddenExpr = mathOverrides.getActualExpression(moConstNames[i], 0);
                    Expression overriddenExpr = mathOverrides.getActualExpression(moConstNames[i], simJob.getJobIndex());
                    // The above constant (from mathoverride) is not the same instance as the one in the MathSymbolMapping hash.
                    // Hence retreive the correct instance from mathSymbolMapping (mathMapping -> mathDescription) and use it to
                    // retrieve its value (symbolTableEntry) from hash.
                    cbit.vcell.math.Variable overriddenVar = msm.findVariableByName(overriddenConstant.getName());
                    cbit.vcell.parser.SymbolTableEntry[] stes = msm.getBiologicalSymbol(overriddenVar);
                    if (stes == null) {
                        throw new NullPointerException("No matching biological symbol for : " + overriddenConstant.getName());
                    }
                    if (stes.length > 1) {
                        throw new RuntimeException("Cannot have more than one mapping entry for constant : " + overriddenConstant.getName());
                    }
                    if (stes[0] instanceof Parameter) {
                        Parameter param = (Parameter) stes[0];
                        if (param.isExpressionEditable()) {
                            if (param instanceof Kinetics.KineticsParameter) {
                                // Kinetics param has to be set separately for the integrity of the kinetics object
                                Kinetics.KineticsParameter kinParam = (Kinetics.KineticsParameter) param;
                                ReactionStep[] rs = overriddenSimContext.getModel().getReactionSteps();
                                for (int j = 0; j < rs.length; j++) {
                                    if (rs[j].getNameScope().getName().equals(kinParam.getNameScope().getName())) {
                                        rs[j].getKinetics().setParameterValue(kinParam, overriddenExpr);
                                    }
                                }
                            } else if (param instanceof cbit.vcell.model.ExpressionContainer) {
                                // If it is any other editable param, set its expression with the
                                ((cbit.vcell.model.ExpressionContainer) param).setExpression(overriddenExpr);
                            }
                        }
                    }
                // end - if (stes[0] is Parameter)
                }
            // end  - for moConstNames
            }
        // end if (sim has MathOverrides)
        } catch (Exception e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Could not apply overrides from simulation to application parameters : " + e.getMessage());
        }
    }
    // end if (simJob != null)
    return overriddenSimContext;
}
Also used : SimulationContext(cbit.vcell.mapping.SimulationContext) MathSymbolMapping(cbit.vcell.mapping.MathSymbolMapping) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) SBMLException(org.sbml.jsbml.SBMLException) IOException(java.io.IOException) ExpressionException(cbit.vcell.parser.ExpressionException) MathOverrides(cbit.vcell.solver.MathOverrides) Simulation(cbit.vcell.solver.Simulation) Expression(cbit.vcell.parser.Expression) BioModel(cbit.vcell.biomodel.BioModel) ReactionStep(cbit.vcell.model.ReactionStep) MathMapping(cbit.vcell.mapping.MathMapping) Parameter(cbit.vcell.model.Parameter) Kinetics(cbit.vcell.model.Kinetics)

Example 38 with BioModel

use of cbit.vcell.biomodel.BioModel in project vcell by virtualcell.

the class XmlHelper method sedmlToBioModel.

public static VCDocument sedmlToBioModel(VCLogger transLogger, ExternalDocInfo externalDocInfo, SedML sedml, AbstractTask selectedTask) throws Exception {
    if (sedml.getModels().isEmpty()) {
        return null;
    }
    VCDocument doc = null;
    try {
        // extract the path only from the sedml file
        String fullPath = FileUtils.getFullPath(externalDocInfo.getFile().getAbsolutePath());
        // Namespace namespace = sedml.getNamespace();
        // iterate through all the elements and show them at the console
        List<org.jlibsedml.Model> mmm = sedml.getModels();
        for (Model mm : mmm) {
            System.out.println(mm.toString());
        }
        List<org.jlibsedml.Simulation> sss = sedml.getSimulations();
        for (org.jlibsedml.Simulation ss : sss) {
            System.out.println(ss.toString());
        }
        List<AbstractTask> ttt = sedml.getTasks();
        for (AbstractTask tt : ttt) {
            System.out.println(tt.toString());
        }
        List<DataGenerator> ddd = sedml.getDataGenerators();
        for (DataGenerator dd : ddd) {
            System.out.println(dd.toString());
        }
        List<Output> ooo = sedml.getOutputs();
        for (Output oo : ooo) {
            System.out.println(oo.toString());
        }
        KisaoTerm sedmlKisao = null;
        // this will become the vCell simulation
        org.jlibsedml.Simulation sedmlSimulation = null;
        // the "original" model referred to by the task
        org.jlibsedml.Model sedmlOriginalModel = null;
        String sedmlOriginalModelName = null;
        if (selectedTask == null) {
            // no task, just pick the Model and find its sbml file
            sedmlOriginalModelName = SEDMLUtil.getName(mmm.get(0));
        } else {
            if (selectedTask instanceof Task) {
                sedmlOriginalModel = sedml.getModelWithId(selectedTask.getModelReference());
                sedmlSimulation = sedml.getSimulation(selectedTask.getSimulationReference());
            } else if (selectedTask instanceof RepeatedTask) {
                RepeatedTask rt = (RepeatedTask) selectedTask;
                assert (rt.getSubTasks().size() == 1);
                // first (and only) subtask
                SubTask st = rt.getSubTasks().entrySet().iterator().next().getValue();
                String taskId = st.getTaskId();
                AbstractTask t = sedml.getTaskWithId(taskId);
                // get model and simulation from subtask
                sedmlOriginalModel = sedml.getModelWithId(t.getModelReference());
                sedmlSimulation = sedml.getSimulation(t.getSimulationReference());
            } else {
                throw new RuntimeException("Unexpected task " + selectedTask);
            }
            sedmlOriginalModelName = sedmlOriginalModel.getId();
            sedmlKisao = KisaoOntology.getInstance().getTermById(sedmlSimulation.getAlgorithm().getKisaoID());
        }
        // UniformTimeCourse [initialTime=0.0, numberOfPoints=1000, outputEndTime=1.0, outputStartTime=0.0,
        // Algorithm [kisaoID=KISAO:0000019], getId()=SimSlow]
        // identify the vCell solvers that would match best the sedml solver kisao id
        List<SolverDescription> solverDescriptions = new ArrayList<>();
        for (SolverDescription sd : SolverDescription.values()) {
            KisaoTerm solverKisaoTerm = KisaoOntology.getInstance().getTermById(sd.getKisao());
            if (solverKisaoTerm == null) {
                break;
            }
            boolean isExactlySame = solverKisaoTerm.equals(sedmlKisao);
            if (isExactlySame && !solverKisaoTerm.isObsolete()) {
                // we make a list with all the solvers that match the kisao
                solverDescriptions.add(sd);
            }
        }
        // from the list of vcell solvers that match the sedml kisao we select the ones that have a matching time step
        SolverDescription solverDescription = null;
        for (SolverDescription sd : solverDescriptions) {
            if (true) {
                solverDescription = sd;
                break;
            }
        }
        // find out everything else we need about the application we're going to use,
        // some of the info will be needed when we parse the sbml file
        boolean bSpatial = false;
        Application appType = Application.NETWORK_DETERMINISTIC;
        Set<SolverDescription.SolverFeature> sfList = solverDescription.getSupportedFeatures();
        for (SolverDescription.SolverFeature sf : sfList) {
            switch(sf) {
                case Feature_Rulebased:
                    appType = Application.RULE_BASED_STOCHASTIC;
                    break;
                case Feature_Stochastic:
                    appType = Application.NETWORK_STOCHASTIC;
                    break;
                case Feature_Deterministic:
                    appType = Application.NETWORK_DETERMINISTIC;
                    break;
                case Feature_Spatial:
                    bSpatial = true;
                    break;
                default:
                    break;
            }
        }
        // -------------------------------------------------------------------------------------------
        // extract bioModel name from sedx (or sedml) file
        String bioModelName = FileUtils.getBaseName(externalDocInfo.getFile().getAbsolutePath());
        // if we have repeated task, we ignore them, we just use the normal resolvers for archive and changes
        // once the application and simulation are built, we iterate through the repeated tasks and
        // add math overrides to the simulation for each repeated task
        ArchiveComponents ac = null;
        if (externalDocInfo.getFile().getPath().toLowerCase().endsWith("sedx") || externalDocInfo.getFile().getPath().toLowerCase().endsWith("omex")) {
            ac = Libsedml.readSEDMLArchive(new FileInputStream(externalDocInfo.getFile().getPath()));
        }
        ModelResolver resolver = new ModelResolver(sedml);
        if (ac != null) {
            resolver.add(new ArchiveModelResolver(ac));
        }
        resolver.add(new FileModelResolver());
        resolver.add(new RelativeFileModelResolver(fullPath));
        String newMdl = resolver.getModelString(sedmlOriginalModel);
        // sbmlSource with all the changes applied
        XMLSource sbmlSource = new XMLSource(newMdl);
        doc = XmlHelper.importSBML(transLogger, sbmlSource, bSpatial);
        BioModel bioModel = (BioModel) doc;
        bioModel.setName(bioModelName);
        // we already have an application loaded from the sbml file, with initial conditions and stuff
        // which may be not be suitable because the sedml kisao may need a different app type
        // so we do a "copy as" to the right type and then delete the original we loaded from the sbml file
        // the new application we're making from the old one
        SimulationContext newSimulationContext = null;
        if (bioModel.getSimulationContexts().length == 1) {
            SimulationContext oldSimulationContext = bioModel.getSimulationContext(0);
            newSimulationContext = SimulationContext.copySimulationContext(oldSimulationContext, sedmlOriginalModelName, bSpatial, appType);
            bioModel.removeSimulationContext(oldSimulationContext);
            bioModel.addSimulationContext(newSimulationContext);
        } else {
            // length == 0
            newSimulationContext = bioModel.addNewSimulationContext(sedmlOriginalModelName, appType);
        }
        // making the new vCell simulation based on the sedml simulation
        newSimulationContext.refreshDependencies();
        MathMappingCallback callback = new MathMappingCallbackTaskAdapter(null);
        newSimulationContext.refreshMathDescription(callback, NetworkGenerationRequirements.ComputeFullStandardTimeout);
        Simulation newSimulation = new Simulation(newSimulationContext.getMathDescription());
        newSimulation.setName(SEDMLUtil.getName(sedmlSimulation));
        // TODO: make sure that everything has proper names
        // we check the repeated tasks, if any, and add to the list of math overrides
        // if(selectedTask instanceof RepeatedTask) {
        // for(Change change : ((RepeatedTask) selectedTask).getChanges()) {
        // if(!(change instanceof SetValue)) {
        // throw new RuntimeException("Only 'SetValue' changes are supported for repeated tasks.");
        // }
        // SetValue setValue = (SetValue)change;
        // // TODO: extract target from XPath
        // // ......
        // //
        // String target = "s0";	// for now we just use a hardcoded thing
        // ConstantArraySpec cas;
        // Range range = ((RepeatedTask) selectedTask).getRange(setValue.getRangeReference());
        // if(range instanceof UniformRange) {
        // cas = ConstantArraySpec.createIntervalSpec(target, ((UniformRange) range).getStart(), ((UniformRange) range).getEnd(),
        // range.getNumElements(), ((UniformRange) range).getType() == UniformRange.UniformType.LOG ? true : false);
        // } else if(range instanceof VectorRange) {
        // //    				List<String> constants = new ArrayList<> ();
        // //    				for(int i=0; i<range.getNumElements(); i++) {
        // //    					constants.add(new Constant(i+"", new Expression(range.getElementAt(i))));
        // //    				}
        // //    				cas = ConstantArraySpec.createListSpec(target, constants);
        // 
        // } else {
        // throw new RuntimeException("Only 'Uniform Range' and 'Vector Range' are supported at this time.");
        // }
        // 
        // }
        // }
        // we identify the type of sedml simulation (uniform time course, etc)
        // and set the vCell simulation parameters accordingly
        SolverTaskDescription simTaskDesc = newSimulation.getSolverTaskDescription();
        TimeBounds timeBounds = new TimeBounds();
        TimeStep timeStep = new TimeStep();
        double outputTimeStep = 0.1;
        if (sedmlSimulation instanceof UniformTimeCourse) {
            // we translate initial time to zero, we provide output for the duration of the simulation
            // because we can't select just an interval the way the SEDML simulation can
            double initialTime = ((UniformTimeCourse) sedmlSimulation).getInitialTime();
            double outputStartTime = ((UniformTimeCourse) sedmlSimulation).getOutputStartTime();
            double outputEndTime = ((UniformTimeCourse) sedmlSimulation).getOutputEndTime();
            double outputNumberOfPoints = ((UniformTimeCourse) sedmlSimulation).getNumberOfPoints();
            outputTimeStep = (outputEndTime - outputStartTime) / outputNumberOfPoints;
            timeBounds = new TimeBounds(0, outputEndTime - initialTime);
        } else if (sedmlSimulation instanceof OneStep) {
        // for anything other than UniformTimeCourse we just ignore
        } else if (sedmlSimulation instanceof SteadyState) {
        } else {
        }
        OutputTimeSpec outputTimeSpec = new UniformOutputTimeSpec(outputTimeStep);
        simTaskDesc.setTimeBounds(timeBounds);
        simTaskDesc.setTimeStep(timeStep);
        simTaskDesc.setOutputTimeSpec(outputTimeSpec);
        newSimulation.setSolverTaskDescription(simTaskDesc);
        bioModel.addSimulation(newSimulation);
        newSimulation.refreshDependencies();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Unable to initialize bioModel for the given selection.");
    }
    return doc;
}
Also used : Task(org.jlibsedml.Task) RepeatedTask(org.jlibsedml.RepeatedTask) SimulationTask(cbit.vcell.messaging.server.SimulationTask) AbstractTask(org.jlibsedml.AbstractTask) SubTask(org.jlibsedml.SubTask) ArrayList(java.util.ArrayList) ArchiveModelResolver(org.jlibsedml.execution.ArchiveModelResolver) FileModelResolver(org.jlibsedml.execution.FileModelResolver) RelativeFileModelResolver(org.vcell.sedml.RelativeFileModelResolver) ModelResolver(org.jlibsedml.execution.ModelResolver) SteadyState(org.jlibsedml.SteadyState) OutputTimeSpec(cbit.vcell.solver.OutputTimeSpec) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) SolverTaskDescription(cbit.vcell.solver.SolverTaskDescription) SubTask(org.jlibsedml.SubTask) VCDocument(org.vcell.util.document.VCDocument) MathMappingCallback(cbit.vcell.mapping.SimulationContext.MathMappingCallback) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) FileInputStream(java.io.FileInputStream) KisaoTerm(org.jlibsedml.modelsupport.KisaoTerm) ArchiveModelResolver(org.jlibsedml.execution.ArchiveModelResolver) DataGenerator(org.jlibsedml.DataGenerator) UniformTimeCourse(org.jlibsedml.UniformTimeCourse) Application(cbit.vcell.mapping.SimulationContext.Application) AbstractTask(org.jlibsedml.AbstractTask) SolverDescription(cbit.vcell.solver.SolverDescription) RelativeFileModelResolver(org.vcell.sedml.RelativeFileModelResolver) OneStep(org.jlibsedml.OneStep) TimeBounds(cbit.vcell.solver.TimeBounds) TimeStep(cbit.vcell.solver.TimeStep) ArchiveComponents(org.jlibsedml.ArchiveComponents) RepeatedTask(org.jlibsedml.RepeatedTask) Output(org.jlibsedml.Output) MathMappingCallbackTaskAdapter(cbit.vcell.mapping.MathMappingCallbackTaskAdapter) FileModelResolver(org.jlibsedml.execution.FileModelResolver) RelativeFileModelResolver(org.vcell.sedml.RelativeFileModelResolver) SimulationContext(cbit.vcell.mapping.SimulationContext) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) SBMLException(org.sbml.jsbml.SBMLException) IOException(java.io.IOException) ExpressionException(cbit.vcell.parser.ExpressionException) Simulation(cbit.vcell.solver.Simulation) Model(org.jlibsedml.Model) BioModel(cbit.vcell.biomodel.BioModel) MathModel(cbit.vcell.mathmodel.MathModel) BioModel(cbit.vcell.biomodel.BioModel) Model(org.jlibsedml.Model)

Example 39 with BioModel

use of cbit.vcell.biomodel.BioModel 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 {
            // 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());
            SimulationContext clonedSimContext = applyOverridesForSBML(modifiedBiomodel, simContextFromModifiedBioModel, simJob);
            // extract sim (in simJob) from modified Biomodel, if not null
            SimulationJob modifiedSimJob = null;
            if (simJob != null) {
                Simulation simFromModifiedBiomodel = clonedSimContext.getSimulation(simJob.getSimulation().getName());
                modifiedSimJob = new SimulationJob(simFromModifiedBiomodel, simJob.getJobIndex(), null);
            }
            SBMLExporter sbmlExporter = new SBMLExporter(modifiedBiomodel, level, version, isSpatial);
            sbmlExporter.setSelectedSimContext(simContextFromModifiedBioModel);
            sbmlExporter.setSelectedSimulationJob(modifiedSimJob);
            return sbmlExporter.getSBMLFile();
        } catch (ExpressionException | 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) ExpressionException(cbit.vcell.parser.ExpressionException) Simulation(cbit.vcell.solver.Simulation) XMLStreamException(javax.xml.stream.XMLStreamException) BioModel(cbit.vcell.biomodel.BioModel) SbmlException(org.vcell.sbml.SbmlException) SimulationJob(cbit.vcell.solver.SimulationJob) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem)

Example 40 with BioModel

use of cbit.vcell.biomodel.BioModel in project vcell by virtualcell.

the class ChooseFile method run.

/**
 * Insert the method's description here.
 * Creation date: (5/31/2004 6:04:14 PM)
 * @param hashTable java.util.Hashtable
 * @param clientWorker cbit.vcell.desktop.controls.ClientWorker
 */
public void run(Hashtable<String, Object> hashTable) throws java.lang.Exception {
    VCDocument documentToExport = fetch(hashTable, DocumentToExport.EXPORT_DOCUMENT, VCDocument.class, true);
    File exportFile = null;
    if (documentToExport instanceof BioModel) {
        exportFile = showBioModelXMLFileChooser(hashTable);
    } else if (documentToExport instanceof MathModel) {
        exportFile = showMathModelXMLFileChooser(hashTable);
    } else if (documentToExport instanceof Geometry) {
        exportFile = showGeometryModelXMLFileChooser(hashTable);
    } else {
        throw new Exception("Unsupported document type for XML export: " + documentToExport.getClass());
    }
    // check to see if we've changed extension from what user entered
    if (extensionUserProvided != null && !extensionUserProvided.isEmpty()) {
        String fp = exportFile.getAbsolutePath();
        String currentExt = FilenameUtils.getExtension(fp);
        if (!extensionUserProvided.equals(currentExt)) {
            hashTable.put(RENAME_KEY, fp);
        }
    }
    hashTable.put(EXPORT_FILE, exportFile);
}
Also used : Geometry(cbit.vcell.geometry.Geometry) MathModel(cbit.vcell.mathmodel.MathModel) VCDocument(org.vcell.util.document.VCDocument) BioModel(cbit.vcell.biomodel.BioModel) File(java.io.File) UserCancelException(org.vcell.util.UserCancelException)

Aggregations

BioModel (cbit.vcell.biomodel.BioModel)158 SimulationContext (cbit.vcell.mapping.SimulationContext)72 Simulation (cbit.vcell.solver.Simulation)53 XMLSource (cbit.vcell.xml.XMLSource)37 KeyValue (org.vcell.util.document.KeyValue)36 MathModel (cbit.vcell.mathmodel.MathModel)33 DataAccessException (org.vcell.util.DataAccessException)29 XmlParseException (cbit.vcell.xml.XmlParseException)28 File (java.io.File)28 Model (cbit.vcell.model.Model)27 BioModelInfo (org.vcell.util.document.BioModelInfo)25 MathDescription (cbit.vcell.math.MathDescription)24 IOException (java.io.IOException)24 BigString (org.vcell.util.BigString)22 Geometry (cbit.vcell.geometry.Geometry)21 UserCancelException (org.vcell.util.UserCancelException)20 User (org.vcell.util.document.User)20 ObjectNotFoundException (org.vcell.util.ObjectNotFoundException)19 SpeciesContext (cbit.vcell.model.SpeciesContext)17 VCDocument (org.vcell.util.document.VCDocument)16