Search in sources :

Example 1 with MathMappingCallbackTaskAdapter

use of cbit.vcell.mapping.MathMappingCallbackTaskAdapter in project vcell by virtualcell.

the class SimulationServiceImpl method computeModel.

private SimulationInfo computeModel(BioModel bioModel, SimulationSpec simSpec, ClientTaskStatusSupport statusCallback) {
    try {
        SimulationContext simContext = bioModel.getSimulationContext(0);
        MathMappingCallback callback = new MathMappingCallbackTaskAdapter(statusCallback);
        Simulation newsim = simContext.addNewSimulation(SimulationOwner.DEFAULT_SIM_NAME_PREFIX, callback, NetworkGenerationRequirements.AllowTruncatedStandardTimeout);
        SimulationInfo simulationInfo = new SimulationInfo();
        simulationInfo.setId(Math.abs(new Random().nextInt(1000000)));
        // ----------- run simulation(s)
        final File localSimDataDir = ResourceUtil.getLocalSimDir(User.tempUser.getName());
        Simulation simulation = new TempSimulation(newsim, false);
        final SimulationServiceContext simServiceContext = new SimulationServiceContext();
        simServiceContext.simInfo = simulationInfo;
        simServiceContext.simState = SimulationState.running;
        simServiceContext.simTask = new SimulationTask(new SimulationJob(simulation, 0, null), 0);
        simServiceContext.vcDataIdentifier = simServiceContext.simTask.getSimulationJob().getVCDataIdentifier();
        simServiceContext.solver = createQuickRunSolver(localSimDataDir, simServiceContext.simTask);
        simServiceContext.localSimDataDir = localSimDataDir;
        if (simServiceContext.solver == null) {
            throw new RuntimeException("null solver");
        }
        sims.put(simulationInfo.id, simServiceContext);
        simServiceContext.solver.addSolverListener(new SolverListener() {

            public void solverStopped(SolverEvent event) {
                simServiceContext.simState = SimulationState.failed;
                System.err.println("Simulation stopped");
            }

            public void solverStarting(SolverEvent event) {
                simServiceContext.simState = SimulationState.running;
                updateStatus(event);
            }

            public void solverProgress(SolverEvent event) {
                simServiceContext.simState = SimulationState.running;
                updateStatus(event);
            }

            public void solverPrinted(SolverEvent event) {
                simServiceContext.simState = SimulationState.running;
            }

            public void solverFinished(SolverEvent event) {
                try {
                    getDataSetController(simServiceContext).getDataSetTimes(simServiceContext.vcDataIdentifier);
                    simServiceContext.simState = SimulationState.done;
                } catch (DataAccessException e) {
                    simServiceContext.simState = SimulationState.failed;
                    e.printStackTrace();
                }
                updateStatus(event);
            }

            public void solverAborted(SolverEvent event) {
                simServiceContext.simState = SimulationState.failed;
                System.err.println(event.getSimulationMessage().getDisplayMessage());
            }

            private void updateStatus(SolverEvent event) {
                if (statusCallback == null)
                    return;
                statusCallback.setMessage(event.getSimulationMessage().getDisplayMessage());
                statusCallback.setProgress((int) (event.getProgress() * 100));
            }
        });
        simServiceContext.solver.startSolver();
        return simServiceContext.simInfo;
    } catch (Exception e) {
        e.printStackTrace(System.out);
        // remember the exceptiopn ... fail the status ... save the error message
        return new SimulationInfo().setId(1);
    }
}
Also used : MathMappingCallbackTaskAdapter(cbit.vcell.mapping.MathMappingCallbackTaskAdapter) SimulationTask(cbit.vcell.messaging.server.SimulationTask) MathMappingCallback(cbit.vcell.mapping.SimulationContext.MathMappingCallback) TempSimulation(cbit.vcell.solver.TempSimulation) SimulationContext(cbit.vcell.mapping.SimulationContext) XMLStreamException(javax.xml.stream.XMLStreamException) ThriftDataAccessException(org.vcell.vcellij.api.ThriftDataAccessException) SbmlException(org.vcell.sbml.SbmlException) SBMLException(org.sbml.jsbml.SBMLException) XmlParseException(cbit.vcell.xml.XmlParseException) SolverException(cbit.vcell.solver.SolverException) TException(org.apache.thrift.TException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) SolverEvent(cbit.vcell.solver.server.SolverEvent) Simulation(cbit.vcell.solver.Simulation) TempSimulation(cbit.vcell.solver.TempSimulation) Random(java.util.Random) SolverListener(cbit.vcell.solver.server.SolverListener) File(java.io.File) SimulationJob(cbit.vcell.solver.SimulationJob) ThriftDataAccessException(org.vcell.vcellij.api.ThriftDataAccessException) DataAccessException(org.vcell.util.DataAccessException) SimulationInfo(org.vcell.vcellij.api.SimulationInfo)

