Search in sources :

Example 1 with ReactionParticipant

use of cbit.vcell.model.ReactionParticipant in project vcell by virtualcell.

the class PathwayMapping method createReactionStepFromPathway.

/*
	 * for reaction:
	 * 1. annotate the selected vcell object using linked pathway conversion
	 * 2. add non-existing speciesContexts from linked pathway conversion
	 * 3. add links between relative vcell objects and pathway objects
	 * Questions:
	 * - how to deal with the case that the reaction is existing in the model?
	 * 		+ add it in no matter what? 
	 * 				(this is the version we have now: 
	 * 					add the duplicated reactions in without name changing, 
	 * 				 	all duplicated reactions share the same participant objects)
	 *      + just modify the existing one?
	 */
private void createReactionStepFromPathway(BioModel bioModel, Process process, ReactionStep reactionStep, RelationshipObject relationshipObject, boolean addSubunits) throws Exception {
    // annotate the selected vcell object using linked pathway object
    // add non-existing speciesContexts from linked pathway conversion
    ReactionParticipant[] rpArray = parseReaction(reactionStep, bioModel, relationshipObject);
    // create a hashtable for interaction Participants
    Hashtable<String, BioPaxObject> participantTable = new Hashtable<String, BioPaxObject>();
    for (BioPaxObject bpObject : ((Conversion) relationshipObject.getBioPaxObject()).getLeft()) {
        if (((PhysicalEntity) bpObject).getName().size() == 0) {
            participantTable.put(getSafetyName(((PhysicalEntity) bpObject).getID()), bpObject);
        } else {
            participantTable.put(getSafetyName(((PhysicalEntity) bpObject).getName().get(0)), bpObject);
        }
    }
    for (BioPaxObject bpObject : ((Conversion) relationshipObject.getBioPaxObject()).getRight()) {
        if (((PhysicalEntity) bpObject).getName().size() == 0) {
            participantTable.put(getSafetyName(((PhysicalEntity) bpObject).getID()), bpObject);
        } else {
            participantTable.put(getSafetyName(((PhysicalEntity) bpObject).getName().get(0)), bpObject);
        }
    }
    for (ReactionParticipant rp : rpArray) {
        SpeciesContext speciesContext = rp.getSpeciesContext();
        if (bioModel.getModel().getSpeciesContext(speciesContext.getName()) == null) {
            // if the speciesContext is not existed, then add it to the bioModel and link it to the corresponding pathway object
            if (bioModel.getModel().getSpecies(speciesContext.getName()) == null) {
                bioModel.getModel().addSpecies(speciesContext.getSpecies());
            }
            bioModel.getModel().addSpeciesContext(speciesContext);
            RelationshipObject newSpeciesContext = new RelationshipObject(speciesContext, participantTable.get(speciesContext.getName()));
            bioModel.getRelationshipModel().addRelationshipObject(newSpeciesContext);
        } else {
            // if it is in the bioModel, then check whether it links to pathway object or not
            HashSet<RelationshipObject> linkedReObjects = bioModel.getRelationshipModel().getRelationshipObjects(bioModel.getModel().getSpeciesContext(speciesContext.getName()));
            if (linkedReObjects != null) {
                boolean isLinked = false;
                for (RelationshipObject reObject : linkedReObjects) {
                    if (reObject.getBioPaxObject() == participantTable.get(speciesContext.getName())) {
                        isLinked = true;
                        break;
                    }
                }
                if (!isLinked) {
                    RelationshipObject newSpeciesContext = new RelationshipObject(speciesContext, participantTable.get(speciesContext.getName()));
                    bioModel.getRelationshipModel().addRelationshipObject(newSpeciesContext);
                }
            } else {
                RelationshipObject newSpeciesContext = new RelationshipObject(speciesContext, participantTable.get(speciesContext.getName()));
                bioModel.getRelationshipModel().addRelationshipObject(newSpeciesContext);
            }
        }
    }
    (reactionStep).setReactionParticipants(rpArray);
    // add Control to the reaction
    if (process.getControl() != null) {
        for (InteractionParticipant pe : process.getControl().getParticipants()) {
            SpeciesContext newSpeciescontext = createSpeciesContextFromBioPaxObject(bioModel, pe.getPhysicalEntity(), addSubunits);
            (reactionStep).addReactionParticipant(new Catalyst(null, reactionStep, newSpeciescontext));
        }
    }
    addKinetics(reactionStep, process);
}
Also used : BioPaxObject(org.vcell.pathway.BioPaxObject) Hashtable(java.util.Hashtable) SpeciesContext(cbit.vcell.model.SpeciesContext) Conversion(org.vcell.pathway.Conversion) PhysicalEntity(org.vcell.pathway.PhysicalEntity) InteractionParticipant(org.vcell.pathway.InteractionParticipant) ReactionParticipant(cbit.vcell.model.ReactionParticipant) Catalyst(cbit.vcell.model.Catalyst)

