Search in sources :

Example 1 with SpeciesReference

use of org.sbml.jsbml.SpeciesReference in project vcell by virtualcell.

the class SBMLImporter method getReferencedSpecies.

/**
 * getReferencedSpecies(Reaction , HashSet<String> ) : Get the species
 * referenced in sbmlRxn (reactants and products); store their names in
 * hashSet (refereceNamesHash) Also, get the species referenced in the
 * reaction kineticLaw expression from getReferencedSpeciesInExpr.
 *
 * @param sbmlRxn
 * @param refSpeciesNameHash
 * @throws ExpressionException
 * @throws XMLStreamException
 * @throws SBMLException
 */
private void getReferencedSpecies(Reaction sbmlRxn, HashSet<String> refSpeciesNameHash) throws ExpressionException, SBMLException, XMLStreamException {
    // get all species referenced in listOfReactants
    for (int i = 0; i < (int) sbmlRxn.getNumReactants(); i++) {
        SpeciesReference reactRef = sbmlRxn.getReactant(i);
        refSpeciesNameHash.add(reactRef.getSpecies());
    }
    // get all species referenced in listOfProducts
    for (int i = 0; i < (int) sbmlRxn.getNumProducts(); i++) {
        SpeciesReference pdtRef = sbmlRxn.getProduct(i);
        refSpeciesNameHash.add(pdtRef.getSpecies());
    }
    // get all species referenced in reaction rate law
    if (sbmlRxn.getKineticLaw() != null) {
        Expression rateExpression = getExpressionFromFormula(sbmlRxn.getKineticLaw().getMath());
        getReferencedSpeciesInExpr(rateExpression, refSpeciesNameHash);
    }
}
Also used : Expression(cbit.vcell.parser.Expression) SpeciesReference(org.sbml.jsbml.SpeciesReference) ModifierSpeciesReference(org.sbml.jsbml.ModifierSpeciesReference) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint)

Example 2 with SpeciesReference

use of org.sbml.jsbml.SpeciesReference 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);
        }
    }
}
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) 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 SpeciesReference

use of org.sbml.jsbml.SpeciesReference in project vcell by virtualcell.

the class SBMLImporter method addReactionParticipants.

/**
 * addReactionParticipant : Adds reactants and products and modifiers to a
 * reaction. Input args are the sbml reaction, vc reaction This method was
 * created mainly to handle reactions where there are reactants and/or
 * products that appear multiple times in a reaction. Virtual Cell now
 * allows the import of such reactions.
 */