Example 2 with MathMappingCallbackTaskAdapter

use of cbit.vcell.mapping.MathMappingCallbackTaskAdapter 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 3 with MathMappingCallbackTaskAdapter

use of cbit.vcell.mapping.MathMappingCallbackTaskAdapter in project vcell by virtualcell.

the class SimulationListPanel method newSimulation.

/**
 * Comment
 */
private void newSimulation(final NetworkGenerationRequirements networkGenerationRequirements) {
    AsynchClientTask task1 = new AsynchClientTask("new simulation", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            MathMappingCallback mathMappingCallback = new MathMappingCallbackTaskAdapter(getClientTaskStatusSupport());
            if (getSimulationWorkspace().getSimulationOwner() instanceof SimulationContext) {
                SimulationContext simulationContext = (SimulationContext) getSimulationWorkspace().getSimulationOwner();
                simulationContext.refreshMathDescription(mathMappingCallback, networkGenerationRequirements);
            }
        }
    };
    AsynchClientTask task2 = new AsynchClientTask("new simulation", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            MathMappingCallback mathMappingCallback = new MathMappingCallbackTaskAdapter(getClientTaskStatusSupport());
            int newSimIndex = getSimulationWorkspace().newSimulation(SimulationListPanel.this, mathMappingCallback, networkGenerationRequirements);
            getScrollPaneTable().getSelectionModel().setSelectionInterval(newSimIndex, newSimIndex);
            getScrollPaneTable().scrollRectToVisible(getScrollPaneTable().getCellRect(newSimIndex, 0, true));
        }
    };
    ClientTaskDispatcher.dispatch(this, new Hashtable<String, Object>(), new AsynchClientTask[] { task1, task2 });
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) MathMappingCallbackTaskAdapter(cbit.vcell.mapping.MathMappingCallbackTaskAdapter) MathMappingCallback(cbit.vcell.mapping.SimulationContext.MathMappingCallback) Hashtable(java.util.Hashtable) SimulationContext(cbit.vcell.mapping.SimulationContext)

Example 4 with MathMappingCallbackTaskAdapter

use of cbit.vcell.mapping.MathMappingCallbackTaskAdapter in project vcell by virtualcell.

the class ParameterEstimationRunTaskPanel method solve.