Example 2 with ReactionParticipant

use of cbit.vcell.model.ReactionParticipant 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);
        }
    }
}
Also used : MembraneMapping(cbit.vcell.mapping.MembraneMapping) LumpedKinetics(cbit.vcell.model.LumpedKinetics) Element(org.jdom.Element) StructureMapping(cbit.vcell.mapping.StructureMapping) SimpleSpeciesReference(org.sbml.jsbml.SimpleSpeciesReference) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) SpeciesReference(org.sbml.jsbml.SpeciesReference) SimpleSpeciesReference(org.sbml.jsbml.SimpleSpeciesReference) ASTNode(org.sbml.jsbml.ASTNode) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) UnitDefinition(org.sbml.jsbml.UnitDefinition) Pair(org.vcell.util.Pair) DistributedKinetics(cbit.vcell.model.DistributedKinetics) SpatialReactionPlugin(org.sbml.jsbml.ext.spatial.SpatialReactionPlugin) ReactionSpec(cbit.vcell.mapping.ReactionSpec) AssignmentRule(org.sbml.jsbml.AssignmentRule) ExpressionException(cbit.vcell.parser.ExpressionException) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) ImageException(cbit.image.ImageException) SBMLException(org.sbml.jsbml.SBMLException) ExpressionException(cbit.vcell.parser.ExpressionException) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) ReactionStep(cbit.vcell.model.ReactionStep) Kinetics(cbit.vcell.model.Kinetics) DistributedKinetics(cbit.vcell.model.DistributedKinetics) LumpedKinetics(cbit.vcell.model.LumpedKinetics) ReactionParticipant(cbit.vcell.model.ReactionParticipant)

Example 3 with ReactionParticipant

use of cbit.vcell.model.ReactionParticipant 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);
    }
}
Also used : Issue(org.vcell.util.Issue) ArrayList(java.util.ArrayList) FluxReaction(cbit.vcell.model.FluxReaction) SpeciesContext(cbit.vcell.model.SpeciesContext) GeneralKinetics(cbit.vcell.model.GeneralKinetics) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) ReactionContext(cbit.vcell.mapping.ReactionContext) HashSet(java.util.HashSet) KineticsProxyParameter(cbit.vcell.model.Kinetics.KineticsProxyParameter) ReactionSpec(cbit.vcell.mapping.ReactionSpec) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) ModelParameter(cbit.vcell.model.Model.ModelParameter) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) ReactionStep(cbit.vcell.model.ReactionStep) Kinetics(cbit.vcell.model.Kinetics) GeneralKinetics(cbit.vcell.model.GeneralKinetics) GeneralLumpedKinetics(cbit.vcell.model.GeneralLumpedKinetics) KineticLaw(org.sbml.jsbml.KineticLaw) ReactionParticipant(cbit.vcell.model.ReactionParticipant) Element(org.jdom.Element) UnresolvedParameter(cbit.vcell.model.Kinetics.UnresolvedParameter) GeneralLumpedKinetics(cbit.vcell.model.GeneralLumpedKinetics) ASTNode(org.sbml.jsbml.ASTNode) Membrane(cbit.vcell.model.Membrane) Structure(cbit.vcell.model.Structure) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem) SpatialReactionPlugin(org.sbml.jsbml.ext.spatial.SpatialReactionPlugin) SimpleReaction(cbit.vcell.model.SimpleReaction) Reaction(org.sbml.jsbml.Reaction) SimpleReaction(cbit.vcell.model.SimpleReaction) FluxReaction(cbit.vcell.model.FluxReaction) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) IOException(java.io.IOException) PropertyVetoException(java.beans.PropertyVetoException) SBMLException(org.sbml.jsbml.SBMLException) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) ExpressionException(cbit.vcell.parser.ExpressionException) LocalParameter(org.sbml.jsbml.LocalParameter) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel)