private void addReactionParticipants(org.sbml.jsbml.Reaction sbmlRxn, ReactionStep vcRxn) throws Exception {
    Model vcModel = vcBioModel.getSimulationContext(0).getModel();
    // if (!(vcRxn instanceof FluxReaction)) {
    if (true) {
        // reactants in sbmlRxn
        HashMap<String, Integer> sbmlReactantsHash = new HashMap<String, Integer>();
        for (int j = 0; j < (int) sbmlRxn.getNumReactants(); j++) {
            SpeciesReference spRef = sbmlRxn.getReactant(j);
            String sbmlReactantSpId = spRef.getSpecies();
            if (sbmlModel.getSpecies(sbmlReactantSpId) != null) {
                // check
                // if
                // spRef
                // is in
                // sbml
                // model
                // If stoichiometry of speciesRef is not an integer, it is
                // not handled in the VCell at this time; no point going
                // further
                double stoichiometry = 0.0;
                if (level < 3) {
                    // for SBML models < L3, default
                    // stoichiometry is 1, if field is not
                    // set.
                    // default value of stoichiometry,
                    stoichiometry = 1.0;
                    // if not set.
                    if (spRef.isSetStoichiometry()) {
                        stoichiometry = spRef.getStoichiometry();
                        if (((int) stoichiometry != stoichiometry) || spRef.isSetStoichiometryMath()) {
                            throw new SBMLImportException("Non-integer stoichiometry ('" + stoichiometry + "' for reactant '" + sbmlReactantSpId + "' in reaction '" + sbmlRxn.getId() + "') or stoichiometryMath not handled in VCell at this time.", Category.NON_INTEGER_STOICH);
                        // logger.sendMessage(VCLogger.Priority.HighPriority,
                        // VCLogger.ErrorType.ReactionError,
                        // "Non-integer stoichiometry or stoichiometryMath not handled in VCell at this time.");
                        }
                    }
                } else {
                    if (spRef.isSetStoichiometry()) {
                        stoichiometry = spRef.getStoichiometry();
                        if (((int) stoichiometry != stoichiometry) || spRef.isSetStoichiometryMath()) {
                            throw new SBMLImportException("Non-integer stoichiometry ('" + stoichiometry + "' for reactant '" + sbmlReactantSpId + "' in reaction '" + sbmlRxn.getId() + "') or stoichiometryMath not handled in VCell at this time.", Category.NON_INTEGER_STOICH);
                        // logger.sendMessage(VCLogger.Priority.HighPriority,
                        // VCLogger.ErrorType.ReactionError,
                        // "Non-integer stoichiometry or stoichiometryMath not handled in VCell at this time.");
                        // logger.sendMessage(VCLogger.Priority.HighPriority,
                        // VCLogger.ErrorType.ReactionError,
                        // "Non-integer stoichiometry or stoichiometryMath not handled in VCell at this time.");
                        }
                    } else {
                        throw new SBMLImportException("This is a SBML level 3 model, stoichiometry is not set for the reactant '" + sbmlReactantSpId + "' and no default value can be assumed.");
                    // logger.sendMessage(VCLogger.Priority.HighPriority,
                    // VCLogger.ErrorType.ReactionError,
                    // "This is a SBML level 3 model, stoichiometry is not set for the reactant '"
                    // + spRef.getSpecies() +
                    // "' and no default value can be assumed.");
                    }
                }
                if (sbmlReactantsHash.get(sbmlReactantSpId) == null) {
                    // if sbmlReactantSpId is NOT in sbmlReactantsHash, add
                    // it with its stoichiometry
                    sbmlReactantsHash.put(sbmlReactantSpId, Integer.valueOf((int) stoichiometry));
                } else {
                    // if sbmlReactantSpId IS in sbmlReactantsHash, update
                    // its stoichiometry value to (existing-from-hash +
                    // stoichiometry) and put it back in hash
                    int intStoich = sbmlReactantsHash.get(sbmlReactantSpId).intValue();
                    intStoich += (int) stoichiometry;
                    sbmlReactantsHash.put(sbmlReactantSpId, Integer.valueOf(intStoich));
                }
            } else {
                // spRef is not in model, throw exception
                throw new SBMLImportException("Reactant '" + sbmlReactantSpId + "' in reaction '" + sbmlRxn.getId() + "' not found as species in SBML model.");
            }
        // end - if (spRef is species in model)
        }
        // sbmlReactionParticipantsHash as reactants to vcRxn
        for (Entry<String, Integer> es : sbmlReactantsHash.entrySet()) {
            SpeciesContext speciesContext = vcModel.getSpeciesContext(es.getKey());
            int stoich = es.getValue();
            vcRxn.addReactant(speciesContext, stoich);
        }
        /*
			Iterator<String> sbmlReactantsIter = sbmlReactantsHash.keySet()
					.iterator();
			while (sbmlReactantsIter.hasNext()) {
				String sbmlReactantStr = sbmlReactantsIter.next();
				SpeciesContext speciesContext = vcModel
						.getSpeciesContext(sbmlReactantStr);
				int stoich = sbmlReactantsHash.get(sbmlReactantStr).intValue();
				((SimpleReaction) vcRxn).addReactant(speciesContext, stoich);
			}
			*/
        // products in sbmlRxn
        HashMap<String, Integer> sbmlProductsHash = new HashMap<String, Integer>();
        for (int j = 0; j < (int) sbmlRxn.getNumProducts(); j++) {
            SpeciesReference spRef = sbmlRxn.getProduct(j);
            String sbmlProductSpId = spRef.getSpecies();
            if (sbmlModel.getSpecies(sbmlProductSpId) != null) {
                /* check if spRef is in sbml model
					If stoichiometry of speciesRef is not an integer, it is
					not handled in the VCell at this time; no point going
					further */
                double stoichiometry = 0.0;
                if (level < 3) {
                    // for sBML models < L3, default
                    // stoichiometry is 1, if field is not
                    // set.
                    // default value of stoichiometry,
                    stoichiometry = 1.0;
                    // if not set.
                    if (spRef.isSetStoichiometry()) {
                        stoichiometry = spRef.getStoichiometry();
                        if (((int) stoichiometry != stoichiometry) || spRef.isSetStoichiometryMath()) {
                            throw new SBMLImportException("Non-integer stoichiometry ('" + stoichiometry + "' for product '" + sbmlProductSpId + "' in reaction '" + sbmlRxn.getId() + "') or stoichiometryMath not handled in VCell at this time.", Category.NON_INTEGER_STOICH);
                        // logger.sendMessage(VCLogger.Priority.HighPriority,
                        // VCLogger.ErrorType.ReactionError,
                        // "Non-integer stoichiometry or stoichiometryMath not handled in VCell at this time.");
                        }
                    }
                } else {
                    if (spRef.isSetStoichiometry()) {
                        stoichiometry = spRef.getStoichiometry();
                        if (((int) stoichiometry != stoichiometry) || spRef.isSetStoichiometryMath()) {
                            throw new SBMLImportException("Non-integer stoichiometry ('" + stoichiometry + "' for product '" + sbmlProductSpId + "' in reaction '" + sbmlRxn.getId() + "') or stoichiometryMath not handled in VCell at this time.", Category.NON_INTEGER_STOICH);
                        // logger.sendMessage(VCLogger.Priority.HighPriority,
                        // VCLogger.ErrorType.ReactionError,
                        // "Non-integer stoichiometry or stoichiometryMath not handled in VCell at this time.");
                        }
                    } else {
                        throw new SBMLImportException("This is a SBML level 3 model, stoichiometry is not set for the product '" + sbmlProductSpId + "' and no default value can be assumed.");
                    // logger.sendMessage(VCLogger.Priority.HighPriority,
                    // VCLogger.ErrorType.ReactionError,
                    // "This is a SBML level 3 model, stoichiometry is not set for the product '"
                    // + spRef.getSpecies() +
                    // "' and no default value can be assumed.");
                    }
                }
                if (sbmlProductsHash.get(sbmlProductSpId) == null) {
                    // if sbmlProductSpId is NOT in sbmlProductsHash, add it
                    // with its stoichiometry
                    sbmlProductsHash.put(sbmlProductSpId, Integer.valueOf((int) stoichiometry));
                } else {
                    // if sbmlProductSpId IS in sbmlProductsHash, update its
                    // stoichiometry value to (existing-value-from-hash +
                    // stoichiometry) and put it back in hash
                    int intStoich = sbmlProductsHash.get(sbmlProductSpId).intValue();
                    intStoich += (int) stoichiometry;
                    sbmlProductsHash.put(sbmlProductSpId, Integer.valueOf(intStoich));
                }
            } else {
                // spRef is not in model, throw exception
                throw new SBMLImportException("Product '" + sbmlProductSpId + "' in reaction '" + sbmlRxn.getId() + "' not found as species in SBML model.");
            }
        // end - if (spRef is species in model)
        }
        // as products to vcRxn
        for (Entry<String, Integer> es : sbmlProductsHash.entrySet()) {
            SpeciesContext speciesContext = vcModel.getSpeciesContext(es.getKey());
            int stoich = es.getValue();
            vcRxn.addProduct(speciesContext, stoich);
        }
    /*
			Iterator<String> sbmlProductsIter = sbmlProductsHash.keySet()
					.iterator();
			while (sbmlProductsIter.hasNext()) {
				String sbmlProductStr = sbmlProductsIter.next();
				SpeciesContext speciesContext = vcModel
						.getSpeciesContext(sbmlProductStr);
				int stoich = sbmlProductsHash.get(sbmlProductStr).intValue();
				((SimpleReaction) vcRxn).addProduct(speciesContext, stoich);
			}
			*/
    // proxy.addProducts(sbmlProductsHash);
    }
    // modifiers
    for (int j = 0; j < (int) sbmlRxn.getNumModifiers(); j++) {
        ModifierSpeciesReference spRef = sbmlRxn.getModifier(j);
        String sbmlSpId = spRef.getSpecies();
        if (sbmlModel.getSpecies(sbmlSpId) != null) {
            // check if this modifier species is preesent in vcRxn (could
            // have been added as reactamt/product/catalyst).
            // If alreay a catalyst in vcRxn, do nothing
            ArrayList<ReactionParticipant> vcRxnParticipants = getVCReactionParticipantsFromSymbol(vcRxn, sbmlSpId);
            SpeciesContext speciesContext = vcModel.getSpeciesContext(sbmlSpId);
            if (vcRxnParticipants == null || vcRxnParticipants.size() == 0) {
                // If not in reactionParticipantList of vcRxn, add as
                // catalyst.
                vcRxn.addCatalyst(speciesContext);
            } else {
                for (ReactionParticipant rp : vcRxnParticipants) {
                    if (rp instanceof Reactant || rp instanceof Product) {
                        // If already a reactant or product in vcRxn, add
                        // warning to localIssuesList, don't do anything
                        localIssueList.add(new Issue(speciesContext, issueContext, IssueCategory.SBMLImport_Reaction, "Species " + speciesContext.getName() + " was already added as a reactant and/or product to " + vcRxn.getName() + "; Cannot add it as a catalyst also.", Issue.SEVERITY_INFO));
                        break;
                    }
                }
            }
        } else {
            // spRef is not in model, throw exception
            throw new SBMLImportException("Modifier '" + sbmlSpId + "' in reaction '" + sbmlRxn.getId() + "' not found as species in SBML model.");
        }
    // end - if (spRef is species in model)
    }
// end - for modifiers
}
Also used : Issue(org.vcell.util.Issue) HashMap(java.util.HashMap) Product(cbit.vcell.model.Product) SpeciesContext(cbit.vcell.model.SpeciesContext) Reactant(cbit.vcell.model.Reactant) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) SpeciesReference(org.sbml.jsbml.SpeciesReference) ModifierSpeciesReference(org.sbml.jsbml.ModifierSpeciesReference) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) ModifierSpeciesReference(org.sbml.jsbml.ModifierSpeciesReference) ReactionParticipant(cbit.vcell.model.ReactionParticipant)