private void solve() throws NumberFormatException {
    CopasiOptimizationMethod com = optimizationMethodParameterTableModel.copasiOptimizationMethod;
    OptimizationSolverSpec optSolverSpec = new OptimizationSolverSpec(com);
    // get num runs for stochstic opt mehtods before starting solving...
    if (com.getType().isStochasticMethod()) {
        int numRuns = Integer.parseInt(((String) numberOfRunComboBox.getSelectedItem()));
        optSolverSpec.setNumOfRuns(numRuns);
    }
    parameterEstimationTask.setOptimizationSolverSpec(optSolverSpec);
    parameterEstimationTask.getModelOptimizationSpec().setComputeProfileDistributions(computeProfileDistributionsCheckBox.isSelected());
    optSolverCallbacks.reset();
    Double endValue = com.getEndValue();
    optSolverCallbacks.setEvaluation(0, Double.POSITIVE_INFINITY, 0, endValue, 0);
    // (endValue != null);
    getRunStatusDialog().showProgressBar(com);
    Collection<AsynchClientTask> taskList = ClientRequestManager.updateMath(this, parameterEstimationTask.getSimulationContext(), false, NetworkGenerationRequirements.ComputeFullStandardTimeout);
    AsynchClientTask task1 = new AsynchClientTask("checking issues", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            getClientTaskStatusSupport().setProgress(0);
            StringBuffer issueText = new StringBuffer();
            java.util.Vector<Issue> issueList = new java.util.Vector<Issue>();
            IssueContext issueContext = new IssueContext();
            parameterEstimationTask.gatherIssues(issueContext, issueList);
            boolean bFailed = false;
            for (int i = 0; i < issueList.size(); i++) {
                Issue issue = (Issue) issueList.elementAt(i);
                issueText.append(issue.getMessage() + "\n");
                if (issue.getSeverity() == Issue.SEVERITY_ERROR) {
                    bFailed = true;
                    break;
                }
            }
            if (bFailed) {
                throw new OptimizationException(issueText.toString());
            }
            parameterEstimationTask.refreshMappings();
        }
    };
    taskList.add(task1);
    AsynchClientTask task2 = new AsynchClientTask("Starting param esitmation job...", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            MathMappingCallback mathMappingCallback = new MathMappingCallbackTaskAdapter(getClientTaskStatusSupport());
            // OptimizationResultSet optResultSet = CopasiOptimizationSolver.solveLocalPython(new ParameterEstimationTaskSimulatorIDA(),parameterEstimationTask,optSolverCallbacks,mathMappingCallback);
            OptimizationResultSet optResultSet = CopasiOptimizationSolver.solveRemoteApi(new ParameterEstimationTaskSimulatorIDA(), parameterEstimationTask, optSolverCallbacks, mathMappingCallback, getClientTaskStatusSupport());
            hashTable.put(ORS_KEY, optResultSet);
        }
    };
    taskList.add(task2);
    AsynchClientTask setResultTask = new AsynchClientTask("set results", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            OptimizationResultSet optResultSet = (OptimizationResultSet) hashTable.get(ORS_KEY);
            parameterEstimationTask.setOptimizationResultSet(optResultSet);
        }
    };
    taskList.add(setResultTask);
    ClientTaskDispatcher.dispatch(this, new Hashtable<String, Object>(), taskList.toArray(new AsynchClientTask[taskList.size()]), getRunStatusDialog(), true, true, true, null, false);
}
Also used : OptimizationException(cbit.vcell.opt.OptimizationException) AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) Issue(org.vcell.util.Issue) MathMappingCallbackTaskAdapter(cbit.vcell.mapping.MathMappingCallbackTaskAdapter) MathMappingCallback(cbit.vcell.mapping.SimulationContext.MathMappingCallback) Hashtable(java.util.Hashtable) OptimizationResultSet(cbit.vcell.opt.OptimizationResultSet) CopasiOptimizationMethod(cbit.vcell.opt.CopasiOptimizationMethod) IssueContext(org.vcell.util.IssueContext) OptimizationSolverSpec(cbit.vcell.opt.OptimizationSolverSpec) EventObject(java.util.EventObject) ParameterEstimationTaskSimulatorIDA(org.vcell.optimization.ParameterEstimationTaskSimulatorIDA)

Example 5 with MathMappingCallbackTaskAdapter

use of cbit.vcell.mapping.MathMappingCallbackTaskAdapter in project vcell by virtualcell.

the class StandaloneRuleBasedTest method checkNonspatialStochasticSimContext.

