use of cbit.vcell.solver.Simulation in project vcell by virtualcell.
the class RunFakeSim method compute0.
@Override
protected void compute0(TaskContext context, final ClientTaskStatusSupport clientTaskStatusSupport) throws Exception {
// set input
Simulation sim = context.getData(simulation_2D);
Double max_intensity = context.getData(maxIntensity);
Double bleachLockingBegin = context.getData(bleachBlackoutBeginTime);
Double bleachLockoutEnd = context.getData(bleachBlackoutEndTime);
Boolean hasNoise = context.getData(bNoise);
// do op
RunFakeSimOp op = new RunFakeSimOp();
ImageTimeSeries<UShortImage> solution = op.runRefSimulation(context.getLocalWorkspace(), sim, max_intensity, bleachLockingBegin, bleachLockoutEnd, hasNoise, clientTaskStatusSupport);
// set output
context.setData(simTimeSeries, solution);
}
use of cbit.vcell.solver.Simulation in project vcell by virtualcell.
the class Generate2DExpModelOpAbstract method generateModel.
public final GeneratedModelResults generateModel(double deltaX, double bleachRadius, double cellRadius, double bleachDuration, double bleachRate, double postbleachDelay, double postbleachDuration, double psfSigma, double outputTimeStep, double primaryDiffusionRate, double primaryFraction, double bleachMonitorRate, double secondaryDiffusionRate, double secondaryFraction, String extracellularName, String cytosolName, Context context) throws PropertyVetoException, ExpressionException, GeometryException, ImageException, ModelException, MappingException, MathException, MatrixException {
double domainSize = 2.2 * cellRadius;
Extent extent = new Extent(domainSize, domainSize, 1.0);
Origin origin = new Origin(-extent.getX() / 2.0, -extent.getY() / 2.0, -extent.getZ() / 2.0);
String EXTRACELLULAR_NAME = extracellularName;
String CYTOSOL_NAME = cytosolName;
AnalyticSubVolume cytosolSubVolume = new AnalyticSubVolume(CYTOSOL_NAME, new Expression("pow(x,2)+pow(y,2)<pow(" + cellRadius + ",2)"));
AnalyticSubVolume extracellularSubVolume = new AnalyticSubVolume(EXTRACELLULAR_NAME, new Expression(1.0));
Geometry geometry = new Geometry("geometry", 2);
geometry.getGeometrySpec().setExtent(extent);
geometry.getGeometrySpec().setOrigin(origin);
geometry.getGeometrySpec().addSubVolume(extracellularSubVolume);
geometry.getGeometrySpec().addSubVolume(cytosolSubVolume, true);
geometry.getGeometrySurfaceDescription().updateAll();
BioModel bioModel = new BioModel(null);
bioModel.setName("unnamed");
Model model = new Model("model");
bioModel.setModel(model);
model.addFeature(EXTRACELLULAR_NAME);
Feature extracellular = (Feature) model.getStructure(EXTRACELLULAR_NAME);
model.addFeature(CYTOSOL_NAME);
Feature cytosol = (Feature) model.getStructure(CYTOSOL_NAME);
SpeciesContext immobileSC = model.createSpeciesContext(cytosol);
SpeciesContext primarySC = model.createSpeciesContext(cytosol);
SpeciesContext secondarySC = model.createSpeciesContext(cytosol);
//
// common bleaching rate for all species
//
double bleachStart = 10 * outputTimeStep - bleachDuration - postbleachDelay;
double bleachEnd = bleachStart + bleachDuration;
Expression bleachRateExp = createBleachExpression(bleachRadius, bleachRate, bleachMonitorRate, bleachStart, bleachEnd);
{
SimpleReaction immobileBWM = model.createSimpleReaction(cytosol);
GeneralKinetics immobileBWMKinetics = new GeneralKinetics(immobileBWM);
immobileBWM.setKinetics(immobileBWMKinetics);
immobileBWM.addReactant(immobileSC, 1);
immobileBWMKinetics.getReactionRateParameter().setExpression(Expression.mult(bleachRateExp, new Expression(immobileSC.getName())));
}
{
SimpleReaction primaryBWM = model.createSimpleReaction(cytosol);
GeneralKinetics primaryBWMKinetics = new GeneralKinetics(primaryBWM);
primaryBWM.setKinetics(primaryBWMKinetics);
primaryBWM.addReactant(primarySC, 1);
primaryBWMKinetics.getReactionRateParameter().setExpression(Expression.mult(bleachRateExp, new Expression(primarySC.getName())));
}
{
SimpleReaction secondaryBWM = model.createSimpleReaction(cytosol);
GeneralKinetics secondaryBWMKinetics = new GeneralKinetics(secondaryBWM);
secondaryBWM.setKinetics(secondaryBWMKinetics);
secondaryBWM.addReactant(secondarySC, 1);
secondaryBWMKinetics.getReactionRateParameter().setExpression(Expression.mult(bleachRateExp, new Expression(secondarySC.getName())));
}
// create simulation context
SimulationContext simContext = bioModel.addNewSimulationContext("simContext", SimulationContext.Application.NETWORK_DETERMINISTIC);
simContext.setGeometry(geometry);
FeatureMapping cytosolFeatureMapping = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(cytosol);
FeatureMapping extracellularFeatureMapping = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(extracellular);
SubVolume cytSubVolume = geometry.getGeometrySpec().getSubVolume(CYTOSOL_NAME);
SubVolume exSubVolume = geometry.getGeometrySpec().getSubVolume(EXTRACELLULAR_NAME);
// unused? SurfaceClass pmSurfaceClass = geometry.getGeometrySurfaceDescription().getSurfaceClass(exSubVolume, cytSubVolume);
cytosolFeatureMapping.setGeometryClass(cytSubVolume);
extracellularFeatureMapping.setGeometryClass(exSubVolume);
cytosolFeatureMapping.getUnitSizeParameter().setExpression(new Expression(1.0));
extracellularFeatureMapping.getUnitSizeParameter().setExpression(new Expression(1.0));
double fixedFraction = 1.0 - primaryFraction - secondaryFraction;
SpeciesContextSpec immobileSCS = simContext.getReactionContext().getSpeciesContextSpec(immobileSC);
immobileSCS.getInitialConditionParameter().setExpression(new Expression(fixedFraction));
immobileSCS.getDiffusionParameter().setExpression(new Expression(0.0));
SpeciesContextSpec primarySCS = simContext.getReactionContext().getSpeciesContextSpec(primarySC);
primarySCS.getInitialConditionParameter().setExpression(new Expression(primaryFraction));
primarySCS.getDiffusionParameter().setExpression(new Expression(primaryDiffusionRate));
SpeciesContextSpec secondarySCS = simContext.getReactionContext().getSpeciesContextSpec(secondarySC);
secondarySCS.getInitialConditionParameter().setExpression(new Expression(secondaryFraction));
secondarySCS.getDiffusionParameter().setExpression(new Expression(secondaryDiffusionRate));
simContext.getMicroscopeMeasurement().addFluorescentSpecies(immobileSC);
simContext.getMicroscopeMeasurement().addFluorescentSpecies(primarySC);
simContext.getMicroscopeMeasurement().addFluorescentSpecies(secondarySC);
simContext.getMicroscopeMeasurement().setConvolutionKernel(new GaussianConvolutionKernel(new Expression(psfSigma), new Expression(psfSigma)));
MathMapping mathMapping = simContext.createNewMathMapping();
MathDescription mathDesc = mathMapping.getMathDescription();
simContext.setMathDescription(mathDesc);
User owner = context.getDefaultOwner();
int meshSize = (int) (domainSize / deltaX);
if (meshSize % 2 == 0) {
// want an odd-sized mesh in x and y ... so centered at the origin.
meshSize = meshSize + 1;
}
TimeBounds timeBounds = new TimeBounds(0.0, postbleachDuration);
//
// simulation to use for data generation (output time steps as recorded by the microscope)
//
double bleachBlackoutBegin = bleachStart - postbleachDelay;
double bleachBlackoutEnd = bleachEnd + postbleachDelay;
// ArrayList<Double> times = new ArrayList<Double>();
// double time = 0;
// while (time<=timeBounds.getEndingTime()){
// if (time<=bleachBlackoutBegin || time>bleachBlackoutEnd){
// // postbleachDelay is the time it takes to switch the filters.
// times.add(time);
// }
// time += outputTimeStep.getData();
// }
// double[] timeArray = new double[times.size()];
// for (int i=0;i<timeArray.length;i++){
// timeArray[i] = times.get(i);
// }
// OutputTimeSpec fakeDataSimOutputTimeSpec = new ExplicitOutputTimeSpec(timeArray);
OutputTimeSpec fakeDataSimOutputTimeSpec = new UniformOutputTimeSpec(outputTimeStep);
KeyValue fakeDataSimKey = context.createNewKeyValue();
SimulationVersion fakeDataSimVersion = new SimulationVersion(fakeDataSimKey, "fakeDataSim", owner, new GroupAccessNone(), new KeyValue("0"), new BigDecimal(0), new Date(), VersionFlag.Current, "", null);
Simulation fakeDataSim = new Simulation(fakeDataSimVersion, mathDesc);
simContext.addSimulation(fakeDataSim);
fakeDataSim.getSolverTaskDescription().setTimeBounds(timeBounds);
fakeDataSim.getMeshSpecification().setSamplingSize(new ISize(meshSize, meshSize, 1));
fakeDataSim.getSolverTaskDescription().setSolverDescription(SolverDescription.SundialsPDE);
fakeDataSim.getSolverTaskDescription().setOutputTimeSpec(fakeDataSimOutputTimeSpec);
//
// simulation to use for viewing the protocol (output time steps to understand the physics)
//
KeyValue fullExperimentSimKey = context.createNewKeyValue();
SimulationVersion fullExperimentSimVersion = new SimulationVersion(fullExperimentSimKey, "fullExperiment", owner, new GroupAccessNone(), new KeyValue("0"), new BigDecimal(0), new Date(), VersionFlag.Current, "", null);
Simulation fullExperimentSim = new Simulation(fullExperimentSimVersion, mathDesc);
simContext.addSimulation(fullExperimentSim);
OutputTimeSpec fullExperimentOutputTimeSpec = new UniformOutputTimeSpec(outputTimeStep / 10.0);
fullExperimentSim.getSolverTaskDescription().setTimeBounds(timeBounds);
fullExperimentSim.getMeshSpecification().setSamplingSize(new ISize(meshSize, meshSize, 1));
fullExperimentSim.getSolverTaskDescription().setSolverDescription(SolverDescription.SundialsPDE);
fullExperimentSim.getSolverTaskDescription().setOutputTimeSpec(fullExperimentOutputTimeSpec);
GeneratedModelResults results = new GeneratedModelResults();
results.bioModel_2D = bioModel;
results.simulation_2D = fakeDataSim;
results.bleachBlackoutBeginTime = bleachBlackoutBegin;
results.bleachBlackoutEndTime = bleachBlackoutEnd;
return results;
}
use of cbit.vcell.solver.Simulation in project vcell by virtualcell.
the class StochtestRunService method computeTrials.
private void computeTrials(SimulationContext simContext, StochtestRun stochtestRun, File baseDirectory, OutputTimeSpec outputTimeSpec, double endTime, int numTrials) throws PropertyVetoException, IOException {
//
// make simulation
//
MathMappingCallback callback = new MathMappingCallback() {
@Override
public void setProgressFraction(float fractionDone) {
}
@Override
public void setMessage(String message) {
}
@Override
public boolean isInterrupted() {
return false;
}
};
NetworkGenerationRequirements networkGenerationRequirements = NetworkGenerationRequirements.getComputeFull(bngTimeoutMS);
simContext.refreshMathDescription(callback, networkGenerationRequirements);
Simulation sim = simContext.addNewSimulation("stochtestrun_" + stochtestRun.key, callback, networkGenerationRequirements);
sim.setSimulationOwner(simContext);
//
// get variables to save
//
simContext.getModel().getSpeciesContexts();
ArrayList<String> varNameList = new ArrayList<String>();
for (SpeciesContextSpec scs : simContext.getReactionContext().getSpeciesContextSpecs()) {
varNameList.add(scs.getSpeciesContext().getName());
}
String[] varNames = varNameList.toArray(new String[0]);
//
// get time points to save
//
ArrayList<Double> sampleTimeList = new ArrayList<Double>();
if (outputTimeSpec instanceof UniformOutputTimeSpec) {
double dT = ((UniformOutputTimeSpec) outputTimeSpec).getOutputTimeStep();
int currTimeIndex = 0;
while (currTimeIndex * dT <= (endTime + 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);
}
//
// run N trials and save data
//
TimeSeriesMultitrialData sampleData = new TimeSeriesMultitrialData(sim.getName(), varNames, sampleTimes, numTrials);
runsolver(sim, baseDirectory, numTrials, sampleData);
StochtestFileUtils.writeData(sampleData, StochtestFileUtils.getStochtestRunDataFile(baseDir, stochtestRun));
}
use of cbit.vcell.solver.Simulation in project vcell by virtualcell.
the class StochtestRunService method runsolver.
private static void runsolver(Simulation newSimulation, File baseDirectory, int numRuns, TimeSeriesMultitrialData timeSeriesMultitrialData) {
Simulation versSimulation = null;
File destDir = null;
boolean bTimeout = false;
// int progress = 1;
for (int trialIndex = 0; trialIndex < numRuns; trialIndex++) {
System.out.println("\n=====================================\n\nStarting trial " + (trialIndex + 1) + " of " + numRuns + "\n\n==============================\n");
long startTime = System.currentTimeMillis();
// }
try {
versSimulation = new TempSimulation(newSimulation, false);
// printout(ruleBasedTestDir.getAbsolutePath());
destDir = new File(baseDirectory, timeSeriesMultitrialData.datasetName);
SimulationTask simTask = new SimulationTask(new SimulationJob(versSimulation, 0, null), 0);
Solver solver = ClientSimManager.createQuickRunSolver(destDir, simTask);
solver.startSolver();
while (true) {
try {
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (System.currentTimeMillis() - startTime > 30 * 1000) {
// timeout after 30 seconds .. otherwise multiple runs will take forever
bTimeout = true;
solver.stopSolver();
throw new RuntimeException("timed out");
}
SolverStatus solverStatus = solver.getSolverStatus();
if (solverStatus != null) {
if (solverStatus.getStatus() == SolverStatus.SOLVER_ABORTED) {
throw new RuntimeException(solverStatus.getSimulationMessage().getDisplayMessage());
}
if (solverStatus.getStatus() != SolverStatus.SOLVER_STARTING && solverStatus.getStatus() != SolverStatus.SOLVER_READY && solverStatus.getStatus() != SolverStatus.SOLVER_RUNNING) {
break;
}
}
}
SimulationData simData = new SimulationData(simTask.getSimulationJob().getVCDataIdentifier(), destDir, null, null);
ODEDataBlock odeDataBlock = simData.getODEDataBlock();
ODESimData odeSimData = odeDataBlock.getODESimData();
timeSeriesMultitrialData.addDataSet(odeSimData, trialIndex);
} catch (Exception e) {
e.printStackTrace();
File file = new File(baseDirectory, Simulation.createSimulationID(versSimulation.getKey()) + "_solverExc.txt");
StochtestFileUtils.writeMessageTofile(file, e.getMessage());
if (bTimeout) {
throw new RuntimeException("timed out");
} else {
throw new RuntimeException("solver failed : " + e.getMessage(), e);
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
StochtestFileUtils.clearDir(destDir);
}
// printout("\n");
}
use of cbit.vcell.solver.Simulation 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);
}
}
Aggregations