Example 4 with SpeciesReference

use of org.sbml.jsbml.SpeciesReference in project vcell by virtualcell.

the class SBMLImporter method addReactionParticipants.

/**
 * addReactionParticipant : Adds reactants and products and modifiers to a
 * reaction. Input args are the sbml reaction, vc reaction This method was
 * created mainly to handle reactions where there are reactants and/or
 * products that appear multiple times in a reaction. Virtual Cell now
 * allows the import of such reactions.
 */
private void addReactionParticipants(org.sbml.jsbml.Reaction sbmlRxn, ReactionStep vcRxn, Map<String, String> sbmlToVclNameMap) throws Exception {
    Model vcModel = vcBioModel.getSimulationContext(0).getModel();
    // if (!(vcRxn instanceof FluxReaction)) {
    if (true) {
        // reactants in sbmlRxn
        HashMap<String, Integer> sbmlReactantsHash = new HashMap<String, Integer>();
        for (int j = 0; j < (int) sbmlRxn.getNumReactants(); j++) {
            SpeciesReference spRef = sbmlRxn.getReactant(j);
            String sbmlReactantSpId = spRef.getSpecies();
            if (sbmlModel.getSpecies(sbmlReactantSpId) != null) {
                // check
                // if
                // spRef
                // is in
                // sbml
                // model
                // If stoichiometry of speciesRef is not an integer, it is
                // not handled in the VCell at this time; no point going
                // further
                double stoichiometry = 0.0;
                if (level < 3) {
                    // for SBML models < L3, default
                    // stoichiometry is 1, if field is not
                    // set.
                    // default value of stoichiometry,
                    stoichiometry = 1.0;
                    // if not set.
                    if (spRef.isSetStoichiometry()) {
                        stoichiometry = spRef.getStoichiometry();
                        if (((int) stoichiometry != stoichiometry) || spRef.isSetStoichiometryMath()) {
                            throw new SBMLImportException("Non-integer stoichiometry ('" + stoichiometry + "' for reactant '" + sbmlReactantSpId + "' in reaction '" + sbmlRxn.getId() + "') or stoichiometryMath not handled in VCell at this time.", Category.NON_INTEGER_STOICH);
                        // logger.sendMessage(VCLogger.Priority.HighPriority,
                        // VCLogger.ErrorType.ReactionError,
                        // "Non-integer stoichiometry or stoichiometryMath not handled in VCell at this time.");
                        }
                    }
                } else {
                    if (spRef.isSetStoichiometry()) {
                        stoichiometry = spRef.getStoichiometry();
                        if (((int) stoichiometry != stoichiometry) || spRef.isSetStoichiometryMath()) {
                            throw new SBMLImportException("Non-integer stoichiometry ('" + stoichiometry + "' for reactant '" + sbmlReactantSpId + "' in reaction '" + sbmlRxn.getId() + "') or stoichiometryMath not handled in VCell at this time.", Category.NON_INTEGER_STOICH);
                        // logger.sendMessage(VCLogger.Priority.HighPriority,
                        // VCLogger.ErrorType.ReactionError,
                        // "Non-integer stoichiometry or stoichiometryMath not handled in VCell at this time.");
                        // logger.sendMessage(VCLogger.Priority.HighPriority,
                        // VCLogger.ErrorType.ReactionError,
                        // "Non-integer stoichiometry or stoichiometryMath not handled in VCell at this time.");
                        }
                    } else {
                        throw new SBMLImportException("This is a SBML level 3 model, stoichiometry is not set for the reactant '" + sbmlReactantSpId + "' and no default value can be assumed.");
                    // logger.sendMessage(VCLogger.Priority.HighPriority,
                    // VCLogger.ErrorType.ReactionError,
                    // "This is a SBML level 3 model, stoichiometry is not set for the reactant '"
                    // + spRef.getSpecies() +
                    // "' and no default value can be assumed.");
                    }
                }
                if (sbmlReactantsHash.get(sbmlReactantSpId) == null) {
                    // if sbmlReactantSpId is NOT in sbmlReactantsHash, add
                    // it with its stoichiometry
                    sbmlReactantsHash.put(sbmlReactantSpId, Integer.valueOf((int) stoichiometry));
                } else {
                    // if sbmlReactantSpId IS in sbmlReactantsHash, update
                    // its stoichiometry value to (existing-from-hash +
                    // stoichiometry) and put it back in hash
                    int intStoich = sbmlReactantsHash.get(sbmlReactantSpId).intValue();
                    intStoich += (int) stoichiometry;
                    sbmlReactantsHash.put(sbmlReactantSpId, Integer.valueOf(intStoich));
                }
            } else {
                // spRef is not in model, throw exception
                throw new SBMLImportException("Reactant '" + sbmlReactantSpId + "' in reaction '" + sbmlRxn.getId() + "' not found as species in SBML model.");
            }
        // end - if (spRef is species in model)
        }
        // sbmlReactionParticipantsHash as reactants to vcRxn
        for (Entry<String, Integer> es : sbmlReactantsHash.entrySet()) {
            String sbmlReactantSpId = es.getKey();
            String vcSpeciesName = sbmlReactantSpId;
            if (sbmlToVclNameMap.get(sbmlReactantSpId) != null) {
                vcSpeciesName = sbmlToVclNameMap.get(sbmlReactantSpId);
            }
            SpeciesContext speciesContext = vcModel.getSpeciesContext(vcSpeciesName);
            int stoich = es.getValue();
            vcRxn.addReactant(speciesContext, stoich);
        }
        /*
			Iterator<String> sbmlReactantsIter = sbmlReactantsHash.keySet()
					.iterator();
			while (sbmlReactantsIter.hasNext()) {
				String sbmlReactantStr = sbmlReactantsIter.next();
				SpeciesContext speciesContext = vcModel
						.getSpeciesContext(sbmlReactantStr);
				int stoich = sbmlReactantsHash.get(sbmlReactantStr).intValue();
				((SimpleReaction) vcRxn).addReactant(speciesContext, stoich);
			}
			*/
        // products in sbmlRxn
        HashMap<String, Integer> sbmlProductsHash = new HashMap<String, Integer>();
        for (int j = 0; j < (int) sbmlRxn.getNumProducts(); j++) {
            SpeciesReference spRef = sbmlRxn.getProduct(j);
            String sbmlProductSpId = spRef.getSpecies();
            if (sbmlModel.getSpecies(sbmlProductSpId) != null) {
                /* check if spRef is in sbml model
					If stoichiometry of speciesRef is not an integer, it is
					not handled in the VCell at this time; no point going
					further */
                double stoichiometry = 0.0;
                if (level < 3) {
                    // for sBML models < L3, default
                    // stoichiometry is 1, if field is not
                    // set.
                    // default value of stoichiometry,
                    stoichiometry = 1.0;
                    // if not set.
                    if (spRef.isSetStoichiometry()) {
                        stoichiometry = spRef.getStoichiometry();
                        if (((int) stoichiometry != stoichiometry) || spRef.isSetStoichiometryMath()) {
                            throw new SBMLImportException("Non-integer stoichiometry ('" + stoichiometry + "' for product '" + sbmlProductSpId + "' in reaction '" + sbmlRxn.getId() + "') or stoichiometryMath not handled in VCell at this time.", Category.NON_INTEGER_STOICH);
                        // logger.sendMessage(VCLogger.Priority.HighPriority,
                        // VCLogger.ErrorType.ReactionError,
                        // "Non-integer stoichiometry or stoichiometryMath not handled in VCell at this time.");
                        }
                    }
                } else {
                    if (spRef.isSetStoichiometry()) {
                        stoichiometry = spRef.getStoichiometry();
                        if (((int) stoichiometry != stoichiometry) || spRef.isSetStoichiometryMath()) {
                            throw new SBMLImportException("Non-integer stoichiometry ('" + stoichiometry + "' for product '" + sbmlProductSpId + "' in reaction '" + sbmlRxn.getId() + "') or stoichiometryMath not handled in VCell at this time.", Category.NON_INTEGER_STOICH);
                        // logger.sendMessage(VCLogger.Priority.HighPriority,
                        // VCLogger.ErrorType.ReactionError,
                        // "Non-integer stoichiometry or stoichiometryMath not handled in VCell at this time.");
                        }
                    } else {
                        throw new SBMLImportException("This is a SBML level 3 model, stoichiometry is not set for the product '" + sbmlProductSpId + "' and no default value can be assumed.");
                    // logger.sendMessage(VCLogger.Priority.HighPriority,
                    // VCLogger.ErrorType.ReactionError,
                    // "This is a SBML level 3 model, stoichiometry is not set for the product '"
                    // + spRef.getSpecies() +
                    // "' and no default value can be assumed.");
                    }
                }
                if (sbmlProductsHash.get(sbmlProductSpId) == null) {
                    // if sbmlProductSpId is NOT in sbmlProductsHash, add it
                    // with its stoichiometry
                    sbmlProductsHash.put(sbmlProductSpId, Integer.valueOf((int) stoichiometry));
                } else {
                    // if sbmlProductSpId IS in sbmlProductsHash, update its
                    // stoichiometry value to (existing-value-from-hash +
                    // stoichiometry) and put it back in hash
                    int intStoich = sbmlProductsHash.get(sbmlProductSpId).intValue();
                    intStoich += (int) stoichiometry;
                    sbmlProductsHash.put(sbmlProductSpId, Integer.valueOf(intStoich));
                }
            } else {
                // spRef is not in model, throw exception
                throw new SBMLImportException("Product '" + sbmlProductSpId + "' in reaction '" + sbmlRxn.getId() + "' not found as species in SBML model.");
            }
        // end - if (spRef is species in model)
        }
        // as products to vcRxn
        for (Entry<String, Integer> es : sbmlProductsHash.entrySet()) {
            String sbmlProductSpId = es.getKey();
            String vcSpeciesName = sbmlProductSpId;
            if (sbmlToVclNameMap.get(sbmlProductSpId) != null) {
                vcSpeciesName = sbmlToVclNameMap.get(sbmlProductSpId);
            }
            SpeciesContext speciesContext = vcModel.getSpeciesContext(vcSpeciesName);
            int stoich = es.getValue();
            vcRxn.addProduct(speciesContext, stoich);
        }
    /*
			Iterator<String> sbmlProductsIter = sbmlProductsHash.keySet()
					.iterator();
			while (sbmlProductsIter.hasNext()) {
				String sbmlProductStr = sbmlProductsIter.next();
				SpeciesContext speciesContext = vcModel
						.getSpeciesContext(sbmlProductStr);
				int stoich = sbmlProductsHash.get(sbmlProductStr).intValue();
				((SimpleReaction) vcRxn).addProduct(speciesContext, stoich);
			}
			*/
    // proxy.addProducts(sbmlProductsHash);
    }
    // modifiers
    for (int j = 0; j < (int) sbmlRxn.getNumModifiers(); j++) {
        ModifierSpeciesReference spRef = sbmlRxn.getModifier(j);
        String sbmlSpId = spRef.getSpecies();
        String vcSpeciesName = sbmlSpId;
        if (sbmlToVclNameMap.get(sbmlSpId) != null) {
            vcSpeciesName = sbmlToVclNameMap.get(sbmlSpId);
        }
        if (sbmlModel.getSpecies(sbmlSpId) != null) {
            // check if this modifier species is preesent in vcRxn (could
            // have been added as reactamt/product/catalyst).
            // If alreay a catalyst in vcRxn, do nothing
            ArrayList<ReactionParticipant> vcRxnParticipants = getVCReactionParticipantsFromSymbol(vcRxn, vcSpeciesName);
            SpeciesContext speciesContext = vcModel.getSpeciesContext(vcSpeciesName);
            if (vcRxnParticipants == null || vcRxnParticipants.size() == 0) {
                // If not in reactionParticipantList of vcRxn, add as
                // catalyst.
                vcRxn.addCatalyst(speciesContext);
            } else {
                for (ReactionParticipant rp : vcRxnParticipants) {
                    if (rp instanceof Reactant || rp instanceof Product) {
                        // If already a reactant or product in vcRxn, add
                        // warning to localIssuesList, don't do anything
                        localIssueList.add(new Issue(speciesContext, issueContext, IssueCategory.SBMLImport_Reaction, "Species " + speciesContext.getName() + " was already added as a reactant and/or product to " + vcRxn.getName() + "; Cannot add it as a catalyst also.", Issue.SEVERITY_INFO));
                        break;
                    }
                }
            }
        } else {
            // spRef is not in model, throw exception
            throw new SBMLImportException("Modifier '" + sbmlSpId + "' in reaction '" + sbmlRxn.getId() + "' not found as species in SBML model.");
        }
    // end - if (spRef is species in model)
    }
// end - for modifiers
}
Also used : Issue(org.vcell.util.Issue) HashMap(java.util.HashMap) Product(cbit.vcell.model.Product) SpeciesContext(cbit.vcell.model.SpeciesContext) Reactant(cbit.vcell.model.Reactant) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) SpeciesReference(org.sbml.jsbml.SpeciesReference) ModifierSpeciesReference(org.sbml.jsbml.ModifierSpeciesReference) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) ModifierSpeciesReference(org.sbml.jsbml.ModifierSpeciesReference) ReactionParticipant(cbit.vcell.model.ReactionParticipant)