Example 4 with ReactionParticipant

use of cbit.vcell.model.ReactionParticipant in project vcell by virtualcell.

the class Xmlproducer method getXML.

/**
 * This method returns the XML represntation of a Simple reaction object.
 * Creation date: (2/27/2001 2:27:28 PM)
 * @return Element
 * @param param cbit.vcell.model.SimpleReaction
 */
private Element getXML(SimpleReaction param) throws XmlParseException {
    Element simplereaction = new Element(XMLTags.SimpleReactionTag);
    // Add attribute
    String nameStr = (param.getName() != null) ? (mangle(param.getName())) : "unnamed_SimpleReaction";
    simplereaction.setAttribute(XMLTags.StructureAttrTag, mangle(param.getStructure().getName()));
    simplereaction.setAttribute(XMLTags.NameAttrTag, nameStr);
    simplereaction.setAttribute(XMLTags.ReversibleAttrTag, mangle(Boolean.valueOf(param.isReversible()).toString()));
    if (param.getPhysicsOptions() == SimpleReaction.PHYSICS_ELECTRICAL_ONLY) {
        simplereaction.setAttribute(XMLTags.FluxOptionAttrTag, XMLTags.FluxOptionElectricalOnly);
    } else if (param.getPhysicsOptions() == SimpleReaction.PHYSICS_MOLECULAR_AND_ELECTRICAL) {
        simplereaction.setAttribute(XMLTags.FluxOptionAttrTag, XMLTags.FluxOptionMolecularAndElectrical);
    } else if (param.getPhysicsOptions() == SimpleReaction.PHYSICS_MOLECULAR_ONLY) {
        simplereaction.setAttribute(XMLTags.FluxOptionAttrTag, XMLTags.FluxOptionMolecularOnly);
    }
    // If keyFlag is on print the Keyvalue
    if (param.getKey() != null && this.printKeysFlag) {
        simplereaction.setAttribute(XMLTags.KeyValueAttrTag, param.getKey().toString());
    }
    // Add subelements: Reactants/Products/Catalysts
    // separate the order of the reactants, products, and modifiers.
    ReactionParticipant[] rpArray = param.getReactionParticipants();
    ArrayList<Element> products = new ArrayList<Element>();
    ArrayList<Element> modifiers = new ArrayList<Element>();
    for (int i = 0; i < rpArray.length; i++) {
        Element rp = getXML(rpArray[i]);
        if (rp != null) {
            if (rpArray[i] instanceof Reactant)
                simplereaction.addContent(rp);
            else if (rpArray[i] instanceof Product)
                products.add(rp);
            else if (rpArray[i] instanceof Catalyst)
                modifiers.add(rp);
        }
    }
    for (int i = 0; i < products.size(); i++) simplereaction.addContent((Element) products.get(i));
    for (int i = 0; i < modifiers.size(); i++) simplereaction.addContent((Element) modifiers.get(i));
    // Add kinetics
    simplereaction.addContent(getXML(param.getKinetics()));
    return simplereaction;
}
Also used : Element(org.jdom.Element) ArrayList(java.util.ArrayList) Product(cbit.vcell.model.Product) ReactionParticipant(cbit.vcell.model.ReactionParticipant) Reactant(cbit.vcell.model.Reactant) Catalyst(cbit.vcell.model.Catalyst)