private static void checkNonspatialStochasticSimContext(SimulationContext srcSimContext, File baseDirectory, int numTrials, long bngTimeoutDuration) throws Exception {
    if (!srcSimContext.getApplicationType().equals(Application.NETWORK_STOCHASTIC) || srcSimContext.getGeometry().getDimension() != 0) {
        throw new RuntimeException("simContext is of type " + srcSimContext.getApplicationType() + " and geometry dimension of " + srcSimContext.getGeometry().getDimension() + ", expecting nonspatial stochastic");
    }
    BioModel origBioModel = srcSimContext.getBioModel();
    BioModel bioModel = XmlHelper.XMLToBioModel(new XMLSource(XmlHelper.bioModelToXML(origBioModel)));
    bioModel.refreshDependencies();
    // create ODE and RuleBased
    SimulationContext newODEApp = SimulationContext.copySimulationContext(srcSimContext, "aUniqueNewODEApp", false, Application.NETWORK_DETERMINISTIC);
    SimulationContext newRuleBasedApp = SimulationContext.copySimulationContext(srcSimContext, "aUniqueNewRuleBasedApp", false, Application.RULE_BASED_STOCHASTIC);
    newODEApp.setBioModel(bioModel);
    newRuleBasedApp.setBioModel(bioModel);
    ArrayList<AnnotatedFunction> outputFunctionsList = srcSimContext.getOutputFunctionContext().getOutputFunctionsList();
    // OutputContext outputContext = new OutputContext(outputFunctionsList.toArray(new AnnotatedFunction[outputFunctionsList.size()]));
    newODEApp.getOutputFunctionContext().setOutputFunctions(outputFunctionsList);
    newRuleBasedApp.getOutputFunctionContext().setOutputFunctions(outputFunctionsList);
    NetworkGenerationRequirements networkGenRequirements = NetworkGenerationRequirements.getComputeFull(bngTimeoutDuration);
    bioModel.addSimulationContext(newODEApp);
    newODEApp.refreshMathDescription(new MathMappingCallbackTaskAdapter(null), networkGenRequirements);
    bioModel.addSimulationContext(newRuleBasedApp);
    newRuleBasedApp.refreshMathDescription(new MathMappingCallbackTaskAdapter(null), networkGenRequirements);
    srcSimContext.refreshMathDescription(new MathMappingCallbackTaskAdapter(null), networkGenRequirements);
    // Create non-spatialStoch, ODE and RuleBased sims
    Simulation nonspatialStochAppNewSim = srcSimContext.addNewSimulation(STOCH_SIM_NAME, /*SimulationOwner.DEFAULT_SIM_NAME_PREFIX*/
    new MathMappingCallbackTaskAdapter(null), networkGenRequirements);
    Simulation newODEAppNewSim = newODEApp.addNewSimulation(ODE_SIM_NAME, new MathMappingCallbackTaskAdapter(null), networkGenRequirements);
    Simulation newRuleBasedAppNewSim = newRuleBasedApp.addNewSimulation(NFS_SIM_NAME, new MathMappingCallbackTaskAdapter(null), networkGenRequirements);
    nonspatialStochAppNewSim.setSimulationOwner(srcSimContext);
    newODEAppNewSim.setSimulationOwner(newODEApp);
    newRuleBasedAppNewSim.setSimulationOwner(newRuleBasedApp);
    try {
        bioModel.getModel().getSpeciesContexts();
        ArrayList<String> varNameList = new ArrayList<String>();
        for (SpeciesContextSpec scs : srcSimContext.getReactionContext().getSpeciesContextSpecs()) {
            varNameList.add(scs.getSpeciesContext().getName());
        }
        String[] varNames = varNameList.toArray(new String[0]);
        OutputTimeSpec outputTimeSpec = nonspatialStochAppNewSim.getSolverTaskDescription().getOutputTimeSpec();
        ArrayList<Double> sampleTimeList = new ArrayList<Double>();
        if (outputTimeSpec instanceof UniformOutputTimeSpec) {
            double endingTime = nonspatialStochAppNewSim.getSolverTaskDescription().getTimeBounds().getEndingTime();
            double dT = ((UniformOutputTimeSpec) outputTimeSpec).getOutputTimeStep();
            int currTimeIndex = 0;
            while (currTimeIndex * dT <= (endingTime + 1e-8)) {
                sampleTimeList.add(currTimeIndex * dT);
                currTimeIndex++;
            }
        }
        double[] sampleTimes = new double[sampleTimeList.size()];
        for (int i = 0; i < sampleTimes.length; i++) {
            sampleTimes[i] = sampleTimeList.get(i);
        }
        TimeSeriesMultitrialData sampleDataStoch1 = new TimeSeriesMultitrialData("stochastic1", varNames, sampleTimes, numTrials);
        TimeSeriesMultitrialData sampleDataStoch2 = new TimeSeriesMultitrialData("stochastic2", varNames, sampleTimes, numTrials);
        TimeSeriesMultitrialData sampleDataDeterministic = new TimeSeriesMultitrialData("determinstic", varNames, sampleTimes, 1);
        runsolver(nonspatialStochAppNewSim, baseDirectory, numTrials, sampleDataStoch1);
        runsolver(newODEAppNewSim, baseDirectory, 1, sampleDataDeterministic);
        runsolver(newRuleBasedAppNewSim, baseDirectory, numTrials, sampleDataStoch2);
        StochtestFileUtils.writeVarDiffData(new File(baseDirectory, VARDIFF_FILE), sampleDataStoch1, sampleDataStoch2);
        StochtestFileUtils.writeKolmogorovSmirnovTest(new File(baseDirectory, KS_TEST_FILE), sampleDataStoch1, sampleDataStoch2);
        StochtestFileUtils.writeChiSquareTest(new File(baseDirectory, ChiSquared_TEST_FILE), sampleDataStoch1, sampleDataStoch2);
        StochtestFileUtils.writeData(sampleDataStoch1, new File(baseDirectory, "data." + sampleDataStoch1.datasetName + ".json"));
        StochtestFileUtils.writeData(sampleDataStoch2, new File(baseDirectory, "data." + sampleDataStoch2.datasetName + ".json"));
        StochtestFileUtils.writeData(sampleDataDeterministic, new File(baseDirectory, "data." + sampleDataDeterministic.datasetName + ".json"));
    } finally {
        srcSimContext.removeSimulation(nonspatialStochAppNewSim);
        newODEApp.removeSimulation(newODEAppNewSim);
        newRuleBasedApp.removeSimulation(newRuleBasedAppNewSim);
    }
}
Also used : MathMappingCallbackTaskAdapter(cbit.vcell.mapping.MathMappingCallbackTaskAdapter) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) TimeSeriesMultitrialData(org.vcell.stochtest.TimeSeriesMultitrialData) ArrayList(java.util.ArrayList) SimulationContext(cbit.vcell.mapping.SimulationContext) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) OutputTimeSpec(cbit.vcell.solver.OutputTimeSpec) TempSimulation(cbit.vcell.solver.TempSimulation) Simulation(cbit.vcell.solver.Simulation) BioModel(cbit.vcell.biomodel.BioModel) NetworkGenerationRequirements(cbit.vcell.mapping.SimulationContext.NetworkGenerationRequirements) XMLSource(cbit.vcell.xml.XMLSource) File(java.io.File) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction)

