use of cbit.vcell.parser.Expression in project vcell by virtualcell.
the class MathModel_SBMLExporter method getFormulaFromExpression.
/**
* getFormulaFromExpression :
* Expression infix strings are not handled gracefully by libSBML, esp when ligical or inequality operators are used.
* This method
* converts the expression into MathML using ExpressionMathMLPrinter;
* converts that into libSBMl-readable formula using libSBML utilties.
* returns the new formula string.
*/
public static ASTNode getFormulaFromExpression(Expression expression, MathType mathType) {
// Convert expression into MathML string
String expMathMLStr = null;
try {
// mangling the identifiers in the expression to make them proper SBase ids.
Expression mangledExpression = new Expression(expression);
String[] symbols = mangledExpression.getSymbols();
if (symbols != null) {
for (String symbol : mangledExpression.getSymbols()) {
String mangledSymbol = TokenMangler.mangleToSName(symbol);
if (!mangledSymbol.equals(symbol)) {
mangledExpression.substituteInPlace(new Expression(symbol), new Expression(mangledSymbol));
}
}
}
expMathMLStr = cbit.vcell.parser.ExpressionMathMLPrinter.getMathML(mangledExpression, false, mathType);
} catch (java.io.IOException e) {
e.printStackTrace(System.out);
throw new RuntimeException("Error converting expression to MathML string :" + e.getMessage());
} catch (cbit.vcell.parser.ExpressionException e1) {
e1.printStackTrace(System.out);
throw new RuntimeException("Error converting expression to MathML string :" + e1.getMessage());
}
// Use libSBMl routines to convert MathML string to MathML document and a libSBML-readable formula string
ASTNode mathNode = ASTNode.readMathMLFromString(expMathMLStr);
return mathNode;
}
use of cbit.vcell.parser.Expression in project vcell by virtualcell.
the class RbmNetworkGenerator method generateModel.
public static void generateModel(BioModel bioModel, String netfile) throws Exception {
Model model = bioModel.getModel();
Map<String, SpeciesContext> speciesMap = new HashMap<String, SpeciesContext>();
Map<String, ReactionStep> reactionMap = new HashMap<String, ReactionStep>();
List<ReactionLine> reactionLineList = new ArrayList<ReactionLine>();
BufferedReader br = new BufferedReader(new StringReader(netfile));
int reversibleCount = 0;
int reactionCount = 0;
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
line = line.trim();
if (line.equals(BEGIN_PARAMETERS)) {
while (true) {
String line2 = br.readLine();
line2 = line2.trim();
if (line2.length() == 0) {
continue;
}
if (line2.equals(END_PARAMETERS)) {
break;
}
StringTokenizer st = new StringTokenizer(line2);
String token1 = st.nextToken();
String token2 = st.nextToken();
String token3 = st.nextToken();
ModelParameter mp = model.new ModelParameter(token2, new Expression(token3), Model.ROLE_UserDefined, bioModel.getModel().getUnitSystem().getInstance_TBD());
model.addModelParameter(mp);
}
} else if (line.equals(BEGIN_SPECIES)) {
while (true) {
String line2 = br.readLine();
line2 = line2.trim();
if (line2.length() == 0) {
continue;
}
if (line2.equals(END_SPECIES)) {
break;
}
StringTokenizer st = new StringTokenizer(line2);
// no
String token1 = st.nextToken();
// pattern
String token2 = st.nextToken();
// initial condition
String token3 = st.nextToken();
String newname = token2.replaceAll("\\.", "_");
newname = newname.replaceAll("[\\(,][a-zA-Z]\\w*", "");
newname = newname.replaceAll("~|!\\d*", "");
newname = newname.replaceAll("\\(\\)", "");
newname = newname.replaceAll("\\)", "");
SpeciesContext sc = model.createSpeciesContext(model.getStructure(0));
sc.setName(newname);
bioModel.getVCMetaData().setFreeTextAnnotation(sc, token2);
bioModel.getVCMetaData().setFreeTextAnnotation(sc.getSpecies(), token2);
speciesMap.put(token1, sc);
}
} else if (line.equals(BEGIN_REACTIONS)) {
while (true) {
String line2 = br.readLine();
line2 = line2.trim();
if (line2.length() == 0) {
continue;
}
if (line2.equals(END_REACTIONS)) {
break;
}
++reactionCount;
StringTokenizer st = new StringTokenizer(line2);
String token1 = st.nextToken();
// reactants
String token2 = st.nextToken();
// products
String token3 = st.nextToken();
// rate
String token4 = st.nextToken();
String token5 = st.nextToken();
boolean bFoundReversible = false;
Expression rate = new Expression(token4);
for (ReactionLine rl : reactionLineList) {
if (token2.equals(rl.products) && token3.equals(rl.reactants) && token5.equals(rl.ruleLabel + "r")) {
ReactionStep rs = reactionMap.get(rl.no);
((MassActionKinetics) rs.getKinetics()).getReverseRateParameter().setExpression(rate);
reactionLineList.remove(rl);
bFoundReversible = true;
break;
}
}
if (bFoundReversible) {
++reversibleCount;
continue;
}
ReactionLine rl = new ReactionLine(token1, token2, token3, token5);
reactionLineList.add(rl);
SimpleReaction reaction = model.createSimpleReaction(model.getStructure(0));
reactionMap.put(token1, reaction);
reaction.setModel(model);
bioModel.getVCMetaData().setFreeTextAnnotation(reaction, line2);
MassActionKinetics kinetics = new MassActionKinetics(reaction);
reaction.setKinetics(kinetics);
st = new StringTokenizer(token2, ",");
while (st.hasMoreTokens()) {
String t = st.nextToken();
SpeciesContext sc = speciesMap.get(t);
if (sc != null) {
boolean bExists = false;
for (ReactionParticipant rp : reaction.getReactionParticipants()) {
if (rp instanceof Reactant && rp.getSpeciesContext() == sc) {
rp.setStoichiometry(rp.getStoichiometry() + 1);
bExists = true;
break;
}
}
if (!bExists) {
reaction.addReactant(sc, 1);
}
}
}
st = new StringTokenizer(token3, ",");
while (st.hasMoreTokens()) {
String t = st.nextToken();
SpeciesContext sc = speciesMap.get(t);
if (sc != null) {
boolean bExists = false;
for (ReactionParticipant rp : reaction.getReactionParticipants()) {
if (rp instanceof Product && rp.getSpeciesContext() == sc) {
rp.setStoichiometry(rp.getStoichiometry() + 1);
bExists = true;
break;
}
}
if (!bExists) {
reaction.addProduct(sc, 1);
}
}
}
kinetics.getForwardRateParameter().setExpression(rate);
}
}
}
System.out.println(model.getNumSpecies() + " species added");
System.out.println(model.getNumReactions() + " reactions added");
System.out.println(reversibleCount + " reversible reactions found");
if (reactionCount != model.getNumReactions() + reversibleCount) {
throw new RuntimeException("Reactions are not imported correctly!");
}
}
use of cbit.vcell.parser.Expression in project vcell by virtualcell.
the class RbmUtils method getBoundExpression.
public static Expression getBoundExpression(String expressionString, final SymbolTable symbolTable) throws ExpressionException {
Expression exp = null;
if (expressionString == null || expressionString.equals("")) {
exp = new Expression(0);
} else {
exp = new Expression(expressionString);
}
//
// look for function invocations of unsupported but known functions
//
FunctionInvocation[] invocations = exp.getFunctionInvocations(new FunctionFilter() {
@Override
public boolean accept(String functionName, FunctionType functionType) {
if (functionName.equalsIgnoreCase("if")) {
return true;
}
return false;
}
});
if (invocations != null && invocations.length > 0) {
for (FunctionInvocation invocation : invocations) {
if (invocation.getFunctionName().equalsIgnoreCase("if")) {
// build new expression
// if (testExp, trueExp, falseExp)
//
Expression testExp = invocation.getArguments()[0];
Expression trueExp = invocation.getArguments()[1];
Expression falseExp = invocation.getArguments()[2];
Expression testPassed = Expression.relational("!=", testExp, new Expression(0.0));
Expression testFailed = Expression.relational("==", testExp, new Expression(0.0));
Expression newExp = Expression.add(Expression.mult(testPassed, trueExp), Expression.mult(testFailed, falseExp));
// substitute new expression replacing if()
exp.substituteInPlace(invocation.getFunctionExpression(), newExp);
}
}
System.out.println(invocations.toString());
}
//
// "if()" functions are goine ... but lets look for BNGL function invocations
// 1) if they have no arguments, drop the "()".
// 2) if they have arguments, have to substitute the arguments in the expression ... flatten it.
//
invocations = exp.getFunctionInvocations(new FunctionFilter() {
@Override
public boolean accept(String functionName, FunctionType functionType) {
return true;
}
});
if (invocations != null && invocations.length > 0) {
for (FunctionInvocation invocation : invocations) {
if (invocation.getArguments().length == 0) {
//
// no arguments, look for existing parameter by name (parameter name is function name).
//
// look up "identifier()" as "identifier" to find a model parameter generated earlier when processing functions (or prior functions)
//
SymbolTableEntry parameter = symbolTable.getEntry(invocation.getFunctionName());
if (parameter != null) {
exp.substituteInPlace(invocation.getFunctionExpression(), new Expression(parameter, parameter.getNameScope()));
} else {
//
// didn't find a parameter, may be a built-in function with zero arguments built into VCell. (none exists right now).
//
SymbolTableFunctionEntry vcellFunction = (SymbolTableFunctionEntry) symbolTable.getEntry(invocation.getFormalDefinition());
if (vcellFunction != null) {
//
// nothing to do, vcell will parse and interpret this correctly
//
} else {
throw new RuntimeException("function \"" + invocation.getFunctionExpression().infix() + "\" not found as a bngl function or as a vcell built-in function");
}
}
} else {
//
// should be a build-in vcell function with arguments ... user defined functions with arguments not supported yet in bngl import.
//
FunctionType builtinFunctionType = cbit.vcell.parser.ASTFuncNode.FunctionType.fromFunctionName(invocation.getFunctionName());
if (builtinFunctionType == null) {
throw new RuntimeException("function \"" + invocation.getFunctionExpression().infix() + "\" not found as a built-in VCell function (and bngl functions with arguments are not yet supported");
} else {
if (invocation.getArguments().length != builtinFunctionType.getArgTypes().length) {
throw new RuntimeException("built-in function \"" + invocation.getFunctionExpression().infix() + "\" expects " + builtinFunctionType.getArgTypes().length + " arguments");
}
}
}
System.out.println(invocations.toString());
}
}
exp.bindExpression(symbolTable);
return exp;
}
use of cbit.vcell.parser.Expression in project vcell by virtualcell.
the class RbmUtils method toBnglStringSortedAlphabetically.
public static String toBnglStringSortedAlphabetically(SimulationContext sc, SpeciesContext speciesContext, CompartmentMode compartmentMode) {
SpeciesContextSpec scs = sc.getReactionContext().getSpeciesContextSpec(speciesContext);
Expression expression = scs.getParameter(SpeciesContextSpec.ROLE_InitialConcentration).getExpression();
SpeciesPattern sp = speciesContext.getSpeciesPattern();
// nothing to sort here, sorting done within the species pattern
String s = "";
if (compartmentMode == CompartmentMode.show) {
s += "@" + speciesContext.getStructure().getName() + ":";
s += toBnglStringSortedAlphabetically(sp, null, CompartmentMode.hide, 0) + "";
} else if (compartmentMode == CompartmentMode.asSite) {
s += toBnglStringSortedAlphabetically(sp, speciesContext.getStructure(), CompartmentMode.asSite, 0) + "";
} else {
s += toBnglStringSortedAlphabetically(sp, null, CompartmentMode.hide, 0) + "";
}
s += " " + expression.infix();
return s;
}
use of cbit.vcell.parser.Expression in project vcell by virtualcell.
the class ParameterEstimationTaskSimulatorIDA method getRowColumnRestultSetByBestEstimations.
public RowColumnResultSet getRowColumnRestultSetByBestEstimations(ParameterEstimationTask parameterEstimationTask, String[] paramNames, double[] paramValues) throws Exception {
// create a temp simulation based on math description
KeyValue key = new KeyValue("" + Math.abs(new Random().nextLong()));
SimulationVersion dummyVersion = new SimulationVersion(key, "name", new User("temp", new KeyValue("1")), null, null, null, null, null, null, null);
Simulation simulation = new Simulation(dummyVersion, parameterEstimationTask.getSimulationContext().getMathDescription());
ReferenceData refData = parameterEstimationTask.getModelOptimizationSpec().getReferenceData();
double[] times = refData.getDataByColumn(0);
double endTime = times[times.length - 1];
ExplicitOutputTimeSpec exTimeSpec = new ExplicitOutputTimeSpec(times);
// set simulation ending time and output interval
simulation.getSolverTaskDescription().setTimeBounds(new TimeBounds(0, endTime));
simulation.getSolverTaskDescription().setOutputTimeSpec(exTimeSpec);
// set parameters as math overrides
MathOverrides mathOverrides = simulation.getMathOverrides();
for (int i = 0; i < paramNames.length; i++) {
mathOverrides.putConstant(new Constant(paramNames[i], new Expression(paramValues[i])));
}
SimulationTask simTask = new SimulationTask(new SimulationJob(simulation, 0, null), 0);
IDASolverStandalone idaSolver = new IDASolverStandalone(simTask, ResourceUtil.getLocalSimDir("temp"), false);
// startSolver();
idaSolver.runSolver();
Thread.sleep(1000);
long startTimeMS = System.currentTimeMillis();
while (idaSolver.getSolverStatus().isRunning() && System.currentTimeMillis() < (startTimeMS + 10000L)) {
Thread.sleep(500);
}
ODESolverResultSet resultset = idaSolver.getODESolverResultSet();
return resultset;
}
Aggregations