use of cbit.vcell.matrix.RationalExp in project vcell by virtualcell.
the class FastSystemAnalyzer method refreshSubstitutedRateExps.
/**
*/
private void refreshSubstitutedRateExps() throws MathException, ExpressionException {
//
// refresh PseudoConstants (temp constants involved with fastInvariants)
//
pseudoConstantList.removeAllElements();
Enumeration<FastInvariant> enum_fi = fastSystem.getFastInvariants();
while (enum_fi.hasMoreElements()) {
FastInvariant fi = enum_fi.nextElement();
Domain domain = new Domain(fastSystem.getSubDomain());
fi.getFunction().bindExpression(this);
PseudoConstant pc = new PseudoConstant(getAvailablePseudoConstantName(), fi.getFunction(), domain);
pseudoConstantList.addElement(pc);
// System.out.println("FastSystem.refreshSubstitutedRateExps() __C"+i+" = "+fi.getFunction());
}
//
// build expressions for dependent variables in terms of independent vars
// and pseudoConstants
//
dependencyExpList.removeAllElements();
for (int row = 0; row < dependentVarList.size(); row++) {
Expression exp = new Expression("0.0;");
//
for (int col = 0; col < independentVarList.size(); col++) {
Variable indepVar = (Variable) independentVarList.elementAt(col);
RationalExp coefExp = dependencyMatrix.get(row, col).simplify();
if (!coefExp.isZero()) {
exp = Expression.add(exp, new Expression(coefExp.infixString() + "*" + indepVar.getName()));
}
}
//
for (int col = independentVarList.size(); col < dependencyMatrix.getNumCols(); col++) {
PseudoConstant pc = (PseudoConstant) pseudoConstantList.elementAt(col - independentVarList.size());
RationalExp coefExp = dependencyMatrix.get(row, col);
if (!coefExp.isZero()) {
exp = Expression.add(exp, new Expression(coefExp.infixString() + "*" + pc.getName()));
}
}
exp.bindExpression(null);
exp = exp.flatten();
exp.bindExpression(this);
// System.out.println("FastSystem.refreshSubstitutedRateExps() "+((Variable)dependentVarList.elementAt(row)).getName()+" = "+exp.toString()+";");
dependencyExpList.addElement(exp);
}
//
// flatten functions, then substitute expressions for dependent vars into rate expressions
//
fastRateExpList.removeAllElements();
// VariableSymbolTable combinedSymbolTable = getCombinedSymbolTable();
Enumeration<FastRate> enum_fr = fastSystem.getFastRates();
while (enum_fr.hasMoreElements()) {
FastRate fr = enum_fr.nextElement();
Expression exp = new Expression(MathUtilities.substituteFunctions(new Expression(fr.getFunction()), this));
// System.out.println("FastSystem.refreshSubstitutedRateExps() fast rate before substitution = "+exp.toString());
for (int j = 0; j < dependentVarList.size(); j++) {
Variable depVar = (Variable) dependentVarList.elementAt(j);
Expression subExp = new Expression((Expression) dependencyExpList.elementAt(j));
exp.substituteInPlace(new Expression(depVar.getName()), subExp);
}
exp.bindExpression(null);
exp = exp.flatten();
// System.out.println("FastSystem.refreshSubstitutedRateExps() fast rate after substitution = "+exp.toString());
exp.bindExpression(this);
fastRateExpList.addElement(exp);
}
}
use of cbit.vcell.matrix.RationalExp in project vcell by virtualcell.
the class FastSystemAnalyzer method refreshInvarianceMatrix.
/**
*/
private void refreshInvarianceMatrix() throws MathException, ExpressionException {
//
// the invariance's are expressed in matrix form
//
// |a a a a a -1 0 0| |x1| |0|
// |a a a a a 0 -1 0| * |x2| = |0|
// |a a a a a 0 0 -1| |x3| |0|
// |x4|
// |x5|
// |c1|
// |c2|
// |c3|
//
Variable[] vars = new Variable[fastVarList.size()];
fastVarList.copyInto(vars);
int numVars = fastVarList.size();
int rows = fastSystem.getNumFastInvariants();
int cols = numVars + fastSystem.getNumFastInvariants();
RationalExpMatrix matrix = new RationalExpMatrix(rows, cols);
Enumeration<FastInvariant> fastInvariantsEnum = fastSystem.getFastInvariants();
for (int i = 0; i < rows && fastInvariantsEnum.hasMoreElements(); i++) {
FastInvariant fi = (FastInvariant) fastInvariantsEnum.nextElement();
Expression function = fi.getFunction();
for (int j = 0; j < numVars; j++) {
Variable var = (Variable) fastVarList.elementAt(j);
Expression exp = function.differentiate(var.getName());
exp.bindExpression(null);
exp = exp.flatten();
RationalExp coeffRationalExp = RationalExpUtils.getRationalExp(exp);
matrix.set_elem(i, j, coeffRationalExp);
}
matrix.set_elem(i, numVars + i, -1);
}
// Print
System.out.println("origMatrix");
matrix.show();
//
// gaussian elimination on the matrix give the following representation
// note that some column pivoting (variable re-ordering) is sometimes required to
// determine N-r dependent vars
//
// |10i0iccc|
// |01i0iccc| where (c)'s are the coefficients for constants of invariances
// |00i1iccc| (i)'s are the coefficients for dependent vars in terms of independent vars
//
// Print
System.out.println("reducedMatrix");
if (rows > 0) {
try {
matrix.gaussianElimination(new RationalExpMatrix(rows, rows));
} catch (MatrixException e) {
e.printStackTrace(System.out);
throw new MathException(e.getMessage());
}
}
matrix.show();
for (int i = 0; i < vars.length; i++) {
System.out.print(vars[i].getName() + " ");
}
System.out.println("");
//
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows; j++) {
RationalExp rexp = matrix.get(i, j).simplify();
matrix.set_elem(i, j, rexp);
}
}
for (int i = 0; i < rows; i++) {
//
if (!matrix.get(i, i).isConstant() || matrix.get(i, i).getConstant().doubleValue() != 1) {
for (int j = i + 1; j < numVars; j++) {
if (matrix.get(i, j).isConstant() && matrix.get(i, j).getConstant().doubleValue() == 1.0) {
for (int ii = 0; ii < rows; ii++) {
RationalExp temp = matrix.get(ii, i);
matrix.set_elem(ii, i, matrix.get(ii, j));
matrix.set_elem(ii, j, temp);
}
Variable tempVar = vars[i];
vars[i] = vars[j];
vars[j] = tempVar;
break;
}
}
}
}
// Print
for (int i = 0; i < vars.length; i++) {
System.out.print(vars[i].getName() + " ");
}
System.out.println("");
matrix.show();
//
// separate into dependent and indepent variables, and chop off identity matrix (left N-r columns)
//
// T |iiccc| T
// [x1 x2 x4] = -1 * |iiccc| * [x3 x5 c1 c2 c3]
// |iiccc|
//
//
int numInvariants = fastSystem.getNumFastInvariants();
dependentVarList.removeAllElements();
for (int i = 0; i < numInvariants; i++) {
dependentVarList.addElement(vars[i]);
}
independentVarList.removeAllElements();
for (int i = numInvariants; i < vars.length; i++) {
independentVarList.addElement(vars[i]);
}
int new_cols = independentVarList.size() + numInvariants;
dependencyMatrix = new RationalExpMatrix(rows, new_cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < new_cols; j++) {
RationalExp rexp = matrix.get(i, j + dependentVarList.size()).simplify().minus();
dependencyMatrix.set_elem(i, j, rexp);
}
}
// Print
System.out.println("\n\nDEPENDENCY MATRIX");
dependencyMatrix.show();
System.out.print("dependent vars: ");
for (int i = 0; i < dependentVarList.size(); i++) {
System.out.print(((Variable) dependentVarList.elementAt(i)).getName() + " ");
}
System.out.println("");
System.out.print("independent vars: ");
for (int i = 0; i < independentVarList.size(); i++) {
System.out.print(((Variable) independentVarList.elementAt(i)).getName() + " ");
}
System.out.println("");
}
use of cbit.vcell.matrix.RationalExp in project vcell by virtualcell.
the class IDAFileWriter method writeEquations.
/**
* Insert the method's description here.
* Creation date: (3/8/00 10:31:52 PM)
*/
protected String writeEquations(HashMap<Discontinuity, String> discontinuityNameMap) throws MathException, ExpressionException {
Simulation simulation = simTask.getSimulation();
StringBuffer sb = new StringBuffer();
MathDescription mathDescription = simulation.getMathDescription();
if (mathDescription.hasFastSystems()) {
//
// define vector of original variables
//
SimulationSymbolTable simSymbolTable = simTask.getSimulationJob().getSimulationSymbolTable();
CompartmentSubDomain subDomain = (CompartmentSubDomain) mathDescription.getSubDomains().nextElement();
FastSystem fastSystem = subDomain.getFastSystem();
FastSystemAnalyzer fs_Analyzer = new FastSystemAnalyzer(fastSystem, simSymbolTable);
int numIndependent = fs_Analyzer.getNumIndependentVariables();
int systemDim = mathDescription.getStateVariableNames().size();
int numDependent = systemDim - numIndependent;
//
// get all variables from fast system (dependent and independent)
//
HashSet<String> fastSystemVarHash = new HashSet<String>();
Enumeration<Variable> dependentfastSystemVarEnum = fs_Analyzer.getDependentVariables();
while (dependentfastSystemVarEnum.hasMoreElements()) {
fastSystemVarHash.add(dependentfastSystemVarEnum.nextElement().getName());
}
Enumeration<Variable> independentfastSystemVarEnum = fs_Analyzer.getIndependentVariables();
while (independentfastSystemVarEnum.hasMoreElements()) {
fastSystemVarHash.add(independentfastSystemVarEnum.nextElement().getName());
}
//
// get all equations including for variables that are not in the fastSystem (ode equations for "slow system")
//
RationalExpMatrix origInitVector = new RationalExpMatrix(systemDim, 1);
RationalExpMatrix origSlowRateVector = new RationalExpMatrix(systemDim, 1);
RationalExpMatrix origVarColumnVector = new RationalExpMatrix(systemDim, 1);
Enumeration<Equation> enumEquations = subDomain.getEquations();
int varIndex = 0;
while (enumEquations.hasMoreElements()) {
Equation equation = enumEquations.nextElement();
origVarColumnVector.set_elem(varIndex, 0, new RationalExp(equation.getVariable().getName()));
Expression rateExpr = equation.getRateExpression();
rateExpr.bindExpression(varsSymbolTable);
rateExpr = MathUtilities.substituteFunctions(rateExpr, varsSymbolTable);
origSlowRateVector.set_elem(varIndex, 0, new RationalExp("(" + rateExpr.flatten().infix() + ")"));
Expression initExpr = new Expression(equation.getInitialExpression());
initExpr.substituteInPlace(new Expression("t"), new Expression(0.0));
initExpr = MathUtilities.substituteFunctions(initExpr, varsSymbolTable).flatten();
origInitVector.set_elem(varIndex, 0, new RationalExp("(" + initExpr.flatten().infix() + ")"));
varIndex++;
}
//
// make symbolic matrix for fast invariants (from FastSystem's fastInvariants as well as a new fast invariant for each variable not included in the fast system.
//
RationalExpMatrix fastInvarianceMatrix = new RationalExpMatrix(numDependent, systemDim);
int row = 0;
for (int i = 0; i < origVarColumnVector.getNumRows(); i++) {
//
if (!fastSystemVarHash.contains(origVarColumnVector.get(i, 0).infixString())) {
fastInvarianceMatrix.set_elem(row, i, RationalExp.ONE);
row++;
}
}
Enumeration<FastInvariant> enumFastInvariants = fastSystem.getFastInvariants();
while (enumFastInvariants.hasMoreElements()) {
FastInvariant fastInvariant = enumFastInvariants.nextElement();
Expression fastInvariantExpression = fastInvariant.getFunction();
for (int col = 0; col < systemDim; col++) {
Expression coeff = fastInvariantExpression.differentiate(origVarColumnVector.get(col, 0).infixString()).flatten();
coeff = simSymbolTable.substituteFunctions(coeff);
fastInvarianceMatrix.set_elem(row, col, RationalExpUtils.getRationalExp(coeff));
}
row++;
}
for (int i = 0; i < systemDim; i++) {
sb.append("VAR " + origVarColumnVector.get(i, 0).infixString() + " INIT " + origInitVector.get(i, 0).infixString() + ";\n");
}
RationalExpMatrix fullMatrix = null;
RationalExpMatrix inverseFullMatrix = null;
RationalExpMatrix newSlowRateVector = null;
try {
RationalExpMatrix fastMat = ((RationalExpMatrix) fastInvarianceMatrix.transpose().findNullSpace());
fullMatrix = new RationalExpMatrix(systemDim, systemDim);
row = 0;
for (int i = 0; i < fastInvarianceMatrix.getNumRows(); i++) {
for (int col = 0; col < systemDim; col++) {
fullMatrix.set_elem(row, col, fastInvarianceMatrix.get(i, col));
}
row++;
}
for (int i = 0; i < fastMat.getNumRows(); i++) {
for (int col = 0; col < systemDim; col++) {
fullMatrix.set_elem(row, col, fastMat.get(i, col));
}
row++;
}
inverseFullMatrix = new RationalExpMatrix(systemDim, systemDim);
inverseFullMatrix.identity();
RationalExpMatrix copyOfFullMatrix = new RationalExpMatrix(fullMatrix);
copyOfFullMatrix.gaussianElimination(inverseFullMatrix);
newSlowRateVector = new RationalExpMatrix(numDependent, 1);
newSlowRateVector.matmul(fastInvarianceMatrix, origSlowRateVector);
} catch (MatrixException ex) {
ex.printStackTrace();
throw new MathException(ex.getMessage());
}
sb.append("TRANSFORM\n");
for (row = 0; row < systemDim; row++) {
for (int col = 0; col < systemDim; col++) {
sb.append(fullMatrix.get(row, col).getConstant().doubleValue() + " ");
}
sb.append("\n");
}
sb.append("INVERSETRANSFORM\n");
for (row = 0; row < systemDim; row++) {
for (int col = 0; col < systemDim; col++) {
sb.append(inverseFullMatrix.get(row, col).getConstant().doubleValue() + " ");
}
sb.append("\n");
}
int numDifferential = numDependent;
int numAlgebraic = numIndependent;
sb.append("RHS DIFFERENTIAL " + numDifferential + " ALGEBRAIC " + numAlgebraic + "\n");
int equationIndex = 0;
while (equationIndex < numDependent) {
// print row of mass matrix followed by slow rate corresponding to fast invariant
Expression slowRateExp = new Expression(newSlowRateVector.get(equationIndex, 0).infixString()).flatten();
slowRateExp.bindExpression(simSymbolTable);
slowRateExp = MathUtilities.substituteFunctions(slowRateExp, varsSymbolTable).flatten();
Vector<Discontinuity> v = slowRateExp.getDiscontinuities();
for (Discontinuity od : v) {
od = getSubsitutedAndFlattened(od, varsSymbolTable);
String dname = discontinuityNameMap.get(od);
if (dname == null) {
dname = ROOT_VARIABLE_PREFIX + discontinuityNameMap.size();
discontinuityNameMap.put(od, dname);
}
slowRateExp.substituteInPlace(od.getDiscontinuityExp(), new Expression("(" + dname + "==1)"));
}
sb.append(slowRateExp.infix() + ";\n");
equationIndex++;
}
Enumeration<FastRate> enumFastRates = fastSystem.getFastRates();
while (enumFastRates.hasMoreElements()) {
// print the fastRate for this row
Expression fastRateExp = new Expression(enumFastRates.nextElement().getFunction());
fastRateExp = MathUtilities.substituteFunctions(fastRateExp, varsSymbolTable).flatten();
Vector<Discontinuity> v = fastRateExp.getDiscontinuities();
for (Discontinuity od : v) {
od = getSubsitutedAndFlattened(od, varsSymbolTable);
String dname = discontinuityNameMap.get(od);
if (dname == null) {
dname = ROOT_VARIABLE_PREFIX + discontinuityNameMap.size();
discontinuityNameMap.put(od, dname);
}
fastRateExp.substituteInPlace(od.getDiscontinuityExp(), new Expression("(" + dname + "==1)"));
}
sb.append(fastRateExp.flatten().infix() + ";\n");
equationIndex++;
}
} else {
for (int i = 0; i < getStateVariableCount(); i++) {
StateVariable stateVar = getStateVariable(i);
Expression initExpr = new Expression(stateVar.getInitialRateExpression());
initExpr = MathUtilities.substituteFunctions(initExpr, varsSymbolTable);
initExpr.substituteInPlace(new Expression("t"), new Expression(0.0));
sb.append("VAR " + stateVar.getVariable().getName() + " INIT " + initExpr.flatten().infix() + ";\n");
}
sb.append("TRANSFORM\n");
for (int row = 0; row < getStateVariableCount(); row++) {
for (int col = 0; col < getStateVariableCount(); col++) {
sb.append((row == col ? 1 : 0) + " ");
}
sb.append("\n");
}
sb.append("INVERSETRANSFORM\n");
for (int row = 0; row < getStateVariableCount(); row++) {
for (int col = 0; col < getStateVariableCount(); col++) {
sb.append((row == col ? 1 : 0) + " ");
}
sb.append("\n");
}
sb.append("RHS DIFFERENTIAL " + getStateVariableCount() + " ALGEBRAIC 0\n");
for (int i = 0; i < getStateVariableCount(); i++) {
StateVariable stateVar = getStateVariable(i);
Expression rateExpr = new Expression(stateVar.getRateExpression());
rateExpr = MathUtilities.substituteFunctions(rateExpr, varsSymbolTable).flatten();
Vector<Discontinuity> v = rateExpr.getDiscontinuities();
for (Discontinuity od : v) {
od = getSubsitutedAndFlattened(od, varsSymbolTable);
String dname = discontinuityNameMap.get(od);
if (dname == null) {
dname = ROOT_VARIABLE_PREFIX + discontinuityNameMap.size();
discontinuityNameMap.put(od, dname);
}
rateExpr.substituteInPlace(od.getDiscontinuityExp(), new Expression("(" + dname + "==1)"));
}
sb.append(rateExpr.infix() + ";\n");
}
}
return sb.toString();
}
use of cbit.vcell.matrix.RationalExp in project vcell by virtualcell.
the class StochMathMapping method getProbabilityRate.
/**
* Get probability expression for the specific elementary reaction.
* Input: ReactionStep, the reaction. isForwardDirection, if the elementary reaction is forward from the reactionstep.
* Output: Expression. the probability expression.
* Creation date: (9/14/2006 3:22:58 PM)
* @throws ExpressionException
*/
private Expression getProbabilityRate(ReactionStep reactionStep, Expression rateConstantExpr, boolean isForwardDirection) throws MappingException, ExpressionException, ModelException {
// the structure where reaction happens
StructureMapping sm = getSimulationContext().getGeometryContext().getStructureMapping(reactionStep.getStructure());
Model model = getSimulationContext().getModel();
Expression reactionStructureSize = new Expression(sm.getStructure().getStructureSize(), getNameScope());
VCUnitDefinition reactionSubstanceUnit = model.getUnitSystem().getSubstanceUnit(reactionStep.getStructure());
VCUnitDefinition stochasticSubstanceUnit = model.getUnitSystem().getStochasticSubstanceUnit();
Expression reactionSubstanceUnitFactor = getUnitFactor(stochasticSubstanceUnit.divideBy(reactionSubstanceUnit));
Expression factorExpr = Expression.mult(reactionStructureSize, reactionSubstanceUnitFactor);
// Using the MassActionFunction to write out the math description
MassActionSolver.MassActionFunction maFunc = null;
Kinetics kinetics = reactionStep.getKinetics();
if (kinetics.getKineticsDescription().equals(KineticsDescription.MassAction) || kinetics.getKineticsDescription().equals(KineticsDescription.General) || kinetics.getKineticsDescription().equals(KineticsDescription.GeneralPermeability)) {
Expression rateExp = kinetics.getKineticsParameterFromRole(Kinetics.ROLE_ReactionRate).getExpression();
Parameter forwardRateParameter = null;
Parameter reverseRateParameter = null;
if (kinetics.getKineticsDescription().equals(KineticsDescription.MassAction)) {
forwardRateParameter = kinetics.getKineticsParameterFromRole(Kinetics.ROLE_KForward);
reverseRateParameter = kinetics.getKineticsParameterFromRole(Kinetics.ROLE_KReverse);
} else if (kinetics.getKineticsDescription().equals(KineticsDescription.GeneralPermeability)) {
forwardRateParameter = kinetics.getKineticsParameterFromRole(Kinetics.ROLE_Permeability);
reverseRateParameter = kinetics.getKineticsParameterFromRole(Kinetics.ROLE_Permeability);
}
maFunc = MassActionSolver.solveMassAction(forwardRateParameter, reverseRateParameter, rateExp, reactionStep);
if (maFunc.getForwardRate() == null && maFunc.getReverseRate() == null) {
throw new MappingException("Cannot generate stochastic math mapping for the reaction:" + reactionStep.getName() + "\nLooking for the rate function according to the form of k1*Reactant1^Stoir1*Reactant2^Stoir2...-k2*Product1^Stoip1*Product2^Stoip2.");
}
} else {
throw new MappingException("Cannot generate stochastic math mapping for the reaction:" + reactionStep.getName() + "\n. Unsupported kinetic type " + kinetics.getKineticsDescription().getName());
}
List<ReactionParticipant> reacPart;
if (isForwardDirection) {
reacPart = maFunc.getReactants();
System.out.println("forward reaction rate (coefficient?) is " + maFunc.getForwardRate().infix());
} else {
reacPart = maFunc.getProducts();
System.out.println("reverse reaction rate (coefficient?) is " + maFunc.getReverseRate().infix());
}
Expression rxnProbabilityExpr = null;
for (int i = 0; i < reacPart.size(); i++) {
VCUnitDefinition speciesSubstanceUnit = model.getUnitSystem().getSubstanceUnit(reacPart.get(i).getStructure());
Expression speciesUnitFactor = getUnitFactor(speciesSubstanceUnit.divideBy(stochasticSubstanceUnit));
int stoichiometry = 0;
stoichiometry = reacPart.get(i).getStoichiometry();
// ******the following part is to form the s*(s-1)(s-2)..(s-stoi+1).portion of the probability rate.
Expression speciesStructureSize = new Expression(reacPart.get(i).getStructure().getStructureSize(), getNameScope());
Expression speciesFactor = Expression.div(speciesUnitFactor, speciesStructureSize);
// s*(s-1)(s-2)..(s-stoi+1)
SpeciesCountParameter spCountParam = getSpeciesCountParameter(reacPart.get(i).getSpeciesContext());
Expression spCount_exp = new Expression(spCountParam, getNameScope());
// species from uM to No. of Particles, form s*(s-1)*(s-2)
Expression speciesFactorial = new Expression(spCount_exp);
for (int j = 1; j < stoichiometry; j++) {
speciesFactorial = Expression.mult(speciesFactorial, Expression.add(spCount_exp, new Expression(-j)));
}
// update total factor with speceies factor
if (stoichiometry == 1) {
factorExpr = Expression.mult(factorExpr, speciesFactor);
} else if (stoichiometry > 1) {
// rxnProbExpr * (structSize^stoichiometry)
factorExpr = Expression.mult(factorExpr, Expression.power(speciesFactor, new Expression(stoichiometry)));
}
if (rxnProbabilityExpr == null) {
rxnProbabilityExpr = new Expression(speciesFactorial);
} else {
// for more than one reactant
rxnProbabilityExpr = Expression.mult(rxnProbabilityExpr, speciesFactorial);
}
}
// Now construct the probability expression.
Expression probExp = null;
if (rateConstantExpr == null) {
throw new MappingException("Can not find reaction rate constant in reaction: " + reactionStep.getName());
} else if (rxnProbabilityExpr == null) {
probExp = new Expression(rateConstantExpr);
} else if ((rateConstantExpr != null) && (rxnProbabilityExpr != null)) {
probExp = Expression.mult(rateConstantExpr, rxnProbabilityExpr);
}
// simplify the factor
RationalExp factorRatExp = RationalExpUtils.getRationalExp(factorExpr);
factorExpr = new Expression(factorRatExp.infixString());
factorExpr.bindExpression(this);
// get probability rate with converting factor
probExp = Expression.mult(probExp, factorExpr);
probExp = probExp.flatten();
return probExp;
}
use of cbit.vcell.matrix.RationalExp in project vcell by virtualcell.
the class FastSystemAnalyzer method refreshInvarianceMatrix.
/**
*/
private void refreshInvarianceMatrix() throws MathException, ExpressionException {
//
// the invariance's are expressed in matrix form
//
// |a a a a a -1 0 0| |x1| |0|
// |a a a a a 0 -1 0| * |x2| = |0|
// |a a a a a 0 0 -1| |x3| |0|
// |x4|
// |x5|
// |c1|
// |c2|
// |c3|
//
Variable[] vars = new Variable[fastVarList.size()];
fastVarList.copyInto(vars);
int numVars = fastVarList.size();
int rows = fastSystem.getNumFastInvariants();
int cols = numVars + fastSystem.getNumFastInvariants();
RationalExpMatrix matrix = new RationalExpMatrix(rows, cols);
Enumeration<FastInvariant> fastInvariantsEnum = fastSystem.getFastInvariants();
for (int i = 0; i < rows && fastInvariantsEnum.hasMoreElements(); i++) {
FastInvariant fi = (FastInvariant) fastInvariantsEnum.nextElement();
Expression function = fi.getFunction();
for (int j = 0; j < numVars; j++) {
Variable var = (Variable) fastVarList.elementAt(j);
Expression exp = function.differentiate(var.getName());
exp.bindExpression(null);
exp = exp.flatten();
RationalExp coeffRationalExp = RationalExpUtils.getRationalExp(exp);
matrix.set_elem(i, j, coeffRationalExp);
}
matrix.set_elem(i, numVars + i, -1);
}
// Print
System.out.println("origMatrix");
matrix.show();
//
// gaussian elimination on the matrix give the following representation
// note that some column pivoting (variable re-ordering) is sometimes required to
// determine N-r dependent vars
//
// |10i0iccc|
// |01i0iccc| where (c)'s are the coefficients for constants of invariances
// |00i1iccc| (i)'s are the coefficients for dependent vars in terms of independent vars
//
// Print
System.out.println("reducedMatrix");
if (rows > 0) {
try {
matrix.gaussianElimination(new RationalExpMatrix(rows, rows));
} catch (MatrixException e) {
e.printStackTrace(System.out);
throw new MathException(e.getMessage());
}
}
matrix.show();
for (int i = 0; i < vars.length; i++) {
System.out.print(vars[i].getName() + " ");
}
System.out.println("");
//
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows; j++) {
RationalExp rexp = matrix.get(i, j).simplify();
matrix.set_elem(i, j, rexp);
}
}
for (int i = 0; i < rows; i++) {
//
if (!matrix.get(i, i).isConstant() || matrix.get(i, i).getConstant().doubleValue() != 1) {
for (int j = i + 1; j < numVars; j++) {
if (matrix.get(i, j).isConstant() && matrix.get(i, j).getConstant().doubleValue() == 1.0) {
for (int ii = 0; ii < rows; ii++) {
RationalExp temp = matrix.get(ii, i);
matrix.set_elem(ii, i, matrix.get(ii, j));
matrix.set_elem(ii, j, temp);
}
Variable tempVar = vars[i];
vars[i] = vars[j];
vars[j] = tempVar;
break;
}
}
}
}
// Print
for (int i = 0; i < vars.length; i++) {
System.out.print(vars[i].getName() + " ");
}
System.out.println("");
matrix.show();
//
// separate into dependent and indepent variables, and chop off identity matrix (left N-r columns)
//
// T |iiccc| T
// [x1 x2 x4] = -1 * |iiccc| * [x3 x5 c1 c2 c3]
// |iiccc|
//
//
int numInvariants = fastSystem.getNumFastInvariants();
dependentVarList.removeAllElements();
for (int i = 0; i < numInvariants; i++) {
dependentVarList.addElement(vars[i]);
}
independentVarList.removeAllElements();
for (int i = numInvariants; i < vars.length; i++) {
independentVarList.addElement(vars[i]);
}
int new_cols = independentVarList.size() + numInvariants;
dependencyMatrix = new RationalExpMatrix(rows, new_cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < new_cols; j++) {
RationalExp rexp = matrix.get(i, j + dependentVarList.size()).simplify().minus();
dependencyMatrix.set_elem(i, j, rexp);
}
}
// Print
System.out.println("\n\nDEPENDENCY MATRIX");
dependencyMatrix.show();
System.out.print("dependent vars: ");
for (int i = 0; i < dependentVarList.size(); i++) {
System.out.print(((Variable) dependentVarList.elementAt(i)).getName() + " ");
}
System.out.println("");
System.out.print("independent vars: ");
for (int i = 0; i < independentVarList.size(); i++) {
System.out.print(((Variable) independentVarList.elementAt(i)).getName() + " ");
}
System.out.println("");
}
Aggregations