Aggregations

MathMappingCallbackTaskAdapter (cbit.vcell.mapping.MathMappingCallbackTaskAdapter)13 SimulationContext (cbit.vcell.mapping.SimulationContext)11 MathMappingCallback (cbit.vcell.mapping.SimulationContext.MathMappingCallback)11 ArrayList (java.util.ArrayList)8 BioModel (cbit.vcell.biomodel.BioModel)7 Simulation (cbit.vcell.solver.Simulation)7 AsynchClientTask (cbit.vcell.client.task.AsynchClientTask)6 Hashtable (java.util.Hashtable)6 SimulationTask (cbit.vcell.messaging.server.SimulationTask)4 TempSimulation (cbit.vcell.solver.TempSimulation)4 UniformOutputTimeSpec (cbit.vcell.solver.UniformOutputTimeSpec)4 File (java.io.File)4 Application (cbit.vcell.mapping.SimulationContext.Application)3 MathModel (cbit.vcell.mathmodel.MathModel)3 AnnotatedFunction (cbit.vcell.solver.AnnotatedFunction)3 OutputTimeSpec (cbit.vcell.solver.OutputTimeSpec)3 XMLSource (cbit.vcell.xml.XMLSource)3 FileInputStream (java.io.FileInputStream)3 IOException (java.io.IOException)3 XMLStreamException (javax.xml.stream.XMLStreamException)3