use of cbit.vcell.model.Kinetics in project vcell by virtualcell.
the class SBMLExporter method addReactions.
/**
* addReactions comment.
* @throws SbmlException
* @throws XMLStreamException
*/
protected void addReactions() throws SbmlException, XMLStreamException {
// Check if any reaction has electrical mapping
boolean bCalculatePotential = false;
StructureMapping[] structureMappings = getSelectedSimContext().getGeometryContext().getStructureMappings();
for (int i = 0; i < structureMappings.length; i++) {
if (structureMappings[i] instanceof MembraneMapping) {
if (((MembraneMapping) structureMappings[i]).getCalculateVoltage()) {
bCalculatePotential = true;
}
}
}
// If it does, VCell doesn't export it to SBML (no representation).
if (bCalculatePotential) {
throw new RuntimeException("This VCell model has Electrical mapping; cannot be exported to SBML at this time");
}
l2gMap.clear();
ReactionSpec[] vcReactionSpecs = getSelectedSimContext().getReactionContext().getReactionSpecs();
for (int i = 0; i < vcReactionSpecs.length; i++) {
if (vcReactionSpecs[i].isExcluded()) {
continue;
}
ReactionStep vcReactionStep = vcReactionSpecs[i].getReactionStep();
// Create sbml reaction
String rxnName = vcReactionStep.getName();
org.sbml.jsbml.Reaction sbmlReaction = sbmlModel.createReaction();
sbmlReaction.setId(org.vcell.util.TokenMangler.mangleToSName(rxnName));
sbmlReaction.setName(rxnName);
// If the reactionStep is a flux reaction, add the details to the annotation (structure, carrier valence, flux carrier, fluxOption, etc.)
// If reactionStep is a simple reaction, add annotation to indicate the structure of reaction.
// Useful when roundtripping ...
Element sbmlImportRelatedElement = null;
// try {
// sbmlImportRelatedElement = getAnnotationElement(vcReactionStep);
// } catch (XmlParseException e1) {
// e1.printStackTrace(System.out);
// // throw new RuntimeException("Error ");
// }
// Get annotation (RDF and non-RDF) for reactionStep from SBMLAnnotationUtils
sbmlAnnotationUtil.writeAnnotation(vcReactionStep, sbmlReaction, sbmlImportRelatedElement);
// Now set notes,
sbmlAnnotationUtil.writeNotes(vcReactionStep, sbmlReaction);
// Get reaction kineticLaw
Kinetics vcRxnKinetics = vcReactionStep.getKinetics();
org.sbml.jsbml.KineticLaw sbmlKLaw = sbmlReaction.createKineticLaw();
try {
// Convert expression from kinetics rate parameter into MathML and use libSBMl utilities to convert it to formula
// (instead of directly using rate parameter's expression infix) to maintain integrity of formula :
// for example logical and inequalities are not handled gracefully by libSBMl if expression.infix is used.
final Expression localRateExpr;
final Expression lumpedRateExpr;
if (vcRxnKinetics instanceof DistributedKinetics) {
localRateExpr = ((DistributedKinetics) vcRxnKinetics).getReactionRateParameter().getExpression();
lumpedRateExpr = null;
} else if (vcRxnKinetics instanceof LumpedKinetics) {
localRateExpr = null;
lumpedRateExpr = ((LumpedKinetics) vcRxnKinetics).getLumpedReactionRateParameter().getExpression();
} else {
throw new RuntimeException("unexpected Rate Law '" + vcRxnKinetics.getClass().getSimpleName() + "', not distributed or lumped type");
}
// if (vcRxnKinetics instanceof DistributedKinetics)
// Expression correctedRateExpr = kineticsAdapter.getExpression();
// Add parameters, if any, to the kineticLaw
Kinetics.KineticsParameter[] vcKineticsParams = vcRxnKinetics.getKineticsParameters();
// In the first pass thro' the kinetic params, store the non-numeric param names and expressions in arrays
String[] kinParamNames = new String[vcKineticsParams.length];
Expression[] kinParamExprs = new Expression[vcKineticsParams.length];
for (int j = 0; j < vcKineticsParams.length; j++) {
if (true) {
// Since local reaction parameters cannot be defined by a rule, such parameters (with rules) are exported as global parameters.
if ((vcKineticsParams[j].getRole() == Kinetics.ROLE_CurrentDensity && (!vcKineticsParams[j].getExpression().isZero())) || (vcKineticsParams[j].getRole() == Kinetics.ROLE_LumpedCurrent && (!vcKineticsParams[j].getExpression().isZero()))) {
throw new RuntimeException("Electric current not handled by SBML export; failed to export reaction \"" + vcReactionStep.getName() + "\" at this time");
}
if (!vcKineticsParams[j].getExpression().isNumeric()) {
// NON_NUMERIC KINETIC PARAM
// Create new name for kinetic parameter and store it in kinParamNames, store corresponding exprs in kinParamExprs
// Will be used later to add this param as global.
String newParamName = TokenMangler.mangleToSName(vcKineticsParams[j].getName() + "_" + vcReactionStep.getName());
kinParamNames[j] = newParamName;
kinParamExprs[j] = new Expression(vcKineticsParams[j].getExpression());
}
}
}
// If so, these need to be added as global param (else the SBML doc will not be valid)
for (int j = 0; j < vcKineticsParams.length; j++) {
final KineticsParameter vcKParam = vcKineticsParams[j];
if ((vcKParam.getRole() != Kinetics.ROLE_ReactionRate) && (vcKParam.getRole() != Kinetics.ROLE_LumpedReactionRate)) {
// if expression of kinetic param evaluates to a double, the parameter value is set
if ((vcKParam.getRole() == Kinetics.ROLE_CurrentDensity && (!vcKParam.getExpression().isZero())) || (vcKParam.getRole() == Kinetics.ROLE_LumpedCurrent && (!vcKParam.getExpression().isZero()))) {
throw new RuntimeException("Electric current not handled by SBML export; failed to export reaction \"" + vcReactionStep.getName() + "\" at this time");
}
if (vcKParam.getExpression().isNumeric()) {
// NUMERIC KINETIC PARAM
// check if it is used in other parameters that have expressions,
boolean bAddedParam = false;
String origParamName = vcKParam.getName();
String newParamName = TokenMangler.mangleToSName(origParamName + "_" + vcReactionStep.getName());
VCUnitDefinition vcUnit = vcKParam.getUnitDefinition();
for (int k = 0; k < vcKineticsParams.length; k++) {
if (kinParamExprs[k] != null) {
// The param could be in the expression for any other param
if (kinParamExprs[k].hasSymbol(origParamName)) {
// mangle its name to avoid conflict with other globals
if (globalParamNamesHash.get(newParamName) == null) {
globalParamNamesHash.put(newParamName, newParamName);
org.sbml.jsbml.Parameter sbmlKinParam = sbmlModel.createParameter();
sbmlKinParam.setId(newParamName);
sbmlKinParam.setValue(vcKParam.getConstantValue());
final boolean constValue = vcKParam.isConstant();
sbmlKinParam.setConstant(true);
// Set SBML units for sbmlParam using VC units from vcParam
if (!vcUnit.isTBD()) {
UnitDefinition unitDefn = getOrCreateSBMLUnit(vcUnit);
sbmlKinParam.setUnits(unitDefn);
}
Pair<String, String> origParam = new Pair<String, String>(rxnName, origParamName);
l2gMap.put(origParam, newParamName);
bAddedParam = true;
} else {
// need to get another name for param and need to change all its refereces in the other kinParam euqations.
}
// update the expression to contain new name, since the globalparam has new name
kinParamExprs[k].substituteInPlace(new Expression(origParamName), new Expression(newParamName));
}
}
}
// If the param hasn't been added yet, it is definitely a local param. add it to kineticLaw now.
if (!bAddedParam) {
org.sbml.jsbml.LocalParameter sbmlKinParam = sbmlKLaw.createLocalParameter();
sbmlKinParam.setId(origParamName);
sbmlKinParam.setValue(vcKParam.getConstantValue());
System.out.println("tis constant " + sbmlKinParam.isExplicitlySetConstant());
// Set SBML units for sbmlParam using VC units from vcParam
if (!vcUnit.isTBD()) {
UnitDefinition unitDefn = getOrCreateSBMLUnit(vcUnit);
sbmlKinParam.setUnits(unitDefn);
}
} else {
// hence change its occurance in rate expression if it contains that param name
if (localRateExpr != null && localRateExpr.hasSymbol(origParamName)) {
localRateExpr.substituteInPlace(new Expression(origParamName), new Expression(newParamName));
}
if (lumpedRateExpr != null && lumpedRateExpr.hasSymbol(origParamName)) {
lumpedRateExpr.substituteInPlace(new Expression(origParamName), new Expression(newParamName));
}
}
}
}
}
// (using the kinParamNames and kinParamExprs above) to ensure uniqueness in the global parameter names.
for (int j = 0; j < vcKineticsParams.length; j++) {
if (((vcKineticsParams[j].getRole() != Kinetics.ROLE_ReactionRate) && (vcKineticsParams[j].getRole() != Kinetics.ROLE_LumpedReactionRate)) && !(vcKineticsParams[j].getExpression().isNumeric())) {
String oldName = vcKineticsParams[j].getName();
String newName = kinParamNames[j];
// change the name of this parameter in the rate expression
if (localRateExpr != null && localRateExpr.hasSymbol(oldName)) {
localRateExpr.substituteInPlace(new Expression(oldName), new Expression(newName));
}
if (lumpedRateExpr != null && lumpedRateExpr.hasSymbol(oldName)) {
lumpedRateExpr.substituteInPlace(new Expression(oldName), new Expression(newName));
}
// Change the occurence of this param in other param expressions
for (int k = 0; k < vcKineticsParams.length; k++) {
if (((vcKineticsParams[k].getRole() != Kinetics.ROLE_ReactionRate) && (vcKineticsParams[j].getRole() != Kinetics.ROLE_LumpedReactionRate)) && !(vcKineticsParams[k].getExpression().isNumeric())) {
if (k != j && vcKineticsParams[k].getExpression().hasSymbol(oldName)) {
// for all params except the current param represented by index j (whose name was changed)
kinParamExprs[k].substituteInPlace(new Expression(oldName), new Expression(newName));
}
if (k == j && vcKineticsParams[k].getExpression().hasSymbol(oldName)) {
throw new RuntimeException("A parameter cannot refer to itself in its expression");
}
}
}
// end for - k
}
}
// In the fifth pass thro' the kinetic params, the non-numeric params are added to the global params of the model
for (int j = 0; j < vcKineticsParams.length; j++) {
if (((vcKineticsParams[j].getRole() != Kinetics.ROLE_ReactionRate) && (vcKineticsParams[j].getRole() != Kinetics.ROLE_LumpedReactionRate)) && !(vcKineticsParams[j].getExpression().isNumeric())) {
// Now, add this param to the globalParamNamesHash and add a global parameter to the sbmlModel
String paramName = kinParamNames[j];
if (globalParamNamesHash.get(paramName) == null) {
globalParamNamesHash.put(paramName, paramName);
} else {
// need to get another name for param and need to change all its refereces in the other kinParam euqations.
}
Pair<String, String> origParam = new Pair<String, String>(rxnName, paramName);
// keeps its name but becomes a global (?)
l2gMap.put(origParam, paramName);
ASTNode paramFormulaNode = getFormulaFromExpression(kinParamExprs[j]);
AssignmentRule sbmlParamAssignmentRule = sbmlModel.createAssignmentRule();
sbmlParamAssignmentRule.setVariable(paramName);
sbmlParamAssignmentRule.setMath(paramFormulaNode);
org.sbml.jsbml.Parameter sbmlKinParam = sbmlModel.createParameter();
sbmlKinParam.setId(paramName);
if (!vcKineticsParams[j].getUnitDefinition().isTBD()) {
sbmlKinParam.setUnits(getOrCreateSBMLUnit(vcKineticsParams[j].getUnitDefinition()));
}
// Since the parameter is being specified by a Rule, its 'constant' field shoud be set to 'false' (default - true).
sbmlKinParam.setConstant(false);
}
}
// end for (j) - fifth pass
// After making all necessary adjustments to the rate expression, now set the sbmlKLaw.
final ASTNode exprFormulaNode;
if (lumpedRateExpr != null) {
exprFormulaNode = getFormulaFromExpression(lumpedRateExpr);
} else {
if (bSpatial) {
exprFormulaNode = getFormulaFromExpression(localRateExpr);
} else {
exprFormulaNode = getFormulaFromExpression(Expression.mult(localRateExpr, new Expression(vcReactionStep.getStructure().getName())));
}
}
sbmlKLaw.setMath(exprFormulaNode);
} catch (cbit.vcell.parser.ExpressionException e) {
e.printStackTrace(System.out);
throw new RuntimeException("Error getting value of parameter : " + e.getMessage());
}
// Add kineticLaw to sbmlReaction - not needed now, since we use sbmlRxn.createKLaw() ??
// sbmlReaction.setKineticLaw(sbmlKLaw);
// Add reactants, products, modifiers
// Simple reactions have catalysts, fluxes have 'flux'
cbit.vcell.model.ReactionParticipant[] rxnParticipants = vcReactionStep.getReactionParticipants();
for (ReactionParticipant rxnParticpant : rxnParticipants) {
SimpleSpeciesReference ssr = null;
SpeciesReference sr = null;
if (rxnParticpant instanceof cbit.vcell.model.Reactant) {
ssr = sr = sbmlReaction.createReactant();
} else if (rxnParticpant instanceof cbit.vcell.model.Product) {
ssr = sr = sbmlReaction.createProduct();
}
if (rxnParticpant instanceof cbit.vcell.model.Catalyst) {
ssr = sbmlReaction.createModifier();
}
if (ssr != null) {
ssr.setSpecies(rxnParticpant.getSpeciesContext().getName());
}
if (sr != null) {
sr.setStoichiometry(Double.parseDouble(Integer.toString(rxnParticpant.getStoichiometry())));
String modelUniqueName = vcReactionStep.getName() + '_' + rxnParticpant.getName();
sr.setId(TokenMangler.mangleToSName(modelUniqueName));
// SBML-REVIEW
sr.setConstant(true);
// int rcode = sr.appendNotes("<
try {
SBMLHelper.addNote(sr, "VCELL guess: how do we know if reaction is constant?");
} catch (Exception e) {
e.printStackTrace();
}
}
}
sbmlReaction.setFast(vcReactionSpecs[i].isFast());
// this attribute is mandatory for L3, optional for L2. So explicitly setting value.
sbmlReaction.setReversible(true);
if (bSpatial) {
// set compartment for reaction if spatial
sbmlReaction.setCompartment(vcReactionStep.getStructure().getName());
// CORE HAS ALT MATH true
// set the "isLocal" attribute = true (in 'spatial' namespace) for each species
SpatialReactionPlugin srplugin = (SpatialReactionPlugin) sbmlReaction.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
srplugin.setIsLocal(vcRxnKinetics instanceof DistributedKinetics);
}
}
}
use of cbit.vcell.model.Kinetics in project vcell by virtualcell.
the class SBMLImporter method addReactions.
/**
* addReactions:
*/
protected void addReactions(VCMetaData metaData) {
if (sbmlModel == null) {
throw new SBMLImportException("SBML model is NULL");
}
ListOf<Reaction> reactions = sbmlModel.getListOfReactions();
final int numReactions = reactions.size();
if (numReactions == 0) {
lg.info("No Reactions");
return;
}
// all reactions
ArrayList<ReactionStep> vcReactionList = new ArrayList<>();
// just the fast ones
ArrayList<ReactionStep> fastReactionList = new ArrayList<>();
Model vcModel = vcBioModel.getSimulationContext(0).getModel();
ModelUnitSystem vcModelUnitSystem = vcModel.getUnitSystem();
SpeciesContext[] vcSpeciesContexts = vcModel.getSpeciesContexts();
try {
for (Reaction sbmlRxn : reactions) {
ReactionStep vcReaction = null;
String rxnName = sbmlRxn.getId();
boolean bReversible = true;
if (sbmlRxn.isSetReversible()) {
bReversible = sbmlRxn.getReversible();
}
// Check of reaction annotation is present; if so, does it have
// an embedded element (flux or simpleRxn).
// Create a fluxReaction or simpleReaction accordingly.
Element sbmlImportRelatedElement = sbmlAnnotationUtil.readVCellSpecificAnnotation(sbmlRxn);
Structure reactionStructure = getReactionStructure(sbmlRxn, vcSpeciesContexts, sbmlImportRelatedElement);
if (sbmlImportRelatedElement != null) {
Element embeddedRxnElement = getEmbeddedElementInAnnotation(sbmlImportRelatedElement, REACTION);
if (embeddedRxnElement != null) {
if (embeddedRxnElement.getName().equals(XMLTags.FluxStepTag)) {
// If embedded element is a flux reaction, set flux
// reaction's strucure, flux carrier, physicsOption
// from the element attributes.
String structName = embeddedRxnElement.getAttributeValue(XMLTags.StructureAttrTag);
CastInfo<Membrane> ci = SBMLHelper.getTypedStructure(Membrane.class, vcModel, structName);
if (!ci.isGood()) {
throw new SBMLImportException("Appears that the flux reaction is occuring on " + ci.actualName() + ", not a membrane.");
}
vcReaction = new FluxReaction(vcModel, ci.get(), null, rxnName, bReversible);
vcReaction.setModel(vcModel);
// Set the fluxOption on the flux reaction based on
// whether it is molecular, molecular & electrical,
// electrical.
String fluxOptionStr = embeddedRxnElement.getAttributeValue(XMLTags.FluxOptionAttrTag);
if (fluxOptionStr.equals(XMLTags.FluxOptionMolecularOnly)) {
((FluxReaction) vcReaction).setPhysicsOptions(ReactionStep.PHYSICS_MOLECULAR_ONLY);
} else if (fluxOptionStr.equals(XMLTags.FluxOptionMolecularAndElectrical)) {
((FluxReaction) vcReaction).setPhysicsOptions(ReactionStep.PHYSICS_MOLECULAR_AND_ELECTRICAL);
} else if (fluxOptionStr.equals(XMLTags.FluxOptionElectricalOnly)) {
((FluxReaction) vcReaction).setPhysicsOptions(ReactionStep.PHYSICS_ELECTRICAL_ONLY);
} else {
localIssueList.add(new Issue(vcReaction, issueContext, IssueCategory.SBMLImport_Reaction, "Unknown FluxOption : " + fluxOptionStr + " for SBML reaction : " + rxnName, Issue.SEVERITY_WARNING));
// logger.sendMessage(VCLogger.Priority.MediumPriority,
// VCLogger.ErrorType.ReactionError,
// "Unknown FluxOption : " + fluxOptionStr +
// " for SBML reaction : " + rxnName);
}
} else if (embeddedRxnElement.getName().equals(XMLTags.SimpleReactionTag)) {
// if embedded element is a simple reaction, set
// simple reaction's structure from element
// attributes
vcReaction = new SimpleReaction(vcModel, reactionStructure, rxnName, bReversible);
}
} else {
vcReaction = new SimpleReaction(vcModel, reactionStructure, rxnName, bReversible);
}
} else {
vcReaction = new SimpleReaction(vcModel, reactionStructure, rxnName, bReversible);
}
// set annotations and notes on vcReactions[i]
sbmlAnnotationUtil.readAnnotation(vcReaction, sbmlRxn);
sbmlAnnotationUtil.readNotes(vcReaction, sbmlRxn);
// the limit on the reactionName length.
if (rxnName.length() > 64) {
String freeTextAnnotation = metaData.getFreeTextAnnotation(vcReaction);
if (freeTextAnnotation == null) {
freeTextAnnotation = "";
}
StringBuffer oldRxnAnnotation = new StringBuffer(freeTextAnnotation);
oldRxnAnnotation.append("\n\n" + rxnName);
metaData.setFreeTextAnnotation(vcReaction, oldRxnAnnotation.toString());
}
// Now add the reactants, products, modifiers as specified by
// the sbmlRxn
addReactionParticipants(sbmlRxn, vcReaction);
KineticLaw kLaw = sbmlRxn.getKineticLaw();
Kinetics kinetics = null;
if (kLaw != null) {
// Convert the formula from kineticLaw into MathML and then
// to an expression (infix) to be used in VCell kinetics
ASTNode sbmlRateMath = kLaw.getMath();
Expression kLawRateExpr = getExpressionFromFormula(sbmlRateMath);
Expression vcRateExpression = new Expression(kLawRateExpr);
// modifier (catalyst) to the reaction.
for (int k = 0; k < vcSpeciesContexts.length; k++) {
if (vcRateExpression.hasSymbol(vcSpeciesContexts[k].getName())) {
if ((vcReaction.getReactant(vcSpeciesContexts[k].getName()) == null) && (vcReaction.getProduct(vcSpeciesContexts[k].getName()) == null) && (vcReaction.getCatalyst(vcSpeciesContexts[k].getName()) == null)) {
// This means that the speciesContext is not a
// reactant, product or modifier : it has to be
// added to the VC Rxn as a catalyst
vcReaction.addCatalyst(vcSpeciesContexts[k]);
}
}
}
// set kinetics on VCell reaction
if (bSpatial) {
// if spatial SBML ('isSpatial' attribute set), create
// DistributedKinetics)
SpatialReactionPlugin ssrplugin = (SpatialReactionPlugin) sbmlRxn.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
// 'spatial'
if (ssrplugin != null && ssrplugin.getIsLocal()) {
kinetics = new GeneralKinetics(vcReaction);
} else {
kinetics = new GeneralLumpedKinetics(vcReaction);
}
} else {
kinetics = new GeneralLumpedKinetics(vcReaction);
}
// set kinetics on vcReaction
vcReaction.setKinetics(kinetics);
// If the name of the rate parameter has been changed by
// user, or matches with global/local param,
// it has to be changed.
resolveRxnParameterNameConflicts(sbmlRxn, kinetics, sbmlImportRelatedElement);
/**
* Now, based on the kinetic law expression, see if the rate
* is expressed in concentration/time or substance/time : If
* the compartment_id of the compartment corresponding to
* the structure in which the reaction takes place occurs in
* the rate law expression, it is in concentration/time;
* divide it by the compartment size and bring in the rate
* law as 'Distributed' kinetics. If not, the rate law is in
* substance/time; bring it in (as is) as 'Lumped' kinetics.
*/
ListOf<LocalParameter> localParameters = kLaw.getListOfLocalParameters();
for (LocalParameter p : localParameters) {
String paramName = p.getId();
KineticsParameter kineticsParameter = kinetics.getKineticsParameter(paramName);
if (kineticsParameter == null) {
// add unresolved for now to prevent errors in kinetics.setParameterValue(kp,vcRateExpression) below
kinetics.addUnresolvedParameter(paramName);
}
}
KineticsParameter kp = kinetics.getAuthoritativeParameter();
if (lg.isDebugEnabled()) {
lg.debug("Setting " + kp.getName() + ": " + vcRateExpression.infix());
}
kinetics.setParameterValue(kp, vcRateExpression);
// If there are any global parameters used in the kinetics,
// and if they have species,
// check if the species are already reactionParticipants in
// the reaction. If not, add them as catalysts.
KineticsProxyParameter[] kpps = kinetics.getProxyParameters();
for (int j = 0; j < kpps.length; j++) {
if (kpps[j].getTarget() instanceof ModelParameter) {
ModelParameter mp = (ModelParameter) kpps[j].getTarget();
HashSet<String> refSpeciesNameHash = new HashSet<String>();
getReferencedSpeciesInExpr(mp.getExpression(), refSpeciesNameHash);
java.util.Iterator<String> refSpIterator = refSpeciesNameHash.iterator();
while (refSpIterator.hasNext()) {
String spName = refSpIterator.next();
org.sbml.jsbml.Species sp = sbmlModel.getSpecies(spName);
ArrayList<ReactionParticipant> rpArray = getVCReactionParticipantsFromSymbol(vcReaction, sp.getId());
if (rpArray == null || rpArray.size() == 0) {
// This means that the speciesContext is not
// a reactant, product or modifier : it has
// to be added as a catalyst
vcReaction.addCatalyst(vcModel.getSpeciesContext(sp.getId()));
}
}
}
}
// model - local params cannot be defined by rules.
for (LocalParameter param : localParameters) {
String paramName = param.getId();
Expression exp = new Expression(param.getValue());
String unitString = param.getUnits();
VCUnitDefinition paramUnit = sbmlUnitIdentifierHash.get(unitString);
if (paramUnit == null) {
paramUnit = vcModelUnitSystem.getInstance_TBD();
}
// check if sbml local param is in kinetic params list;
// if so, add its value.
boolean lpSet = false;
KineticsParameter kineticsParameter = kinetics.getKineticsParameter(paramName);
if (kineticsParameter != null) {
if (lg.isDebugEnabled()) {
lg.debug("Setting local " + kineticsParameter.getName() + ": " + exp.infix());
}
kineticsParameter.setExpression(exp);
kineticsParameter.setUnitDefinition(paramUnit);
lpSet = true;
} else {
UnresolvedParameter ur = kinetics.getUnresolvedParameter(paramName);
if (ur != null) {
kinetics.addUserDefinedKineticsParameter(paramName, exp, paramUnit);
lpSet = true;
}
}
if (!lpSet) {
// check if it is a proxy parameter (specifically,
// speciesContext or model parameter (structureSize
// too)).
KineticsProxyParameter kpp = kinetics.getProxyParameter(paramName);
// and units to local param values
if (kpp != null && kpp.getTarget() instanceof ModelParameter) {
kinetics.convertParameterType(kpp, false);
kineticsParameter = kinetics.getKineticsParameter(paramName);
kinetics.setParameterValue(kineticsParameter, exp);
kineticsParameter.setUnitDefinition(paramUnit);
}
}
}
} else {
// sbmlKLaw was null, so creating a GeneralKinetics with 0.0
// as rate.
kinetics = new GeneralKinetics(vcReaction);
}
// end - if-else KLaw != null
// set the reaction kinetics, and add reaction to the vcell
// model.
kinetics.resolveUndefinedUnits();
// System.out.println("ADDED SBML REACTION : \"" + rxnName +
// "\" to VCModel");
vcReactionList.add(vcReaction);
if (sbmlRxn.isSetFast() && sbmlRxn.getFast()) {
fastReactionList.add(vcReaction);
}
}
// end - for vcReactions
ReactionStep[] array = vcReactionList.toArray(new ReactionStep[vcReactionList.size()]);
vcModel.setReactionSteps(array);
final ReactionContext rc = vcBioModel.getSimulationContext(0).getReactionContext();
for (ReactionStep frs : fastReactionList) {
final ReactionSpec rs = rc.getReactionSpec(frs);
rs.setReactionMapping(ReactionSpec.FAST);
}
} catch (ModelPropertyVetoException mpve) {
throw new SBMLImportException(mpve.getMessage(), mpve);
} catch (Exception e1) {
e1.printStackTrace(System.out);
throw new SBMLImportException(e1.getMessage(), e1);
}
}
use of cbit.vcell.model.Kinetics in project vcell by virtualcell.
the class Xmlproducer method getXML.
/**
* This method returns a XML representation of a Kinetics object type.
* Creation date: (2/26/2001 7:31:43 PM)
* @return Element
* @param param cbit.vcell.model.Kinetics
*/
private Element getXML(Kinetics param) throws XmlParseException {
String kineticsType = null;
if (param instanceof GeneralKinetics) {
// process a GeneralKinetics object
kineticsType = XMLTags.KineticsTypeGeneralKinetics;
} else if (param instanceof MassActionKinetics) {
// Process a MassActionKinetics
kineticsType = XMLTags.KineticsTypeMassAction;
} else if (param instanceof NernstKinetics) {
// Process a NernstKinetics
kineticsType = XMLTags.KineticsTypeNernst;
} else if (param instanceof GHKKinetics) {
// Process a GHKKinetics
kineticsType = XMLTags.KineticsTypeGHK;
} else if (param instanceof GeneralCurrentKinetics) {
// Process a GeneralCurrentKinetics
kineticsType = XMLTags.KineticsTypeGeneralCurrentKinetics;
} else if (param instanceof HMM_IRRKinetics) {
// Process a HenriMichaelasMentenKinetics (irreversible)
kineticsType = XMLTags.KineticsTypeHMM_Irr;
} else if (param instanceof HMM_REVKinetics) {
// Process a HenriMichaelasMentenKinetics (reversible)
kineticsType = XMLTags.KineticsTypeHMM_Rev;
} else if (param instanceof GeneralLumpedKinetics) {
// Process a GeneralLumpedKinetics
kineticsType = XMLTags.KineticsTypeGeneralLumped;
} else if (param instanceof GeneralCurrentLumpedKinetics) {
// Process a GeneralCurrentLumpedKinetics
kineticsType = XMLTags.KineticsTypeGeneralCurrentLumped;
} else if (param instanceof GeneralPermeabilityKinetics) {
// Process a GeneralPermeabilityKinetics
kineticsType = XMLTags.KineticsTypeGeneralPermeability;
} else if (param instanceof Macroscopic_IRRKinetics) {
// Process a Macroscopic_IRRKinetics
kineticsType = XMLTags.KineticsTypeMacroscopic_Irr;
} else if (param instanceof Microscopic_IRRKinetics) {
// Process a Microscopic_IRRKinetics
kineticsType = XMLTags.KineticsTypeMicroscopic_Irr;
}
Element kinetics = new Element(XMLTags.KineticsTag);
// Add atributes
kinetics.setAttribute(XMLTags.KineticsTypeAttrTag, kineticsType);
// Add Kinetics Parameters
Kinetics.KineticsParameter[] parameters = param.getKineticsParameters();
for (int i = 0; i < parameters.length; i++) {
Kinetics.KineticsParameter parm = parameters[i];
Element tempparameter = new Element(XMLTags.ParameterTag);
// Get parameter attributes
tempparameter.setAttribute(XMLTags.NameAttrTag, mangle(parm.getName()));
tempparameter.setAttribute(XMLTags.ParamRoleAttrTag, param.getDefaultParameterDesc(parm.getRole()));
VCUnitDefinition unit = parm.getUnitDefinition();
if (unit != null) {
tempparameter.setAttribute(XMLTags.VCUnitDefinitionAttrTag, unit.getSymbol());
}
tempparameter.addContent(mangleExpression(parm.getExpression()));
// Add the parameter to the general kinetics object
kinetics.addContent(tempparameter);
}
return kinetics;
}
use of cbit.vcell.model.Kinetics in project vcell by virtualcell.
the class SBPAXKineticsExtractor method extractKineticsExactMatch.
public static boolean extractKineticsExactMatch(ReactionStep reaction, Process process) throws ExpressionException, PropertyVetoException {
// we try a perfect match first based on the existence of a SBOTerm in the kinetic law
if (process.getControl() == null) {
// no control means no kinetic law - nothing more to do
return true;
}
Control control = process.getControl();
ArrayList<SBEntity> sbEntities = control.getSBSubEntity();
for (SBEntity sbE : sbEntities) {
// the only SBSubEntities allowed in a control are kinetic laws
if (sbE.getID().contains("kineticLaw")) {
// build list of the parameters of this kinetic law in sboParams
// params of this kinetic law
ArrayList<SBOParam> sboParams = new ArrayList<SBOParam>();
ArrayList<SBEntity> subEntities = sbE.getSBSubEntity();
for (SBEntity subEntity : subEntities) {
if (subEntity instanceof SBMeasurable) {
SBMeasurable m = (SBMeasurable) subEntity;
if (!m.hasTerm()) {
// we don't know what to do with a measurable with no SBTerm
break;
}
String termName = m.extractSBOTermAsString();
SBOTerm sboT = SBOListEx.sboMap.get(termName);
System.out.println(" " + sboT.getIndex() + " " + sboT.getName());
SBOParam sboParam = matchSBOParam(sboT);
if (m.hasNumber()) {
double number = m.getNumber().get(0);
sboParam.setNumber(number);
}
if (m.hasUnit()) {
String unit = m.extractSBOUnitAsString();
sboParam.setUnit(unit);
}
sboParams.add(sboParam);
}
}
// find if a kinetic law type exists and if not guesstimate one based on parameters
// simple rule: if we have a Km param it's MM, otherwise it's mass action
ArrayList<SBVocabulary> sbTerms = sbE.getSBTerm();
if (sbTerms.isEmpty()) {
// return false;
SBVocabulary sbTerm = new SBVocabulary();
ArrayList<String> termNames = new ArrayList<String>();
String id;
SBOParam kMichaelis = extractMichaelisForwardParam(sboParams);
if (kMichaelis == null) {
// mass action rate law
id = new String("SBO:0000012");
} else {
// irreversible Henri-Michaelis-Menten rate law
id = new String("SBO:0000029");
}
// termNames.add(id);
// sbTerm.setTerm(termNames);
sbTerm.setID(id);
sbTerms.add(sbTerm);
}
System.out.println(" kinetic law ID: " + sbTerms.get(0).getID());
// identify the kinetic law type (mass action, michaelis menten, etc) and bring it in vCell
for (SBVocabulary sbv : sbTerms) {
// use for loop even though we only expect 1 SBTerm
// SBVocabulary id, used to retrieve the kinetic law type
String vocabularyID = sbv.getID();
SBOTerm sboT = SBOUtil.getSBOTermFromVocabularyId(vocabularyID);
System.out.println(vocabularyID + " " + sboT.getName());
SBOParam kForward;
SBOParam kCat;
SBOParam vM;
SBOParam kReverse;
SBOParam kMichaelis;
Kinetics kinetics;
MappedKinetics current = matchSBOKineticLaw(sboT);
switch(current) {
case SBO_0000069:
case SBO_0000432:
// some kinetic laws unknown to vCell will fall through to this category
// honestly i don't know what to do with them
System.out.println("GeneralKinetics");
// TODO: what to do here?
return true;
case SBO_0000012:
case SBO_0000078:
System.out.println("MassActionKinetics - reversible");
kForward = extractKForwardParam(sboParams);
kReverse = extractKReverseParam(sboParams);
kinetics = new MassActionKinetics(reaction);
reaction.setKinetics(kinetics);
setKForwardParam(reaction, kForward, kinetics);
setKReverseParam(reaction, kReverse, kinetics);
return true;
case SBO_0000043:
System.out.println("MassActionKinetics - zeroth order irreversible, Kr <- 0 ");
kForward = extractKForwardParam(sboParams);
kinetics = new MassActionKinetics(reaction);
// TODO: what to do here?
return true;
case SBO_0000044:
System.out.println("MassActionKinetics - first order irreversible, Kr <- 0 ");
kForward = extractKForwardParam(sboParams);
kinetics = new MassActionKinetics(reaction);
reaction.setKinetics(kinetics);
setKForwardParam(reaction, kForward, kinetics);
return true;
case SBO_0000028:
case SBO_0000029:
System.out.println("HMM_IRRKinetics");
// TODO: make kCat global variable, set its number and unit in annotation
// TODO: make vM global variable, set its number and unit in annotation
// get the numbers, if present (may be null)
kMichaelis = extractMichaelisForwardParam(sboParams);
vM = extractVMForwardParam(sboParams, process);
kCat = extractKCatForwardParam(sboParams);
kinetics = new HMM_IRRKinetics((SimpleReaction) reaction);
try {
// TODO: create expression only if kCat != null, otherwise use vM directly (if != null) otherwise ???
kinetics.reading(true);
setVMForwardParamAsExpression(reaction, kCat, kinetics);
} finally {
kinetics.reading(false);
}
reaction.setKinetics(kinetics);
setMichaelisForwardParam(reaction, kMichaelis, kinetics);
return true;
case SBO_0000438:
System.out.println("HMMREVKinetics");
kinetics = new HMM_REVKinetics((SimpleReaction) reaction);
return true;
default:
// TODO: guessing happens above - if we have nothing by now we need to raise runtime exception
// change the code below !!!
System.out.println("Unable to match the SBOTerm with any compatible kinetic law.");
// found unmapped kinetic law, we'll try to guess a match
return false;
}
}
}
}
// no SBTerm found so we cannot know for sure the kinetic law, we'll have to guess it
return false;
}
use of cbit.vcell.model.Kinetics in project vcell by virtualcell.
the class BioModelParametersTableModel method propertyChange.
@Override
public void propertyChange(java.beans.PropertyChangeEvent evt) {
super.propertyChange(evt);
if (evt.getSource() instanceof EditableSymbolTableEntry) {
int changeRow = getRowIndex((EditableSymbolTableEntry) evt.getSource());
if (changeRow >= 0) {
fireTableRowsUpdated(changeRow, changeRow);
}
} else {
String propertyName = evt.getPropertyName();
if (evt.getSource() == bioModel.getModel()) {
if (propertyName.equals(Model.PROPERTY_NAME_MODEL_PARAMETERS)) {
ModelParameter[] oldValue = (ModelParameter[]) evt.getOldValue();
if (oldValue != null) {
for (EditableSymbolTableEntry parameter : oldValue) {
parameter.removePropertyChangeListener(this);
}
}
ModelParameter[] newValue = (ModelParameter[]) evt.getNewValue();
if (newValue != null) {
for (EditableSymbolTableEntry parameter : newValue) {
parameter.addPropertyChangeListener(this);
}
}
refreshData();
} else if (propertyName.equals(Model.PROPERTY_NAME_SPECIES_CONTEXTS)) {
SpeciesContext[] oldValue = (SpeciesContext[]) evt.getOldValue();
if (oldValue != null) {
for (SpeciesContext sc : oldValue) {
sc.removePropertyChangeListener(this);
}
}
SpeciesContext[] newValue = (SpeciesContext[]) evt.getNewValue();
if (newValue != null) {
for (SpeciesContext sc : newValue) {
sc.addPropertyChangeListener(this);
}
}
refreshData();
} else if (propertyName.equals(Model.PROPERTY_NAME_REACTION_STEPS)) {
ReactionStep[] oldValue = (ReactionStep[]) evt.getOldValue();
if (oldValue != null) {
for (ReactionStep reactionStep : oldValue) {
reactionStep.removePropertyChangeListener(this);
reactionStep.getKinetics().removePropertyChangeListener(this);
for (KineticsParameter kineticsEditableSymbolTableEntry : reactionStep.getKinetics().getKineticsParameters()) {
kineticsEditableSymbolTableEntry.removePropertyChangeListener(this);
}
for (ProxyParameter proxyEditableSymbolTableEntry : reactionStep.getKinetics().getProxyParameters()) {
proxyEditableSymbolTableEntry.removePropertyChangeListener(this);
}
for (UnresolvedParameter unresolvedEditableSymbolTableEntry : reactionStep.getKinetics().getUnresolvedParameters()) {
unresolvedEditableSymbolTableEntry.removePropertyChangeListener(this);
}
}
}
ReactionStep[] newValue = (ReactionStep[]) evt.getNewValue();
if (newValue != null) {
for (ReactionStep reactionStep : newValue) {
reactionStep.addPropertyChangeListener(this);
reactionStep.getKinetics().addPropertyChangeListener(this);
for (KineticsParameter kineticsEditableSymbolTableEntry : reactionStep.getKinetics().getKineticsParameters()) {
kineticsEditableSymbolTableEntry.addPropertyChangeListener(this);
}
for (ProxyParameter proxyEditableSymbolTableEntry : reactionStep.getKinetics().getProxyParameters()) {
proxyEditableSymbolTableEntry.addPropertyChangeListener(this);
}
for (UnresolvedParameter unresolvedEditableSymbolTableEntry : reactionStep.getKinetics().getUnresolvedParameters()) {
unresolvedEditableSymbolTableEntry.addPropertyChangeListener(this);
}
}
}
refreshData();
} else if (evt.getPropertyName().equals(RbmModelContainer.PROPERTY_NAME_REACTION_RULE_LIST)) {
List<ReactionRule> oldValue = (List<ReactionRule>) evt.getOldValue();
if (oldValue != null) {
for (ReactionRule rs : oldValue) {
rs.removePropertyChangeListener(this);
}
}
List<ReactionRule> newValue = (List<ReactionRule>) evt.getNewValue();
if (newValue != null) {
for (ReactionRule rs : newValue) {
rs.addPropertyChangeListener(this);
}
}
refreshData();
}
} else if (evt.getSource() == bioModel) {
if (propertyName.equals(BioModel.PROPERTY_NAME_SIMULATION_CONTEXTS)) {
SimulationContext[] oldValue = (SimulationContext[]) evt.getOldValue();
for (SimulationContext simulationContext : oldValue) {
simulationContext.removePropertyChangeListener(this);
simulationContext.getGeometryContext().removePropertyChangeListener(this);
for (StructureMapping mapping : simulationContext.getGeometryContext().getStructureMappings()) {
mapping.removePropertyChangeListener(this);
for (EditableSymbolTableEntry parameter : mapping.getParameters()) {
parameter.removePropertyChangeListener(this);
}
}
simulationContext.getReactionContext().removePropertyChangeListener(this);
for (SpeciesContextSpec spec : simulationContext.getReactionContext().getSpeciesContextSpecs()) {
spec.removePropertyChangeListener(this);
for (EditableSymbolTableEntry parameter : spec.getParameters()) {
parameter.removePropertyChangeListener(this);
}
}
for (ElectricalStimulus elect : simulationContext.getElectricalStimuli()) {
elect.removePropertyChangeListener(this);
for (EditableSymbolTableEntry parameter : elect.getParameters()) {
parameter.removePropertyChangeListener(this);
}
}
for (SpatialObject spatialObject : simulationContext.getSpatialObjects()) {
spatialObject.removePropertyChangeListener(this);
}
for (SpatialProcess spatialProcess : simulationContext.getSpatialProcesses()) {
spatialProcess.removePropertyChangeListener(this);
for (LocalParameter p : spatialProcess.getParameters()) {
p.removePropertyChangeListener(this);
}
}
for (SimulationContextParameter p : simulationContext.getSimulationContextParameters()) {
p.removePropertyChangeListener(this);
}
}
SimulationContext[] newValue = (SimulationContext[]) evt.getNewValue();
for (SimulationContext simulationContext : newValue) {
simulationContext.addPropertyChangeListener(this);
simulationContext.getGeometryContext().addPropertyChangeListener(this);
for (StructureMapping mapping : simulationContext.getGeometryContext().getStructureMappings()) {
mapping.addPropertyChangeListener(this);
for (EditableSymbolTableEntry parameter : mapping.getParameters()) {
parameter.addPropertyChangeListener(this);
}
}
simulationContext.getReactionContext().addPropertyChangeListener(this);
for (SpeciesContextSpec spec : simulationContext.getReactionContext().getSpeciesContextSpecs()) {
spec.addPropertyChangeListener(this);
for (EditableSymbolTableEntry parameter : spec.getParameters()) {
parameter.addPropertyChangeListener(this);
}
}
for (ElectricalStimulus elect : simulationContext.getElectricalStimuli()) {
elect.addPropertyChangeListener(this);
for (EditableSymbolTableEntry parameter : elect.getParameters()) {
parameter.addPropertyChangeListener(this);
}
}
for (SpatialObject spatialObject : simulationContext.getSpatialObjects()) {
spatialObject.addPropertyChangeListener(this);
}
for (SpatialProcess spatialProcess : simulationContext.getSpatialProcesses()) {
spatialProcess.addPropertyChangeListener(this);
for (LocalParameter p : spatialProcess.getParameters()) {
p.addPropertyChangeListener(this);
}
}
for (SimulationContextParameter p : simulationContext.getSimulationContextParameters()) {
p.addPropertyChangeListener(this);
}
}
refreshData();
}
} else if (evt.getSource() instanceof GeometryContext && evt.getPropertyName().equals(GeometryContext.PROPERTY_STRUCTURE_MAPPINGS)) {
StructureMapping[] oldValue = (StructureMapping[]) evt.getOldValue();
if (oldValue != null) {
for (StructureMapping mapping : oldValue) {
mapping.removePropertyChangeListener(this);
for (EditableSymbolTableEntry parameter : mapping.getParameters()) {
parameter.removePropertyChangeListener(this);
}
}
}
StructureMapping[] newValue = (StructureMapping[]) evt.getNewValue();
if (newValue != null) {
for (StructureMapping mapping : newValue) {
mapping.addPropertyChangeListener(this);
for (EditableSymbolTableEntry parameter : mapping.getParameters()) {
parameter.addPropertyChangeListener(this);
}
}
}
refreshData();
} else if (evt.getSource() instanceof ReactionStep && (evt.getPropertyName().equals(ReactionStep.PROPERTY_NAME_KINETICS))) {
Kinetics oldValue = (Kinetics) evt.getOldValue();
if (oldValue != null) {
oldValue.removePropertyChangeListener(this);
for (KineticsParameter kineticsEditableSymbolTableEntry : oldValue.getKineticsParameters()) {
kineticsEditableSymbolTableEntry.removePropertyChangeListener(this);
}
for (ProxyParameter proxyEditableSymbolTableEntry : oldValue.getProxyParameters()) {
proxyEditableSymbolTableEntry.removePropertyChangeListener(this);
}
for (UnresolvedParameter unresolvedEditableSymbolTableEntry : oldValue.getUnresolvedParameters()) {
unresolvedEditableSymbolTableEntry.removePropertyChangeListener(this);
}
}
Kinetics newValue = (Kinetics) evt.getNewValue();
if (newValue != null) {
newValue.addPropertyChangeListener(this);
for (KineticsParameter kineticsEditableSymbolTableEntry : newValue.getKineticsParameters()) {
kineticsEditableSymbolTableEntry.addPropertyChangeListener(this);
}
for (ProxyParameter proxyEditableSymbolTableEntry : newValue.getProxyParameters()) {
proxyEditableSymbolTableEntry.addPropertyChangeListener(this);
}
for (UnresolvedParameter unresolvedEditableSymbolTableEntry : newValue.getUnresolvedParameters()) {
unresolvedEditableSymbolTableEntry.addPropertyChangeListener(this);
}
}
refreshData();
} else if (evt.getSource() instanceof SimulationContext && evt.getPropertyName().equals(SimulationContext.PROPERTY_NAME_SPATIALPROCESSES)) {
SpatialProcess[] oldValue = (SpatialProcess[]) evt.getOldValue();
if (oldValue != null) {
for (SpatialProcess process : oldValue) {
process.removePropertyChangeListener(this);
for (EditableSymbolTableEntry parameter : process.getParameters()) {
parameter.removePropertyChangeListener(this);
}
}
}
SpatialProcess[] newValue = (SpatialProcess[]) evt.getNewValue();
if (newValue != null) {
for (SpatialProcess process : newValue) {
process.addPropertyChangeListener(this);
for (EditableSymbolTableEntry parameter : process.getParameters()) {
parameter.addPropertyChangeListener(this);
}
}
}
refreshData();
} else if (evt.getSource() instanceof SimulationContext && evt.getPropertyName().equals(SimulationContext.PROPERTY_NAME_SPATIALOBJECTS)) {
SpatialObject[] oldValue = (SpatialObject[]) evt.getOldValue();
if (oldValue != null) {
for (SpatialObject spatialObject : oldValue) {
spatialObject.removePropertyChangeListener(this);
}
}
SpatialObject[] newValue = (SpatialObject[]) evt.getNewValue();
if (newValue != null) {
for (SpatialObject spatialObject : newValue) {
spatialObject.addPropertyChangeListener(this);
}
}
refreshData();
} else if (evt.getSource() instanceof SpatialObject && evt.getPropertyName().equals(SpatialObject.PROPERTY_NAME_QUANTITYCATEGORIESENABLED)) {
refreshData();
} else if (evt.getSource() instanceof SimulationContext && evt.getPropertyName().equals(SimulationContext.PROPERTY_NAME_SIMULATIONCONTEXTPARAMETERS)) {
SimulationContextParameter[] oldValue = (SimulationContextParameter[]) evt.getOldValue();
if (oldValue != null) {
for (SimulationContextParameter param : oldValue) {
param.removePropertyChangeListener(this);
}
}
SimulationContextParameter[] newValue = (SimulationContextParameter[]) evt.getNewValue();
if (newValue != null) {
for (SimulationContextParameter param : newValue) {
param.addPropertyChangeListener(this);
}
}
refreshData();
} else if (evt.getSource() instanceof Kinetics && (evt.getPropertyName().equals(Kinetics.PROPERTY_NAME_KINETICS_PARAMETERS))) {
EditableSymbolTableEntry[] oldValue = (EditableSymbolTableEntry[]) evt.getOldValue();
if (oldValue != null) {
for (int i = 0; i < oldValue.length; i++) {
oldValue[i].removePropertyChangeListener(this);
}
}
EditableSymbolTableEntry[] newValue = (EditableSymbolTableEntry[]) evt.getNewValue();
if (newValue != null) {
for (int i = 0; i < newValue.length; i++) {
newValue[i].addPropertyChangeListener(this);
}
}
refreshData();
// } else if(evt.getSource() instanceof ReactionRuleEmbedded) {
// ReactionRuleEmbedded reactionRule = (ReactionRuleEmbedded) evt.getSource();
// int changeRow = getRowIndex(reactionRule);
// if (changeRow >= 0) {
// fireTableRowsUpdated(changeRow, changeRow);
// }
}
}
}
Aggregations