use of org.sbml.jsbml.ext.spatial.SpatialReactionPlugin 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 org.sbml.jsbml.ext.spatial.SpatialReactionPlugin in project vcell by virtualcell.
the class SBMLImporter method addReactions.
/**
* addReactions:
*/
protected void addReactions(VCMetaData metaData, Map<String, String> vcToSbmlNameMap, Map<String, String> sbmlToVcNameMap) {
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 rxnSbmlId = sbmlRxn.getId();
String rxnSbmlName = sbmlRxn.getName();
if (isRestrictedXYZT(rxnSbmlId)) {
// simply rename any x,y,z reaction if non-spatial model
rxnSbmlId = "r_" + rxnSbmlId;
vcToSbmlNameMap.put(rxnSbmlId, sbmlRxn.getId());
sbmlToVcNameMap.put(sbmlRxn.getId(), rxnSbmlId);
}
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, rxnSbmlId, 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 : " + rxnSbmlId, 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, rxnSbmlId, bReversible);
}
} else {
vcReaction = new SimpleReaction(vcModel, reactionStructure, rxnSbmlId, bReversible);
}
} else {
vcReaction = new SimpleReaction(vcModel, reactionStructure, rxnSbmlId, bReversible);
}
if (rxnSbmlName != null && !rxnSbmlName.isEmpty()) {
vcReaction.setSbmlName(rxnSbmlName);
}
// set annotations and notes on vcReactions[i]
sbmlAnnotationUtil.readAnnotation(vcReaction, sbmlRxn);
sbmlAnnotationUtil.readNotes(vcReaction, sbmlRxn);
// the limit on the reactionName length.
if (rxnSbmlId.length() > 64) {
String freeTextAnnotation = metaData.getFreeTextAnnotation(vcReaction);
if (freeTextAnnotation == null) {
freeTextAnnotation = "";
}
StringBuffer oldRxnAnnotation = new StringBuffer(freeTextAnnotation);
oldRxnAnnotation.append("\n\n" + rxnSbmlId);
metaData.setFreeTextAnnotation(vcReaction, oldRxnAnnotation.toString());
}
// Now add the reactants, products, modifiers as specified by
// the sbmlRxn
addReactionParticipants(sbmlRxn, vcReaction, sbmlToVcNameMap);
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);
// we don't need to make sure it's not spatial here, we checked before renaming the variables
for (Map.Entry<String, String> entry : sbmlToVcNameMap.entrySet()) {
String sbmlName = entry.getKey();
String vcName = entry.getValue();
kLawRateExpr.substituteInPlace(new Expression(sbmlName), new Expression(vcName));
}
Expression vcRateExpression = new Expression(kLawRateExpr);
// modifier (catalyst) to the reaction.
for (int k = 0; k < vcSpeciesContexts.length; k++) {
SpeciesContext sc = vcSpeciesContexts[k];
if (vcRateExpression.hasSymbol(sc.getName())) {
ReactionParticipant r = vcReaction.getReactant(sc.getName());
ReactionParticipant p = vcReaction.getProduct(sc.getName());
ReactionParticipant c = vcReaction.getCatalyst(sc.getName());
if ((r == null) && (p == null) && (c == 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(sc);
}
}
}
// 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);
// (a) the requiredElements attributes should be '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);
String spId = sp.getId();
String vcSpeciesName = spId;
if (sbmlToVcNameMap.get(spId) != null) {
vcSpeciesName = sbmlToVcNameMap.get(spId);
}
ArrayList<ReactionParticipant> rpArray = getVCReactionParticipantsFromSymbol(vcReaction, vcSpeciesName);
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(vcSpeciesName));
}
}
}
}
// 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 org.sbml.jsbml.ext.spatial.SpatialReactionPlugin 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);
String rxnSbmlName = vcReactionStep.getSbmlName();
if (rxnSbmlName != null && !rxnSbmlName.isEmpty()) {
sbmlReaction.setName(rxnSbmlName);
}
// 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;
// to get unique ID when the same species is both a reactant and a product
String rolePostfix = "";
if (rxnParticpant instanceof cbit.vcell.model.Reactant) {
rolePostfix = "r";
ssr = sr = sbmlReaction.createReactant();
} else if (rxnParticpant instanceof cbit.vcell.model.Product) {
rolePostfix = "p";
ssr = sr = sbmlReaction.createProduct();
}
if (rxnParticpant instanceof cbit.vcell.model.Catalyst) {
rolePostfix = "c";
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() + rolePostfix;
sr.setId(TokenMangler.mangleToSName(modelUniqueName));
// SBML-REVIEW
sr.setConstant(true);
// int rcode = sr.appendNotes("<
// we know that in VCell we can't override stoichiometry anywhere, below is no longer questionable
// 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);
}
}
}
Aggregations