use of cbit.vcell.solver.ode.CVodeFileWriter in project vcell by virtualcell.
the class VCellSedMLSolver method solveCvode.
private static ODESolverResultSet solveCvode(File outDir, BioModel bioModel) throws Exception {
String docName = bioModel.getName();
Simulation sim = bioModel.getSimulation(0);
File cvodeInputFile = new File(outDir, docName + SimDataConstants.CVODEINPUT_DATA_EXTENSION);
PrintWriter cvodePW = new java.io.PrintWriter(cvodeInputFile);
SimulationJob simJob = new SimulationJob(sim, 0, null);
SimulationTask simTask = new SimulationTask(simJob, 0);
CVodeFileWriter cvodeFileWriter = new CVodeFileWriter(cvodePW, simTask);
cvodeFileWriter.write();
cvodePW.close();
// use the cvodeStandalone solver
String outDirPath = outDir.getAbsolutePath();
int indexOfLastSlash = outDirPath.lastIndexOf("/");
String task_name = outDirPath.substring(indexOfLastSlash + 1);
String idaFilePath = outDirPath.substring(0, indexOfLastSlash);
File cvodeOutputFile = new File(idaFilePath, task_name + SimDataConstants.IDA_DATA_EXTENSION);
String executableName = null;
try {
// we need to specify the vCell install dir in the Eclipse Debug configuration, as VM argument
// so that the code next knows where to look for the solver
// -Dvcell.installDir=G:\dan\jprojects\git\vcell
// OR
// just type the string with the full path explicitly
// OR
// provide a .properties file in the working directory
executableName = SolverUtilities.getExes(SolverDescription.CVODE)[0].getAbsolutePath();
} catch (IOException e) {
throw new RuntimeException("failed to get executable for solver " + SolverDescription.CVODE.getDisplayLabel() + ": " + e.getMessage(), e);
}
Executable executable = new Executable(new String[] { executableName, cvodeInputFile.getAbsolutePath(), cvodeOutputFile.getAbsolutePath() });
executable.start();
ODESolverResultSet odeSolverResultSet = VCellSBMLSolver.getODESolverResultSet(simJob, cvodeOutputFile.getPath());
return odeSolverResultSet;
}
use of cbit.vcell.solver.ode.CVodeFileWriter in project vcell by virtualcell.
the class SbmlVcmlConverter method solveSimulation.
/**
* solves the simulation that is passed in throught the simulation job.
*/
private static void solveSimulation(SimulationJob simJob, String filePathName, SimSpec argSimSpec) /* Hashtable argSpUnitsHash, double argTimeFactor, Model.ReservedSymbol kMoleSymbol*/
{
ODESolverResultSet odeSolverResultSet = null;
try {
/* // Generate .idaInput string
File idaInputFile = new File(filePathName.replace(".vcml", ".idaInput"));
PrintWriter idaPW = new java.io.PrintWriter(idaInputFile);
IDAFileWriter idaFileWriter = new IDAFileWriter(idaPW, simJob);
idaFileWriter.write();
idaPW.close();
// use the SundialsStandaloneSolver
File idaOutputFile = new File(filePathName.replace(".vcml", ".ida"));
Executable executable = new Executable(new String[]{"SundialsSolverStandalone", idaInputFile.getAbsolutePath(), idaOutputFile.getAbsolutePath()});
executable.start();
*/
// Generate .cvodeInput string
File cvodeInputFile = new File(filePathName.replace(".vcml", ".cvodeInput"));
PrintWriter cvodePW = new java.io.PrintWriter(cvodeInputFile);
SimulationTask simTask = new SimulationTask(simJob, 0);
CVodeFileWriter cvodeFileWriter = new CVodeFileWriter(cvodePW, simTask);
cvodeFileWriter.write();
cvodePW.close();
// use the cvodeStandalone solver
// use the SundialsStandaloneSolver
File cvodeOutputFile = new File(filePathName.replace(".vcml", ".ida"));
/*
Executable executable = new Executable(new String[]{"d:/workspace/VCell_5.3_VCell/SundialsSolverStandalone_x64", cvodeInputFile.getAbsolutePath(), cvodeOutputFile.getAbsolutePath()});
executable.start();
*/
// use the cvodeStandalone solver
// use the SundialsStandaloneSolver
File[] exes = SolverUtilities.getExes(SolverDescription.CombinedSundials);
assert exes.length == 1 : "one and only one smoldyn solver expected";
File sundialsExe = exes[0];
Executable executable = new Executable(new String[] { sundialsExe.getAbsolutePath(), cvodeInputFile.getAbsolutePath(), cvodeOutputFile.getAbsolutePath() });
executable.start();
// get the result
odeSolverResultSet = VCellSBMLSolver.getODESolverResultSet(simJob, cvodeOutputFile.getPath());
} catch (Exception e) {
e.printStackTrace(System.out);
throw new RuntimeException("Error running NativeIDA solver : " + e.getMessage());
}
// now write out the results into CSV file
try {
if (odeSolverResultSet != null) {
File csvFile = new File(filePathName.replace(".vcml", ".csv"));
PrintStream outputStream = new PrintStream(new BufferedOutputStream(new FileOutputStream(csvFile)));
outputStream.print("time");
for (int i = 0; i < argSimSpec.getVarsList().length; i++) {
outputStream.print("," + argSimSpec.getVarsList()[i]);
}
outputStream.println();
// extract data for time and species
double[][] data = new double[argSimSpec.getVarsList().length + 1][];
int column = odeSolverResultSet.findColumn("t");
data[0] = odeSolverResultSet.extractColumn(column);
int origDataLength = data[0].length;
for (int i = 0; i < argSimSpec.getVarsList().length; i++) {
column = odeSolverResultSet.findColumn(argSimSpec.getVarsList()[i]);
if (column == -1) {
Variable var = simJob.getSimulationSymbolTable().getVariable(argSimSpec.getVarsList()[i]);
data[i + 1] = new double[data[0].length];
if (var instanceof cbit.vcell.math.Constant) {
double value = ((cbit.vcell.math.Constant) var).getExpression().evaluateConstant();
for (int j = 0; j < data[i + 1].length; j++) {
data[i + 1][j] = value;
}
} else {
throw new RuntimeException("Did not find " + argSimSpec.getVarsList()[i] + " in simulation");
}
} else {
data[i + 1] = odeSolverResultSet.extractColumn(column);
}
}
double endTime = (simJob.getSimulation().getSolverTaskDescription().getTimeBounds().getEndingTime());
// for each time, print row
int index = 0;
double[] sampleTimes = new double[numTimeSteps + 1];
for (int i = 0; i <= numTimeSteps; i++) {
sampleTimes[i] = endTime * i / numTimeSteps;
}
for (int i = 0; i < sampleTimes.length; i++) {
// find largest index whose time is not past sample time
while (true) {
// if already at last time point, then if it equals the sampleTime, we're done if it doesn't then we don't have this time point.
if (index == odeSolverResultSet.getRowCount() - 1) {
if (data[0][index] == sampleTimes[i]) {
break;
} else {
throw new RuntimeException("sampleTime does not match at last time point");
}
}
// haven't gotten to last time point yet, stop when next time step is past sampleTime.
if (data[0][index + 1] > sampleTimes[i]) {
break;
}
// sampleTime must be later in our data list.
index++;
}
// if (data[0][index] == sampleTimes[i]) {
if (Math.abs(data[0][index] - sampleTimes[i]) < 1e-12) {
// if timeFactor is not 1.0, time is not in seconds (mins or hrs); if timeFactor is 60, divide sampleTime/60; if it is 3600, divide sampleTime/3600.
// if (argTimeFactor != 1.0) {
// outputStream.print(data[0][index]/argTimeFactor);
// } else {
outputStream.print(data[0][index]);
// }
for (int j = 0; j < argSimSpec.getVarsList().length; j++) {
// SBMLImporter.SBVCConcentrationUnits spConcUnits = (SBMLImporter.SBVCConcentrationUnits)argSpUnitsHash.get(argSimSpec.getVarsList()[j]);
// if (spConcUnits != null) {
// VCUnitDefinition sbunits = spConcUnits.getSBConcentrationUnits();
// VCUnitDefinition vcunits = spConcUnits.getVCConcentrationUnits();
// SBMLUnitParameter unitFactor = SBMLUtils.getConcUnitFactor("spConcParam", vcunits, sbunits, kMoleSymbol);
// outputStream.print("," + data[j + 1][index] * unitFactor.getExpression().evaluateConstant()); //earlier, hack unitfactor = 0.000001
// earlier, hack unitfactor = 0.000001
outputStream.print("," + data[j + 1][index]);
}
// }
outputStream.println();
} else {
// if data[0][index] < sampleTime, must interpolate
double fraction = (sampleTimes[i] - data[0][index]) / (data[0][index + 1] - data[0][index]);
// if argTimeFactor is not 1.0, time is not in seconds (mins or hrs); if argTimeFactor is 60, divide sampleTime/60; if it is 3600, divide sampleTime/3600.
// if (argTimeFactor != 1.0) {
// outputStream.print(sampleTimes[i]/argTimeFactor);
// } else {
outputStream.print(sampleTimes[i]);
// }
for (int j = 0; j < argSimSpec.getVarsList().length; j++) {
double interpolatedValue = 0.0;
double[] speciesVals = null;
double[] times = null;
// Currently using 2nd order interpolation
if (index == 0) {
// can only do 1st order interpolation
times = new double[] { data[0][index], data[0][index + 1] };
speciesVals = new double[] { data[j + 1][index], data[j + 1][index + 1] };
interpolatedValue = MathTestingUtilities.taylorInterpolation(sampleTimes[i], times, speciesVals);
} else {
if (index >= 1 && index <= origDataLength - 3) {
double val_1 = Math.abs(sampleTimes[i] - data[0][index - 1]);
double val_2 = Math.abs(sampleTimes[i] - data[0][index + 2]);
if (val_1 < val_2) {
times = new double[] { data[0][index - 1], data[0][index], data[0][index + 1] };
speciesVals = new double[] { data[j + 1][index - 1], data[j + 1][index], data[j + 1][index + 1] };
} else {
times = new double[] { data[0][index], data[0][index + 1], data[0][index + 2] };
speciesVals = new double[] { data[j + 1][index], data[j + 1][index + 1], data[j + 1][index + 2] };
}
interpolatedValue = MathTestingUtilities.taylorInterpolation(sampleTimes[i], times, speciesVals);
} else {
times = new double[] { data[0][index - 1], data[0][index], data[0][index + 1] };
speciesVals = new double[] { data[j + 1][index - 1], data[j + 1][index], data[j + 1][index + 1] };
interpolatedValue = MathTestingUtilities.taylorInterpolation(sampleTimes[i], times, speciesVals);
}
}
// end if-else - calc of interpolated value
// interpolatedValue = interpolatedValue * unitFactor.getExpression().evaluateConstant();
outputStream.print("," + interpolatedValue);
}
// end for - sp values for each time point (row)
outputStream.println();
}
}
outputStream.close();
} else {
throw new RuntimeException("Result set was null, could not write to CSV file");
}
} catch (Exception e) {
e.printStackTrace(System.out);
throw new RuntimeException("Errors saving results to CSV file" + e.getMessage());
}
}
use of cbit.vcell.solver.ode.CVodeFileWriter in project vcell by virtualcell.
the class VCellSBMLSolver method solve.
public File solve(String filePrefix, File outDir, String sbmlFileName, SimSpec testSpec) throws IOException, SolverException, SbmlException {
try {
cbit.util.xml.VCLogger sbmlImportLogger = new LocalLogger();
//
// Instantiate an SBMLImporter to get the speciesUnitsHash - to compute the conversion factor from VC->SB species units.
// and import SBML (sbml->bioModel)
BioModel bioModel = importSBML(sbmlFileName, sbmlImportLogger, false);
// Hashtable<String, SBMLImporter.SBVCConcentrationUnits> speciesUnitsHash = sbmlImporter.getSpeciesUnitsHash();
// double timeFactor = sbmlImporter.getSBMLTimeUnitsFactor();
String vcml_1 = XmlHelper.bioModelToXML(bioModel);
SBMLUtils.writeStringToFile(vcml_1, new File(outDir, filePrefix + ".vcml").getAbsolutePath(), true);
if (bRoundTrip) {
// Round trip the bioModel (bioModel->sbml->bioModel).
// save imported "bioModel" as VCML
// String vcml_1 = XmlHelper.bioModelToXML(bioModel);
// SBMLUtils.writeStringToFile(vcml_1, new File(outDir,filePrefix+".vcml").getAbsolutePath());
// export bioModel as sbml and save
// String vcml_sbml = cbit.vcell.xml.XmlHelper.exportSBML(bioModel, 2, 1, bioModel.getSimulationContexts(0).getName());
// SimulationJob simJob = new SimulationJob(bioModel.getSimulations(bioModel.getSimulationContexts(0))[0], null, 0);
String vcml_sbml = cbit.vcell.xml.XmlHelper.exportSBML(bioModel, 2, 1, 0, false, bioModel.getSimulationContext(0), null);
SBMLUtils.writeStringToFile(vcml_sbml, new File(outDir, filePrefix + ".vcml.sbml").getAbsolutePath(), true);
// re-import bioModel from exported sbml
XMLSource vcml_sbml_Src = new XMLSource(vcml_sbml);
BioModel newBioModel = (BioModel) XmlHelper.importSBML(sbmlImportLogger, vcml_sbml_Src, false);
String vcml_sbml_vcml = XmlHelper.bioModelToXML(newBioModel);
SBMLUtils.writeStringToFile(vcml_sbml_vcml, new File(outDir, filePrefix + ".vcml.sbml.vcml").getAbsolutePath(), true);
// have rest of code use the round-tripped biomodel
bioModel = newBioModel;
}
//
// select only Application, generate math, and create a single Simulation.
//
SimulationContext simContext = bioModel.getSimulationContext(0);
MathMapping mathMapping = simContext.createNewMathMapping();
MathDescription mathDesc = mathMapping.getMathDescription();
String vcml = mathDesc.getVCML();
try (PrintWriter pw = new PrintWriter("vcmlTrace.txt")) {
pw.println(vcml);
}
simContext.setMathDescription(mathDesc);
SimulationVersion simVersion = new SimulationVersion(new KeyValue("100"), "unnamed", null, null, null, null, null, null, null, null);
Simulation sim = new Simulation(simVersion, mathDesc);
sim.setName("unnamed");
// if time factor from SBML is not 1 (i.e., it is not in secs but in minutes or hours), convert endTime to min/hr as : endTime*timeFactor
// double endTime = testSpec.getEndTime()*timeFactor;
double endTime = testSpec.getEndTime();
sim.getSolverTaskDescription().setTimeBounds(new TimeBounds(0, endTime));
TimeStep timeStep = new TimeStep();
sim.getSolverTaskDescription().setTimeStep(new TimeStep(timeStep.getMinimumTimeStep(), timeStep.getDefaultTimeStep(), endTime / 10000));
sim.getSolverTaskDescription().setOutputTimeSpec(new UniformOutputTimeSpec((endTime - 0) / testSpec.getNumTimeSteps()));
sim.getSolverTaskDescription().setErrorTolerance(new ErrorTolerance(1e-10, 1e-12));
// sim.getSolverTaskDescription().setErrorTolerance(new cbit.vcell.solver.ErrorTolerance(1e-10, 1e-12));
// Generate .idaInput string
/* IDAFileWriter idaFileWriter = new IDAFileWriter(sim);
File idaInputFile = new File(filePathName.replace(".vcml", ".idaInput"));
PrintWriter idaPW = new java.io.PrintWriter(idaInputFile);
idaFileWriter.writeInputFile(idaPW);
idaPW.close();
// use the idastandalone solver
File idaOutputFile = new File(filePathName.replace(".vcml", ".ida"));
Executable executable = new Executable("IDAStandalone " + idaInputFile + " " + idaOutputFile);
executable.start();
*/
// Generate .cvodeInput string
File cvodeFile = new File(outDir, filePrefix + SimDataConstants.CVODEINPUT_DATA_EXTENSION);
PrintWriter cvodePW = new java.io.PrintWriter(cvodeFile);
SimulationJob simJob = new SimulationJob(sim, 0, null);
SimulationTask simTask = new SimulationTask(simJob, 0);
CVodeFileWriter cvodeFileWriter = new CVodeFileWriter(cvodePW, simTask);
cvodeFileWriter.write();
cvodePW.close();
// use the cvodeStandalone solver
File cvodeOutputFile = new File(outDir, filePrefix + SimDataConstants.IDA_DATA_EXTENSION);
String executableName = null;
try {
executableName = SolverUtilities.getExes(SolverDescription.CVODE)[0].getAbsolutePath();
} catch (IOException e) {
throw new RuntimeException("failed to get executable for solver " + SolverDescription.CVODE.getDisplayLabel() + ": " + e.getMessage(), e);
}
Executable executable = new Executable(new String[] { executableName, cvodeFile.getAbsolutePath(), cvodeOutputFile.getAbsolutePath() });
executable.start();
// get the result
ODESolverResultSet odeSolverResultSet = getODESolverResultSet(simJob, cvodeOutputFile.getPath());
//
// print header
//
File outputFile = new File(outDir, filePrefix + ".vcell.csv");
java.io.PrintStream outputStream = new java.io.PrintStream(new java.io.BufferedOutputStream(new java.io.FileOutputStream(outputFile)));
outputStream.print("time");
for (int i = 0; i < testSpec.getVarsList().length; i++) {
outputStream.print("," + testSpec.getVarsList()[i]);
}
outputStream.println();
//
// extract data for time and species
//
double[][] data = new double[testSpec.getVarsList().length + 1][];
int column = odeSolverResultSet.findColumn("t");
data[0] = odeSolverResultSet.extractColumn(column);
int origDataLength = data[0].length;
for (int i = 0; i < testSpec.getVarsList().length; i++) {
column = odeSolverResultSet.findColumn(testSpec.getVarsList()[i]);
if (column == -1) {
Variable var = simJob.getSimulationSymbolTable().getVariable(testSpec.getVarsList()[i]);
data[i + 1] = new double[data[0].length];
if (var instanceof cbit.vcell.math.Constant) {
double value = ((cbit.vcell.math.Constant) var).getExpression().evaluateConstant();
for (int j = 0; j < data[i + 1].length; j++) {
data[i + 1][j] = value;
}
} else {
throw new RuntimeException("Did not find " + testSpec.getVarsList()[i] + " in simulation");
}
} else {
data[i + 1] = odeSolverResultSet.extractColumn(column);
}
}
//
// for each time, print row
//
int index = 0;
double[] sampleTimes = new double[testSpec.getNumTimeSteps() + 1];
for (int i = 0; i <= testSpec.getNumTimeSteps(); i++) {
sampleTimes[i] = endTime * i / testSpec.getNumTimeSteps();
}
Model vcModel = bioModel.getModel();
ReservedSymbol kMole = vcModel.getKMOLE();
for (int i = 0; i < sampleTimes.length; i++) {
//
while (true) {
//
if (index == odeSolverResultSet.getRowCount() - 1) {
if (data[0][index] == sampleTimes[i]) {
break;
} else {
throw new RuntimeException("sampleTime does not match at last time point");
}
}
//
if (data[0][index + 1] > sampleTimes[i]) {
break;
}
//
// sampleTime must be later in our data list.
//
index++;
}
// if data[0][index] == sampleTime no need to interpolate
if (data[0][index] == sampleTimes[i]) {
// if timeFactor is not 1.0, time is not in seconds (mins or hrs); if timeFactor is 60, divide sampleTime/60; if it is 3600, divide sampleTime/3600.
// if (timeFactor != 1.0) {
// outputStream.print(data[0][index]/timeFactor);
// } else {
outputStream.print(data[0][index]);
// }
for (int j = 0; j < testSpec.getVarsList().length; j++) {
// SBMLImporter.SBVCConcentrationUnits spConcUnits = speciesUnitsHash.get(testSpec.getVarsList()[j]);
// if (spConcUnits != null) {
// VCUnitDefinition sbunits = spConcUnits.getSBConcentrationUnits();
// VCUnitDefinition vcunits = spConcUnits.getVCConcentrationUnits();
// SBMLUnitParameter unitFactor = SBMLUtils.getConcUnitFactor("spConcParam", vcunits, sbunits, kMole);
// outputStream.print("," + data[j + 1][index] * unitFactor.getExpression().evaluateConstant()); //earlier, hack unitfactor = 0.000001
// earlier, hack unitfactor = 0.000001
outputStream.print("," + data[j + 1][index]);
// }
}
// System.out.println("No interpolation needed!");
outputStream.println();
} else {
// if data[0][index] < sampleTime, must interpolate
double fraction = (sampleTimes[i] - data[0][index]) / (data[0][index + 1] - data[0][index]);
// if timeFactor is not 1.0, time is not in seconds (mins or hrs); if timeFactor is 60, divide sampleTime/60; if it is 3600, divide sampleTime/3600.
// if (timeFactor != 1.0) {
// outputStream.print(sampleTimes[i]/timeFactor);
// } else {
outputStream.print(sampleTimes[i]);
// }
for (int j = 0; j < testSpec.getVarsList().length; j++) {
double interpolatedValue = 0.0;
double[] speciesVals = null;
double[] times = null;
// Currently using 2nd order interpolation
if (index == 0) {
// can only do 1st order interpolation
times = new double[] { data[0][index], data[0][index + 1] };
speciesVals = new double[] { data[j + 1][index], data[j + 1][index + 1] };
interpolatedValue = MathTestingUtilities.taylorInterpolation(sampleTimes[i], times, speciesVals);
} else if (index >= 1 && index <= origDataLength - 3) {
double val_1 = Math.abs(sampleTimes[i] - data[0][index - 1]);
double val_2 = Math.abs(sampleTimes[i] - data[0][index + 2]);
if (val_1 < val_2) {
times = new double[] { data[0][index - 1], data[0][index], data[0][index + 1] };
speciesVals = new double[] { data[j + 1][index - 1], data[j + 1][index], data[j + 1][index + 1] };
} else {
times = new double[] { data[0][index], data[0][index + 1], data[0][index + 2] };
speciesVals = new double[] { data[j + 1][index], data[j + 1][index + 1], data[j + 1][index + 2] };
}
interpolatedValue = MathTestingUtilities.taylorInterpolation(sampleTimes[i], times, speciesVals);
} else {
times = new double[] { data[0][index - 1], data[0][index], data[0][index + 1] };
speciesVals = new double[] { data[j + 1][index - 1], data[j + 1][index], data[j + 1][index + 1] };
interpolatedValue = MathTestingUtilities.taylorInterpolation(sampleTimes[i], times, speciesVals);
}
// // Currently using 1st order interpolation
// times = new double[] { data[0][index], data[0][index+1] };
// speciesVals = new double[] { data[j+1][index], data[j+1][index+1] };
// interpolatedValue = taylorInterpolation(sampleTimes[i], times, speciesVals);
// interpolatedValue = interpolatedValue * unitFactor.getExpression().evaluateConstant(); //earlier, hack unitfactor = 0.000001
// System.out.println("Sample time: " + sampleTimes[i] + ", between time[" + index + "]=" + data[0][index]+" and time["+(index+1)+"]="+(data[0][index+1])+", interpolated = "+interpolatedValue);
outputStream.print("," + interpolatedValue);
}
outputStream.println();
}
}
outputStream.close();
return outputFile;
} catch (RuntimeException e) {
e.printStackTrace(System.out);
// rethrow without losing context
throw e;
} catch (Exception e) {
e.printStackTrace(System.out);
throw new SolverException(e.getMessage(), e);
}
}
Aggregations