use of cbit.vcell.matrix.RationalNumber in project vcell by virtualcell.
the class RationalExpUtils method getRationalExp.
private static RationalExp getRationalExp(SimpleNode node, boolean bAllowFunctions) throws ExpressionException {
if (node == null) {
return null;
}
if (node instanceof ASTAndNode || node instanceof ASTOrNode || node instanceof ASTNotNode || node instanceof ASTRelationalNode || node instanceof DerivativeNode || node instanceof ASTLaplacianNode) {
throw new ExpressionException("sub-expression " + node.infixString(SimpleNode.LANGUAGE_DEFAULT) + " cannot be translated to a Rational Expression");
} else if (node instanceof ASTFuncNode) {
if (((ASTFuncNode) node).getFunction() == FunctionType.POW) {
try {
double constantExponent = node.jjtGetChild(1).evaluateConstant();
if (constantExponent != Math.floor(constantExponent)) {
throw new ExpressionException("sub-expression " + node.infixString(SimpleNode.LANGUAGE_DEFAULT) + " cannot be translated to a Rational Expression, exponent is not an integer");
}
int intExponent = (int) constantExponent;
if (intExponent == 0) {
return RationalExp.ONE;
}
RationalExp base = getRationalExp((SimpleNode) node.jjtGetChild(0), bAllowFunctions);
if (intExponent < 0) {
base = base.inverse();
intExponent = -intExponent;
}
RationalExp baseUnit = new RationalExp(base);
for (int i = 1; i < intExponent; i++) {
base = base.mult(baseUnit);
}
return base;
} catch (ExpressionException e) {
throw new ExpressionException("sub-expression " + node.infixString(SimpleNode.LANGUAGE_DEFAULT) + " cannot be translated to a Rational Expression, exponent is not constant");
}
} else {
if (bAllowFunctions) {
return new RationalExp(((ASTFuncNode) node).infixString(SimpleNode.LANGUAGE_DEFAULT));
} else {
throw new ExpressionException("sub-expression " + node.infixString(SimpleNode.LANGUAGE_DEFAULT) + " cannot be translated to a Rational Expression");
}
}
} else if (node instanceof ASTPowerNode) {
try {
double constantExponent = node.jjtGetChild(1).evaluateConstant();
if (constantExponent != Math.floor(constantExponent)) {
throw new ExpressionException("sub-expression " + node.infixString(SimpleNode.LANGUAGE_DEFAULT) + " cannot be translated to a Rational Expression, exponent is not an integer");
}
int intExponent = (int) constantExponent;
if (intExponent == 0) {
return RationalExp.ONE;
}
RationalExp base = getRationalExp((SimpleNode) node.jjtGetChild(0), bAllowFunctions);
if (intExponent < 0) {
base = base.inverse();
intExponent = -intExponent;
}
RationalExp baseUnit = new RationalExp(base);
for (int i = 1; i < intExponent; i++) {
base = base.mult(baseUnit);
}
return base;
} catch (ExpressionException e) {
throw new ExpressionException("sub-expression " + node.infixString(SimpleNode.LANGUAGE_DEFAULT) + " cannot be translated to a Rational Expression, exponent is not constant");
}
} else if (node instanceof ASTAddNode) {
RationalExp exp = RationalExp.ZERO;
for (int i = 0; i < node.jjtGetNumChildren(); i++) {
exp = exp.add(getRationalExp((SimpleNode) node.jjtGetChild(i), bAllowFunctions));
}
return exp;
} else if (node instanceof ASTMinusTermNode) {
return getRationalExp((SimpleNode) node.jjtGetChild(0), bAllowFunctions).minus();
} else if (node instanceof ASTMultNode) {
if (node.jjtGetNumChildren() == 1) {
return getRationalExp((SimpleNode) node.jjtGetChild(0), bAllowFunctions);
}
RationalExp exp = RationalExp.ONE;
for (int i = 0; i < node.jjtGetNumChildren(); i++) {
exp = exp.mult(getRationalExp((SimpleNode) node.jjtGetChild(i), bAllowFunctions));
}
return exp;
} else if (node instanceof ASTInvertTermNode) {
SimpleNode child = (SimpleNode) node.jjtGetChild(0);
return getRationalExp(child, bAllowFunctions).inverse();
} else if (node instanceof ASTFloatNode) {
// return TBD instead of dimensionless.
RationalNumber r = RationalNumber.getApproximateFraction(((ASTFloatNode) node).value.doubleValue());
return new RationalExp(r);
// } else if (node instanceof ASTFuncNode) {
// String functionName = ((ASTFuncNode)node).getName();
// if (functionName.equalsIgnoreCase("pow")) {
// SimpleNode child0 = (SimpleNode)node.jjtGetChild(0);
// SimpleNode child1 = (SimpleNode)node.jjtGetChild(1);
// VCUnitDefinition unit0 = getRationalExp(child0);
// VCUnitDefinition unit1 = getRationalExp(child1);
// if (!unit1.compareEqual(VCUnitDefinition.UNIT_DIMENSIONLESS) && !unit1.compareEqual(VCUnitDefinition.UNIT_TBD)){
// throw new VCUnitException("exponent of '"+node.infixString(SimpleNode.LANGUAGE_DEFAULT,SimpleNode.NAMESCOPE_DEFAULT)+"' has units of "+unit0);
// }
// if (unit0.compareEqual(VCUnitDefinition.UNIT_DIMENSIONLESS) || unit0.isTBD()){
// return unit0;
// }
// try {
// double d = ((SimpleNode)node.jjtGetChild(1)).evaluateConstant();
// RationalNumber rn = RationalNumber.getApproximateFraction(d);
// return unit0.raiseTo(rn);
// }catch(ExpressionException e){
// return VCUnitDefinition.UNIT_TBD; // ????? don't know the unit now
// }
// }
// } else if (node instanceof ASTPowerNode) {
// SimpleNode child0 = (SimpleNode)node.jjtGetChild(0);
// SimpleNode child1 = (SimpleNode)node.jjtGetChild(1);
// VCUnitDefinition unit0 = getRationalExp(child0);
// VCUnitDefinition unit1 = getRationalExp(child1);
// if (!unit1.compareEqual(VCUnitDefinition.UNIT_DIMENSIONLESS) && !unit1.compareEqual(VCUnitDefinition.UNIT_TBD)){
// throw new VCUnitException("exponent of '"+node.infixString(SimpleNode.LANGUAGE_DEFAULT,SimpleNode.NAMESCOPE_DEFAULT)+"' has units of "+unit0);
// }
// if (unit0.compareEqual(VCUnitDefinition.UNIT_DIMENSIONLESS)){
// return VCUnitDefinition.UNIT_DIMENSIONLESS;
// }
// boolean bConstantExponent = false;
// double exponentValue = 1;
// try {
// exponentValue = child1.evaluateConstant();
// bConstantExponent = true;
// }catch(ExpressionException e){
// bConstantExponent = false;
// }
// if (bConstantExponent){ //
// if (unit0.isTBD()){
// return VCUnitDefinition.UNIT_TBD;
// }else{
// RationalNumber rn = RationalNumber.getApproximateFraction(exponentValue);
// return unit0.raiseTo(rn);
// }
// }else{
// return VCUnitDefinition.UNIT_TBD;
// }
} else if (node instanceof ASTIdNode) {
return new RationalExp(((ASTIdNode) node).name);
} else {
throw new ExpressionException("node type " + node.getClass().toString() + " not supported yet");
}
}
use of cbit.vcell.matrix.RationalNumber in project vcell by virtualcell.
the class SpeciesContextSpec method initializeForSpatial.
public void initializeForSpatial() {
if (getDiffusionParameter() != null && getDiffusionParameter().getExpression() != null && getDiffusionParameter().getExpression().isZero()) {
Expression e = null;
ModelUnitSystem modelUnitSystem = getSimulationContext().getModel().getUnitSystem();
VCUnitDefinition micronsqpersecond = modelUnitSystem.getInstance("um2.s-1");
if (speciesContext.getStructure() instanceof Feature) {
RationalNumber rn = RationalNumber.getApproximateFraction(micronsqpersecond.convertTo(10, getDiffusionParameter().getUnitDefinition()));
e = new Expression(rn.doubleValue());
} else if (speciesContext.getStructure() instanceof Membrane) {
RationalNumber rn = RationalNumber.getApproximateFraction(micronsqpersecond.convertTo(0.1, getDiffusionParameter().getUnitDefinition()));
e = new Expression(rn.doubleValue());
} else {
RationalNumber rn = RationalNumber.getApproximateFraction(micronsqpersecond.convertTo(1.0, getDiffusionParameter().getUnitDefinition()));
e = new Expression(rn.doubleValue());
}
try {
getDiffusionParameter().setExpression(e);
} catch (ExpressionBindingException e1) {
e1.printStackTrace();
throw new RuntimeException("Error while initializing diffusion rate, " + e1.getMessage());
}
}
}
use of cbit.vcell.matrix.RationalNumber in project vcell by virtualcell.
the class StructureAnalyzer method refreshTotalDependancies.
/**
* This method was created by a SmartGuide.
* @param b cbit.vcell.math.Matrix
* @param vars java.lang.String[]
*/
public static StructureAnalyzer.Dependency[] refreshTotalDependancies(RationalMatrix nullSpaceMatrix, SpeciesContextMapping[] speciesContextMappings, AbstractMathMapping argMathMapping, boolean bFast) throws Exception {
// System.out.println("StructureAnalyzer.refreshTotalDependancies()");
SimulationContext argSimContext = argMathMapping.getSimulationContext();
if (nullSpaceMatrix == null) {
// System.out.println("the matrix has full rank, there are no dependencies");
return new StructureAnalyzer.Dependency[0];
}
if (speciesContextMappings.length != nullSpaceMatrix.getNumCols()) {
// throw new Exception("varName array not same dimension as b matrix");
System.out.println("varName array not same dimension as b matrix");
nullSpaceMatrix.show();
for (int i = 0; i < speciesContextMappings.length; i++) {
System.out.println("scm[" + i + "] is " + speciesContextMappings[i].getSpeciesContext().getName());
}
}
System.out.println("there are " + nullSpaceMatrix.getNumRows() + " dependencies, " + nullSpaceMatrix.getNumCols() + " columns.");
long startTime = System.currentTimeMillis();
Vector<Dependency> dependencyList = new Vector<Dependency>();
for (int i = 0; i < nullSpaceMatrix.getNumRows(); i++) {
//
// find first variable
//
ArrayList<Expression> el = new ArrayList<Expression>();
ArrayList<Expression> cel = new ArrayList<Expression>();
String constantName = null;
SpeciesContextMapping firstSCM = null;
boolean bFirst = true;
for (int j = 0; j < nullSpaceMatrix.getNumCols(); j++) {
RationalNumber coeff = nullSpaceMatrix.get_elem(i, j);
if (coeff.doubleValue() != 0.0) {
if (bFirst) {
if (coeff.doubleValue() != 1.0) {
System.out.println("i=" + i + " j=" + j);
nullSpaceMatrix.show();
throw new Exception("expecting a coefficient of 1.0, instead coeff = " + coeff.infix());
}
firstSCM = speciesContextMappings[j];
//
// first term of dependancy expression ("K_CalciumCyt")
//
SpeciesContext firstSC = firstSCM.getSpeciesContext();
constantName = DiffEquMathMapping.PARAMETER_MASS_CONSERVATION_PREFIX + firstSC.getName() + DiffEquMathMapping.PARAMETER_MASS_CONSERVATION_SUFFIX;
Expression exp = new Expression(constantName);
el.add(exp);
//
// first term of K expression
//
StructureMapping firstSM = argSimContext.getGeometryContext().getStructureMapping(firstSC.getStructure());
SpeciesContextSpec firstSCS = argSimContext.getReactionContext().getSpeciesContextSpec(firstSC);
SymbolTableEntry scSTE = null;
if (bFast) {
scSTE = firstSCS.getSpeciesContext();
} else {
scSTE = firstSCS.getParameterFromRole(SpeciesContextSpec.ROLE_InitialConcentration);
}
Expression constantExp = Expression.mult(new Expression(coeff), firstSM.getNormalizedConcentrationCorrection(argSimContext, argMathMapping), new Expression(scSTE, argMathMapping.getNameScope()));
cel.add(constantExp);
bFirst = false;
} else {
//
// add term to dependancy expression (" - 2*IP3Cyt ")
//
SpeciesContextMapping scm = speciesContextMappings[j];
SpeciesContext sc = scm.getSpeciesContext();
StructureMapping sm = argSimContext.getGeometryContext().getStructureMapping(sc.getStructure());
SpeciesContextSpec scs = argSimContext.getReactionContext().getSpeciesContextSpec(sc);
Expression negate = Expression.negate(Expression.mult(new Expression(coeff), sm.getNormalizedConcentrationCorrection(argSimContext, argMathMapping), new Expression(sc, argMathMapping.getNameScope())));
el.add(negate);
//
// add term to K expression
//
SymbolTableEntry scSTE = null;
if (bFast) {
scSTE = sc;
} else {
scSTE = scs.getParameterFromRole(SpeciesContextSpec.ROLE_InitialConcentration);
}
Expression mult = Expression.mult(new Expression(coeff), sm.getNormalizedConcentrationCorrection(argSimContext, argMathMapping), new Expression(scSTE, argMathMapping.getNameScope()));
cel.add(mult);
}
}
}
if (firstSCM != null) {
//
// store totalMass parameter (e.g. K_xyz_total = xyz_init + wzy_init)
//
// MathMapping.MathMappingParameter totalMassParameter = mathMapping.addMathMappingParameter(constantName,constantExp.flatten(),MathMapping.PARAMETER_ROLE_TOTALMASS,cbit.vcell.units.VCUnitDefinition.UNIT_uM);
//
// store dependency parameter (e.g. xyz = K_xyz_total - wzy)
//
StructureMapping sm = argSimContext.getGeometryContext().getStructureMapping(firstSCM.getSpeciesContext().getStructure());
Expression invert = Expression.invert(sm.getNormalizedConcentrationCorrection(argSimContext, argMathMapping));
Dependency dependency = new Dependency();
// exp = Expression.mult(exp,invert);
// exp = exp.flatten(); // old way
// System.out.println(exp.infix());
// //exp.bindExpression(mathMapping_temp);
// //firstSCM.setDependencyExpression(exp);
// dependency.dependencyExpression = exp;
Expression[] ev = el.toArray(new Expression[el.size()]);
Expression e = Expression.add(ev);
e = Expression.mult(e, invert);
// new way
e = e.flatten();
// System.out.println(e.infix());
// e.bindExpression(mathMapping_temp);
// firstSCM.setDependencyExpression(e);
dependency.dependencyExpression = e;
dependency.speciesContextMapping = firstSCM;
dependency.invariantSymbolName = constantName;
// Expression slow = constantExp.flatten(); // old way, very slow
// dependency.conservedMoietyExpression = slow;
Expression[] cev = cel.toArray(new Expression[cel.size()]);
Expression ce = Expression.add(cev);
// new way, much faster
ce = ce.flatten();
dependency.conservedMoietyExpression = ce;
dependencyList.add(dependency);
}
}
long endTime = System.currentTimeMillis();
long elapsedTime = endTime - startTime;
System.out.println(" " + elapsedTime + " milliseconds");
return (StructureAnalyzer.Dependency[]) BeanUtils.getArray(dependencyList, StructureAnalyzer.Dependency.class);
}
use of cbit.vcell.matrix.RationalNumber in project vcell by virtualcell.
the class AbstractMathMapping method getUnitFactorAsRationalExp.
/**
* This method was created in VisualAge.
* @return Expression
*/
public RationalExp getUnitFactorAsRationalExp(VCUnitDefinition unitFactor) {
if (unitFactor.isEquivalent(getSimulationContext().getModel().getUnitSystem().getInstance_DIMENSIONLESS())) {
return RationalExp.ONE;
}
for (MathMappingParameter p : fieldMathMappingParameters) {
if (p instanceof UnitFactorParameter && p.getUnitDefinition().isEquivalent(unitFactor)) {
return new RationalExp(p.getName());
}
}
RationalNumber factor = unitFactor.getDimensionlessScale();
String name = PARAMETER_K_UNITFACTOR_PREFIX + TokenMangler.fixTokenStrict(unitFactor.getSymbol().replace("-", "_neg_"));
UnitFactorParameter unitFactorParameter = new UnitFactorParameter(name, new Expression(factor), unitFactor);
MathMappingParameter[] newMathMappingParameters = (MathMappingParameter[]) BeanUtils.addElement(this.fieldMathMappingParameters, unitFactorParameter);
try {
setMathMapppingParameters(newMathMappingParameters);
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace(System.out);
throw new RuntimeException(e.getMessage());
}
return new RationalExp(factor);
}
use of cbit.vcell.matrix.RationalNumber in project vcell by virtualcell.
the class AbstractMathMapping method getUnitFactor.
/**
* This method was created in VisualAge.
* @return Expression
*/
public Expression getUnitFactor(VCUnitDefinition unitFactor) {
if (unitFactor.isEquivalent(getSimulationContext().getModel().getUnitSystem().getInstance_DIMENSIONLESS())) {
return new Expression(1.0);
}
for (MathMappingParameter p : fieldMathMappingParameters) {
if (p instanceof UnitFactorParameter && p.getUnitDefinition().isEquivalent(unitFactor)) {
return new Expression(p, getNameScope());
}
}
RationalNumber factor = unitFactor.getDimensionlessScale();
String name = PARAMETER_K_UNITFACTOR_PREFIX + TokenMangler.fixTokenStrict(unitFactor.getSymbol().replace("-", "_neg_"));
UnitFactorParameter unitFactorParameter = new UnitFactorParameter(name, new Expression(factor), unitFactor);
MathMappingParameter[] newMathMappingParameters = (MathMappingParameter[]) BeanUtils.addElement(this.fieldMathMappingParameters, unitFactorParameter);
try {
setMathMapppingParameters(newMathMappingParameters);
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace(System.out);
throw new RuntimeException(e.getMessage());
}
return new Expression(unitFactorParameter, getNameScope());
}
Aggregations