Search in sources :

Example 6 with TimeStep

use of cbit.vcell.solver.TimeStep in project vcell by virtualcell.

the class TimeStepPanel method setNewTimeStep.

public void setNewTimeStep() {
    try {
        TimeStep oldTimeStep = solverTaskDescription.getTimeStep();
        double defaultTimeStep = !getDefaultTimeStepTextField().isEnabled() ? oldTimeStep.getDefaultTimeStep() : new Double(getDefaultTimeStepTextField().getText()).doubleValue();
        double minTimeStep = !getMinimumTimeStepTextField().isEnabled() ? oldTimeStep.getMinimumTimeStep() : new Double(getMinimumTimeStepTextField().getText()).doubleValue();
        double maxTimeStep = !getMaximumTimeStepTextField().isEnabled() ? oldTimeStep.getMaximumTimeStep() : new Double(getMaximumTimeStepTextField().getText()).doubleValue();
        TimeStep newTimeStep = new TimeStep(minTimeStep, defaultTimeStep, maxTimeStep);
        solverTaskDescription.setTimeStep(newTimeStep);
    } catch (java.lang.Throwable ivjExc) {
        // user code begin {3}
        // user code end
        handleException(ivjExc);
    }
}
Also used : TimeStep(cbit.vcell.solver.TimeStep)

Example 7 with TimeStep

use of cbit.vcell.solver.TimeStep in project vcell by virtualcell.

the class TimeStepPanel method refresh.

private void refresh() {
    if (solverTaskDescription == null) {
        return;
    }
    SolverDescription solverDescription = solverTaskDescription.getSolverDescription();
    if (solverDescription.compareEqual(SolverDescription.StochGibson)) {
        // stochastic time
        enableDefaultTimeStep(false);
        enableMinTimeStep(false);
        enableMaxTimeStep(false);
    } else if (solverDescription.compareEqual(SolverDescription.NFSim)) {
        ivjTimeStepLabel.setEnabled(false);
        enableDefaultTimeStep(false);
        enableMinTimeStep(false);
        enableMaxTimeStep(false);
    } else {
        setEnabled(true);
        TimeStep ts = solverTaskDescription.getTimeStep();
        getDefaultTimeStepTextField().setText(ts.getDefaultTimeStep() + "");
        getMinimumTimeStepTextField().setText(ts.getMinimumTimeStep() + "");
        getMaximumTimeStepTextField().setText(ts.getMaximumTimeStep() + "");
        // fixed time step solvers and non spatial stochastic solvers only show default time step.
        if (!solverDescription.hasVariableTimestep() || solverDescription.isNonSpatialStochasticSolver()) {
            enableDefaultTimeStep(true);
            enableMinTimeStep(false);
            enableMaxTimeStep(false);
        } else {
            // variable time step solvers shows min and max, but sundials solvers don't show min
            enableDefaultTimeStep(false);
            if (solverDescription.hasSundialsTimeStepping()) {
                enableMinTimeStep(false);
            }
            enableMaxTimeStep(true);
        }
    }
}
Also used : TimeStep(cbit.vcell.solver.TimeStep) SolverDescription(cbit.vcell.solver.SolverDescription)

Example 8 with TimeStep

use of cbit.vcell.solver.TimeStep 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 9 with TimeStep

use of cbit.vcell.solver.TimeStep in project vcell by virtualcell.

the class OptXmlWriter method getModelXML.

