use of cbit.vcell.math.Variable in project vcell by virtualcell.
the class MathSymbolMapping method reconcileVarNames.
/**
* Insert the method's description here.
* Creation date: (5/3/2006 4:03:51 PM)
* @param mathDesc cbit.vcell.math.MathDescription
*/
public void reconcileVarNames(MathDescription mathDesc) {
//
// clear secondary hashmaps in case called multiple times.
//
biologicalToMathHash.clear();
mathToBiologicalHash.clear();
java.util.Set<SymbolTableEntry> keyset = biologicalToMathSymbolNameHash.keySet();
java.util.Iterator<SymbolTableEntry> keysetIter = keyset.iterator();
while (keysetIter.hasNext()) {
SymbolTableEntry biologicalSymbol = keysetIter.next();
String mathVarName = (String) biologicalToMathSymbolNameHash.get(biologicalSymbol);
Variable var = mathDesc.getVariable(mathVarName);
if (var != null) {
biologicalToMathHash.put(biologicalSymbol, var);
SymbolTableEntry[] previousBiologicalSymbolArr = (SymbolTableEntry[]) mathToBiologicalHash.put(var, new SymbolTableEntry[] { biologicalSymbol });
if (previousBiologicalSymbolArr != null) {
SymbolTableEntry[] steArr = (SymbolTableEntry[]) BeanUtils.addElement(previousBiologicalSymbolArr, biologicalSymbol);
mathToBiologicalHash.put(var, steArr);
}
}
}
}
use of cbit.vcell.math.Variable in project vcell by virtualcell.
the class ParticleMathMapping method combineHybrid.
private void combineHybrid() throws MappingException, ExpressionException, MatrixException, MathException, ModelException {
ArrayList<SpeciesContext> continuousSpecies = new ArrayList<SpeciesContext>();
ArrayList<ParticleVariable> continuousSpeciesParticleVars = new ArrayList<ParticleVariable>();
ArrayList<SpeciesContext> stochSpecies = new ArrayList<SpeciesContext>();
//
// categorize speciesContexts as continuous and stochastic
//
SpeciesContextSpec[] scsArray = getSimulationContext().getReactionContext().getSpeciesContextSpecs();
continuousSpecies = new ArrayList<SpeciesContext>();
stochSpecies = new ArrayList<SpeciesContext>();
for (SpeciesContextSpec speciesContextSpec : scsArray) {
if (!getSimulationContext().isStoch() || speciesContextSpec.isForceContinuous()) {
continuousSpecies.add(speciesContextSpec.getSpeciesContext());
Variable variable = getMathSymbolMapping().getVariable(speciesContextSpec.getSpeciesContext());
if (variable instanceof ParticleVariable) {
continuousSpeciesParticleVars.add((ParticleVariable) variable);
}
} else {
stochSpecies.add(speciesContextSpec.getSpeciesContext());
}
}
if (continuousSpecies.isEmpty()) {
return;
}
//
// create continuous mathDescription ... add stochastic variables and processes to the continuous Math and use this.
//
DiffEquMathMapping mathMapping = new DiffEquMathMapping(getSimulationContext(), callback, networkGenerationRequirements);
mathMapping.refresh(null);
MathDescription contMathDesc = mathMapping.getMathDescription();
//
// get list of all continuous variables
//
HashMap<String, Variable> allContinuousVars = new HashMap<String, Variable>();
Enumeration<Variable> enumVar = contMathDesc.getVariables();
while (enumVar.hasMoreElements()) {
Variable var = enumVar.nextElement();
allContinuousVars.put(var.getName(), var);
}
//
// replace those continuous variables and equations for stochastic speciesContexts
// with the particleVariables and particleProperties
// (ParticleJumpProcesses removed later)
//
ModelUnitSystem unitSystem = getSimulationContext().getModel().getUnitSystem();
for (SpeciesContext stochSpeciesContext : stochSpecies) {
Variable contVar = mathMapping.getMathSymbolMapping().getVariable(stochSpeciesContext);
Variable stochVar = getMathSymbolMapping().getVariable(stochSpeciesContext);
allContinuousVars.put(stochVar.getName(), stochVar);
//
// replace continuous "concentration" VolVariable/MemVariable for this particle with a Function for concentration
//
allContinuousVars.remove(contVar);
VCUnitDefinition sizeUnit = unitSystem.getLengthUnit().raiseTo(new RationalNumber(stochSpeciesContext.getStructure().getDimension()));
VCUnitDefinition stochasticDensityUnit = unitSystem.getStochasticSubstanceUnit().divideBy(sizeUnit);
VCUnitDefinition continuousDensityUnit = unitSystem.getConcentrationUnit(stochSpeciesContext.getStructure());
if (stochasticDensityUnit.isEquivalent(continuousDensityUnit)) {
allContinuousVars.put(contVar.getName(), new Function(contVar.getName(), new Expression(stochVar, getNameScope()), contVar.getDomain()));
} else {
Expression conversionFactorExp = getUnitFactor(continuousDensityUnit.divideBy(stochasticDensityUnit));
allContinuousVars.put(contVar.getName(), new Function(contVar.getName(), Expression.mult(new Expression(stochVar, getNameScope()), conversionFactorExp), contVar.getDomain()));
}
//
// remove continuous equation
//
Enumeration<SubDomain> contSubDomains = contMathDesc.getSubDomains();
while (contSubDomains.hasMoreElements()) {
SubDomain contSubDomain = contSubDomains.nextElement();
contSubDomain.removeEquation(contVar);
if (contSubDomain instanceof MembraneSubDomain) {
((MembraneSubDomain) contSubDomain).removeJumpCondition(contVar);
}
}
//
// remove all continuous variables for speciesContextSpec parameters (e.g. initial conditions, diffusion rates, boundary conditions, velocities)
//
SpeciesContextSpec scs = getSimulationContext().getReactionContext().getSpeciesContextSpec(stochSpeciesContext);
Parameter[] scsParameters = scs.getParameters();
for (Parameter parameter : scsParameters) {
Variable continuousScsParmVariable = mathMapping.getMathSymbolMapping().getVariable(parameter);
allContinuousVars.remove(continuousScsParmVariable);
}
//
// copy ParticleJumpProcess and ParticleProperties to the continuous math
//
SubDomain contSubDomain = contMathDesc.getSubDomain(contVar.getDomain().getName());
SubDomain stochSubDomain = mathDesc.getSubDomain(stochVar.getDomain().getName());
ParticleProperties particleProperties = stochSubDomain.getParticleProperties(stochVar);
contSubDomain.addParticleProperties(particleProperties);
}
//
// add all ParticleJumpProcesses to the continuous model
//
Enumeration<SubDomain> enumStochSubdomains = mathDesc.getSubDomains();
while (enumStochSubdomains.hasMoreElements()) {
SubDomain stochSubdomain = enumStochSubdomains.nextElement();
SubDomain contSubdomain = contMathDesc.getSubDomain(stochSubdomain.getName());
for (ParticleJumpProcess particleJumpProcess : stochSubdomain.getParticleJumpProcesses()) {
//
// modify "selection list" (particleVariables), probability rate, and actions if referenced particleVariable is to be "forced continuous"
//
ParticleVariable[] selectedParticles = particleJumpProcess.getParticleVariables();
for (ParticleVariable particleVariable : selectedParticles) {
if (continuousSpeciesParticleVars.contains(particleVariable)) {
particleJumpProcess.remove(particleVariable);
JumpProcessRateDefinition jumpProcessRateDefinition = particleJumpProcess.getParticleRateDefinition();
if (jumpProcessRateDefinition instanceof MacroscopicRateConstant) {
MacroscopicRateConstant macroscopicRateConstant = (MacroscopicRateConstant) jumpProcessRateDefinition;
macroscopicRateConstant.setExpression(Expression.mult(macroscopicRateConstant.getExpression(), new Expression(particleVariable, null)));
} else if (jumpProcessRateDefinition instanceof InteractionRadius) {
throw new MappingException("cannot adjust interaction radius for reaction process " + particleJumpProcess.getName() + ", particle " + particleVariable.getName() + " is continuous");
} else {
throw new MappingException("rate definition type " + jumpProcessRateDefinition.getClass().getSimpleName() + " not yet implemented for hybrid PDE/Particle math generation");
}
}
Iterator<Action> iterAction = particleJumpProcess.getActions().iterator();
while (iterAction.hasNext()) {
Action action = iterAction.next();
if (continuousSpeciesParticleVars.contains(action.getVar())) {
iterAction.remove();
}
}
}
if (!particleJumpProcess.getActions().isEmpty()) {
contSubdomain.addParticleJumpProcess(particleJumpProcess);
}
}
}
//
for (MathMappingParameter mathMappingParameter : fieldMathMappingParameters) {
if (mathMappingParameter instanceof UnitFactorParameter) {
String name = mathMappingParameter.getName();
if (!allContinuousVars.containsKey(name)) {
allContinuousVars.put(name, newFunctionOrConstant(name, mathMappingParameter.getExpression(), null));
}
}
}
//
// add constants and functions from the particle math that aren't already defined in the continuous math
//
Enumeration<Variable> enumVars = mathDesc.getVariables();
while (enumVars.hasMoreElements()) {
Variable var = enumVars.nextElement();
if (var instanceof Constant || var instanceof Function) {
String name = var.getName();
if (!allContinuousVars.containsKey(name)) {
allContinuousVars.put(name, var);
}
}
}
contMathDesc.setAllVariables(allContinuousVars.values().toArray(new Variable[0]));
mathDesc = contMathDesc;
//
for (int i = 0; i < fieldMathMappingParameters.length; i++) {
if (fieldMathMappingParameters[i] instanceof UnitFactorParameter) {
GeometryClass geometryClass = fieldMathMappingParameters[i].getGeometryClass();
Variable variable = newFunctionOrConstant(getMathSymbol(fieldMathMappingParameters[i], geometryClass), getIdentifierSubstitutions(fieldMathMappingParameters[i].getExpression(), fieldMathMappingParameters[i].getUnitDefinition(), geometryClass), fieldMathMappingParameters[i].getGeometryClass());
if (mathDesc.getVariable(variable.getName()) == null) {
mathDesc.addVariable(variable);
}
}
}
if (!mathDesc.isValid()) {
System.out.println(mathDesc.getVCML_database());
throw new MappingException("generated an invalid mathDescription: " + mathDesc.getWarning());
}
System.out.println("]]]]]]]]]]]]]]]]]]]]]] VCML string begin ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]");
System.out.println(mathDesc.getVCML());
System.out.println("]]]]]]]]]]]]]]]]]]]]]] VCML string end ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]");
}
use of cbit.vcell.math.Variable in project vcell by virtualcell.
the class ApplicationConstraintsGenerator method steadyStateFromApplication.
/**
* Insert the method's description here.
* Creation date: (6/26/01 8:25:55 AM)
* @return cbit.vcell.constraints.ConstraintContainerImpl
*/
public static ConstraintContainerImpl steadyStateFromApplication(SimulationContext simContext, double tolerance) {
try {
ConstraintContainerImpl ccImpl = new ConstraintContainerImpl();
// ====================
// add physical limits
// ====================
//
// no negative concentrations
//
cbit.vcell.model.Model model = simContext.getModel();
cbit.vcell.model.SpeciesContext[] speciesContexts = model.getSpeciesContexts();
for (int i = 0; i < speciesContexts.length; i++) {
ccImpl.addSimpleBound(new SimpleBounds(speciesContexts[i].getName(), new RealInterval(0, Double.POSITIVE_INFINITY), AbstractConstraint.PHYSICAL_LIMIT, "non-negative concentration"));
}
for (int i = 0; i < speciesContexts.length; i++) {
SpeciesContextSpecParameter initParam = (simContext.getReactionContext().getSpeciesContextSpec(speciesContexts[i])).getInitialConditionParameter();
if (initParam != null) {
double initialValue = initParam.getExpression().evaluateConstant();
double lowInitialValue = Math.min(initialValue / tolerance, initialValue * tolerance);
double highInitialValue = Math.max(initialValue / tolerance, initialValue * tolerance);
ccImpl.addSimpleBound(new SimpleBounds(speciesContexts[i].getName(), new RealInterval(lowInitialValue, highInitialValue), AbstractConstraint.MODELING_ASSUMPTION, "close to specified \"initialCondition\""));
}
}
// =========================
// add modeling assumptions
// =========================
//
// mass action forward and reverse rates should be non-negative
//
cbit.vcell.model.ReactionStep[] reactionSteps = model.getReactionSteps();
for (int i = 0; i < reactionSteps.length; i++) {
Kinetics kinetics = reactionSteps[i].getKinetics();
if (kinetics instanceof MassActionKinetics) {
Expression forwardRateConstraintExp = new Expression(((MassActionKinetics) kinetics).getForwardRateParameter().getExpression().infix() + ">=0");
forwardRateConstraintExp = getSteadyStateExpression(forwardRateConstraintExp);
if (!forwardRateConstraintExp.compareEqual(new Expression(1.0))) {
ccImpl.addGeneralConstraint(new GeneralConstraint(forwardRateConstraintExp, AbstractConstraint.MODELING_ASSUMPTION, "non-negative forward rate"));
}
Expression reverseRateConstraintExp = new Expression(((MassActionKinetics) kinetics).getReverseRateParameter().getExpression().infix() + ">=0");
reverseRateConstraintExp = getSteadyStateExpression(reverseRateConstraintExp);
if (!reverseRateConstraintExp.compareEqual(new Expression(1.0))) {
ccImpl.addGeneralConstraint(new GeneralConstraint(reverseRateConstraintExp, AbstractConstraint.MODELING_ASSUMPTION, "non-negative reverse rate"));
}
}
KineticsParameter authoritativeParameter = kinetics.getAuthoritativeParameter();
Expression kineticRateConstraintExp = new Expression(authoritativeParameter.getName() + "==" + authoritativeParameter.getExpression().infix());
kineticRateConstraintExp = getSteadyStateExpression(kineticRateConstraintExp);
if (!kineticRateConstraintExp.compareEqual(new Expression(1.0))) {
ccImpl.addGeneralConstraint(new GeneralConstraint(kineticRateConstraintExp, AbstractConstraint.MODELING_ASSUMPTION, "definition"));
}
}
//
try {
simContext.setMathDescription(simContext.createNewMathMapping().getMathDescription());
} catch (Throwable e) {
e.printStackTrace(System.out);
throw new RuntimeException("cannot create mathDescription");
}
MathDescription mathDesc = simContext.getMathDescription();
if (mathDesc.getGeometry().getDimension() > 0) {
throw new RuntimeException("spatial simulations not yet supported");
}
CompartmentSubDomain subDomain = (CompartmentSubDomain) mathDesc.getSubDomains().nextElement();
java.util.Enumeration<Equation> enumEquations = subDomain.getEquations();
while (enumEquations.hasMoreElements()) {
Equation equation = (Equation) enumEquations.nextElement();
Expression rateConstraintExp = new Expression(equation.getRateExpression().infix() + "==0");
rateConstraintExp = getSteadyStateExpression(rateConstraintExp);
if (!rateConstraintExp.compareEqual(new Expression(1.0))) {
// not a trivial constraint (always true)
ccImpl.addGeneralConstraint(new GeneralConstraint(rateConstraintExp, AbstractConstraint.PHYSICAL_LIMIT, "definition of steady state"));
}
}
//
for (int i = 0; i < reactionSteps.length; i++) {
Kinetics kinetics = reactionSteps[i].getKinetics();
Kinetics.KineticsParameter[] parameters = kinetics.getKineticsParameters();
for (int j = 0; j < parameters.length; j++) {
Expression exp = parameters[j].getExpression();
if (exp.getSymbols() == null || exp.getSymbols().length == 0) {
//
try {
double constantValue = exp.evaluateConstant();
double lowValue = Math.min(constantValue / tolerance, constantValue * tolerance);
double highValue = Math.max(constantValue / tolerance, constantValue * tolerance);
RealInterval interval = new RealInterval(lowValue, highValue);
ccImpl.addSimpleBound(new SimpleBounds(parameters[j].getName(), interval, AbstractConstraint.MODELING_ASSUMPTION, "parameter close to model default"));
} catch (cbit.vcell.parser.ExpressionException e) {
System.out.println("error evaluating parameter " + parameters[j].getName() + " in reaction step " + reactionSteps[i].getName());
}
} else {
Expression parameterDefinitionExp = new Expression(parameters[j].getName() + "==" + parameters[j].getExpression().infix());
ccImpl.addGeneralConstraint(new GeneralConstraint(getSteadyStateExpression(parameterDefinitionExp), AbstractConstraint.MODELING_ASSUMPTION, "parameter definition"));
}
}
}
ccImpl.addSimpleBound(new SimpleBounds(model.getFARADAY_CONSTANT().getName(), new RealInterval(model.getFARADAY_CONSTANT().getExpression().evaluateConstant()), AbstractConstraint.PHYSICAL_LIMIT, "Faraday's constant"));
ccImpl.addSimpleBound(new SimpleBounds(model.getTEMPERATURE().getName(), new RealInterval(300), AbstractConstraint.PHYSICAL_LIMIT, "Absolute Temperature Kelvin"));
ccImpl.addSimpleBound(new SimpleBounds(model.getGAS_CONSTANT().getName(), new RealInterval(model.getGAS_CONSTANT().getExpression().evaluateConstant()), AbstractConstraint.PHYSICAL_LIMIT, "ideal gas constant"));
ccImpl.addSimpleBound(new SimpleBounds(model.getKMILLIVOLTS().getName(), new RealInterval(model.getKMILLIVOLTS().getExpression().evaluateConstant()), AbstractConstraint.PHYSICAL_LIMIT, "ideal gas constant"));
//
// add K_fluxs
//
java.util.Enumeration<Variable> enumVars = mathDesc.getVariables();
while (enumVars.hasMoreElements()) {
Variable var = (Variable) enumVars.nextElement();
if (var.getName().startsWith("Kflux_") && var instanceof Function) {
Expression kfluxExp = new Expression(((Function) var).getExpression());
kfluxExp.bindExpression(mathDesc);
kfluxExp = MathUtilities.substituteFunctions(kfluxExp, mathDesc);
kfluxExp = kfluxExp.flatten();
ccImpl.addSimpleBound(new SimpleBounds(var.getName(), new RealInterval(kfluxExp.evaluateConstant()), AbstractConstraint.MODELING_ASSUMPTION, "flux conversion factor"));
}
}
return ccImpl;
} catch (cbit.vcell.parser.ExpressionException e) {
e.printStackTrace(System.out);
return null;
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace(System.out);
return null;
}
}
use of cbit.vcell.math.Variable in project vcell by virtualcell.
the class PDEDataViewer method calcAutoAllTimes.
private void calcAutoAllTimes() throws Exception {
HashSet<String> stateVarNames = null;
Variable theVariable = null;
boolean bStateVar = true;
boolean isFieldData = getPdeDataContext().getVCDataIdentifier() instanceof ExternalDataIdentifier || getPdeDataContext().getVCDataIdentifier() instanceof MergedDataInfo;
if (isFieldData) {
// fielddata
DataIdentifier[] dataids = getPdeDataContext().getDataIdentifiers();
stateVarNames = new HashSet<>();
for (int i = 0; i < dataids.length; i++) {
if (!dataids[i].isFunction()) {
stateVarNames.add(dataids[i].getName());
}
// System.out.println("name:'"+dataids[i].getName()+"' type:"+dataids[i].getVariableType()+" func:"+dataids[i].isFunction());
}
bStateVar = !getPdeDataContext().getDataIdentifier().isFunction();
if (bStateVar) {
theVariable = new VolVariable(getPdeDataContext().getDataIdentifier().getName(), getPdeDataContext().getDataIdentifier().getDomain());
} else {
AnnotatedFunction[] funcs = getPdeDataContext().getFunctions();
for (int i = 0; i < funcs.length; i++) {
if (funcs[i].getName().equals(getPdeDataContext().getDataIdentifier().getName())) {
theVariable = funcs[i];
break;
}
}
}
} else {
stateVarNames = getSimulation().getMathDescription().getStateVariableNames();
theVariable = getSimulation().getMathDescription().getVariable(getPdeDataContext().getVariableName());
if (theVariable == null) {
theVariable = ((ClientPDEDataContext) getPdeDataContext()).getDataManager().getOutputContext().getOutputFunction(getPdeDataContext().getVariableName());
}
if (theVariable == null) {
DataProcessingOutputInfo dataProcessingOutputInfo = DataProcessingResultsPanel.getDataProcessingOutputInfo(getPdeDataContext());
if (dataProcessingOutputInfo != null && Arrays.asList(dataProcessingOutputInfo.getVariableNames()).contains(getPdeDataContext().getVariableName())) {
// PostProcess Variable
return;
}
}
bStateVar = stateVarNames.contains(getPdeDataContext().getVariableName());
}
if (theVariable == null) {
throw new Exception("Unexpected Alltimes... selected variable '" + getPdeDataContext().getVariableName() + "' is not stateVariable or OutputFunction");
}
if (getPDEDataContextPanel1().getdisplayAdapterService1().getAllTimes()) {
// min-max over all timepoints (allTimes)
if (theVariable.isConstant()) {
getPDEDataContextPanel1().getdisplayAdapterServicePanel1().changeAllTimesButtonText(DisplayAdapterServicePanel.ALL_TIMES__STATE_TEXT);
double constVal = theVariable.getExpression().evaluateConstant();
getPDEDataContextPanel1().setFunctionStatisticsRange(new Range(constVal, constVal));
} else if (bStateVar) {
getPDEDataContextPanel1().getdisplayAdapterServicePanel1().changeAllTimesButtonText(DisplayAdapterServicePanel.ALL_TIMES__STATE_TEXT);
ArrayList<VarStatistics> varStatsArr = calcVarStat(getPdeDataContext(), new String[] { theVariable.getName() });
if (errorAutoAllTimes(varStatsArr != null, (varStatsArr == null ? null : varStatsArr.size() > 0), isFieldData)) {
// no postprocessinfo
return;
}
FunctionStatistics functionStatistics = new FunctionStatistics(varStatsArr.get(0).minValuesOverTime, varStatsArr.get(0).maxValuesOverTime);
getPDEDataContextPanel1().setFunctionStatisticsRange(new Range(functionStatistics.getMinOverTime(), functionStatistics.getMaxOverTime()));
} else if (theVariable instanceof Function) {
getPDEDataContextPanel1().getdisplayAdapterServicePanel1().changeAllTimesButtonText(DisplayAdapterServicePanel.ALL_TIMES__APPROX_TEXT);
Function flattened = MathDescription.getFlattenedFunctions(SimulationSymbolTable.createMathSymbolTableFactory(), getSimulation().getMathDescription(), new String[] { theVariable.getName() })[0];
if (flattened == null) {
flattened = (Function) theVariable;
}
ArrayList<VarStatistics> varStatsArr = calcVarStat(getPdeDataContext(), stateVarNames.toArray(new String[0]));
if (errorAutoAllTimes(varStatsArr != null, (varStatsArr == null ? null : varStatsArr.size() > 0), isFieldData)) {
// check for no postprocessinfo
return;
}
if (varStatsArr.size() == stateVarNames.size()) {
if (getSimulation().getMeshSpecification().getGeometry().getGeometrySurfaceDescription().getRegionImage() == null) {
getSimulation().getMeshSpecification().getGeometry().getGeometrySurfaceDescription().updateAll();
}
FunctionStatistics functionStatistics = FunctionRangeGenerator.getFunctionStatistics(flattened.getExpression(), varStatsArr.toArray(new VarStatistics[0]), getPdeDataContext().getTimePoints(), getPdeDataContext().getCartesianMesh(), calcInDomainBitSet(), getPdeDataContext().getDataIdentifier().getVariableType());
getPDEDataContextPanel1().setFunctionStatisticsRange(new Range(functionStatistics.getMinOverTime(), functionStatistics.getMaxOverTime()));
} else {
throw new Exception("Unexpectede AllTimes... calculated state var stats size != mathdescr state var size");
}
} else {
throw new Exception("Unexpected AllTimes... not constant, stateVar or function");
}
} else {
// min-max at each timepoint (currTime)
if (!(theVariable instanceof Function)) {
getPDEDataContextPanel1().getdisplayAdapterServicePanel1().changeAllTimesButtonText(DisplayAdapterServicePanel.ALL_TIMES__STATE_TEXT);
} else {
getPDEDataContextPanel1().getdisplayAdapterServicePanel1().changeAllTimesButtonText(DisplayAdapterServicePanel.ALL_TIMES__APPROX_TEXT);
}
getPDEDataContextPanel1().setFunctionStatisticsRange(null);
}
}
use of cbit.vcell.math.Variable in project vcell by virtualcell.
the class XmlReader method getKinetics.
/**
* This method returns a Kinetics object from a XML Element based on the value of the kinetics type attribute.
* Creation date: (3/19/2001 4:42:04 PM)
* @return cbit.vcell.model.Kinetics
* @param param org.jdom.Element
*/
private Kinetics getKinetics(Element param, ReactionStep reaction, Model model) throws XmlParseException {
VariableHash varHash = new VariableHash();
addResevedSymbols(varHash, model);
String type = param.getAttributeValue(XMLTags.KineticsTypeAttrTag);
Kinetics newKinetics = null;
try {
if (type.equalsIgnoreCase(XMLTags.KineticsTypeGeneralKinetics)) {
// create a general kinetics
newKinetics = new GeneralKinetics(reaction);
} else if (type.equalsIgnoreCase(XMLTags.KineticsTypeGeneralCurrentKinetics)) {
// Create GeneralCurrentKinetics
newKinetics = new GeneralCurrentKinetics(reaction);
} else if (type.equalsIgnoreCase(XMLTags.KineticsTypeMassAction) && reaction instanceof SimpleReaction) {
// create a Mass Action kinetics
newKinetics = new MassActionKinetics((SimpleReaction) reaction);
} else if (type.equalsIgnoreCase(XMLTags.KineticsTypeNernst) && reaction instanceof FluxReaction) {
// create NernstKinetics
newKinetics = new NernstKinetics((FluxReaction) reaction);
} else if (type.equalsIgnoreCase(XMLTags.KineticsTypeGHK) && reaction instanceof FluxReaction) {
// create GHKKinetics
newKinetics = new GHKKinetics((FluxReaction) reaction);
} else if (type.equalsIgnoreCase(XMLTags.KineticsTypeHMM_Irr) && reaction instanceof SimpleReaction) {
// create HMM_IrrKinetics
newKinetics = new HMM_IRRKinetics((SimpleReaction) reaction);
} else if (type.equalsIgnoreCase(XMLTags.KineticsTypeHMM_Rev) && reaction instanceof SimpleReaction) {
// create HMM_RevKinetics
newKinetics = new HMM_REVKinetics((SimpleReaction) reaction);
} else if (type.equalsIgnoreCase(XMLTags.KineticsTypeGeneralTotal_oldname)) {
// create GeneralTotalKinetics
newKinetics = new GeneralLumpedKinetics(reaction);
} else if (type.equalsIgnoreCase(XMLTags.KineticsTypeGeneralLumped)) {
// create GeneralLumpedKinetics
newKinetics = new GeneralLumpedKinetics(reaction);
} else if (type.equalsIgnoreCase(XMLTags.KineticsTypeGeneralCurrentLumped)) {
// create GeneralCurrentLumpedKinetics
newKinetics = new GeneralCurrentLumpedKinetics(reaction);
} else if (type.equalsIgnoreCase(XMLTags.KineticsTypeGeneralPermeability) && reaction instanceof FluxReaction) {
// create GeneralPermeabilityKinetics
newKinetics = new GeneralPermeabilityKinetics((FluxReaction) reaction);
} else if (type.equalsIgnoreCase(XMLTags.KineticsTypeMacroscopic_Irr) && reaction instanceof SimpleReaction) {
// create Macroscopic_IRRKinetics
newKinetics = new Macroscopic_IRRKinetics((SimpleReaction) reaction);
} else if (type.equalsIgnoreCase(XMLTags.KineticsTypeMicroscopic_Irr) && reaction instanceof SimpleReaction) {
// create Microscopic_IRRKinetics
newKinetics = new Microscopic_IRRKinetics((SimpleReaction) reaction);
} else {
throw new XmlParseException("Unknown kinetics type: " + type);
}
} catch (ExpressionException e) {
e.printStackTrace();
throw new XmlParseException("Error creating the kinetics for reaction: " + reaction.getName(), e);
}
try {
// transaction begin flag ... yeah, this is a hack
newKinetics.reading(true);
// Read all of the parameters
List<Element> list = param.getChildren(XMLTags.ParameterTag, vcNamespace);
// add constants that may be used in kinetics.
// VariableHash varHash = getVariablesHash();
ArrayList<String> reserved = new ArrayList<String>();
ReservedSymbol[] reservedSymbols = reaction.getModel().getReservedSymbols();
for (ReservedSymbol rs : reservedSymbols) {
reserved.add(rs.getName());
}
try {
if (reaction.getStructure() instanceof Membrane) {
Membrane membrane = (Membrane) reaction.getStructure();
varHash.addVariable(new Constant(membrane.getMembraneVoltage().getName(), new Expression(0.0)));
reserved.add(membrane.getMembraneVoltage().getName());
}
//
// add Reactants, Products, and Catalysts (ReactionParticipants)
//
ReactionParticipant[] rp = reaction.getReactionParticipants();
for (int i = 0; i < rp.length; i++) {
varHash.addVariable(new Constant(rp[i].getName(), new Expression(0.0)));
}
} catch (MathException e) {
e.printStackTrace(System.out);
throw new XmlParseException("error reordering parameters according to dependencies: ", e);
}
//
for (Element xmlParam : list) {
String paramName = unMangle(xmlParam.getAttributeValue(XMLTags.NameAttrTag));
String role = xmlParam.getAttributeValue(XMLTags.ParamRoleAttrTag);
String paramExpStr = xmlParam.getText();
Expression paramExp = unMangleExpression(paramExpStr);
try {
if (varHash.getVariable(paramName) == null) {
varHash.addVariable(new Function(paramName, paramExp, null));
} else {
if (reserved.contains(paramName)) {
varHash.removeVariable(paramName);
varHash.addVariable(new Function(paramName, paramExp, null));
}
}
} catch (MathException e) {
e.printStackTrace(System.out);
throw new XmlParseException("error reordering parameters according to dependencies: ", e);
}
Kinetics.KineticsParameter tempParam = null;
if (!role.equals(XMLTags.ParamRoleUserDefinedTag)) {
tempParam = newKinetics.getKineticsParameterFromRole(Kinetics.getParamRoleFromDefaultDesc(role));
} else {
continue;
}
// hack for bringing in General Total kinetics without breaking.
if (tempParam == null && newKinetics instanceof GeneralLumpedKinetics) {
if (role.equals(Kinetics.GTK_AssumedCompartmentSize_oldname) || role.equals(Kinetics.GTK_ReactionRate_oldname) || role.equals(Kinetics.GTK_CurrentDensity_oldname)) {
continue;
} else if (role.equals(VCMODL.TotalRate_oldname)) {
tempParam = newKinetics.getKineticsParameterFromRole(Kinetics.ROLE_LumpedReactionRate);
}
}
// hack from bringing in chargeValence parameters without breaking
if (tempParam == null && Kinetics.getParamRoleFromDefaultDesc(role) == Kinetics.ROLE_ChargeValence) {
tempParam = newKinetics.getChargeValenceParameter();
}
if (tempParam == null) {
throw new XmlParseException("parameter with role '" + role + "' not found in kinetics type '" + type + "'");
}
//
if (!tempParam.getName().equals(paramName)) {
Kinetics.KineticsParameter multNameParam = newKinetics.getKineticsParameter(paramName);
int n = 0;
while (multNameParam != null) {
String tempName = paramName + "_" + n++;
newKinetics.renameParameter(paramName, tempName);
multNameParam = newKinetics.getKineticsParameter(tempName);
}
newKinetics.renameParameter(tempParam.getName(), paramName);
}
}
//
// create unresolved parameters for all unresolved symbols
//
String unresolvedSymbol = varHash.getFirstUnresolvedSymbol();
while (unresolvedSymbol != null) {
try {
// will turn into an UnresolvedParameter.
varHash.addVariable(new Function(unresolvedSymbol, new Expression(0.0), null));
} catch (MathException e) {
e.printStackTrace(System.out);
throw new XmlParseException(e);
}
newKinetics.addUnresolvedParameter(unresolvedSymbol);
unresolvedSymbol = varHash.getFirstUnresolvedSymbol();
}
Variable[] sortedVariables = varHash.getTopologicallyReorderedVariables();
ModelUnitSystem modelUnitSystem = reaction.getModel().getUnitSystem();
for (int i = sortedVariables.length - 1; i >= 0; i--) {
if (sortedVariables[i] instanceof Function) {
Function paramFunction = (Function) sortedVariables[i];
Element xmlParam = null;
for (int j = 0; j < list.size(); j++) {
Element tempParam = (Element) list.get(j);
if (paramFunction.getName().equals(unMangle(tempParam.getAttributeValue(XMLTags.NameAttrTag)))) {
xmlParam = tempParam;
break;
}
}
if (xmlParam == null) {
// must have been an unresolved parameter
continue;
}
String symbol = xmlParam.getAttributeValue(XMLTags.VCUnitDefinitionAttrTag);
VCUnitDefinition unit = null;
if (symbol != null) {
unit = modelUnitSystem.getInstance(symbol);
}
Kinetics.KineticsParameter tempParam = newKinetics.getKineticsParameter(paramFunction.getName());
if (tempParam == null) {
newKinetics.addUserDefinedKineticsParameter(paramFunction.getName(), paramFunction.getExpression(), unit);
} else {
newKinetics.setParameterValue(tempParam, paramFunction.getExpression());
tempParam.setUnitDefinition(unit);
}
}
}
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace(System.out);
throw new XmlParseException("Exception while setting parameters for Reaction : " + reaction.getName(), e);
} catch (ExpressionException e) {
e.printStackTrace(System.out);
throw new XmlParseException("Exception while settings parameters for Reaction : " + reaction.getName(), e);
} finally {
newKinetics.reading(false);
}
return newKinetics;
}
Aggregations