Aggregations

SpeciesReference (org.sbml.jsbml.SpeciesReference)4 InteriorPoint (org.sbml.jsbml.ext.spatial.InteriorPoint)4 ReactionParticipant (cbit.vcell.model.ReactionParticipant)3 ModifierSpeciesReference (org.sbml.jsbml.ModifierSpeciesReference)3 BioModel (cbit.vcell.biomodel.BioModel)2 Model (cbit.vcell.model.Model)2 Product (cbit.vcell.model.Product)2 Reactant (cbit.vcell.model.Reactant)2 SpeciesContext (cbit.vcell.model.SpeciesContext)2 Expression (cbit.vcell.parser.Expression)2 HashMap (java.util.HashMap)2 Issue (org.vcell.util.Issue)2 MembraneMapping (cbit.vcell.mapping.MembraneMapping)1 ReactionSpec (cbit.vcell.mapping.ReactionSpec)1 StructureMapping (cbit.vcell.mapping.StructureMapping)1 DistributedKinetics (cbit.vcell.model.DistributedKinetics)1 Kinetics (cbit.vcell.model.Kinetics)1 KineticsParameter (cbit.vcell.model.Kinetics.KineticsParameter)1 LumpedKinetics (cbit.vcell.model.LumpedKinetics)1 ReactionStep (cbit.vcell.model.ReactionStep)1