use of cbit.vcell.solver.SimulationJob in project vcell by virtualcell.
the class ClientSimManager method runQuickSimulation.
public void runQuickSimulation(final Simulation originalSimulation, ViewerType viewerType) {
Collection<AsynchClientTask> taskList = new ArrayList<AsynchClientTask>();
final SimulationOwner simulationOwner = simWorkspace.getSimulationOwner();
// ----------- update math if it is from biomodel (simulationContext)
if (simulationOwner instanceof SimulationContext) {
Collection<AsynchClientTask> ut = ClientRequestManager.updateMath(documentWindowManager.getComponent(), ((SimulationContext) simulationOwner), false, NetworkGenerationRequirements.ComputeFullStandardTimeout);
taskList.addAll(ut);
}
// ----------- run simulation(s)
final File localSimDataDir = ResourceUtil.getLocalSimDir(User.tempUser.getName());
AsynchClientTask runSimTask = new AsynchClientTask("running simulation", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
Simulation simulation = new TempSimulation(originalSimulation, false);
SimulationTask simTask = new SimulationTask(new SimulationJob(simulation, 0, null), 0);
Solver solver = createQuickRunSolver(localSimDataDir, simTask);
if (solver == null) {
throw new RuntimeException("null solver");
}
// check if spatial stochastic simulation (smoldyn solver) has data processing instructions with field data - need to access server for field data, so cannot do local simulation run.
if (solver instanceof SmoldynSolver) {
DataProcessingInstructions dpi = simulation.getDataProcessingInstructions();
if (dpi != null) {
FieldDataIdentifierSpec fdis = dpi.getSampleImageFieldData(simulation.getVersion().getOwner());
if (fdis != null) {
throw new RuntimeException("Spatial Stochastic simulation '" + simulation.getName() + "' (Smoldyn solver) with field data (in data processing instructions) cannot be run locally at this time since field data needs to be retrieved from the VCell server.");
}
}
}
solver.addSolverListener(new SolverListener() {
public void solverStopped(SolverEvent event) {
getClientTaskStatusSupport().setMessage(event.getSimulationMessage().getDisplayMessage());
}
public void solverStarting(SolverEvent event) {
String displayMessage = event.getSimulationMessage().getDisplayMessage();
System.out.println(displayMessage);
getClientTaskStatusSupport().setMessage(displayMessage);
if (displayMessage.equals(SimulationMessage.MESSAGE_SOLVEREVENT_STARTING_INIT.getDisplayMessage())) {
getClientTaskStatusSupport().setProgress(75);
} else if (displayMessage.equals(SimulationMessage.MESSAGE_SOLVER_RUNNING_INPUT_FILE.getDisplayMessage())) {
getClientTaskStatusSupport().setProgress(90);
}
}
public void solverProgress(SolverEvent event) {
getClientTaskStatusSupport().setMessage("Running...");
int progress = (int) (event.getProgress() * 100);
getClientTaskStatusSupport().setProgress(progress);
}
public void solverPrinted(SolverEvent event) {
getClientTaskStatusSupport().setMessage("Running...");
}
public void solverFinished(SolverEvent event) {
getClientTaskStatusSupport().setMessage(event.getSimulationMessage().getDisplayMessage());
}
public void solverAborted(SolverEvent event) {
getClientTaskStatusSupport().setMessage(event.getSimulationMessage().getDisplayMessage());
}
});
solver.startSolver();
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
if (getClientTaskStatusSupport().isInterrupted()) {
solver.stopSolver();
throw UserCancelException.CANCEL_GENERIC;
}
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;
}
}
}
ArrayList<AnnotatedFunction> outputFunctionsList = getSimWorkspace().getSimulationOwner().getOutputFunctionContext().getOutputFunctionsList();
OutputContext outputContext = new OutputContext(outputFunctionsList.toArray(new AnnotatedFunction[outputFunctionsList.size()]));
Simulation[] simsArray = new Simulation[] { simulation };
hashTable.put("outputContext", outputContext);
hashTable.put("simsArray", simsArray);
}
};
taskList.add(runSimTask);
// --------- add tasks from showSimResults : retrieve data, display results
AsynchClientTask[] showResultsTask = showSimulationResults0(true, viewerType);
for (AsynchClientTask task : showResultsTask) {
taskList.add(task);
}
// ------- dispatch
AsynchClientTask[] taskArray = new AsynchClientTask[taskList.size()];
taskList.toArray(taskArray);
ClientTaskDispatcher.dispatch(documentWindowManager.getComponent(), new Hashtable<String, Object>(), taskArray, true, true, null);
}
use of cbit.vcell.solver.SimulationJob in project vcell by virtualcell.
the class FVSolverStandalone method initialize.
//
//
// /**
// * Insert the method's description here.
// * Creation date: (6/27/2001 2:33:03 PM)
// */
// public void propertyChange(java.beans.PropertyChangeEvent event) {
// super.propertyChange(event);
//
// if (event.getSource() == getMathExecutable() && event.getPropertyName().equals("applicationMessage")) {
// String messageString = (String)event.getNewValue();
// if (messageString==null || messageString.length()==0){
// return;
// }
// ApplicationMessage appMessage = getApplicationMessage(messageString);
// if (appMessage!=null && appMessage.getMessageType() == ApplicationMessage.DATA_MESSAGE) {
// fireSolverPrinted(appMessage.getTimepoint());
// }
// }
// }
/**
* This method was created by a SmartGuide.
*/
protected void initialize() throws SolverException {
try {
Simulation sim = simTask.getSimulation();
if (sim.isSerialParameterScan()) {
// write functions file for all the simulations in the scan
for (int scan = 0; scan < sim.getScanCount(); scan++) {
SimulationJob simJob = new SimulationJob(sim, scan, simTask.getSimulationJob().getFieldDataIdentifierSpecs());
// ** Dumping the functions of a simulation into a '.functions' file.
String basename = new File(getSaveDirectory(), simJob.getSimulationJobID()).getPath();
String functionFileName = basename + FUNCTIONFILE_EXTENSION;
Vector<AnnotatedFunction> funcList = simJob.getSimulationSymbolTable().createAnnotatedFunctionsList(simTask.getSimulation().getMathDescription());
// Try to save existing user defined functions
try {
File existingFunctionFile = new File(functionFileName);
if (existingFunctionFile.exists()) {
Vector<AnnotatedFunction> oldFuncList = FunctionFileGenerator.readFunctionsFile(existingFunctionFile, simTask.getSimulationJobID());
for (AnnotatedFunction func : oldFuncList) {
if (func.isOldUserDefined()) {
funcList.add(func);
}
}
}
} catch (Exception e) {
e.printStackTrace();
// ignore
}
// Try to save existing user defined functions
FunctionFileGenerator functionFileGenerator = new FunctionFileGenerator(functionFileName, funcList);
try {
functionFileGenerator.generateFunctionFile();
} catch (Exception e) {
e.printStackTrace(System.out);
throw new RuntimeException("Error creating .function file for " + functionFileGenerator.getBasefileName() + e.getMessage());
}
}
} else {
writeFunctionsFile();
}
// not for Chombo solver
if (!isChombo) {
writeVCGAndResampleFieldData();
}
setSolverStatus(new SolverStatus(SolverStatus.SOLVER_RUNNING, SimulationMessage.MESSAGE_SOLVER_RUNNING_INIT));
fireSolverStarting(SimulationMessage.MESSAGE_SOLVEREVENT_STARTING_INIT);
setSolverStatus(new SolverStatus(SolverStatus.SOLVER_RUNNING, SimulationMessage.MESSAGE_SOLVER_RUNNING_INPUT_FILE));
File fvinputFile = new File(getInputFilename());
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileWriter(fvinputFile));
new FiniteVolumeFileWriter(pw, simTask, getResampledGeometry(), getSaveDirectory(), destinationDirectory, bMessaging).write();
} finally {
if (pw != null) {
pw.close();
}
}
} catch (Exception ex) {
ex.printStackTrace(System.out);
throw new SolverException(ex.getMessage());
}
}
use of cbit.vcell.solver.SimulationJob in project vcell by virtualcell.
the class LocalSolverController method solverAborted.
/**
* Invoked when the solver aborts a calculation (abnormal termination).
* @param event indicates the solver and the event type
*/
public void solverAborted(SolverEvent event) {
try {
if (lg.isTraceEnabled())
lg.trace("LocalSolverController Caught solverAborted(" + event.getSource().toString() + ",error='" + event.getSimulationMessage() + "')");
SimulationJob simJob = getSimulationTask().getSimulationJob();
if (serialParameterScanJobIndex >= 0) {
SimulationTask newSimTask = new SimulationTask(new SimulationJob(simJob.getSimulation(), serialParameterScanJobIndex, simJob.getFieldDataIdentifierSpecs()), getSimulationTask().getTaskID());
fireWorkerEvent(new WorkerEvent(WorkerEvent.JOB_FAILURE, this, newSimTask, hostname, event.getSimulationMessage()));
} else {
fireWorkerEvent(new WorkerEvent(WorkerEvent.JOB_FAILURE, this, getSimulationTask(), hostname, event.getSimulationMessage()));
}
} catch (Throwable e) {
lg.error(e.getMessage(), e);
}
}
use of cbit.vcell.solver.SimulationJob 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;
}
use of cbit.vcell.solver.SimulationJob in project vcell by virtualcell.
the class HybridSolverTester method runHybridTest.
public void runHybridTest(String site) {
try {
double[] timePoints = null;
File mathModelFile = new File(mathModelVCMLFileName);
XMLSource vcmlSource = new XMLSource(mathModelFile);
MathModel mathModel = XmlHelper.XMLToMathModel(vcmlSource);
File simDataDir = mathModelFile.getParentFile();
Simulation sim = mathModel.getSimulations()[0];
// run multiple trials and each run will have a simID = origSimID + i
for (int i = 0; i < numRuns; i++) {
System.out.println("--------------Trial No: " + (startTrialNo + i) + "----------------");
// replace random seed
sim.getSolverTaskDescription().getSmoldynSimulationOptions().setRandomSeed(new Integer(startTrialNo + i));
// create sim job
int jobIndex = startTrialNo + i;
SimulationTask simTask = new SimulationTask(new SimulationJob(sim, jobIndex, null), 0);
/*
* When you want to run the multiple trials on local uncomment the line below.
*/
// ResourceUtil.prepareSolverExecutable(sim.getSolverTaskDescription().getSolverDescription());
/*
* When you want to run the multiple trials on server (without VCell user interface), use the next line of code
* Corresponding changes should be made in the shell script runhybridtest for the location of executable on server
*/
FVSolverStandalone fvSolver = new FVSolverStandalone(simTask, simDataDir, false);
fvSolver.startSolver();
SolverStatus status = fvSolver.getSolverStatus();
while (status.getStatus() != SolverStatus.SOLVER_FINISHED && status.getStatus() != SolverStatus.SOLVER_ABORTED) {
System.out.println("progress: " + (int) (fvSolver.getProgress() * 100) + "%");
// ask status every 2 seconds
Thread.sleep(2000);
status = fvSolver.getSolverStatus();
}
if (status.getStatus() == SolverStatus.SOLVER_FINISHED) {
// get data
VCSimulationIdentifier vcSimID = new VCSimulationIdentifier(sim.getVersion().getVersionKey(), sim.getVersion().getOwner());
VCSimulationDataIdentifier vcSimDataID = new VCSimulationDataIdentifier(vcSimID, jobIndex);
File hdf5File = new File(simDataDir, vcSimDataID.getID() + SimDataConstants.DATA_PROCESSING_OUTPUT_EXTENSION_HDF5);
DataOperationResults.DataProcessingOutputInfo dataProcessingOutputInfo = (DataOperationResults.DataProcessingOutputInfo) DataSetControllerImpl.getDataProcessingOutput(new DataOperation.DataProcessingOutputInfoOP(vcSimDataID, false, null), hdf5File);
if (i == 0) {
// do only one time
timePoints = dataProcessingOutputInfo.getVariableTimePoints();
for (int j = 0; j < varNames.length; j++) {
// row: numTimePoints, col:first col time + numRuns
double[][] data = new double[numRuns + 1][timePoints.length];
data[0] = timePoints;
results.add(data);
}
}
// write into results after each run
for (int j = 0; j < varNames.length; j++) {
results.get(j)[i + 1] = dataProcessingOutputInfo.getVariableStatValues().get(varNames[j]);
}
// delete the file generated for this run
deleteSimFiles(simDataDir, vcSimDataID);
} else {
throw new Exception("Sover did not finish normally." + status);
}
}
// write to output file, tab delimited
if (results != null && results.size() > 0) {
for (int j = 0; j < varNames.length; j++) {
File file = new File(simDataDir, "SimID_" + sim.getVersion().getVersionKey().toString() + "_" + varNames[j] + "_" + startTrialNo + ".txt");
PrintWriter pw = new PrintWriter(file);
double[][] data = results.get(j);
if (data != null) {
for (int k = 0; k < data.length; k++) {
if (!bPrintTime && k == 0) {
continue;
}
String rowStr = (k == 0) ? "Time\t" : ("trialNo_" + (startTrialNo + k - 1) + "\t");
double[] rowData = data[k];
for (int q = 0; q < rowData.length; q++) {
rowStr += rowData[q] + "\t";
}
pw.println(rowStr);
}
}
pw.close();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Aggregations