Example 5 with ReactionParticipant

use of cbit.vcell.model.ReactionParticipant in project vcell by virtualcell.

the class RbmNetworkGenerator method generateModel.

public static void generateModel(BioModel bioModel, String netfile) throws Exception {
    Model model = bioModel.getModel();
    Map<String, SpeciesContext> speciesMap = new HashMap<String, SpeciesContext>();
    Map<String, ReactionStep> reactionMap = new HashMap<String, ReactionStep>();
    List<ReactionLine> reactionLineList = new ArrayList<ReactionLine>();
    BufferedReader br = new BufferedReader(new StringReader(netfile));
    int reversibleCount = 0;
    int reactionCount = 0;
    while (true) {
        String line = br.readLine();
        if (line == null) {
            break;
        }
        line = line.trim();
        if (line.equals(BEGIN_PARAMETERS)) {
            while (true) {
                String line2 = br.readLine();
                line2 = line2.trim();
                if (line2.length() == 0) {
                    continue;
                }
                if (line2.equals(END_PARAMETERS)) {
                    break;
                }
                StringTokenizer st = new StringTokenizer(line2);
                String token1 = st.nextToken();
                String token2 = st.nextToken();
                String token3 = st.nextToken();
                ModelParameter mp = model.new ModelParameter(token2, new Expression(token3), Model.ROLE_UserDefined, bioModel.getModel().getUnitSystem().getInstance_TBD());
                model.addModelParameter(mp);
            }
        } else if (line.equals(BEGIN_SPECIES)) {
            while (true) {
                String line2 = br.readLine();
                line2 = line2.trim();
                if (line2.length() == 0) {
                    continue;
                }
                if (line2.equals(END_SPECIES)) {
                    break;
                }
                StringTokenizer st = new StringTokenizer(line2);
                // no
                String token1 = st.nextToken();
                // pattern
                String token2 = st.nextToken();
                // initial condition
                String token3 = st.nextToken();
                String newname = token2.replaceAll("\\.", "_");
                newname = newname.replaceAll("[\\(,][a-zA-Z]\\w*", "");
                newname = newname.replaceAll("~|!\\d*", "");
                newname = newname.replaceAll("\\(\\)", "");
                newname = newname.replaceAll("\\)", "");
                SpeciesContext sc = model.createSpeciesContext(model.getStructure(0));
                sc.setName(newname);
                bioModel.getVCMetaData().setFreeTextAnnotation(sc, token2);
                bioModel.getVCMetaData().setFreeTextAnnotation(sc.getSpecies(), token2);
                speciesMap.put(token1, sc);
            }
        } else if (line.equals(BEGIN_REACTIONS)) {
            while (true) {
                String line2 = br.readLine();
                line2 = line2.trim();
                if (line2.length() == 0) {
                    continue;
                }
                if (line2.equals(END_REACTIONS)) {
                    break;
                }
                ++reactionCount;
                StringTokenizer st = new StringTokenizer(line2);
                String token1 = st.nextToken();
                // reactants
                String token2 = st.nextToken();
                // products
                String token3 = st.nextToken();
                // rate
                String token4 = st.nextToken();
                String token5 = st.nextToken();
                boolean bFoundReversible = false;
                Expression rate = new Expression(token4);
                for (ReactionLine rl : reactionLineList) {
                    if (token2.equals(rl.products) && token3.equals(rl.reactants) && token5.equals(rl.ruleLabel + "r")) {
                        ReactionStep rs = reactionMap.get(rl.no);
                        ((MassActionKinetics) rs.getKinetics()).getReverseRateParameter().setExpression(rate);
                        reactionLineList.remove(rl);
                        bFoundReversible = true;
                        break;
                    }
                }
                if (bFoundReversible) {
                    ++reversibleCount;
                    continue;
                }
                ReactionLine rl = new ReactionLine(token1, token2, token3, token5);
                reactionLineList.add(rl);
                SimpleReaction reaction = model.createSimpleReaction(model.getStructure(0));
                reactionMap.put(token1, reaction);
                reaction.setModel(model);
                bioModel.getVCMetaData().setFreeTextAnnotation(reaction, line2);
                MassActionKinetics kinetics = new MassActionKinetics(reaction);
                reaction.setKinetics(kinetics);
                st = new StringTokenizer(token2, ",");
                while (st.hasMoreTokens()) {
                    String t = st.nextToken();
                    SpeciesContext sc = speciesMap.get(t);
                    if (sc != null) {
                        boolean bExists = false;
                        for (ReactionParticipant rp : reaction.getReactionParticipants()) {
                            if (rp instanceof Reactant && rp.getSpeciesContext() == sc) {
                                rp.setStoichiometry(rp.getStoichiometry() + 1);
                                bExists = true;
                                break;
                            }
                        }
                        if (!bExists) {
                            reaction.addReactant(sc, 1);
                        }
                    }
                }
                st = new StringTokenizer(token3, ",");
                while (st.hasMoreTokens()) {
                    String t = st.nextToken();
                    SpeciesContext sc = speciesMap.get(t);
                    if (sc != null) {
                        boolean bExists = false;
                        for (ReactionParticipant rp : reaction.getReactionParticipants()) {
                            if (rp instanceof Product && rp.getSpeciesContext() == sc) {
                                rp.setStoichiometry(rp.getStoichiometry() + 1);
                                bExists = true;
                                break;
                            }
                        }
                        if (!bExists) {
                            reaction.addProduct(sc, 1);
                        }
                    }
                }
                kinetics.getForwardRateParameter().setExpression(rate);
            }
        }
    }
    System.out.println(model.getNumSpecies() + " species added");
    System.out.println(model.getNumReactions() + " reactions added");
    System.out.println(reversibleCount + " reversible reactions found");
    if (reactionCount != model.getNumReactions() + reversibleCount) {
        throw new RuntimeException("Reactions are not imported correctly!");
    }
}
Also used : SimpleReaction(cbit.vcell.model.SimpleReaction) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Product(cbit.vcell.model.Product) SpeciesContext(cbit.vcell.model.SpeciesContext) Reactant(cbit.vcell.model.Reactant) ModelParameter(cbit.vcell.model.Model.ModelParameter) StringTokenizer(java.util.StringTokenizer) Expression(cbit.vcell.parser.Expression) ReactionStep(cbit.vcell.model.ReactionStep) BioModel(cbit.vcell.biomodel.BioModel) Model(cbit.vcell.model.Model) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) MassActionKinetics(cbit.vcell.model.MassActionKinetics) ReactionParticipant(cbit.vcell.model.ReactionParticipant)

Aggregations

ReactionParticipant (cbit.vcell.model.ReactionParticipant)55 Reactant (cbit.vcell.model.Reactant)30 SpeciesContext (cbit.vcell.model.SpeciesContext)30 ReactionStep (cbit.vcell.model.ReactionStep)29 Product (cbit.vcell.model.Product)26 SimpleReaction (cbit.vcell.model.SimpleReaction)20 Structure (cbit.vcell.model.Structure)19 Expression (cbit.vcell.parser.Expression)18 FluxReaction (cbit.vcell.model.FluxReaction)16 Catalyst (cbit.vcell.model.Catalyst)14 ArrayList (java.util.ArrayList)14 KineticsParameter (cbit.vcell.model.Kinetics.KineticsParameter)13 Model (cbit.vcell.model.Model)13 ExpressionException (cbit.vcell.parser.ExpressionException)13 Membrane (cbit.vcell.model.Membrane)12 PropertyVetoException (java.beans.PropertyVetoException)12 Kinetics (cbit.vcell.model.Kinetics)11 Point (java.awt.Point)10 HashMap (java.util.HashMap)10 Shape (cbit.gui.graph.Shape)9