use of cbit.vcell.model.ReactionStep 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 cbit.vcell.model.ReactionStep in project vcell by virtualcell.
the class SBMLImporter method getBioModel.
// /**
// * @ TODO: This method doesn't take care of adjusting species in nested
// parameter rules with the species_concetration_factor.
// * @param kinetics
// * @param paramExpr
// * @throws ExpressionException
// */
// private void substituteOtherGlobalParams(Kinetics kinetics, Expression
// paramExpr) throws ExpressionException, PropertyVetoException {
// String[] exprSymbols = paramExpr.getSymbols();
// if (exprSymbols == null || exprSymbols.length == 0) {
// return;
// }
// Model vcModel = vcBioModel.getSimulationContext(0).getModel();
// for (int kk = 0; kk < exprSymbols.length; kk++) {
// ModelParameter mp = vcModel.getModelParameter(exprSymbols[kk]);
// if (mp != null) {
// Expression expr = mp.getExpression();
// if (expr != null) {
// Expression newExpr = new Expression(expr);
// substituteGlobalParamRulesInPlace(newExpr, false);
// // param has constant value, add it as a kinetic parameter if it is not
// already in the kinetics
// kinetics.setParameterValue(exprSymbols[kk], newExpr.infix());
// kinetics.getKineticsParameter(exprSymbols[kk]).setUnitDefinition(getSBMLUnit(sbmlModel.getParameter(exprSymbols[kk]).getUnits(),
// null));
// if (newExpr.getSymbols() != null) {
// substituteOtherGlobalParams(kinetics, newExpr);
// }
// }
// }
// }
// }
/**
* parse SBML file into biomodel logs errors to log4j if present in source
* document
*
* @return new Biomodel
* @throws IOException
* @throws XMLStreamException
*/
public BioModel getBioModel() throws XMLStreamException, IOException {
if (sbmlFileName == null && sbmlModel == null) {
throw new IllegalStateException("Expected non-null SBML model");
}
SBMLDocument document;
String defaultErrorPrefix = "Unable to read SBML file";
if (sbmlFileName != null) {
try {
// Read SBML model into libSBML SBMLDocument and create an SBML model
List<String> readLines = FileUtils.readLines(new File(sbmlFileName), Charset.defaultCharset());
StringBuffer sb = new StringBuffer();
// throws NPE when "<sbml ... xmlns:render... " is defined in input document
for (String line : readLines) {
String str = "xmlns:render=\"http://www.sbml.org/sbml/level3/version1/render/version1\"";
int indexOf = line.indexOf(str);
if (indexOf != -1) {
line = line.substring(0, indexOf - 1) + line.substring(indexOf + str.length());
}
str = "render:required=\"false\"";
indexOf = line.indexOf(str);
if (indexOf != -1) {
line = line.substring(0, indexOf - 1) + line.substring(indexOf + str.length());
}
sb.append(line + "\n");
}
SBMLReader reader = new SBMLReader();
document = reader.readSBMLFromString(sb.toString());
// check for VCell origin
String topNotes = document.getNotesString();
if (topNotes != null && topNotes.contains("VCell")) {
isFromVCell = true;
}
// document.checkConsistencyOffline();
// long numProblems = document.getNumErrors();
//
// System.out.println("\n\nSBML Import Error Report");
// ByteArrayOutputStream os = new ByteArrayOutputStream();
// PrintStream ps = new PrintStream(os);
// document.printErrors(ps);
// String output = os.toString();
// if (numProblems > 0 && lg.isEnabledFor(Level.WARN)) {
// lg.warn("Num problems in original SBML document : " + numProblems);
// lg.warn(output);
// }
sbmlModel = document.getModel();
} catch (Exception e) {
throw new SBMLImportException(defaultErrorPrefix + ": \n" + sbmlFileName, e);
}
if (sbmlModel == null) {
throw new SBMLImportException(defaultErrorPrefix + ": \n" + sbmlFileName);
}
} else {
// sbmlModel != null
try {
document = sbmlModel.getSBMLDocument();
} catch (Exception e) {
throw new SBMLImportException(defaultErrorPrefix + ".\n", e);
}
}
if (document == null) {
throw new SBMLImportException(defaultErrorPrefix + ".\n");
}
int numPackages = 0;
String msgPackages = "";
try {
boolean b = document.getPackageRequired("comp");
if (document.isPackageEnabled("comp")) {
numPackages++;
msgPackages += "'comp', ";
CompSBMLDocumentPlugin cdp = null;
CompModelPlugin cmp = null;
CompSBasePlugin csp = null;
CompFlatteningConverter ccc = null;
}
if (document.isPackageEnabled("fbc")) {
numPackages++;
msgPackages += "'fbc', ";
}
if (document.isPackageEnabled("multi")) {
numPackages++;
msgPackages += "'multi', ";
}
if (document.isPackageEnabled("qual")) {
numPackages++;
msgPackages += "'qual', ";
}
} catch (Exception e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Unable to check the SBML file package requirements.");
}
String ext = "extension";
String is = "is";
String has = "has";
if (numPackages > 0) {
if (numPackages > 1) {
ext += "s";
is = "are";
}
msgPackages = msgPackages.substring(0, msgPackages.length() - 1);
msgPackages = "The model includes elements of SBML " + ext + " " + msgPackages + " which " + is + " required for simulating the model but " + is + " not supported.";
throw new SBMLImportException("Unable to import the SBML file.\n" + msgPackages);
}
try {
if (document.isPackageEnabled("groups")) {
numPackages++;
msgPackages += "'groups', ";
}
if (document.isPackageEnabled("layout")) {
numPackages++;
msgPackages += "'layout', ";
}
if (document.isPackageEnabled("render")) {
numPackages++;
msgPackages += "'render', ";
}
} catch (Exception e) {
// we're going to ignore these packages anyway
e.printStackTrace(System.out);
}
if (numPackages > 0) {
if (numPackages > 1) {
ext += "s";
is = "are";
has = "have";
}
msgPackages = "The model includes elements of SBML " + ext + " " + msgPackages + " which " + is + " not required for simulating the model and " + has + " been ignored.";
localIssueList.add(new Issue(vcBioModel, issueContext, IssueCategory.SBMLImport_UnsupportedFeature, msgPackages, Issue.Severity.WARNING));
}
// Convert SBML Model to VCell model
// An SBML model will correspond to a simcontext - which needs a Model and a Geometry
// SBML handles only nonspatial geometries at this time, hence creating a non-spatial default geometry
// get namespace based on SBML model level and version to use in SBMLAnnotationUtil
this.level = sbmlModel.getLevel();
// this.version = sbmlModel.getVersion();
String ns = document.getNamespace();
// create SBML unit system for the model and create the bioModel.
ModelUnitSystem modelUnitSystem;
try {
modelUnitSystem = createSBMLUnitSystemForVCModel();
} catch (Exception e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Inconsistent unit system. Cannot import SBML model into VCell.", Category.INCONSISTENT_UNIT, e);
}
try {
Geometry geometry = new Geometry(BioModelChildSummary.COMPARTMENTAL_GEO_STR, 0);
vcBioModel = new BioModel(null, modelUnitSystem);
SimulationContext simulationContext = new SimulationContext(vcBioModel.getModel(), geometry, null, null, Application.NETWORK_DETERMINISTIC);
vcBioModel.addSimulationContext(simulationContext);
simulationContext.setName(vcBioModel.getSimulationContext(0).getModel().getName());
// vcBioModel.getSimulationContext(0).setName(vcBioModel.getSimulationContext(0).getModel().getName()+"_"+vcBioModel.getSimulationContext(0).getGeometry().getName());
} catch (Exception e) {
// PropertyVetoException
e.printStackTrace(System.out);
throw new SBMLImportException("Could not create simulation context corresponding to the input SBML model.\n", e);
}
try {
String biomodelName = sbmlModel.getName();
if ((biomodelName == null) || biomodelName.trim().equals("")) {
biomodelName = sbmlModel.getId();
}
if ((biomodelName == null) || biomodelName.trim().equals("")) {
biomodelName = "newBioModel";
}
vcBioModel.setName(biomodelName);
sbmlAnnotationUtil = new SBMLAnnotationUtil(vcBioModel.getVCMetaData(), vcBioModel, ns);
sbmlAnnotationUtil.readAnnotation(vcBioModel, sbmlModel);
sbmlAnnotationUtil.readNotes(vcBioModel, sbmlModel);
// vcBioModel.getVCMetaData().printRdfPretty();
// vcBioModel.getVCMetaData().printRdfStatements();
translateSBMLModel();
vcBioModel.refreshDependencies();
ReactionStep[] reax = vcBioModel.getModel().getReactionSteps();
for (int i = 0; i < reax.length; i++) {
if (reax[i].getKinetics().getKineticsDescription().isLumped()) {
DistributedKinetics.toDistributedKinetics((LumpedKinetics) reax[i].getKinetics());
}
}
} catch (Exception e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Could not create Biomodel corresponding to the input SBML model.\n", e);
}
Issue[] warnings = localIssueList.toArray(new Issue[localIssueList.size()]);
if (warnings != null && warnings.length > 0) {
StringBuffer messageBuffer = new StringBuffer("Issues encountered during SBML Import:\n");
int issueCount = 0;
for (int i = 0; i < warnings.length; i++) {
if (warnings[i].getSeverity() == Issue.Severity.WARNING || warnings[i].getSeverity() == Issue.Severity.INFO) {
// messageBuffer.append("- " + warnings[i].getMessage() + " (" + warnings[i].getCategory() + ", " + warnings[i].getSeverity().name() + ")\n");
messageBuffer.append("- " + warnings[i].getMessage() + "\n");
issueCount++;
}
}
if (issueCount > 0) {
try {
logger.sendMessage(VCLogger.Priority.MediumPriority, VCLogger.ErrorType.OverallWarning, messageBuffer.toString());
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
// if called from GUI application convert if VCell origin, otherwise ask user
if (isFromVCell) {
ModelUnitSystem vcUnitSystem = ModelUnitSystem.createDefaultVCModelUnitSystem();
try {
BioModel convertedBioModel = ModelUnitConverter.createBioModelWithNewUnitSystem(vcBioModel, vcUnitSystem);
return convertedBioModel;
} catch (ExpressionException | XmlParseException e) {
// TODO maybe alert user? for now fail silently...
e.printStackTrace();
return vcBioModel;
}
}
return vcBioModel;
}
use of cbit.vcell.model.ReactionStep in project vcell by virtualcell.
the class SBMLExporter method addInitialAssignments.
protected void addInitialAssignments() throws ExpressionException, MappingException, MathException, MatrixException, ModelException {
// for species, the initial assignments are done in addSpecies()
if (vcSelectedSimJob == null) {
return;
}
int index = vcSelectedSimJob.getJobIndex();
System.out.println("Simulation Job index = " + index);
MathOverrides mo = vcSelectedSimJob.getSimulation().getMathOverrides();
if (mo == null || !mo.hasOverrides()) {
return;
}
//
// TODO: SEDMLExporter is doing it differently, much more complicated
//
MathMapping mm = vcSelectedSimContext.createNewMathMapping();
MathSymbolMapping msm = mm.getMathSymbolMapping();
String[] ocns = mo.getOverridenConstantNames();
for (String ocn : ocns) {
SymbolTableEntry ste = SEDMLExporter.getSymbolTableEntryForModelEntity(msm, ocn);
ModelParameter mp = vcSelectedSimContext.getModel().getModelParameter(ocn);
Expression exp = mo.getActualExpression(ocn, index);
String name = "";
if (ste != null && ste instanceof SpeciesContextSpecParameter) {
SpeciesContextSpecParameter scsp = (SpeciesContextSpecParameter) ste;
SpeciesContext sc = scsp.getSpeciesContext();
name = sc.getName();
} else if (ste != null && ste instanceof ModelParameter) {
name = ste.getName();
} else if (ste != null && ste instanceof KineticsParameter) {
// note: if we call this before adding the reactions, we can't verify that the name we use
// here will match the name we assign when we actually add the reaction
KineticsParameter kp = (KineticsParameter) ste;
Kinetics ks = kp.getKinetics();
ReactionStep rs = ks.getReactionStep();
name = TokenMangler.mangleToSName(kp.getName() + "_" + rs.getName());
} else {
name = ocn;
System.out.println("Unexpected override or parameter scan entity: " + ocn);
}
// System.out.println(" symbol: " + name + ", overriden constant: " + ocn + ", expression: " + exp.infix());
org.sbml.jsbml.InitialAssignment ia = sbmlModel.createInitialAssignment();
// String id = TokenMangler.mangleToSName("initialAssignment_" + name "_" + index); // no point in defining id or name for initial assignment
// ia.setId(id);
// ia.setName(id);
ia.setVariable(name);
ASTNode math = getFormulaFromExpression(exp);
ia.setMath(math);
}
}
use of cbit.vcell.model.ReactionStep 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);
}
}
}
use of cbit.vcell.model.ReactionStep in project vcell by virtualcell.
the class AnnotationMapping method annotation2BioPaxObject.
public String annotation2BioPaxObject(BioModel bioModel, Identifiable identifiable) {
String name = "";
String type = "";
ArrayList<String> componentInfo = getComponentInfo(bioModel, identifiable);
if (componentInfo.size() > 0) {
name = componentInfo.get(0);
type = componentInfo.get(1);
}
String info = type + " : " + name;
HashMap<String, String> refInfo = getRefInfo(bioModel, identifiable);
// otherwise, create object and add link
if (type.equals(VCID.CLASS_SPECIES)) {
// lookup name by speciesContext
ArrayList<SpeciesContext> speciesContextArrList = new ArrayList<SpeciesContext>(Arrays.asList(new SpeciesContext[] { bioModel.getModel().getSpeciesContext(name) }));
if (speciesContextArrList.get(0) == null) {
speciesContextArrList.clear();
// lookup name by species
for (int i = 0; i < bioModel.getModel().getSpeciesContexts().length; i++) {
if (bioModel.getModel().getSpeciesContexts()[i].getSpecies().getCommonName().equals(name)) {
speciesContextArrList.add(bioModel.getModel().getSpeciesContexts()[i]);
}
}
}
for (int i = 0; i < speciesContextArrList.size(); i++) {
SpeciesContext speciesContext = speciesContextArrList.get(i);
if (bioModel.getRelationshipModel().getRelationshipObjects(speciesContext).size() == 0) {
ArrayList<Xref> xRef = getXrefs(bioModel, refInfo);
ArrayList<String> refName = getNameRef(xRef, name);
BioPaxObject bpObject = bioModel.getPathwayModel().findFromNameAndType(refName.get(0), EntityImpl.TYPE_PHYSICALENTITY);
//
// Commenting out legacy code from the times when we didn't have proper annotation visualization
// What we were doing below was to create a bioPax object, link it to the species and create
// copies of the annotations in order to be able to navigate to external databases through XRef
// Commenting out this code since we can now navigate to external databases from the annotation panel
//
// if(bpObject == null){
// bpObject = createPhysicalEntity(xRef, refName, name);
// bioModel.getPathwayModel().add(bpObject);
// }
// if(bpObject != null && !isLinked(bioModel, bpObject, speciesContext)) {
// // create linkage
// RelationshipObject newRelationship = new RelationshipObject(speciesContext, bpObject);
// bioModel.getRelationshipModel().addRelationshipObject(newRelationship);
// return info;
// }
}
}
} else if (type.equals(VCID.CLASS_BIOMODEL)) {
// BioPaxObject bpObject = bioModel.getPathwayModel().findFromName(refName.get(0), "Pathway");
// if(bpObject == null){
// bpObject = createPathway(componentInfo, refInfo);
// bioModel.getPathwayModel().add(bpObject);
// return info;
// }
} else if (type.equals(VCID.CLASS_REACTION_STEP)) {
ReactionStep reactionStep = bioModel.getModel().getReactionStep(name);
ArrayList<Xref> xRef = getXrefs(bioModel, refInfo);
ArrayList<String> refName = getNameRef(xRef, name);
if (bioModel.getRelationshipModel().getRelationshipObjects(reactionStep).size() == 0) {
BioPaxObject bpObject = bioModel.getPathwayModel().findFromNameAndType(refName.get(0), EntityImpl.TYPE_INTERACTION);
//
// We are eliminating some obsolete code, see above the species context comment
//
// if(bpObject == null){
// bpObject = createInteraction(reactionStep, xRef, refName);
// bioModel.getPathwayModel().add(bpObject);
// }
// if(bpObject != null && !isLinked(bioModel, bpObject, reactionStep)) {
// // create linkage
// RelationshipObject newRelationship = new RelationshipObject(reactionStep, bpObject);
// bioModel.getRelationshipModel().addRelationshipObject(newRelationship);
// return info;
// }
}
}
return null;
}
Aggregations