use of cbit.vcell.solver.SimulationSymbolTable in project vcell by virtualcell.
the class SimulationWorkspace method checkSimulationParameters.
/**
* Insert the method's description here.
* Creation date: (5/11/2004 2:57:10 PM)
* @return boolean
* @param simulation cbit.vcell.solver.Simulation
*/
private static boolean checkSimulationParameters(Simulation simulation, Component parent) {
SimulationSymbolTable simSymbolTable = new SimulationSymbolTable(simulation, 0);
String errorMessage = null;
long maxTimepoints = Simulation.MAX_LIMIT_NON_SPATIAL_TIMEPOINTS;
long warningTimepoints = Simulation.WARNING_NON_SPATIAL_TIMEPOINTS;
boolean bSpatial = simulation.isSpatial();
if (bSpatial) {
maxTimepoints = Simulation.MAX_LIMIT_SPATIAL_TIMEPOINTS;
warningTimepoints = Simulation.WARNING_SPATIAL_TIMEPOINTS;
}
long maxSizeBytes = megabytesToBytes(Simulation.MAX_LIMIT_0DE_MEGABYTES);
long warningSizeBytes = megabytesToBytes(Simulation.WARNING_0DE_MEGABYTES);
if (bSpatial) {
maxSizeBytes = megabytesToBytes(Simulation.MAX_LIMIT_PDE_MEGABYTES);
warningSizeBytes = megabytesToBytes(Simulation.WARNING_PDE_MEGABYTES);
} else if (simulation.getMathDescription().isNonSpatialStoch()) {
maxSizeBytes = megabytesToBytes(Simulation.MAX_LIMIT_STOCH_MEGABYTES);
warningSizeBytes = megabytesToBytes(Simulation.WARNING_STOCH_MEGABYTES);
}
long expectedNumTimePoints = getExpectedNumTimePoints(simulation);
long expectedSizeBytes = getExpectedSizeBytes(simSymbolTable);
//
// check for error conditions (hard limits on resources) ... Note: each user should have it's own limits (and quotas).
//
SolverTaskDescription solverTaskDescription = simulation.getSolverTaskDescription();
SolverDescription solverDescription = solverTaskDescription.getSolverDescription();
if (expectedNumTimePoints > maxTimepoints) {
errorMessage = "Errors in Simulation: '" + simulation.getName() + "'!\n" + "The simulation has too many timepoints (" + expectedNumTimePoints + ") to be saved, which has exceeded our limit.\n\n" + "maximum saving timepoints limits are:\n" + " " + Simulation.MAX_LIMIT_NON_SPATIAL_TIMEPOINTS + " for compartmental simulations\n" + " " + Simulation.MAX_LIMIT_SPATIAL_TIMEPOINTS + " for spatial simulations\n" + "suggested saving timepoints limits are:\n" + " " + Simulation.WARNING_NON_SPATIAL_TIMEPOINTS + " for compartmental simulations\n" + " " + Simulation.WARNING_SPATIAL_TIMEPOINTS + " for spatial simulations\n" + "Try saving fewer timepoints\n" + "If you need to exceed the quota, please contact us";
// not used for multiple stochastic run
if (solverTaskDescription.getStochOpt() != null && solverTaskDescription.getStochOpt().getNumOfTrials() > 1) {
errorMessage = null;
}
} else if (expectedSizeBytes > maxSizeBytes) {
errorMessage = "Errors in Simulation: '" + simulation.getName() + "'!\n" + "The simulation's result dataset (" + CodeUtil.humanBytePrint(expectedSizeBytes) + ") is too large, which has exceeded our limit.\n\n" + "maximum size limits are:\n" + " " + Simulation.MAX_LIMIT_0DE_MEGABYTES + " MB for compartmental ODE simulations\n" + " " + Simulation.MAX_LIMIT_PDE_MEGABYTES + " MB for spatial simulations\n" + " " + Simulation.MAX_LIMIT_STOCH_MEGABYTES + " MB for compartmental stochastic simulations\n" + "suggested size limits are:\n" + " " + Simulation.WARNING_0DE_MEGABYTES + " MB for compartmental ODE simulations\n" + " " + Simulation.WARNING_PDE_MEGABYTES + " MB for spatial simulations\n" + " " + Simulation.WARNING_STOCH_MEGABYTES + " MB for compartmental stochastic simulations\n" + "Try saving fewer timepoints or using a smaller mesh (if spatial)\n" + "If you need to exceed the quota, please contact us";
// not used for multiple stochastic run
if (solverTaskDescription.getStochOpt() != null && solverTaskDescription.getStochOpt().getNumOfTrials() > 1) {
errorMessage = null;
}
} else if (simulation.getScanCount() > Simulation.MAX_LIMIT_SCAN_JOBS) {
errorMessage = "Errors in Simulation: '" + simulation.getName() + "'!\n" + "The simulation generates too many simulations (" + simulation.getScanCount() + ") required for parameter scan, which has exceeded our limit.\n\n" + "maximum number of parameter sets is: " + Simulation.MAX_LIMIT_SCAN_JOBS + " \n" + "suggested limit for number of parameter sets is: " + Simulation.WARNING_SCAN_JOBS + " \n" + "Try choosing fewer parameters or reducing the size of scan for each parameter.";
// not used for multiple stochastic run
if (simulation.getMathDescription().isNonSpatialStoch() && solverTaskDescription.getStochOpt() != null && solverTaskDescription.getStochOpt().getNumOfTrials() > 1) {
errorMessage = null;
}
} else if (solverDescription.equals(SolverDescription.SundialsPDE)) {
if (solverTaskDescription.getOutputTimeSpec().isDefault()) {
DefaultOutputTimeSpec dot = (DefaultOutputTimeSpec) solverTaskDescription.getOutputTimeSpec();
int maxNumberOfSteps = dot.getKeepEvery() * dot.getKeepAtMost();
double maximumTimeStep = solverTaskDescription.getTimeStep().getMaximumTimeStep();
double maxSimTime = maxNumberOfSteps * maximumTimeStep;
double endingTime = solverTaskDescription.getTimeBounds().getEndingTime();
if (maxSimTime < endingTime) {
errorMessage = "Errors in Simulation: '" + simulation.getName() + "'!\n" + "The maximum possible simulation time (keepEvery * maxTimestep * keepAtMost = " + maxSimTime + ") is less than simulation end time (" + endingTime + ").\n\n" + "You have chosen a variable time step solver and specified a maximum number of time steps of " + maxNumberOfSteps + " (keepEvery*keepAtMost). " + "Actual time steps are often small, but even if all steps were at the maximum time step of " + maximumTimeStep + ", the simulation end time of " + endingTime + " would not be reached. \n\n" + "Either adjust the parameters or choose the \"Output Interval\" option.";
}
}
} else if (simulation.getMathDescription().isNonSpatialStoch() && !(solverDescription.isNonSpatialStochasticSolver())) {
// to guarantee stochastic model uses stochastic methods and deterministic model uses ODE/PDE methods.
errorMessage = "Errors in Simulation: '" + simulation.getName() + "'!\n" + "Stochastic simulation(s) must use stochastic solver(s).\n" + solverDescription.getDisplayLabel() + " is not a stochastic solver!";
} else if (!simulation.getMathDescription().isNonSpatialStoch() && (solverDescription.isNonSpatialStochasticSolver())) {
errorMessage = "Errors in Simulation: '" + simulation.getName() + "'!\n" + "ODE/PDE simulation(s) must use ODE/PDE solver(s).\n" + solverDescription.getDisplayLabel() + " is not a ODE/PDE solver!";
} else if (simulation.getSolverTaskDescription().getSolverDescription().isChomboSolver()) {
MeshSpecification meshSpecification = simulation.getMeshSpecification();
boolean bCellCentered = simulation.hasCellCenteredMesh();
if (meshSpecification != null && !meshSpecification.isAspectRatioOK(1e-4, bCellCentered)) {
errorMessage = "Non uniform spatial step is detected. This will affect the accuracy of the solution.\n\n" + "\u0394x=" + meshSpecification.getDx(bCellCentered) + "\n" + "\u0394y=" + meshSpecification.getDy(bCellCentered) + (meshSpecification.getGeometry().getDimension() < 3 ? "" : "\n\u0394z=" + meshSpecification.getDz(bCellCentered));
}
} else {
errorMessage = null;
}
if (errorMessage != null) {
DialogUtils.showErrorDialog(parent, errorMessage);
return false;
} else if (simulation.getSolverTaskDescription().getSolverDescription().isChomboSolver()) {
Geometry geometry = simulation.getMathDescription().getGeometry();
ChomboMeshValidator meshValidator = new ChomboMeshValidator(geometry, simulation.getSolverTaskDescription().getChomboSolverSpec());
ChomboMeshRecommendation chomboMeshRecommendation = meshValidator.computeMeshSpecs();
boolean bValid = chomboMeshRecommendation.validate();
if (!bValid) {
String option = DialogUtils.showWarningDialog(parent, "Error", chomboMeshRecommendation.getErrorMessage(), chomboMeshRecommendation.getDialogOptions(), ChomboMeshRecommendation.optionClose);
if (ChomboMeshRecommendation.optionSuggestions.equals(option)) {
DialogUtils.showInfoDialog(parent, ChomboMeshRecommendation.optionSuggestions, chomboMeshRecommendation.getMeshSuggestions());
}
}
return bValid;
} else {
String warningMessage = null;
// don't check warning message for stochastic multiple trials, let it run.
if (simulation.getMathDescription().isNonSpatialStoch() && simulation.getSolverTaskDescription().getStochOpt() != null && simulation.getSolverTaskDescription().getStochOpt().getNumOfTrials() > 1) {
return true;
}
//
if (expectedNumTimePoints > warningTimepoints) {
warningMessage = "Warnings from Simulation: '" + simulation.getName() + "'!\n" + "The simulation has large number of saving timepoints (" + expectedNumTimePoints + "), suggested saving timepoints limits are:\n" + " " + Simulation.WARNING_NON_SPATIAL_TIMEPOINTS + " for compartmental simulations\n" + " " + Simulation.WARNING_SPATIAL_TIMEPOINTS + " for spatial simulations\n" + "Try saving fewer timepoints";
} else if (expectedSizeBytes > warningSizeBytes) {
warningMessage = "Warnings from Simulation: '" + simulation.getName() + "'!\n" + "The simulation has large result dataset (" + (expectedSizeBytes / 1000000L) + "MB), suggested size limits are:\n" + " " + Simulation.WARNING_0DE_MEGABYTES + " MB for compartmental ODE simulations\n" + " " + Simulation.WARNING_PDE_MEGABYTES + " MB for spatial simulations\n" + " " + Simulation.WARNING_STOCH_MEGABYTES + " MB for compartmental stochastic simulations\n" + "Try saving fewer timepoints or using a coarser mesh if spatial.";
} else if (simulation.getScanCount() > Simulation.WARNING_SCAN_JOBS) {
warningMessage = "Warnings from Simulation: '" + simulation.getName() + "'!\n" + "The simulation generates a large number of simulations (" + simulation.getScanCount() + ") required for parameter scan.\n" + "maximum number of parameter sets is: " + Simulation.MAX_LIMIT_SCAN_JOBS + " \n" + "suggested limit for the number of parameter sets is: " + Simulation.WARNING_SCAN_JOBS + " \n" + "Try choosing fewer parameters or reducing the size of scan for each parameter.";
}
if (solverDescription.equals(SolverDescription.SundialsPDE)) {
if (solverTaskDescription.getErrorTolerance().getRelativeErrorTolerance() > 1e-4) {
String msg = "Warnings from Simulation: '" + simulation.getName() + "'!\n" + "Warning: it is not reccomended to use a relative tolerance that is greater than \n1e-4 for " + solverDescription.getDisplayLabel() + ".";
warningMessage = warningMessage == null ? msg : warningMessage + "\n\n" + msg;
}
} else if (solverDescription.isSemiImplicitPdeSolver()) {
if (solverTaskDescription.getErrorTolerance().getRelativeErrorTolerance() > 1e-8) {
String msg = "Warnings from Simulation: '" + simulation.getName() + "'!\n" + "Warning: it is not reccomended to use a relative tolerance that is greater than \n1e-8 for " + solverDescription.getDisplayLabel() + ".";
warningMessage = warningMessage == null ? msg : warningMessage + "\n\n" + msg;
}
}
MeshSpecification meshSpecification = simulation.getMeshSpecification();
boolean bCellCentered = simulation.hasCellCenteredMesh();
if (meshSpecification != null && !meshSpecification.isAspectRatioOK(bCellCentered)) {
warningMessage = (warningMessage == null ? "" : warningMessage + "\n\n") + "Non uniform spatial step is detected. This might affect the accuracy of the solution.\n\n" + "\u0394x=" + meshSpecification.getDx(bCellCentered) + "\n" + "\u0394y=" + meshSpecification.getDy(bCellCentered) + (meshSpecification.getGeometry().getDimension() < 3 ? "" : "\n\u0394z=" + meshSpecification.getDz(bCellCentered));
}
if (warningMessage != null) {
String result = DialogUtils.showWarningDialog(parent, warningMessage + "\n\nDo you want to continue anyway?", new String[] { UserMessage.OPTION_OK, UserMessage.OPTION_CANCEL }, UserMessage.OPTION_OK);
return (result != null && result.equals(UserMessage.OPTION_OK));
} else {
return true;
}
}
}
use of cbit.vcell.solver.SimulationSymbolTable in project vcell by virtualcell.
the class SimulationWorkspace method checkSimulationParameters.
/**
* Insert the method's description here.
* Creation date: (5/11/2004 2:57:10 PM)
* @return boolean
* @param simulation cbit.vcell.solver.Simulation
*/
private static boolean checkSimulationParameters(Simulation simulation, Component parent, boolean bCheckLimits) {
SimulationSymbolTable simSymbolTable = new SimulationSymbolTable(simulation, 0);
String errorMessage = null;
long maxTimepoints = Simulation.MAX_LIMIT_NON_SPATIAL_TIMEPOINTS;
long warningTimepoints = Simulation.WARNING_NON_SPATIAL_TIMEPOINTS;
boolean bSpatial = simulation.isSpatial();
if (bSpatial) {
maxTimepoints = Simulation.MAX_LIMIT_SPATIAL_TIMEPOINTS;
warningTimepoints = Simulation.WARNING_SPATIAL_TIMEPOINTS;
}
long maxSizeBytes = megabytesToBytes(Simulation.MAX_LIMIT_0DE_MEGABYTES);
long warningSizeBytes = megabytesToBytes(Simulation.WARNING_0DE_MEGABYTES);
if (bSpatial) {
maxSizeBytes = megabytesToBytes(Simulation.MAX_LIMIT_PDE_MEGABYTES);
warningSizeBytes = megabytesToBytes(Simulation.WARNING_PDE_MEGABYTES);
} else if (simulation.getMathDescription().isNonSpatialStoch()) {
maxSizeBytes = megabytesToBytes(Simulation.MAX_LIMIT_STOCH_MEGABYTES);
warningSizeBytes = megabytesToBytes(Simulation.WARNING_STOCH_MEGABYTES);
}
long expectedNumTimePoints = getExpectedNumTimePoints(simulation);
long expectedSizeBytes = getExpectedSizeBytes(simSymbolTable);
//
// check for error conditions (hard limits on resources) ... Note: each user should have it's own limits (and quotas).
//
SolverTaskDescription solverTaskDescription = simulation.getSolverTaskDescription();
SolverDescription solverDescription = solverTaskDescription.getSolverDescription();
if (bCheckLimits && expectedNumTimePoints > maxTimepoints) {
errorMessage = "Errors in Simulation: '" + simulation.getName() + "'!\n" + "The simulation has too many timepoints (" + expectedNumTimePoints + ") to be saved, which has exceeded our limit.\n\n" + "maximum saving timepoints limits are:\n" + " " + Simulation.MAX_LIMIT_NON_SPATIAL_TIMEPOINTS + " for compartmental simulations\n" + " " + Simulation.MAX_LIMIT_SPATIAL_TIMEPOINTS + " for spatial simulations\n" + "suggested saving timepoints limits are:\n" + " " + Simulation.WARNING_NON_SPATIAL_TIMEPOINTS + " for compartmental simulations\n" + " " + Simulation.WARNING_SPATIAL_TIMEPOINTS + " for spatial simulations\n" + "Try saving fewer timepoints\n" + "If you need to exceed the quota, please contact us";
// not used for multiple stochastic run
if (solverTaskDescription.getStochOpt() != null && solverTaskDescription.getStochOpt().getNumOfTrials() > 1) {
errorMessage = null;
}
} else if (bCheckLimits && expectedSizeBytes > maxSizeBytes) {
errorMessage = "Errors in Simulation: '" + simulation.getName() + "'!\n" + "The simulation's result dataset (" + CodeUtil.humanBytePrint(expectedSizeBytes) + ") is too large, which has exceeded our limit.\n\n" + "maximum size limits are:\n" + " " + Simulation.MAX_LIMIT_0DE_MEGABYTES + " MB for compartmental ODE simulations\n" + " " + Simulation.MAX_LIMIT_PDE_MEGABYTES + " MB for spatial simulations\n" + " " + Simulation.MAX_LIMIT_STOCH_MEGABYTES + " MB for compartmental stochastic simulations\n" + "suggested size limits are:\n" + " " + Simulation.WARNING_0DE_MEGABYTES + " MB for compartmental ODE simulations\n" + " " + Simulation.WARNING_PDE_MEGABYTES + " MB for spatial simulations\n" + " " + Simulation.WARNING_STOCH_MEGABYTES + " MB for compartmental stochastic simulations\n" + "Try saving fewer timepoints or using a smaller mesh (if spatial)\n" + "If you need to exceed the quota, please contact us";
// not used for multiple stochastic run
if (solverTaskDescription.getStochOpt() != null && solverTaskDescription.getStochOpt().getNumOfTrials() > 1) {
errorMessage = null;
}
} else if (bCheckLimits && simulation.getScanCount() > Simulation.MAX_LIMIT_SCAN_JOBS) {
errorMessage = "Errors in Simulation: '" + simulation.getName() + "'!\n" + "The simulation generates too many simulations (" + simulation.getScanCount() + ") required for parameter scan, which has exceeded our limit.\n\n" + "maximum number of parameter sets is: " + Simulation.MAX_LIMIT_SCAN_JOBS + " \n" + "suggested limit for number of parameter sets is: " + Simulation.WARNING_SCAN_JOBS + " \n" + "Try choosing fewer parameters or reducing the size of scan for each parameter.";
// not used for multiple stochastic run
if (simulation.getMathDescription().isNonSpatialStoch() && solverTaskDescription.getStochOpt() != null && solverTaskDescription.getStochOpt().getNumOfTrials() > 1) {
errorMessage = null;
}
} else if (solverDescription.equals(SolverDescription.SundialsPDE)) {
if (solverTaskDescription.getOutputTimeSpec().isDefault()) {
DefaultOutputTimeSpec dot = (DefaultOutputTimeSpec) solverTaskDescription.getOutputTimeSpec();
int maxNumberOfSteps = dot.getKeepEvery() * dot.getKeepAtMost();
double maximumTimeStep = solverTaskDescription.getTimeStep().getMaximumTimeStep();
double maxSimTime = maxNumberOfSteps * maximumTimeStep;
double endingTime = solverTaskDescription.getTimeBounds().getEndingTime();
if (maxSimTime < endingTime) {
errorMessage = "Errors in Simulation: '" + simulation.getName() + "'!\n" + "The maximum possible simulation time (keepEvery * maxTimestep * keepAtMost = " + maxSimTime + ") is less than simulation end time (" + endingTime + ").\n\n" + "You have chosen a variable time step solver and specified a maximum number of time steps of " + maxNumberOfSteps + " (keepEvery*keepAtMost). " + "Actual time steps are often small, but even if all steps were at the maximum time step of " + maximumTimeStep + ", the simulation end time of " + endingTime + " would not be reached. \n\n" + "Either adjust the parameters or choose the \"Output Interval\" option.";
}
}
} else if (simulation.getMathDescription().isNonSpatialStoch() && !(solverDescription.isNonSpatialStochasticSolver())) {
// to guarantee stochastic model uses stochastic methods and deterministic model uses ODE/PDE methods.
errorMessage = "Errors in Simulation: '" + simulation.getName() + "'!\n" + "Stochastic simulation(s) must use stochastic solver(s).\n" + solverDescription.getDisplayLabel() + " is not a stochastic solver!";
} else if (!simulation.getMathDescription().isNonSpatialStoch() && (solverDescription.isNonSpatialStochasticSolver())) {
errorMessage = "Errors in Simulation: '" + simulation.getName() + "'!\n" + "ODE/PDE simulation(s) must use ODE/PDE solver(s).\n" + solverDescription.getDisplayLabel() + " is not a ODE/PDE solver!";
} else if (simulation.getSolverTaskDescription().getSolverDescription().isChomboSolver()) {
MeshSpecification meshSpecification = simulation.getMeshSpecification();
boolean bCellCentered = simulation.hasCellCenteredMesh();
if (meshSpecification != null && !meshSpecification.isAspectRatioOK(1e-4, bCellCentered)) {
errorMessage = "Non uniform spatial step is detected. This will affect the accuracy of the solution.\n\n" + "\u0394x=" + meshSpecification.getDx(bCellCentered) + "\n" + "\u0394y=" + meshSpecification.getDy(bCellCentered) + (meshSpecification.getGeometry().getDimension() < 3 ? "" : "\n\u0394z=" + meshSpecification.getDz(bCellCentered));
}
} else {
errorMessage = null;
}
if (errorMessage != null) {
DialogUtils.showErrorDialog(parent, errorMessage);
return false;
} else if (simulation.getSolverTaskDescription().getSolverDescription().isChomboSolver()) {
Geometry geometry = simulation.getMathDescription().getGeometry();
ChomboMeshValidator meshValidator = new ChomboMeshValidator(geometry, simulation.getSolverTaskDescription().getChomboSolverSpec());
ChomboMeshRecommendation chomboMeshRecommendation = meshValidator.computeMeshSpecs();
boolean bValid = chomboMeshRecommendation.validate();
if (!bValid) {
String option = DialogUtils.showWarningDialog(parent, "Error", chomboMeshRecommendation.getErrorMessage(), chomboMeshRecommendation.getDialogOptions(), ChomboMeshRecommendation.optionClose);
if (ChomboMeshRecommendation.optionSuggestions.equals(option)) {
DialogUtils.showInfoDialog(parent, ChomboMeshRecommendation.optionSuggestions, chomboMeshRecommendation.getMeshSuggestions());
}
}
return bValid;
} else {
String warningMessage = null;
// don't check warning message for stochastic multiple trials, let it run.
if (simulation.getMathDescription().isNonSpatialStoch() && simulation.getSolverTaskDescription().getStochOpt() != null && simulation.getSolverTaskDescription().getStochOpt().getNumOfTrials() > 1) {
return true;
}
//
if (expectedNumTimePoints > warningTimepoints) {
warningMessage = "Warnings from Simulation: '" + simulation.getName() + "'!\n" + "The simulation has large number of saving timepoints (" + expectedNumTimePoints + "), suggested saving timepoints limits are:\n" + " " + Simulation.WARNING_NON_SPATIAL_TIMEPOINTS + " for compartmental simulations\n" + " " + Simulation.WARNING_SPATIAL_TIMEPOINTS + " for spatial simulations\n" + "Try saving fewer timepoints";
} else if (expectedSizeBytes > warningSizeBytes) {
warningMessage = "Warnings from Simulation: '" + simulation.getName() + "'!\n" + "The simulation has large result dataset (" + (expectedSizeBytes / 1000000L) + "MB), suggested size limits are:\n" + " " + Simulation.WARNING_0DE_MEGABYTES + " MB for compartmental ODE simulations\n" + " " + Simulation.WARNING_PDE_MEGABYTES + " MB for spatial simulations\n" + " " + Simulation.WARNING_STOCH_MEGABYTES + " MB for compartmental stochastic simulations\n" + "Try saving fewer timepoints or using a coarser mesh if spatial.";
} else if (simulation.getScanCount() > Simulation.WARNING_SCAN_JOBS) {
warningMessage = "Warnings from Simulation: '" + simulation.getName() + "'!\n" + "The simulation generates a large number of simulations (" + simulation.getScanCount() + ") required for parameter scan.\n" + "maximum number of parameter sets is: " + Simulation.MAX_LIMIT_SCAN_JOBS + " \n" + "suggested limit for the number of parameter sets is: " + Simulation.WARNING_SCAN_JOBS + " \n" + "Try choosing fewer parameters or reducing the size of scan for each parameter.";
}
if (solverDescription.equals(SolverDescription.SundialsPDE)) {
if (solverTaskDescription.getErrorTolerance().getRelativeErrorTolerance() > 1e-4) {
String msg = "Warnings from Simulation: '" + simulation.getName() + "'!\n" + "Warning: it is not reccomended to use a relative tolerance that is greater than \n1e-4 for " + solverDescription.getDisplayLabel() + ".";
warningMessage = warningMessage == null ? msg : warningMessage + "\n\n" + msg;
}
} else if (solverDescription.isSemiImplicitPdeSolver()) {
if (solverTaskDescription.getErrorTolerance().getRelativeErrorTolerance() > 1e-8) {
String msg = "Warnings from Simulation: '" + simulation.getName() + "'!\n" + "Warning: it is not reccomended to use a relative tolerance that is greater than \n1e-8 for " + solverDescription.getDisplayLabel() + ".";
warningMessage = warningMessage == null ? msg : warningMessage + "\n\n" + msg;
}
}
MeshSpecification meshSpecification = simulation.getMeshSpecification();
boolean bCellCentered = simulation.hasCellCenteredMesh();
if (meshSpecification != null && !meshSpecification.isAspectRatioOK(bCellCentered)) {
warningMessage = (warningMessage == null ? "" : warningMessage + "\n\n") + "Non uniform spatial step is detected. This might affect the accuracy of the solution.\n\n" + "\u0394x=" + meshSpecification.getDx(bCellCentered) + "\n" + "\u0394y=" + meshSpecification.getDy(bCellCentered) + (meshSpecification.getGeometry().getDimension() < 3 ? "" : "\n\u0394z=" + meshSpecification.getDz(bCellCentered));
}
if (warningMessage != null) {
String result = DialogUtils.showWarningDialog(parent, warningMessage + "\n\nDo you want to continue anyway?", new String[] { UserMessage.OPTION_OK, UserMessage.OPTION_CANCEL }, UserMessage.OPTION_OK);
return (result != null && result.equals(UserMessage.OPTION_OK));
} else {
return true;
}
}
}
use of cbit.vcell.solver.SimulationSymbolTable in project vcell by virtualcell.
the class MovingBoundaryFileWriter method flattenExpression.
private Expression flattenExpression(Expression ex, VariableDomain varDomain) throws ExpressionException, MathException {
SimulationSymbolTable simSymbolTable = simTask.getSimulationJob().getSimulationSymbolTable();
Variable normalX = new Variable("normalX", null) {
public boolean compareEqual(Matchable object, boolean bIgnoreMissingDomains) {
return false;
}
public String getVCML() throws MathException {
return null;
}
};
Variable normalY = new Variable("normalY", null) {
public boolean compareEqual(Matchable object, boolean bIgnoreMissingDomains) {
return false;
}
public String getVCML() throws MathException {
return null;
}
};
SymbolTable augmentedSymbolTable = new SymbolTable() {
@Override
public SymbolTableEntry getEntry(String identifierString) {
if (identifierString.equals(normalX.getName())) {
return normalX;
}
if (identifierString.equals(normalY.getName())) {
return normalY;
}
return simSymbolTable.getEntry(identifierString);
}
@Override
public void getEntries(Map<String, SymbolTableEntry> entryMap) {
simSymbolTable.getEntries(entryMap);
entryMap.put(normalX.getName(), normalX);
entryMap.put(normalY.getName(), normalY);
}
};
ex = new Expression(ex);
ex.bindExpression(augmentedSymbolTable);
Expression flattended = MathUtilities.substituteFunctions(ex, augmentedSymbolTable).flatten();
Expression substituted = SolverUtilities.substituteSizeAndNormalFunctions(flattended, varDomain).flatten();
return substituted;
// return simSymbolTable.substituteFunctions(ex).flatten().infix();
}
use of cbit.vcell.solver.SimulationSymbolTable in project vcell by virtualcell.
the class NFsimXMLWriter method writeNFsimXML.
public static Element writeNFsimXML(SimulationTask origSimTask, long randomSeed, NFsimSimulationOptions nfsimSimulationOptions, boolean bUseLocationMarks) throws SolverException {
try {
System.out.println("VCML ORIGINAL .... START\n" + origSimTask.getSimulation().getMathDescription().getVCML_database() + "\nVCML ORIGINAL .... END\n====================\n");
} catch (MathException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
SimulationTask clonedSimTask = null;
try {
clonedSimTask = (SimulationTask) BeanUtils.cloneSerializable(origSimTask);
} catch (Exception eee) {
throw new SolverException("failed to clone mathDescription while preparing NFSim input: " + eee.getMessage(), eee);
}
MathDescription clonedMathDesc = clonedSimTask.getSimulation().getMathDescription();
if (bUseLocationMarks) {
try {
//
// get list of Compartment Names (stored in locations).
//
ArrayList<String> locations = new ArrayList<String>();
Enumeration<Variable> varEnum = clonedMathDesc.getVariables();
ArrayList<VolumeParticleSpeciesPattern> volumeParticleSpeciesPatterns = new ArrayList<VolumeParticleSpeciesPattern>();
while (varEnum.hasMoreElements()) {
Variable var = varEnum.nextElement();
if (var instanceof VolumeParticleSpeciesPattern) {
VolumeParticleSpeciesPattern speciesPattern = (VolumeParticleSpeciesPattern) var;
if (!locations.contains(speciesPattern.getLocationName())) {
locations.add(speciesPattern.getLocationName());
}
volumeParticleSpeciesPatterns.add(speciesPattern);
}
}
//
for (ParticleMolecularType particleMolecularType : clonedMathDesc.getParticleMolecularTypes()) {
String pmcLocationName = RbmUtils.SiteStruct;
String pmcLocationId = particleMolecularType.getName() + "_" + RbmUtils.SiteStruct;
ParticleMolecularComponent locationComponent = new ParticleMolecularComponent(pmcLocationId, pmcLocationName);
for (String location : locations) {
locationComponent.addComponentStateDefinition(new ParticleComponentStateDefinition(location));
}
particleMolecularType.insertMolecularComponent(0, locationComponent);
String pmcMarkName = RbmUtils.SiteProduct;
String pmcMarkId = particleMolecularType.getName() + "_" + RbmUtils.SiteProduct;
ParticleMolecularComponent markComponent = new ParticleMolecularComponent(pmcMarkId, pmcMarkName);
markComponent.addComponentStateDefinition(new ParticleComponentStateDefinition("0"));
markComponent.addComponentStateDefinition(new ParticleComponentStateDefinition("1"));
particleMolecularType.insertMolecularComponent(1, markComponent);
}
//
for (VolumeParticleSpeciesPattern speciesPattern : volumeParticleSpeciesPatterns) {
for (ParticleMolecularTypePattern molTypePattern : speciesPattern.getParticleMolecularTypePatterns()) {
//
// add location component to pattern ... state=<location>
//
{
final ParticleMolecularComponent locationComponentDefinition = molTypePattern.getMolecularType().getComponentList().get(0);
ParticleMolecularComponentPattern locationPattern = new ParticleMolecularComponentPattern(locationComponentDefinition);
ParticleComponentStateDefinition locationStateDefinition = null;
for (ParticleComponentStateDefinition stateDef : locationComponentDefinition.getComponentStateDefinitions()) {
if (stateDef.getName().equals(speciesPattern.getLocationName())) {
locationStateDefinition = stateDef;
}
}
ParticleComponentStatePattern locationStatePattern = new ParticleComponentStatePattern(locationStateDefinition);
locationPattern.setComponentStatePattern(locationStatePattern);
locationPattern.setBondType(ParticleBondType.None);
locationPattern.setBondId(-1);
molTypePattern.insertMolecularComponentPattern(0, locationPattern);
}
//
// add mark component to pattern ... state="0" (for observables and reactants ... later we will clone and use "1" for products).
{
final ParticleMolecularComponent markComponentDefinition = molTypePattern.getMolecularType().getComponentList().get(1);
ParticleMolecularComponentPattern markPattern = new ParticleMolecularComponentPattern(markComponentDefinition);
final int clearStateIndex = 0;
final int setStateIndex = 1;
ParticleComponentStateDefinition markStateClearedDefinition = markComponentDefinition.getComponentStateDefinitions().get(clearStateIndex);
ParticleComponentStatePattern markStatePattern = new ParticleComponentStatePattern(markStateClearedDefinition);
markPattern.setComponentStatePattern(markStatePattern);
markPattern.setBondType(ParticleBondType.None);
markPattern.setBondId(-1);
molTypePattern.insertMolecularComponentPattern(1, markPattern);
}
}
}
//
// when processing ParticleJumpProcesses, we add a new "product" species pattern (by cloning the original speciesPattern)
// and setting the mark site to "1", change name to name+"_PRODUCT", and add to math model if it doesn't already exist.
//
// cloned the "standard" reactant/observable speciesPattern, set the mark for all molecules, and add to mathDesc.
//
CompartmentSubDomain subDomain = (CompartmentSubDomain) clonedMathDesc.getSubDomains().nextElement();
for (ParticleJumpProcess particleJumpProcess : subDomain.getParticleJumpProcesses()) {
for (Action action : particleJumpProcess.getActions()) {
if (action.getOperation().equals(Action.ACTION_CREATE)) {
VolumeParticleSpeciesPattern volumeParticleSpeciesPattern = (VolumeParticleSpeciesPattern) action.getVar();
String newSpeciesPatternName = volumeParticleSpeciesPattern.getName() + "_" + particleJumpProcess.getName();
VolumeParticleSpeciesPattern productPattern = new VolumeParticleSpeciesPattern(volumeParticleSpeciesPattern, newSpeciesPatternName);
// VolumeParticleSpeciesPattern productPattern = (VolumeParticleSpeciesPattern) BeanUtils.cloneSerializable(volumeParticleSpeciesPattern);
for (ParticleMolecularTypePattern productMolTypePattern : productPattern.getParticleMolecularTypePatterns()) {
ParticleComponentStateDefinition markSet = productMolTypePattern.getMolecularType().getComponentList().get(1).getComponentStateDefinitions().get(1);
productMolTypePattern.getMolecularComponentPatternList().get(1).setComponentStatePattern(new ParticleComponentStatePattern(markSet));
}
System.out.println(productPattern.getName());
if (clonedMathDesc.getVariable(productPattern.getName()) == null) {
clonedMathDesc.addVariable(productPattern);
}
action.setVar(productPattern);
}
}
}
try {
System.out.println("===============================\n ----------- VCML HACKED .... START\n" + clonedMathDesc.getVCML_database() + "\nVCML HACKED .... END\n====================\n");
} catch (MathException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (Exception e) {
throw new SolverException("failed to apply location mark transformation: " + e.getMessage(), e);
}
}
Element sbmlElement = new Element("sbml");
Element modelElement = new Element("model");
modelElement.setAttribute("id", "nameless");
SimulationSymbolTable simulationSymbolTable = new SimulationSymbolTable(clonedSimTask.getSimulation(), clonedSimTask.getSimulationJob().getJobIndex());
Element listOfParametersElement = getListOfParameters(clonedMathDesc, simulationSymbolTable);
Element listOfMoleculeTypesElement = getListOfMoleculeTypes(clonedMathDesc);
Element listOfSpeciesElement = getListOfSpecies(clonedMathDesc, simulationSymbolTable);
CompartmentSubDomain compartmentSubDomain = (CompartmentSubDomain) clonedMathDesc.getSubDomains().nextElement();
Element listOfReactionRules = new Element("ListOfReactionRules");
for (int reactionRuleIndex = 0; reactionRuleIndex < compartmentSubDomain.getParticleJumpProcesses().size(); reactionRuleIndex++) {
ParticleJumpProcess particleJumpProcess = compartmentSubDomain.getParticleJumpProcesses().get(reactionRuleIndex);
MathRuleFactory mathRuleFactory = new MathRuleFactory();
MathRuleEntry rule = mathRuleFactory.createRuleEntry(particleJumpProcess, reactionRuleIndex);
RuleAnalysisReport report = RuleAnalysis.analyze(rule, true);
// remember, we have to add RateLaw
Element reactionRuleElement = RuleAnalysis.getNFSimXML(rule, report);
// ArrayList<MolecularTypeOfReactionParticipant> currentReactantElementsOfReaction = new ArrayList<MolecularTypeOfReactionParticipant>();
// ArrayList<ComponentOfMolecularTypeOfReactionParticipant> currentComponentOfReactantElementsOfReaction = new ArrayList<ComponentOfMolecularTypeOfReactionParticipant>();
// ArrayList<MolecularTypeOfReactionParticipant> currentProductElementsOfReaction = new ArrayList<MolecularTypeOfReactionParticipant>();
// ArrayList<ComponentOfMolecularTypeOfReactionParticipant> currentComponentOfProductElementsOfReaction = new ArrayList<ComponentOfMolecularTypeOfReactionParticipant>();
// currentMappingOfReactionParticipants.clear();
// reactionProductBondSites.clear();
// reactionReactantBondSites.clear();
//
// Element reactionRuleElement = new Element("ReactionRule");
// String reactionRuleID = "RR" + (reactionRuleIndex + 1);
// reactionRuleElement.setAttribute("id",reactionRuleID);
// reactionRuleElement.setAttribute("name",particleJumpProcess.getName());
// reactionRuleElement.setAttribute("symmetry_factor","1");
// reactionRule.resolveBonds();
//
// ArrayList<VolumeParticleSpeciesPattern> selectedPatterns = new ArrayList<VolumeParticleSpeciesPattern>();
// for (ParticleVariable particleVariable : particleJumpProcess.getParticleVariables()){
// if (!(particleVariable instanceof VolumeParticleSpeciesPattern)){
// throw new SolverException("expecting only "+VolumeParticleSpeciesPattern.class.getSimpleName()+"s for "+ParticleJumpProcess.class.getSimpleName()+" "+particleJumpProcess.getName());
// }
// selectedPatterns.add((VolumeParticleSpeciesPattern) particleVariable);
// }
// ArrayList<VolumeParticleSpeciesPattern> createdPatterns = new ArrayList<VolumeParticleSpeciesPattern>();
// HashSet<VolumeParticleSpeciesPattern> destroyedPatterns = new HashSet<VolumeParticleSpeciesPattern>();
// for (Action action : particleJumpProcess.getActions()){
// if (!(action.getVar() instanceof VolumeParticleSpeciesPattern)){
// throw new SolverException("expecting only "+VolumeParticleSpeciesPattern.class.getSimpleName()+"s for "+ParticleJumpProcess.class.getSimpleName()+" "+particleJumpProcess.getName());
// }
// if (action.getOperation().equals(Action.ACTION_CREATE)){
// createdPatterns.add((VolumeParticleSpeciesPattern) action.getVar());
// }else if (action.getOperation().equals(Action.ACTION_DESTROY)){
// destroyedPatterns.add((VolumeParticleSpeciesPattern) action.getVar());
// }else{
// throw new RuntimeException("unexpected action operation "+action.getOperation()+" for jump process "+particleJumpProcess.getName());
// }
// }
//
// Element listOfReactantPatternsElement = new Element("ListOfReactantPatterns");
// for(int reactantPatternIndex=0; reactantPatternIndex < selectedPatterns.size(); reactantPatternIndex++) {
// VolumeParticleSpeciesPattern reactantSpeciesPattern = selectedPatterns.get(reactantPatternIndex);
// String reactantPatternID = "RP" + (reactantPatternIndex + 1);
// patternReactantBondSites.clear();
// Element reactantPatternElement = getReactionParticipantPattern1(reactionRuleID, reactantPatternID, reactantSpeciesPattern,
// currentReactantElementsOfReaction, currentComponentOfReactantElementsOfReaction, "ReactantPattern");
// listOfReactantPatternsElement.addContent(reactantPatternElement);
// reactionReactantBondSites.addAll(patternReactantBondSites);
// }
// reactionRuleElement.addContent(listOfReactantPatternsElement);
//
// Element listOfProductPatternsElement = new Element("ListOfProductPatterns");
// ArrayList<VolumeParticleSpeciesPattern> productSpeciesPatterns = new ArrayList<VolumeParticleSpeciesPattern>(selectedPatterns);
// productSpeciesPatterns.removeAll(destroyedPatterns);
// productSpeciesPatterns.addAll(createdPatterns);
// // for products, add all "created" species from Actions and all "particles" that are selected but not destroyed
// for(int productPatternIndex=0; productPatternIndex < productSpeciesPatterns.size(); productPatternIndex++) {
// VolumeParticleSpeciesPattern productSpeciesPattern = productSpeciesPatterns.get(productPatternIndex);
// String productPatternID = "PP" + (productPatternIndex + 1);
// patternProductBondSites.clear();
// Element productPatternElement = getReactionParticipantPattern1(reactionRuleID, productPatternID, productSpeciesPattern,
// currentProductElementsOfReaction, currentComponentOfProductElementsOfReaction, "ProductPattern");
// listOfProductPatternsElement.addContent(productPatternElement);
// reactionProductBondSites.addAll(patternProductBondSites);
// }
// reactionRuleElement.addContent(listOfProductPatternsElement);
// <RateLaw id="RR1_RateLaw" type="Ele" totalrate="0">
// <ListOfRateConstants>
// <RateConstant value="kon"/>
// </ListOfRateConstants>
// </RateLaw>
Element rateLawElement = new Element("RateLaw");
rateLawElement.setAttribute("id", RuleAnalysis.getID(rule));
String rateConstantValue = null;
JumpProcessRateDefinition particleProbabilityRate = particleJumpProcess.getParticleRateDefinition();
if (particleProbabilityRate.getExpressions().length > 0) {
JumpProcessRateDefinition particleRateDefinition = particleJumpProcess.getParticleRateDefinition();
Expression expression = null;
if (particleRateDefinition instanceof MacroscopicRateConstant) {
expression = ((MacroscopicRateConstant) particleProbabilityRate).getExpression();
} else {
throw new SolverException("ParticleRateDefinition type " + particleRateDefinition.getClass().getSimpleName() + " not supported");
}
rateConstantValue = expression.infixBng();
// all rates constants are being flattened and given reserved names
Expression substitutedValExpr = null;
try {
substitutedValExpr = simulationSymbolTable.substituteFunctions(expression);
} catch (MathException | ExpressionException e) {
e.printStackTrace(System.out);
throw new SolverException("ParticleJumpProcess " + particleJumpProcess.getName() + " substitution failed : exp = \"" + expression.infix() + "\": " + e.getMessage());
}
Double value = null;
try {
value = substitutedValExpr.evaluateConstant();
Element parameterElement = new Element("Parameter");
String id = "K_reserved_" + reactionRuleIndex;
parameterElement.setAttribute("id", id);
if (value != null) {
parameterElement.setAttribute("type", "Constant");
parameterElement.setAttribute("value", value.toString());
parameterElement.addContent(new Comment(rateConstantValue));
rateConstantValue = id;
listOfParametersElement.addContent(parameterElement);
}
} catch (ExpressionException e) {
System.out.println("ParticleJumpProcess " + particleJumpProcess.getName() + " = " + substitutedValExpr.infix() + " does not have a constant value");
}
}
if (isFunction(rateConstantValue, clonedMathDesc, simulationSymbolTable)) {
rateLawElement.setAttribute("type", "Function");
rateLawElement.setAttribute("totalrate", "0");
rateLawElement.setAttribute("name", rateConstantValue);
} else {
rateLawElement.setAttribute("type", "Ele");
rateLawElement.setAttribute("totalrate", "0");
Element listOfRateConstantsElement = new Element("ListOfRateConstants");
Element rateConstantElement = new Element("RateConstant");
// System.out.println(" --- " + particleJumpProcess.getParticleRateDefinition().getExpressions());
if (particleProbabilityRate.getExpressions().length > 0) {
rateConstantElement.setAttribute("value", rateConstantValue);
}
listOfRateConstantsElement.addContent(rateConstantElement);
rateLawElement.addContent(listOfRateConstantsElement);
}
reactionRuleElement.addContent(rateLawElement);
// // <Map>
// // <MapItem sourceID="RR1_RP1_M1" targetID="RR1_PP1_M1"/>
// // <MapItem sourceID="RR1_RP1_M1_C1" targetID="RR1_PP1_M1_C1"/>
// // <MapItem sourceID="RR1_RP1_M1_C2" targetID="RR1_PP1_M1_C2"/>
// // <MapItem sourceID="RR1_RP2_M1" targetID="RR1_PP1_M2"/>
// // <MapItem sourceID="RR1_RP2_M1_C1" targetID="RR1_PP1_M2_C1"/>
// // </Map>
// Element mapElement = new Element("Map");
// System.out.println("----------------------------------------------------------------------");
// for(MolecularTypeOfReactionParticipant p : currentReactantElementsOfReaction) {
// System.out.println(p.moleculeName + ", " + p.elementID);
// }
// for(ComponentOfMolecularTypeOfReactionParticipant c : currentComponentOfReactantElementsOfReaction) {
// System.out.println(c.moleculeName + ", " + c.componentName + ", " + c.elementID);
// }
// System.out.println("----------------------------------------------------------------------");
// for(MolecularTypeOfReactionParticipant p : currentProductElementsOfReaction) {
// System.out.println(p.moleculeName + ", " + p.elementID);
// }
// for(ComponentOfMolecularTypeOfReactionParticipant c : currentComponentOfProductElementsOfReaction) {
// System.out.println(c.moleculeName + ", " + c.componentName + ", " + c.elementID);
// }
// System.out.println("----------------------------------------------------------------------");
//
// List<MolecularTypeOfReactionParticipant> cloneOfReactants = new ArrayList<MolecularTypeOfReactionParticipant>(currentReactantElementsOfReaction);
// List<MolecularTypeOfReactionParticipant> cloneOfProducts = new ArrayList<MolecularTypeOfReactionParticipant>(currentProductElementsOfReaction);
// for(Iterator<MolecularTypeOfReactionParticipant> itReactant = cloneOfReactants.iterator(); itReactant.hasNext();) { // participants
// MolecularTypeOfReactionParticipant reactant = itReactant.next();
// boolean foundProduct = false;
// for(Iterator<MolecularTypeOfReactionParticipant> itProduct = cloneOfProducts.iterator(); itProduct.hasNext();) {
// MolecularTypeOfReactionParticipant product = itProduct.next();
// if(reactant.find(product)) {
// MappingOfReactionParticipants m = new MappingOfReactionParticipants(reactant.elementID, product.elementID, "");
// currentMappingOfReactionParticipants.add(m );
// itProduct.remove();
// foundProduct = true;
// break; // we exit inner loop if we find a match for current reactant
// }
// }
// if(foundProduct == false) {
// System.out.println("Did not found a match for reactant " + reactant.moleculeName + ", " + reactant.elementID);
// }
// itReactant.remove(); // found or not, we remove the reactant
// }
// if(!currentProductElementsOfReaction.isEmpty()) {
// for(MolecularTypeOfReactionParticipant p : currentProductElementsOfReaction) {
// System.out.println("Did not found a match for product " + p.moleculeName + ", " + p.elementID);
// }
// }
// for(Iterator<ComponentOfMolecularTypeOfReactionParticipant> itReactant = currentComponentOfReactantElementsOfReaction.iterator(); itReactant.hasNext();) { // components
// ComponentOfMolecularTypeOfReactionParticipant reactant = itReactant.next();
// boolean foundProduct = false;
// for(Iterator<ComponentOfMolecularTypeOfReactionParticipant> itProduct = currentComponentOfProductElementsOfReaction.iterator(); itProduct.hasNext();) {
// ComponentOfMolecularTypeOfReactionParticipant product = itProduct.next();
// String state = "";
// if(reactant.find(product)) {
// if(!reactant.state.equals(product.state)) {
// state = product.state;
// }
// MappingOfReactionParticipants m = new MappingOfReactionParticipants(reactant.elementID, product.elementID, state);
// currentMappingOfReactionParticipants.add(m );
// itProduct.remove();
// foundProduct = true;
// break; // we exit inner loop if we find a match for current reactant
// }
// }
// if(foundProduct == false) {
// System.out.println("Did not found a match for reactant " + reactant.moleculeName + ", " + reactant.elementID);
// }
// itReactant.remove(); // found or not, we remove the reactant
// }
// if(!currentComponentOfProductElementsOfReaction.isEmpty()) {
// for(ComponentOfMolecularTypeOfReactionParticipant p : currentComponentOfProductElementsOfReaction) {
// System.out.println("Did not found a match for product " + p.moleculeName + ", " + p.elementID);
// }
// }
// for(Iterator<MappingOfReactionParticipants> it = currentMappingOfReactionParticipants.iterator(); it.hasNext();) {
// MappingOfReactionParticipants m = it.next();
// Element mapItemElement = new Element("MapItem");
// mapItemElement.setAttribute("sourceID", m.reactantElementID);
// mapItemElement.setAttribute("targetID", m.productElementID);
// mapElement.addContent(mapItemElement);
// }
// reactionRuleElement.addContent(mapElement);
//
// // <ListOfOperations>
// // <AddBond site1="RR1_RP1_M1_C1" site2="RR1_RP2_M1_C1"/>
// // <StateChange site="RR0_RP0_M0_C2" finalState="Y"/>
// // </ListOfOperations>
// Element listOfOperationsElement = new Element("ListOfOperations");
//
// // AddBond elements
// // add any bond in the product which is not present in the reactant
// Iterator<BondSites> it = patternProductBondSites.iterator();
// while (it.hasNext()) {
// BondSites bs = it.next();
// String reactantS1 = MappingOfReactionParticipants.findMatchingReactant(bs.component1, currentMappingOfReactionParticipants);
// String reactantS2 = MappingOfReactionParticipants.findMatchingReactant(bs.component2, currentMappingOfReactionParticipants);
// // we check if the bonds in the product existed already in the reactant, in which case they were not "added" in this reaction
// BondSites candidate = new BondSites(reactantS1, reactantS2);
// boolean preExistent = false;
// for(BondSites bsReactant : reactionReactantBondSites) {
// if(bsReactant.equals(candidate)) {
// preExistent = true;
// break;
// }
// }
// if(preExistent == true) {
// continue; // we don't add preexisting bonds
// }
// Element addBondElement = new Element("AddBond");
// addBondElement.setAttribute("site1", reactantS1);
// addBondElement.setAttribute("site2", reactantS2);
// listOfOperationsElement.addContent(addBondElement);
// }
// // StateChange elements
// for(Iterator<MappingOfReactionParticipants> it1 = currentMappingOfReactionParticipants.iterator(); it1.hasNext();) {
// MappingOfReactionParticipants m = it1.next();
// if(!m.componentFinalState.equals("")) { // state has changed if it's different from ""
// Element stateChangeElement = new Element("StateChange");
// stateChangeElement.setAttribute("site", m.reactantElementID);
// stateChangeElement.setAttribute("finalState", m.componentFinalState);
// listOfOperationsElement.addContent(stateChangeElement);
// }
// }
// // eliminate all the common entries (molecule types) in reactants and products
// // what's left in reactants was deleted, what's left in products was added
// List<MolecularTypeOfReactionParticipant> commonParticipants = new ArrayList<MolecularTypeOfReactionParticipant>();
// for(Iterator<MolecularTypeOfReactionParticipant> itReactant = currentReactantElementsOfReaction.iterator(); itReactant.hasNext();) { // participants
// MolecularTypeOfReactionParticipant reactant = itReactant.next();
// for(Iterator<MolecularTypeOfReactionParticipant> itProduct = currentProductElementsOfReaction.iterator(); itProduct.hasNext();) {
// MolecularTypeOfReactionParticipant product = itProduct.next();
// if(reactant.find(product)) {
// // commonParticipants contains the reactant molecules with a equivalent molecule in the product (meaning they are not in the "Deleted" category)
// commonParticipants.add(reactant);
// itReactant.remove();
// itProduct.remove();
// break; // we exit inner loop if we find a match for current reactant
// }
// }
// }
// // DeleteBond element
// // there is no need to mention deletion of bond if the particleSpeciesPattern
// // or the MolecularType involved in the bond are deleted as well
// // We only keep those "Deleted" bonds which belong to the molecules (of the reactant) present in commonParticipants
// // Both components (sites) of the bond need to have their molecules in commonParticipants
// boolean foundMoleculeForComponent1 = false;
// boolean foundMoleculeForComponent2 = false;
// HashSet<BondSites> cloneOfReactantBondSites = new HashSet<BondSites>(patternReactantBondSites);
// Iterator<BondSites> itbs = cloneOfReactantBondSites.iterator();
// while (itbs.hasNext()) {
// BondSites bs = itbs.next();
// String bondComponent1MoleculeId = BondSites.extractMoleculeId(bs.component1);
// String bondComponent2MoleculeId = BondSites.extractMoleculeId(bs.component2);
// for(MolecularTypeOfReactionParticipant commonReactionMoleculeule : commonParticipants) {
// String commonReactantPatternId = commonReactionMoleculeule.elementID;
// if(bondComponent1MoleculeId.equals(commonReactantPatternId)) {
// foundMoleculeForComponent1 = true;
// }
// if(bondComponent2MoleculeId.equals(commonReactantPatternId)) {
// foundMoleculeForComponent2 = true;
// }
// }
// if(!foundMoleculeForComponent1 || !foundMoleculeForComponent2) {
// // at least one of bond's molecule is not in common, hence we don't need to report the deletion of this bond
// itbs.remove();
// }
// }
// // the clone has now all the deleted bonds whose molecules have not been deleted
// itbs = cloneOfReactantBondSites.iterator();
// while (itbs.hasNext()) {
// BondSites bs = itbs.next();
// Element addBondElement = new Element("DeleteBond");
// addBondElement.setAttribute("site1", bs.component1);
// addBondElement.setAttribute("site2", bs.component2);
// listOfOperationsElement.addContent(addBondElement);
// }
// // Add MolecularType element
// for(MolecularTypeOfReactionParticipant molecule : currentProductElementsOfReaction) {
// System.out.println("created molecule: " + molecule.elementID + "' " + molecule.moleculeName);
// Element addMolecularTypePatternElement = new Element("Add");
// addMolecularTypePatternElement.setAttribute("id", molecule.elementID);
// listOfOperationsElement.addContent(addMolecularTypePatternElement);
// }
// // Delete MolecularType element
// // if the reactant pattern of the molecule being deleted still exists as part of the common, then we only delete the molecule
// // if the reactant pattern of the molecule being deleted is not as part of the common, then it's gone completely and we delete the reactant pattern
// ArrayList<String> patternsToDelete = new ArrayList<String>();
// for(MolecularTypeOfReactionParticipant molecule : currentReactantElementsOfReaction) {
// String reactantPatternId = molecule.extractReactantPatternId();
// boolean found = false;
// for(MolecularTypeOfReactionParticipant common : commonParticipants) {
// String commonId = common.extractReactantPatternId();
// if(reactantPatternId.equals(commonId)) {
// found = true;
// break; // some other molecule of this pattern still there, we don't delete the pattern
// }
// }
// if(found == true) { // some other molecule of this pattern still there, we don't delete the pattern
// System.out.println("deleted molecule: " + molecule.elementID + "' " + molecule.moleculeName);
// Element addMolecularTypePatternElement = new Element("Delete");
// addMolecularTypePatternElement.setAttribute("id", molecule.elementID);
// addMolecularTypePatternElement.setAttribute("DeleteMolecules", "0");
// listOfOperationsElement.addContent(addMolecularTypePatternElement);
// } else { // no molecule of this pattern left, we delete the pattern
// if(patternsToDelete.contains(reactantPatternId)) {
// // nothing to do, we're already deleting this pattern
// break;
// } else {
// patternsToDelete.add(reactantPatternId);
// System.out.println("deleted pattern: " + reactantPatternId);
// Element addParticleSpeciesPatternElement = new Element("Delete");
// addParticleSpeciesPatternElement.setAttribute("id", reactantPatternId);
// addParticleSpeciesPatternElement.setAttribute("DeleteMolecules", "0");
// listOfOperationsElement.addContent(addParticleSpeciesPatternElement);
// }
// }
// }
// reactionRuleElement.addContent(listOfOperationsElement);
listOfReactionRules.addContent(reactionRuleElement);
}
Element listOfObservablesElement = getListOfObservables(clonedMathDesc);
Element listOfFunctionsElement = getListOfFunctions(clonedMathDesc, simulationSymbolTable);
modelElement.addContent(listOfParametersElement);
modelElement.addContent(listOfMoleculeTypesElement);
modelElement.addContent(listOfSpeciesElement);
modelElement.addContent(listOfReactionRules);
modelElement.addContent(listOfObservablesElement);
modelElement.addContent(listOfFunctionsElement);
sbmlElement.addContent(modelElement);
// // return e1;
return sbmlElement;
}
use of cbit.vcell.solver.SimulationSymbolTable in project vcell by virtualcell.
the class StochFileWriter method write.
/**
* Write the model to a text file which serves as an input for Stochastic simulation engine.
* Creation date: (6/22/2006 5:37:26 PM)
*/
public void write(String[] parameterNames) throws Exception, ExpressionException {
Simulation simulation = simTask.getSimulation();
SimulationSymbolTable simSymbolTable = simTask.getSimulationJob().getSimulationSymbolTable();
initialize();
if (bUseMessaging) {
writeJMSParamters();
}
// Write control information
printWriter.println("<control>");
cbit.vcell.solver.SolverTaskDescription solverTaskDescription = simulation.getSolverTaskDescription();
cbit.vcell.solver.TimeBounds timeBounds = solverTaskDescription.getTimeBounds();
cbit.vcell.solver.OutputTimeSpec outputTimeSpec = solverTaskDescription.getOutputTimeSpec();
ErrorTolerance errorTolerance = solverTaskDescription.getErrorTolerance();
NonspatialStochSimOptions stochOpt = solverTaskDescription.getStochOpt();
printWriter.println("STARTING_TIME" + "\t" + timeBounds.getStartingTime());
printWriter.println("ENDING_TIME " + "\t" + timeBounds.getEndingTime());
// pw.println("MAX_ITERATION"+"\t"+outputTimeSpec.getKeepAtMost());
printWriter.println("TOLERANCE " + "\t" + errorTolerance.getAbsoluteErrorTolerance());
if (outputTimeSpec.isDefault()) {
printWriter.println("SAMPLE_INTERVAL" + "\t" + ((DefaultOutputTimeSpec) outputTimeSpec).getKeepEvery());
printWriter.println("MAX_SAVE_POINTS" + "\t" + ((DefaultOutputTimeSpec) outputTimeSpec).getKeepAtMost());
} else if (outputTimeSpec.isUniform()) {
printWriter.println("SAVE_PERIOD" + "\t" + ((UniformOutputTimeSpec) outputTimeSpec).getOutputTimeStep());
// need to overwrite limit hardcoded in C++
double savePoints = (timeBounds.getEndingTime() - timeBounds.getStartingTime()) / ((UniformOutputTimeSpec) outputTimeSpec).getOutputTimeStep();
printWriter.println("MAX_SAVE_POINTS" + "\t" + (Math.ceil(savePoints) + 1));
}
// boolean isMultiTrial = !solverTaskDescription.getStochOpt().isHistogram() &&
// solverTaskDescription.getStochOpt().getNumOfTrials() > 1;
// //Multi-trial 'NUM_TRIAL' handled by slurm array within .slurm.sh script
// printWriter.println("NUM_TRIAL"+"\t"+(isMultiTrial?1:solverTaskDescription.getStochOpt().getNumOfTrials()));
printWriter.println("NUM_TRIAL" + "\t" + solverTaskDescription.getStochOpt().getNumOfTrials());
if (stochOpt.isUseCustomSeed()) {
printWriter.println("SEED" + "\t" + stochOpt.getCustomSeed());
} else {
// we generate our own random seed
RandomDataGenerator rdg = new RandomDataGenerator();
int randomSeed = rdg.nextInt(1, Integer.MAX_VALUE);
printWriter.println("SEED" + "\t" + randomSeed);
}
if (isMultiTrialNonHisto) {
printWriter.println("BMULTIBUTNOTHISTO" + "\t" + "1");
}
printWriter.println("</control>");
printWriter.println();
// write model information
// Model info. will be extracted from subDomain of mathDescription
Enumeration<SubDomain> e = simulation.getMathDescription().getSubDomains();
SubDomain subDomain = null;
if (e.hasMoreElements()) {
subDomain = e.nextElement();
}
if (subDomain != null) {
printWriter.println("<model>");
// variables
printWriter.println("<discreteVariables>");
// Species iniCondition (if in concentration) is sampled from a poisson distribution(which has a mean of the current iniExp value)
// There is only one subDomain for compartmental model
List<VarIniCondition> varInis = subDomain.getVarIniConditions();
if ((varInis != null) && (varInis.size() > 0)) {
RandomDataGenerator dist = new RandomDataGenerator();
if (simulation.getSolverTaskDescription().getStochOpt().isUseCustomSeed()) {
Integer randomSeed = simulation.getSolverTaskDescription().getStochOpt().getCustomSeed();
if (randomSeed != null) {
dist.reSeed(randomSeed);
}
}
printWriter.println("TotalVars" + "\t" + varInis.size());
for (VarIniCondition varIniCondition : varInis) {
try {
Expression iniExp = varIniCondition.getIniVal();
iniExp.bindExpression(simSymbolTable);
iniExp = simSymbolTable.substituteFunctions(iniExp).flatten();
double expectedCount = iniExp.evaluateConstant();
// 1000 mill
final Integer limit = 1000000000;
if (limit < expectedCount) {
String eMessage = "The Initial count for Species '" + varIniCondition.getVar().getName() + "' is " + BigDecimal.valueOf(expectedCount).toBigInteger() + "\n";
eMessage += "which is higher than the internal vCell limit of " + limit + ".\n";
eMessage += "Please reduce the Initial Condition value for this Species or reduce the compartment size.";
throw new MathFormatException(eMessage);
}
long varCount = 0;
if (varIniCondition instanceof VarIniCount) {
varCount = (long) Math.round(expectedCount);
} else {
if (expectedCount > 0) {
varCount = dist.nextPoisson(expectedCount);
}
}
// System.out.println("expectedCount: " + expectedCount + ", varCount: " + varCount);
printWriter.println(varIniCondition.getVar().getName() + "\t" + varCount);
} catch (ExpressionException ex) {
ex.printStackTrace();
throw new MathFormatException("variable " + varIniCondition.getVar().getName() + "'s initial condition is required to be a constant.");
}
}
} else
printWriter.println("TotalVars" + "\t" + "0");
printWriter.println("</discreteVariables>");
printWriter.println();
// jump processes
printWriter.println("<jumpProcesses>");
List<JumpProcess> jumpProcesses = subDomain.getJumpProcesses();
if ((jumpProcesses != null) && (jumpProcesses.size() > 0)) {
printWriter.println("TotalProcesses" + "\t" + jumpProcesses.size());
for (int i = 0; i < jumpProcesses.size(); i++) {
printWriter.println(jumpProcesses.get(i).getName());
}
} else
printWriter.println("TotalProcesses" + "\t" + "0");
printWriter.println("</jumpProcesses>");
printWriter.println();
// process description
printWriter.println("<processDesc>");
if ((jumpProcesses != null) && (jumpProcesses.size() > 0)) {
printWriter.println("TotalDescriptions" + "\t" + jumpProcesses.size());
for (int i = 0; i < jumpProcesses.size(); i++) {
JumpProcess temProc = (JumpProcess) jumpProcesses.get(i);
// jump process name
printWriter.println("JumpProcess" + "\t" + temProc.getName());
Expression probExp = temProc.getProbabilityRate();
try {
probExp.bindExpression(simSymbolTable);
probExp = simSymbolTable.substituteFunctions(probExp).flatten();
if (!isValidProbabilityExpression(probExp)) {
throw new MathFormatException("probability rate in jump process " + temProc.getName() + " has illegal symbols(should only contain variable names).");
}
} catch (cbit.vcell.parser.ExpressionException ex) {
ex.printStackTrace();
throw new cbit.vcell.parser.ExpressionException("Binding math description error in probability rate in jump process " + temProc.getName() + ". Some symbols can not be resolved.");
}
// Expression temp = replaceVarIniInProbability(probExp);
// Propensity
printWriter.println("\t" + "Propensity" + "\t" + probExp.infix());
// effects
printWriter.println("\t" + "Effect" + "\t" + temProc.getActions().size());
for (int j = 0; j < temProc.getActions().size(); j++) {
printWriter.print("\t\t" + ((Action) temProc.getActions().get(j)).getVar().getName() + "\t" + ((Action) temProc.getActions().get(j)).getOperation());
printWriter.println("\t" + ((Action) temProc.getActions().get(j)).evaluateOperand());
printWriter.println();
}
// dependencies
Vector<String> dependencies = getDependencies(temProc, jumpProcesses);
if ((dependencies != null) && (dependencies.size() > 0)) {
printWriter.println("\t" + "DependentProcesses" + "\t" + dependencies.size());
for (int j = 0; j < dependencies.size(); j++) printWriter.println("\t\t" + dependencies.elementAt(j));
} else
printWriter.println("\t" + "DependentProcesses" + "\t" + "0");
printWriter.println();
}
} else
printWriter.println("TotalDescriptions" + "\t" + "0");
printWriter.println("</processDesc>");
printWriter.println("</model>");
}
// if (subDomain != null)
}
Aggregations