public static Element getModelXML(PdeObjectiveFunction pdeObjectiveFunction, String[] parameterNames) {
    Element modelElement = new Element(OptXmlTags.Model_Tag);
    try {
        SpatialReferenceData refData = pdeObjectiveFunction.getReferenceData();
        double refDataEndTime = refData.getDataByRow(refData.getNumDataRows() - 1)[0];
        // 
        // post the problem either as an IDA or CVODE model
        // 
        org.vcell.util.document.SimulationVersion simVersion = new org.vcell.util.document.SimulationVersion(new KeyValue("12345"), "name", new org.vcell.util.document.User("user", new KeyValue("123")), new org.vcell.util.document.GroupAccessNone(), // versionBranchPointRef
        null, // branchID
        new java.math.BigDecimal(1.0), new java.util.Date(), org.vcell.util.document.VersionFlag.Archived, "", null);
        Simulation simulation = new Simulation(simVersion, pdeObjectiveFunction.getMathDescription());
        simulation.getMeshSpecification().setSamplingSize(refData.getDataISize());
        double[] times = refData.getDataByColumn(0);
        double minDt = Double.POSITIVE_INFINITY;
        for (int i = 1; i < times.length; i++) {
            minDt = Math.min(minDt, times[i] - times[i - 1]);
        }
        simulation.getSolverTaskDescription().setTimeBounds(new cbit.vcell.solver.TimeBounds(0.0, refDataEndTime));
        simulation.getSolverTaskDescription().setSolverDescription(SolverDescription.FiniteVolume);
        simulation.getSolverTaskDescription().setTimeStep(new TimeStep(minDt / 5, minDt / 5, minDt / 5));
        // clone and resample geometry
        Geometry resampledGeometry = null;
        try {
            resampledGeometry = (Geometry) BeanUtils.cloneSerializable(simulation.getMathDescription().getGeometry());
            GeometrySurfaceDescription geoSurfaceDesc = resampledGeometry.getGeometrySurfaceDescription();
            ISize newSize = simulation.getMeshSpecification().getSamplingSize();
            geoSurfaceDesc.setVolumeSampleSize(newSize);
            geoSurfaceDesc.updateAll();
        } catch (Exception e) {
            e.printStackTrace();
            throw new SolverException(e.getMessage());
        }
        SimulationTask simTask = new SimulationTask(new SimulationJob(simulation, 0, pdeObjectiveFunction.getFieldDataIDSs()), 0);
        StringWriter simulationInputStringWriter = new StringWriter();
        FiniteVolumeFileWriter fvFileWriter = new FiniteVolumeFileWriter(new PrintWriter(simulationInputStringWriter, true), simTask, resampledGeometry, pdeObjectiveFunction.getWorkingDirectory());
        fvFileWriter.write(parameterNames);
        simulationInputStringWriter.close();
        modelElement.setAttribute(OptXmlTags.ModelType_Attr, OptXmlTags.ModelType_Attr_FVSOLVER);
        CDATA simulationInputText = new CDATA(simulationInputStringWriter.getBuffer().toString());
        modelElement.addContent(simulationInputText);
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new OptimizationException("failed to create fv input file: " + e.getMessage());
    }
    return modelElement;
}
Also used : OptimizationException(cbit.vcell.opt.OptimizationException) KeyValue(org.vcell.util.document.KeyValue) SimulationTask(cbit.vcell.messaging.server.SimulationTask) GeometrySurfaceDescription(cbit.vcell.geometry.surface.GeometrySurfaceDescription) ISize(org.vcell.util.ISize) Element(org.jdom.Element) FiniteVolumeFileWriter(cbit.vcell.solvers.FiniteVolumeFileWriter) TimeStep(cbit.vcell.solver.TimeStep) StringWriter(java.io.StringWriter) SpatialReferenceData(cbit.vcell.opt.SpatialReferenceData) SimulationJob(cbit.vcell.solver.SimulationJob) PrintWriter(java.io.PrintWriter) Constraint(cbit.vcell.opt.Constraint) OptimizationException(cbit.vcell.opt.OptimizationException) XMLStreamException(javax.xml.stream.XMLStreamException) SBMLException(org.sbml.jsbml.SBMLException) XmlParseException(cbit.vcell.xml.XmlParseException) SolverException(cbit.vcell.solver.SolverException) IOException(java.io.IOException) ExpressionException(cbit.vcell.parser.ExpressionException) Geometry(cbit.vcell.geometry.Geometry) Simulation(cbit.vcell.solver.Simulation) SolverException(cbit.vcell.solver.SolverException) CDATA(org.jdom.CDATA)

