use of cbit.vcell.solver.Simulation in project vcell by virtualcell.
the class SmoldynFileWriter method writeDataProcessor.
private void writeDataProcessor() throws DataAccessException, IOException, MathException, DivideByZeroException, ExpressionException {
Simulation simulation = simTask.getSimulation();
DataProcessingInstructions dpi = simulation.getDataProcessingInstructions();
if (dpi == null) {
printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.B + " " + VCellSmoldynKeyword.vcellDataProcess + " begin " + DataProcessingInstructions.ROI_TIME_SERIES);
printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.B + " " + VCellSmoldynKeyword.vcellDataProcess + " end");
} else {
FieldDataIdentifierSpec fdis = dpi.getSampleImageFieldData(simulation.getVersion().getOwner());
if (fdis == null) {
throw new DataAccessException("Can't find sample image in data processing instructions");
}
File userDirectory = outputFile.getParentFile();
String secondarySimDataDir = PropertyLoader.getProperty(PropertyLoader.secondarySimDataDirInternalProperty, null);
DataSetControllerImpl dsci = new DataSetControllerImpl(null, userDirectory.getParentFile(), secondarySimDataDir == null ? null : new File(secondarySimDataDir));
CartesianMesh origMesh = dsci.getMesh(fdis.getExternalDataIdentifier());
SimDataBlock simDataBlock = dsci.getSimDataBlock(null, fdis.getExternalDataIdentifier(), fdis.getFieldFuncArgs().getVariableName(), fdis.getFieldFuncArgs().getTime().evaluateConstant());
VariableType varType = fdis.getFieldFuncArgs().getVariableType();
VariableType dataVarType = simDataBlock.getVariableType();
if (!varType.equals(VariableType.UNKNOWN) && !varType.equals(dataVarType)) {
throw new IllegalArgumentException("field function variable type (" + varType.getTypeName() + ") doesn't match real variable type (" + dataVarType.getTypeName() + ")");
}
double[] origData = simDataBlock.getData();
String filename = SimulationJob.createSimulationJobID(Simulation.createSimulationID(simulation.getKey()), simTask.getSimulationJob().getJobIndex()) + SimulationData.getDefaultFieldDataFileNameForSimulation(fdis.getFieldFuncArgs());
File fdatFile = new File(userDirectory, filename);
DataSet.writeNew(fdatFile, new String[] { fdis.getFieldFuncArgs().getVariableName() }, new VariableType[] { simDataBlock.getVariableType() }, new ISize(origMesh.getSizeX(), origMesh.getSizeY(), origMesh.getSizeZ()), new double[][] { origData });
printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.B + " " + VCellSmoldynKeyword.vcellDataProcess + " begin " + dpi.getScriptName());
StringTokenizer st = new StringTokenizer(dpi.getScriptInput(), "\n\r");
while (st.hasMoreTokens()) {
String str = st.nextToken();
if (str.trim().length() > 0) {
printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.B + " " + VCellSmoldynKeyword.vcellDataProcess + " " + str);
}
}
printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.B + " " + VCellSmoldynKeyword.vcellDataProcess + " SampleImageFile " + fdis.getFieldFuncArgs().getVariableName() + " " + fdis.getFieldFuncArgs().getTime().infix() + " " + fdatFile);
printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.B + " " + VCellSmoldynKeyword.vcellDataProcess + " end");
}
}
use of cbit.vcell.solver.Simulation in project vcell by virtualcell.
the class StandaloneSEDMLTest method doit.
public static void doit(File archiveFile) throws Exception {
ArchiveComponents ac = null;
ac = Libsedml.readSEDMLArchive(new FileInputStream(archiveFile));
SEDMLDocument sedmlDoc = ac.getSedmlDocument();
SedML sedml = sedmlDoc.getSedMLModel();
if (sedml == null || sedml.getModels().isEmpty()) {
throw new RuntimeException("sedml null or empty");
}
ModelResolver resolver = new ModelResolver(sedml);
// resolver.add(new FileModelResolver());
resolver.add(new ArchiveModelResolver(ac));
resolver.add(new BioModelsModelsRetriever());
resolver.add(new URLResourceRetriever());
// resolver.add(new RelativeFileModelResolver(FileUtils.getFullPath(archiveFile.getAbsolutePath())));
//
// 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());
}
//
// extract models referenced in tasks.
//
KisaoOntology kisaoInstance = KisaoOntology.getInstance();
// HashMap<String,Model> flattenedModels = new HashMap<String, Model>();
List<AbstractTask> taskList = sedml.getTasks();
for (AbstractTask task : taskList) {
String modelReference = task.getModelReference();
org.jlibsedml.Model sedmlOriginalModel = sedml.getModelWithId(modelReference);
String sbmlModelString = resolver.getModelString(sedmlOriginalModel);
// sbmlSource with all the changes applied
XMLSource sbmlSource = new XMLSource(sbmlModelString);
org.jlibsedml.Simulation sedmlSimulation = sedml.getSimulation(task.getSimulationReference());
Algorithm algorithm = sedmlSimulation.getAlgorithm();
KisaoTerm sedmlKisao = kisaoInstance.getTermById(algorithm.getKisaoID());
//
// try to find a VCell solverDescription to match the Kisao term
//
// 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 = kisaoInstance.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);
}
}
if (solverDescriptions.isEmpty()) {
throw new RuntimeException("cannot find the solverDescription with exact match for Kisao term '" + sedmlKisao + "'");
}
// choose first one
SolverDescription solverDescription = solverDescriptions.get(0);
// 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;
}
}
BioModel bioModel = (BioModel) XmlHelper.importSBML(transLogger, sbmlSource, bSpatial);
//
// 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);
String newSCName = bioModel.getFreeSimulationContextName();
newSimulationContext = SimulationContext.copySimulationContext(oldSimulationContext, newSCName, bSpatial, appType);
bioModel.addSimulationContext(newSimulationContext);
bioModel.removeSimulationContext(oldSimulationContext);
} else {
newSimulationContext = bioModel.addNewSimulationContext("App1", appType);
}
//
// making the new vCell simulation based on the sedml simulation
//
newSimulationContext.refreshDependencies();
MathMappingCallback callback = new MathMappingCallbackTaskAdapter(progressListener);
newSimulationContext.refreshMathDescription(callback, NetworkGenerationRequirements.ComputeFullStandardTimeout);
Simulation newSimulation = new Simulation(newSimulationContext.getMathDescription());
newSimulation.setName(sedmlSimulation.getName());
bioModel.addSimulation(newSimulation);
// and set the vCell simulation parameters accordingly
if (sedmlSimulation instanceof UniformTimeCourse) {
} else if (sedmlSimulation instanceof OneStep) {
} else if (sedmlSimulation instanceof SteadyState) {
} else {
}
System.out.println(XmlHelper.bioModelToXML(bioModel));
}
}
use of cbit.vcell.solver.Simulation 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);
}
}
use of cbit.vcell.solver.Simulation in project vcell by virtualcell.
the class XmlReader method getSimulation.
/**
* This method returns a Simulation object from a XML element.
* Creation date: (4/26/2001 12:14:30 PM)
* @return cbit.vcell.solver.Simulation
* @param param org.jdom.Element
* @exception cbit.vcell.xml.XmlParseException The exception description.
*/
Simulation getSimulation(Element param, MathDescription mathDesc) throws XmlParseException {
// retrive metadata (if any)
SimulationVersion simulationVersion = getSimulationVersion(param.getChild(XMLTags.VersionTag, vcNamespace));
// create new simulation
Simulation simulation = null;
if (simulationVersion != null) {
simulation = new Simulation(simulationVersion, mathDesc);
} else {
simulation = new Simulation(mathDesc);
}
// set attributes
String name = unMangle(param.getAttributeValue(XMLTags.NameAttrTag));
try {
simulation.setName(name);
// String annotation = param.getAttributeValue(XMLTags.AnnotationAttrTag);
// if (annotation!=null) {
// simulation.setDescription(unMangle(annotation));
// }
// Add Annotation
String annotationText = param.getChildText(XMLTags.AnnotationTag, vcNamespace);
if (annotationText != null && annotationText.length() > 0) {
simulation.setDescription(unMangle(annotationText));
}
} catch (java.beans.PropertyVetoException e) {
throw new XmlParseException(e);
}
// Retrieve MathOverrides
simulation.setMathOverrides(getMathOverrides(param.getChild(XMLTags.MathOverridesTag, vcNamespace), simulation));
// Retrieve SolverTaskDescription
try {
simulation.setSolverTaskDescription(getSolverTaskDescription(param.getChild(XMLTags.SolverTaskDescriptionTag, vcNamespace), simulation));
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace();
throw new XmlParseException("A PropertyVetoException was fired when setting the SolverTaskDescroiption object to the Simulation object " + name, e);
}
Element dataProcessingInstructionsElement = param.getChild(XMLTags.DataProcessingInstructionsTag, vcNamespace);
if (dataProcessingInstructionsElement != null) {
String scriptName = dataProcessingInstructionsElement.getAttributeValue(XMLTags.DataProcessingScriptNameAttrTag);
String scriptInput = dataProcessingInstructionsElement.getText();
simulation.setDataProcessingInstructions(new DataProcessingInstructions(scriptName, scriptInput));
}
// Retrieve MeshEspecification (if any)
Element tempElement = param.getChild(XMLTags.MeshSpecTag, vcNamespace);
if (tempElement != null) {
try {
simulation.setMeshSpecification(getMeshSpecification(tempElement, mathDesc.getGeometry()));
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace();
throw new XmlParseException("A ProperyVetoException was fired when setting the MeshSpecification to a new Simulation!", e);
}
}
return simulation;
}
use of cbit.vcell.solver.Simulation in project vcell by virtualcell.
the class ParameterEstimationTaskSimulatorIDA method getRowColumnRestultSetByBestEstimations.
public RowColumnResultSet getRowColumnRestultSetByBestEstimations(ParameterEstimationTask parameterEstimationTask, String[] paramNames, double[] paramValues) throws Exception {
// create a temp simulation based on math description
KeyValue key = new KeyValue("" + Math.abs(new Random().nextLong()));
SimulationVersion dummyVersion = new SimulationVersion(key, "name", new User("temp", new KeyValue("1")), null, null, null, null, null, null, null);
Simulation simulation = new Simulation(dummyVersion, parameterEstimationTask.getSimulationContext().getMathDescription());
ReferenceData refData = parameterEstimationTask.getModelOptimizationSpec().getReferenceData();
double[] times = refData.getDataByColumn(0);
double endTime = times[times.length - 1];
ExplicitOutputTimeSpec exTimeSpec = new ExplicitOutputTimeSpec(times);
// set simulation ending time and output interval
simulation.getSolverTaskDescription().setTimeBounds(new TimeBounds(0, endTime));
simulation.getSolverTaskDescription().setOutputTimeSpec(exTimeSpec);
// set parameters as math overrides
MathOverrides mathOverrides = simulation.getMathOverrides();
for (int i = 0; i < paramNames.length; i++) {
mathOverrides.putConstant(new Constant(paramNames[i], new Expression(paramValues[i])));
}
SimulationTask simTask = new SimulationTask(new SimulationJob(simulation, 0, null), 0);
IDASolverStandalone idaSolver = new IDASolverStandalone(simTask, ResourceUtil.getLocalSimDir("temp"), false);
// startSolver();
idaSolver.runSolver();
Thread.sleep(1000);
long startTimeMS = System.currentTimeMillis();
while (idaSolver.getSolverStatus().isRunning() && System.currentTimeMillis() < (startTimeMS + 10000L)) {
Thread.sleep(500);
}
ODESolverResultSet resultset = idaSolver.getODESolverResultSet();
return resultset;
}
Aggregations