use of cbit.vcell.parser.ExpressionException in project vcell by virtualcell.
the class OutputFunctionContext method computeFunctionTypeWRTExpression.
// check if the new expression is valid for outputFunction of functionType
public VariableType computeFunctionTypeWRTExpression(AnnotatedFunction outputFunction, Expression exp) throws ExpressionException, InconsistentDomainException {
MathDescription mathDescription = getSimulationOwner().getMathDescription();
boolean bSpatial = getSimulationOwner().getGeometry().getDimension() > 0;
if (!bSpatial) {
return VariableType.NONSPATIAL;
}
Expression newexp = new Expression(exp);
// making sure that output function is not direct function of constant.
newexp.bindExpression(this);
// here use math description as symbol table because we allow
// new expression itself to be function of constant.
newexp = MathUtilities.substituteFunctions(newexp, this).flatten();
String[] symbols = newexp.getSymbols();
VariableType functionType = outputFunction.getFunctionType();
String funcName = outputFunction.getName();
Domain funcDomain = outputFunction.getDomain();
VariableType[] varTypes = null;
if (symbols != null && symbols.length > 0) {
// making sure that new expression is defined in the same domain
varTypes = new VariableType[symbols.length];
for (int i = 0; i < symbols.length; i++) {
if (ReservedMathSymbolEntries.getReservedVariableEntry(symbols[i]) != null) {
varTypes[i] = functionType;
} else {
Variable var = mathDescription.getVariable(symbols[i]);
if (var == null) {
var = mathDescription.getPostProcessingBlock().getDataGenerator(symbols[i]);
}
varTypes[i] = VariableType.getVariableType(var);
if (funcDomain != null) {
if (var.getDomain() == null) {
// OK
continue;
}
GeometryClass funcGeoClass = simulationOwner.getGeometry().getGeometryClass(funcDomain.getName());
GeometryClass varGeoClass = simulationOwner.getGeometry().getGeometryClass(var.getDomain().getName());
if (varGeoClass instanceof SubVolume && funcGeoClass instanceof SurfaceClass) {
// seems ok if membrane refereces volume
if (!((SurfaceClass) funcGeoClass).isAdjacentTo((SubVolume) varGeoClass)) {
// but has to be adjacent
String errMsg = "'" + funcName + "' defined on Membrane '" + funcDomain.getName() + "' directly or indirectly references " + " variable '" + symbols[i] + "' defined on Volume '" + var.getDomain().getName() + " which is not adjacent to Membrane '" + funcDomain.getName() + "'.";
throw new ExpressionException(errMsg);
}
} else if (!var.getDomain().compareEqual(funcDomain)) {
String errMsg = "'" + funcName + "' defined on '" + funcDomain.getName() + "' directly or indirectly references " + " variable '" + symbols[i] + "' defined on '" + var.getDomain().getName() + ".";
throw new ExpressionException(errMsg);
}
}
}
}
}
// if there are no variables (like built in function, vcRegionArea), check with flattened expression to find out the variable type of the new expression
VariableDomain functionVariableDomain = functionType.getVariableDomain();
Function flattenedFunction = new Function(funcName, newexp, funcDomain);
flattenedFunction.bind(this);
VariableType newVarType = SimulationSymbolTable.getFunctionVariableType(flattenedFunction, getSimulationOwner().getMathDescription(), symbols, varTypes, bSpatial);
if (!newVarType.getVariableDomain().equals(functionVariableDomain)) {
String errMsg = "The expression for '" + funcName + "' includes at least one " + newVarType.getVariableDomain().getName() + " variable. Please make sure that only " + functionVariableDomain.getName() + " variables are " + "referenced in " + functionVariableDomain.getName() + " output functions.";
throw new ExpressionException(errMsg);
}
return newVarType;
}
use of cbit.vcell.parser.ExpressionException in project vcell by virtualcell.
the class NetCDFWriter method getReactionRateLaws.
/**
* @param reacs
* @return ReactionRateLaw[]
*/
private ReactionRateLaw[] getReactionRateLaws(Expression[] probs) throws ExpressionException, MathException {
SimulationSymbolTable simSymbolTable = simTask.getSimulationJob().getSimulationSymbolTable();
ReactionRateLaw[] results = new ReactionRateLaw[probs.length];
varInProbOrderHash = new Hashtable[probs.length];
for (int i = 0; i < probs.length; i++) {
varInProbOrderHash[i] = new Hashtable<String, Integer>();
results[i] = new ReactionRateLaw();
Expression prob = probs[i];
String[] symbols = prob.getSymbols();
// get stoch variables involved in the reaction
String[] varSymbols = getVariableSymbols(symbols);
// max allowed order for each variable(species)
int maxOrder = 5;
// order of the reaction
int totalOrder = 0;
// the expression of the rate constant
Expression coefExp = null;
if (symbols != null) {
if ((varSymbols != null && !Compare.isEqual(symbols, varSymbols)) || varSymbols == null) {
throw new MathException("Unrecognized symbols in propensity function " + prob + ". Propensity function should contain stochastic variable symbols only.");
}
if (symbols != null && varSymbols != null) {
PropensitySolver.PropensityFunction pf = PropensitySolver.solvePropensity(prob, varSymbols, maxOrder);
// get total order and save each var's order according to each reaction.
for (int j = 0; j < pf.getSpeciesOrders().length; j++) {
varInProbOrderHash[i].put(pf.getSpeceisNames()[j], pf.getSpeciesOrders()[j]);
totalOrder = totalOrder + pf.getSpeciesOrders()[j];
}
// get rate constant
coefExp = new Expression(pf.getRateExpression());
}
} else {
coefExp = new Expression(prob);
}
if (totalOrder == 0) {
results[i].setLawType(ReactionRateLaw.order_0);
coefExp = new Expression(coefExp.flatten().infix() + "/6.02e23");
try {
coefExp.bindExpression(simSymbolTable);
coefExp = simSymbolTable.substituteFunctions(coefExp).flatten();
double val = coefExp.evaluateConstant();
results[i].setRateConstant(val);
} catch (Exception e) {
e.printStackTrace(System.err);
throw new ExpressionException(e.getMessage());
}
} else if (totalOrder == 1) {
results[i].setLawType(ReactionRateLaw.order_1);
coefExp = coefExp.flatten();
try {
coefExp.bindExpression(simSymbolTable);
coefExp = simSymbolTable.substituteFunctions(coefExp).flatten();
double val = coefExp.evaluateConstant();
results[i].setRateConstant(val);
} catch (Exception e) {
e.printStackTrace(System.err);
throw new ExpressionException(e.getMessage());
}
} else if (totalOrder == 2) {
if (// second order, two same molecules
varSymbols.length == 1) {
// k= c*6.02e23/2, since in VCell, "/2" is already incorporated into c, so we don'y need to take care of this item from the conversion.
coefExp = new Expression(coefExp.flatten().infix() + "*6.02e23");
results[i].setLawType(ReactionRateLaw.order_2_1substrate);
try {
coefExp.bindExpression(simSymbolTable);
coefExp = simSymbolTable.substituteFunctions(coefExp).flatten();
double val = coefExp.evaluateConstant();
results[i].setRateConstant(val);
} catch (Exception e) {
e.printStackTrace(System.err);
throw new ExpressionException(e.getMessage());
}
} else if (// second order, two different molecules
varSymbols.length == 2) {
coefExp = new Expression(coefExp.flatten().infix() + "*6.02e23");
results[i].setLawType(ReactionRateLaw.order_2_2substrate);
try {
coefExp.bindExpression(simSymbolTable);
coefExp = simSymbolTable.substituteFunctions(coefExp).flatten();
double val = coefExp.evaluateConstant();
results[i].setRateConstant(val);
} catch (Exception e) {
e.printStackTrace(System.err);
throw new ExpressionException(e.getMessage());
}
}
} else if (totalOrder == 3) {
if (// third order, three same molecules
varSymbols.length == 1) {
results[i].setLawType(ReactionRateLaw.order_3_1substrate);
// use c directly. "/3!" is already incorporated into c, so we compensate this item from the conversion.
coefExp = new Expression(coefExp.flatten().infix() + "*6");
} else if (// third order, three different molecules
varSymbols.length == 3) {
results[i].setLawType(ReactionRateLaw.order_3_3substrate);
} else if (// third order, two different molecules
varSymbols.length == 2) {
results[i].setLawType(ReactionRateLaw.order_3_2substrate);
// use c directly. "/(2!*1!)" is already incorporated into c, so we compensate this item from the conversion.
coefExp = new Expression(coefExp.flatten().infix() + "*2");
}
coefExp = coefExp.flatten();
try {
coefExp.bindExpression(simSymbolTable);
coefExp = simSymbolTable.substituteFunctions(coefExp).flatten();
double val = coefExp.evaluateConstant();
results[i].setRateConstant(val);
} catch (Exception e) {
e.printStackTrace(System.err);
throw new ExpressionException(e.getMessage());
}
} else // order more than 3, throw exception
{
throw new RuntimeException("Reaction order is more than 3, we couldn't solve it by Hybrid simulation.");
}
}
return results;
}
use of cbit.vcell.parser.ExpressionException 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());
}
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);
}
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) 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)
}
use of cbit.vcell.parser.ExpressionException in project vcell by virtualcell.
the class AugmentedObjectiveFunctionTest method getExample1.
/**
* Insert the method's description here.
* Creation date: (5/3/2002 2:49:06 PM)
* @return opt.AugmentedObjectiveFunction
*/
public static AugmentedObjectiveFunction getExample1() {
try {
Expression scalarFn_exp = new Expression("pow(x1-2,4)+pow(x1-2*x2,2)");
Expression[] eqConstraints_exps = { new Expression("pow(x1,2)-x2") };
Expression[] ineqConstraints_exps = { new Expression("pow(x1,2)-x2") };
;
String[] ids = { "x1", "x2" };
ScalarFunction scalarFn = new DynamicScalarFunction(scalarFn_exp, ids);
VectorFunction eqConstraints = new DynamicVectorFunction(eqConstraints_exps, ids);
VectorFunction ineqConstraints = new DynamicVectorFunction(ineqConstraints_exps, ids);
AugmentedObjectiveFunction aof = new AugmentedObjectiveFunction(scalarFn, eqConstraints, ineqConstraints, 2.0, 0.1, new DefaultOptSolverCallbacks());
return aof;
} catch (ExpressionException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
use of cbit.vcell.parser.ExpressionException in project vcell by virtualcell.
the class ExpressionCanvas method getMinimumSize.
/**
* Insert the method's description here.
* Creation date: (11/19/2002 11:26:26 AM)
* @return java.awt.Dimension
*/
public Dimension getMinimumSize() {
Graphics2D g = (Graphics2D) getGraphics();
if (g != null) {
g.setClip(0, 0, getSize().width, getSize().height);
Font canvasFont = new Font("SansSerif", Font.ITALIC, 11);
g.setFont(canvasFont);
FontMetrics fontMetrics = g.getFontMetrics();
try {
Dimension minSize = new Dimension(10, 10);
if (fieldExpressions != null) {
for (int i = 0; i < fieldExpressions.length; i++) {
ExpressionPrintFormatter expPrintFormatter = new ExpressionPrintFormatter(fieldExpressions[i]);
Dimension expressionDim = expPrintFormatter.getSize(g);
int labelWidth = 0;
if (fieldPrefixLabels != null) {
labelWidth += g.getFontMetrics().stringWidth(fieldPrefixLabels[i]) + 20;
}
if (fieldSuffixLabels != null) {
labelWidth += g.getFontMetrics().stringWidth(fieldSuffixLabels[i]) + 20;
}
minSize.width = Math.max(minSize.width, expressionDim.width + 20 + labelWidth);
minSize.height += expressionDim.height + 20;
}
} else {
for (String expString : fieldStrings) {
int stringWidth = fontMetrics.stringWidth(expString);
int stringHeight = fontMetrics.getHeight();
minSize.width = Math.max(minSize.width, stringWidth);
minSize.height += stringHeight + 20;
}
}
return minSize;
} catch (ExpressionException e) {
e.printStackTrace(System.out);
return super.getMinimumSize();
}
} else {
return super.getMinimumSize();
}
}
Aggregations