Example 10 with TimeStep

use of cbit.vcell.solver.TimeStep in project vcell by virtualcell.

the class SbmlVcmlConverter method main.

/**
 * @param args -import or -export
 */
public static void main(String[] args) {
    Logging.init();
    ResourceUtil.setNativeLibraryDirectory();
    if (args.length < 2 || args.length > 3) {
        System.out.println("Usage:\n\t -export path_of_input_file\n\tOR\n\t -import path_of_input_file [-simulate]");
        System.exit(1);
    }
    if (args.length > 2 && args[0].equals("-export")) {
        System.out.println("Export cannot have arguments other than input file.");
        System.out.println("Usage:\n\t -export path_of_input_file\n\tOR\n\t-import path_of_input_file [-simulate]");
        System.exit(1);
    }
    try {
        String pathName = args[1];
        // Read xml file (Sbml or Vcml) into stringbuffer, pass the string into VCell's importer/exporter
        String xmlString = getXMLString(pathName);
        if (args[0].equals("-import")) {
            if (args.length > 3 || (args.length == 3 && !args[2].equals("-simulate"))) {
                System.out.println(args[2] + " : Unknown arguments for import; please check and re-run import command");
                System.out.println("Usage:\n\t -import path_of_input_file [-simulate]");
                System.exit(1);
            }
            boolean bSimulate = false;
            if (args.length == 3 && args[2].equals("-simulate")) {
                bSimulate = true;
            }
            // Create a default VCLogger - SBMLImporter needs it
            cbit.util.xml.VCLogger logger = new cbit.util.xml.VCLogger() {

                @Override
                public void sendMessage(Priority p, ErrorType et, String message) {
                    System.err.println("LOGGER: msgLevel=" + p + ", msgType=" + et + ", " + message);
                    if (p == VCLogger.Priority.HighPriority) {
                        throw new RuntimeException("Import failed : " + message);
                    }
                }

                public void sendAllMessages() {
                }

                public boolean hasMessages() {
                    return false;
                }
            };
            // invoke SBMLImporter, which returns a Biomodel, convert that to VCML using XMLHelper
            try {
                // import SBML model into VCML, store VCML string in 'fileName.vcml'
                // Instantiate an SBMLImporter to get the speciesUnitsHash - to compute the conversion factor from VC->SB species units.
                // and import SBML  (sbml->bioModel)
                org.vcell.sbml.vcell.SBMLImporter sbmlImporter = new org.vcell.sbml.vcell.SBMLImporter(pathName, logger, false);
                BioModel bioModel = sbmlImporter.getBioModel();
                // Hashtable<String, SBMLImporter.SBVCConcentrationUnits> speciesUnitsHash = sbmlImporter.getSpeciesUnitsHash();
                // double timeFactor = sbmlImporter.getSBMLTimeUnitsFactor();
                // convert biomodel to vcml and save to file.
                String vcmlString = XmlHelper.bioModelToXML(bioModel);
                String fileExtensionStr;
                if (pathName.endsWith(".xml")) {
                    fileExtensionStr = ".xml";
                } else if (pathName.endsWith(".sbml")) {
                    fileExtensionStr = ".sbml";
                } else {
                    throw new RuntimeException("Unknown file extension for SBML file name; Exiting SbmlConverter.");
                }
                String vcmlFileName = pathName.replace(fileExtensionStr, ".vcml");
                File vcmlFile = new File(vcmlFileName);
                XmlUtil.writeXMLStringToFile(vcmlString, vcmlFile.getAbsolutePath(), true);
                // If user doesn't choose to simulate, you are done.
                if (!bSimulate) {
                    return;
                }
                // Generate math for lone simContext
                SimulationContext simContext = (SimulationContext) bioModel.getSimulationContext(0);
                MathDescription mathDesc = simContext.createNewMathMapping().getMathDescription();
                simContext.setMathDescription(mathDesc);
                // Create basic simulation, with IDA solver (set in solve method) and other defaults, and end time 'Te'
                org.vcell.util.document.SimulationVersion simVersion = new org.vcell.util.document.SimulationVersion(new KeyValue("12345"), "name", new org.vcell.util.document.User("user", new KeyValue("123")), new org.vcell.util.document.GroupAccessNone(), // versionBranchPointRef
                null, // branchID
                new java.math.BigDecimal(1.0), new java.util.Date(), org.vcell.util.document.VersionFlag.Archived, "", null);
                Simulation sim1 = new Simulation(simVersion, simContext.getMathDescription());
                simContext.addSimulation(sim1);
                sim1.setName("sim1");
                // using a default end time of 10.0 secs, and a forcing default output time step of 0.01.
                // If user wants anything different, user can modify the .idaInput file and re-run simulation separately.
                // double newEndTime = endTime * timeFactor;
                double newEndTime = endTime;
                sim1.getSolverTaskDescription().setTimeBounds(new cbit.vcell.solver.TimeBounds(0, newEndTime));
                TimeStep timeStep_1 = new TimeStep();
                sim1.getSolverTaskDescription().setTimeStep(new TimeStep(timeStep_1.getMinimumTimeStep(), timeStep_1.getDefaultTimeStep(), newEndTime / 10000));
                sim1.getSolverTaskDescription().setOutputTimeSpec(new UniformOutputTimeSpec((newEndTime - 0) / numTimeSteps));
                sim1.getSolverTaskDescription().setErrorTolerance(new ErrorTolerance(1e-10, 1e-12));
                // save the new vcml with generated math and new sim in file named : fileName_IDA_simulation.vcml
                String newVcmlString = XmlHelper.bioModelToXML(bioModel);
                String newVcmlFileName = vcmlFile.getPath().replace(".vcml", "_IDA_simulation.vcml");
                File newVcmlFile = new File(newVcmlFileName);
                XmlUtil.writeXMLStringToFile(newVcmlString, newVcmlFile.getAbsolutePath(), true);
                // Solve simulation, which also generates and saves the .idainput file and .csv
                // SimSpec to get vars to solve and output in .csv
                SimSpec simSpec = SimSpec.fromSBML(xmlString);
                solveSimulation(new SimulationJob(sim1, 0, null), vcmlFile.getPath(), simSpec);
            } catch (Exception e) {
                e.printStackTrace(System.err);
                // and an annotation saying why it failed.
                try {
                    String fileExtensionStr;
                    if (pathName.endsWith(".xml")) {
                        fileExtensionStr = ".xml";
                    } else if (pathName.endsWith(".sbml")) {
                        fileExtensionStr = ".sbml";
                    } else {
                        throw new RuntimeException("Unknown file extension for SBML file name; Exiting SbmlConverter.");
                    }
                    String dummyVcmlFileName = pathName.replace(fileExtensionStr, ".vcml");
                    File dummyVcmlFile = new File(dummyVcmlFileName);
                    BioModel dummy_biomodel = new BioModel(null);
                    String dummyName = dummyVcmlFile.getName().substring(0, dummyVcmlFile.getName().indexOf(".vcml"));
                    dummy_biomodel.setName(dummyName);
                    dummy_biomodel.setDescription("SBML Model could not be automatically converted to VCML : " + e.getMessage());
                    String vcmlString = XmlHelper.bioModelToXML(dummy_biomodel);
                    XmlUtil.writeXMLStringToFile(vcmlString, dummyVcmlFile.getAbsolutePath(), true);
                } catch (Exception e1) {
                    e.printStackTrace(System.err);
                }
            }
        } else if (args[0].equals("-export")) {
            try {
                BioModel bioModel = XmlHelper.XMLToBioModel(new XMLSource(xmlString));
                for (int i = 0; i < bioModel.getSimulationContexts().length; i++) {
                    SimulationContext simContext = bioModel.getSimulationContext(i);
                    if (simContext.getGeometry().getDimension() == 0 && !simContext.isStoch()) {
                        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, with default overrides
                        String sbmlString = XmlHelper.exportSBML(bioModel, 2, 4, 0, false, simContext, null);
                        String filePath = pathName.substring(0, pathName.lastIndexOf("\\") + 1);
                        String sbmlFileName = TokenMangler.mangleToSName(bioModel.getName() + "_" + i);
                        File sbmlFile = new File(filePath + sbmlFileName + ".xml");
                        XmlUtil.writeXMLStringToFile(sbmlString, sbmlFile.getAbsolutePath(), true);
                        // Now export each simulation in the application that has overrides
                        Simulation[] simulations = bioModel.getSimulations(simContext);
                        for (int j = 0; j < simulations.length; j++) {
                            if (simulations[j].getMathOverrides().hasOverrides()) {
                                // Check for parameter scan and create simJob to pass into exporter
                                for (int k = 0; k < simulations[j].getScanCount(); k++) {
                                    SimulationJob simJob = new SimulationJob(simulations[j], k, null);
                                    sbmlString = XmlHelper.exportSBML(bioModel, 2, 4, 0, false, simContext, simJob);
                                    String fileName = TokenMangler.mangleToSName(sbmlFileName + "_" + j + "_" + k);
                                    sbmlFile = new File(filePath + fileName + ".xml");
                                    XmlUtil.writeXMLStringToFile(sbmlString, sbmlFile.getAbsolutePath(), true);
                                }
                            }
                        }
                    }
                }
                System.out.println("Successfully translated model : " + pathName);
            } catch (Exception e) {
                e.printStackTrace(System.err);
            }
        }
        System.exit(0);
    } catch (IOException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }
}
Also used : KeyValue(org.vcell.util.document.KeyValue) MathDescription(cbit.vcell.math.MathDescription) StructureMapping(cbit.vcell.mapping.StructureMapping) TimeStep(cbit.vcell.solver.TimeStep) ErrorTolerance(cbit.vcell.solver.ErrorTolerance) Structure(cbit.vcell.model.Structure) SimulationJob(cbit.vcell.solver.SimulationJob) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) VCLogger(cbit.util.xml.VCLogger) IOException(java.io.IOException) SimulationContext(cbit.vcell.mapping.SimulationContext) IOException(java.io.IOException) Simulation(cbit.vcell.solver.Simulation) BioModel(cbit.vcell.biomodel.BioModel) File(java.io.File) XMLSource(cbit.vcell.xml.XMLSource) VCLogger(cbit.util.xml.VCLogger)

Aggregations

TimeStep (cbit.vcell.solver.TimeStep)18 UniformOutputTimeSpec (cbit.vcell.solver.UniformOutputTimeSpec)9 Simulation (cbit.vcell.solver.Simulation)8 BioModel (cbit.vcell.biomodel.BioModel)7 SimulationContext (cbit.vcell.mapping.SimulationContext)7 TimeBounds (cbit.vcell.solver.TimeBounds)7 IOException (java.io.IOException)7 MathDescription (cbit.vcell.math.MathDescription)6 KeyValue (org.vcell.util.document.KeyValue)6 Geometry (cbit.vcell.geometry.Geometry)5 Model (cbit.vcell.model.Model)5 ImageException (cbit.image.ImageException)4 SubVolume (cbit.vcell.geometry.SubVolume)4 SurfaceClass (cbit.vcell.geometry.SurfaceClass)4 SimulationTask (cbit.vcell.messaging.server.SimulationTask)4 Expression (cbit.vcell.parser.Expression)4 ErrorTolerance (cbit.vcell.solver.ErrorTolerance)4 SimulationJob (cbit.vcell.solver.SimulationJob)4 SolverException (cbit.vcell.solver.SolverException)4 SimulationVersion (org.vcell.util.document.SimulationVersion)4