Search in sources :

Example 1 with KineticLaw

use of org.sbml.jsbml.KineticLaw 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 2 with KineticLaw

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

the class SBMLImporter method resolveRxnParameterNameConflicts.

/**
 * checkCompartmentScaleFactorInRxnRateExpr : Used to check if reaction rate
 * expression has a compartment scale factor. Need to remove this factor
 * from the rate expression. Differentiate the rate expression wrt the
 * compartmentSizeParamName. If the differentiated expression contains the
 * compartmentSizeParamName, VCell doesn't support non-linear functions of
 * compartmentSizeParam. Substitute 1.0 for the compartmentSizeParam in the
 * rateExpr and check its equivalency with the differentiated expr above. If
 * they are not equal, the rate expression is a non-linear function of
 * compartmentSizeParam - not acceptable. Substitute 0.0 for
 * compartmentSizeParam in rateExpr. If the value doesn't evaluate to 0.0,
 * it is not valid for the same reason above.
 */
/*
	 * pending delete? gcw 4/2014 private Expression
	 * removeCompartmentScaleFactorInRxnRateExpr(Expression rateExpr, String
	 * compartmentSizeParamName, String rxnName) throws Exception { Expression
	 * diffExpr = rateExpr.differentiate(compartmentSizeParamName).flatten(); if
	 * (diffExpr.hasSymbol(compartmentSizeParamName)) {
	 * logger.sendMessage(VCLogger.Priority.HighPriority,
	 * VCLogger.ErrorType.UnitError,
	 * "Unable to interpret Kinetic rate for reaction : " + rxnName +
	 * " Cannot interpret non-linear function of compartment size"); }
	 * 
	 * Expression expr1 = rateExpr.getSubstitutedExpression(new
	 * Expression(compartmentSizeParamName), new Expression(1.0)).flatten(); if
	 * (!expr1.compareEqual(diffExpr) &&
	 * !(ExpressionUtils.functionallyEquivalent(expr1, diffExpr))) {
	 * logger.sendMessage(VCLogger.Priority.HighPriority,
	 * VCLogger.ErrorType.UnitError,
	 * "Unable to interpret Kinetic rate for reaction : " + rxnName +
	 * " Cannot interpret non-linear function of compartment size"); }
	 * 
	 * Expression expr0 = rateExpr.getSubstitutedExpression(new
	 * Expression(compartmentSizeParamName), new Expression(0.0)).flatten(); if
	 * (!expr0.isZero()) { logger.sendMessage(VCLogger.Priority.HighPriority,
	 * VCLogger.ErrorType.UnitError,
	 * "Unable to interpret Kinetic rate for reaction : " + rxnName +
	 * " Cannot interpret non-linear function of compartment size"); }
	 * 
	 * return expr1; }
	 */
/**
 * resolveRxnParameterNameConflicts : Check if the reaction rate name
 * matches with any global or local parameter, in which case, we have to
 * change the rate name (to oldName_rxnName); since the global or local
 * parameter value will override the rate equation/value. Also, when we
 * import a VCell model that has been exported to SBML, if the user has
 * changed the rate name in a reaction, it is stored in the reaction
 * annotation. This has to be retrieved and set as reaction rate name.
 *
 * @param sbmlRxn
 * @param newKinetics
 * @throws ExpressionException
 */
private void resolveRxnParameterNameConflicts(Reaction sbmlRxn, Kinetics vcKinetics, Element sbmlImportElement) throws PropertyVetoException {
    // Retrieve this to re-set rate param name.
    if (sbmlImportElement != null) {
        Element embeddedRxnElement = getEmbeddedElementInAnnotation(sbmlImportElement, RATE_NAME);
        String vcRateParamName = null;
        if (embeddedRxnElement != null) {
            if (embeddedRxnElement.getName().equals(XMLTags.RateTag)) {
                vcRateParamName = embeddedRxnElement.getAttributeValue(XMLTags.NameAttrTag);
                vcKinetics.getAuthoritativeParameter().setName(vcRateParamName);
            }
        }
    }
    /*
		 * Get the rate name from the kinetics : if it is from GeneralKinetics,
		 * it is the reactionRateParamter name; if it is from LumpedKinetics, it
		 * is the LumpedReactionRateParameter name.
		 */
    String origRateParamName = vcKinetics.getAuthoritativeParameter().getName();
    /*
		 * Check if any parameters (global/local) have the same name as kinetics
		 * rate param name; This will replace any rate expression with the
		 * global/local param value; which is unacceptable. If there is a match,
		 * replace it with a new name for rate param - say,
		 * origName_reactionName.
		 */
    ListOf listofGlobalParams = sbmlModel.getListOfParameters();
    for (int j = 0; j < sbmlModel.getNumParameters(); j++) {
        org.sbml.jsbml.Parameter param = (org.sbml.jsbml.Parameter) listofGlobalParams.get(j);
        String paramName = param.getId();
        // reaction name to it).
        if (paramName.equals(origRateParamName)) {
            vcKinetics.getAuthoritativeParameter().setName(origRateParamName + "_" + TokenMangler.mangleToSName(sbmlRxn.getId()));
        }
    }
    KineticLaw kLaw = sbmlRxn.getKineticLaw();
    if (kLaw != null) {
        ListOf listofLocalParams = kLaw.getListOfParameters();
        for (int j = 0; j < kLaw.getNumParameters(); j++) {
            org.sbml.jsbml.LocalParameter param = (org.sbml.jsbml.LocalParameter) listofLocalParams.get(j);
            String paramName = param.getId();
            // reaction name to it).
            if (paramName.equals(origRateParamName)) {
                vcKinetics.getAuthoritativeParameter().setName(origRateParamName + "_" + TokenMangler.mangleToSName(sbmlRxn.getId()));
            }
        }
    }
}
Also used : LocalParameter(org.sbml.jsbml.LocalParameter) Parameter(org.sbml.jsbml.Parameter) Element(org.jdom.Element) ListOf(org.sbml.jsbml.ListOf) LocalParameter(org.sbml.jsbml.LocalParameter) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) Parameter(org.sbml.jsbml.Parameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) LocalParameter(org.sbml.jsbml.LocalParameter) KineticsProxyParameter(cbit.vcell.model.Kinetics.KineticsProxyParameter) UnresolvedParameter(cbit.vcell.model.Kinetics.UnresolvedParameter) KineticLaw(org.sbml.jsbml.KineticLaw) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint)

Example 3 with KineticLaw

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

the class SBMLImporter method getReactionStructure.

/**
 * getReactionStructure :
 */
private Structure getReactionStructure(org.sbml.jsbml.Reaction sbmlRxn, SpeciesContext[] speciesContexts, Element sbmlImportElement) throws Exception {
    Structure struct = null;
    String structName = null;
    Model vcModel = vcBioModel.getSimulationContext(0).getModel();
    // return structure from vcmodel, if present.
    if (bSpatial) {
        structName = sbmlRxn.getCompartment();
        if (structName != null && structName.length() > 0) {
            struct = vcModel.getStructure(structName);
            if (struct != null) {
                return struct;
            }
        }
    }
    // If annotation has structure name, return the corresponding structure.
    if (sbmlImportElement != null) {
        // Get the embedded element in the annotation str (fluxStep or
        // simpleReaction), and the structure attribute from the element.
        Element embeddedElement = getEmbeddedElementInAnnotation(sbmlImportElement, REACTION);
        if (embeddedElement != null) {
            structName = embeddedElement.getAttributeValue(XMLTags.StructureAttrTag);
            // Using the structName, get the structure from the structures
            // (compartments) list.
            struct = vcModel.getStructure(structName);
            return struct;
        }
    }
    if (sbmlRxn.isSetKineticLaw()) {
        // String rxnName = sbmlRxn.getId();
        KineticLaw kLaw = sbmlRxn.getKineticLaw();
        Expression kRateExp = getExpressionFromFormula(kLaw.getMath());
        String[] symbols = kRateExp.getSymbols();
        if (symbols != null) {
            for (String symbol : symbols) {
                Compartment sbmlCompartment = sbmlModel.getCompartment(symbol);
                if (sbmlCompartment != null) {
                    return vcBioModel.getSimulationContext(0).getModel().getStructure(sbmlCompartment.getId());
                }
            }
        }
    }
    HashSet<String> refSpeciesNameHash = new HashSet<String>();
    getReferencedSpecies(sbmlRxn, refSpeciesNameHash);
    java.util.Iterator<String> refSpIterator = refSpeciesNameHash.iterator();
    HashSet<String> compartmentNamesHash = new HashSet<String>();
    while (refSpIterator.hasNext()) {
        String spName = refSpIterator.next();
        String rxnCompartmentName = sbmlModel.getSpecies(spName).getCompartment();
        compartmentNamesHash.add(rxnCompartmentName);
    }
    if (compartmentNamesHash.size() == 1) {
        struct = vcModel.getStructure(compartmentNamesHash.iterator().next());
        return struct;
    } else if (compartmentNamesHash.size() == 0) {
        struct = vcModel.getStructures()[0];
        return struct;
    } else {
        // more than one structure in reaction participants, try to figure
        // out which one to choose
        HashMap<String, Integer> structureFrequencyHash = new HashMap<String, Integer>();
        for (String structureName : compartmentNamesHash) {
            if (structureFrequencyHash.containsKey(structureName)) {
                structureFrequencyHash.put(structureName, structureFrequencyHash.get(structName) + 1);
            } else {
                structureFrequencyHash.put(structureName, 1);
            }
        }
        Iterator<Entry<String, Integer>> iterator = structureFrequencyHash.entrySet().iterator();
        Entry<String, Integer> mostUsedStructureEntry = iterator.next();
        while (iterator.hasNext()) {
            Entry<String, Integer> currentStructureEntry = iterator.next();
            if (currentStructureEntry.getValue() > mostUsedStructureEntry.getValue()) {
                mostUsedStructureEntry = currentStructureEntry;
            }
        }
        String mostUsedStructureName = mostUsedStructureEntry.getKey();
        struct = vcModel.getStructure(mostUsedStructureName);
        return struct;
    }
}
Also used : HashMap(java.util.HashMap) Compartment(org.sbml.jsbml.Compartment) Element(org.jdom.Element) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) Entry(java.util.Map.Entry) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) Iterator(java.util.Iterator) Structure(cbit.vcell.model.Structure) KineticLaw(org.sbml.jsbml.KineticLaw) HashSet(java.util.HashSet)

Example 4 with KineticLaw

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

the class SBMLImporter method createSBMLUnitSystemForVCModel.

private ModelUnitSystem createSBMLUnitSystemForVCModel() throws Exception {
    if (sbmlModel == null) {
        throw new SBMLImportException("SBML model is NULL");
    }
    ListOf listofUnitDefns = sbmlModel.getListOfUnitDefinitions();
    if (listofUnitDefns == null) {
        System.out.println("No Unit Definitions");
        // @TODO: deal with SBML level < 3.
        return ModelUnitSystem.createDefaultVCModelUnitSystem();
    }
    @SuppressWarnings("serial") VCUnitSystem tempVCUnitSystem = new VCUnitSystem() {
    };
    sbmlUnitIdentifierHash = new HashMap<String, VCUnitDefinition>();
    // add base SI unit identifiers (as defined in SBML spec) to hash
    sbmlUnitIdentifierHash.put("ampere", tempVCUnitSystem.getInstance("A"));
    sbmlUnitIdentifierHash.put("avogadro", tempVCUnitSystem.getInstance("6.02e23"));
    // sbmlUnitIdentifierHash.put("becquerel",
    // tempVCUnitSystem.getInstance("becquerel"));
    // sbmlUnitIdentifierHash.put("candela",
    // tempVCUnitSystem.getInstance("candela"));
    sbmlUnitIdentifierHash.put("coulomb", tempVCUnitSystem.getInstance("C"));
    sbmlUnitIdentifierHash.put("dimensionless", tempVCUnitSystem.getInstance("1"));
    sbmlUnitIdentifierHash.put("farad", tempVCUnitSystem.getInstance("F"));
    sbmlUnitIdentifierHash.put("gram", tempVCUnitSystem.getInstance("g"));
    // sbmlUnitIdentifierHash.put("gray",
    // tempVCUnitSystem.getInstance("gray"));
    sbmlUnitIdentifierHash.put("henry", tempVCUnitSystem.getInstance("H"));
    sbmlUnitIdentifierHash.put("hertz", tempVCUnitSystem.getInstance("Hz"));
    sbmlUnitIdentifierHash.put("item", tempVCUnitSystem.getInstance("molecules"));
    sbmlUnitIdentifierHash.put("joule", tempVCUnitSystem.getInstance("J"));
    // sbmlUnitIdentifierHash.put("katal",
    // tempVCUnitSystem.getInstance("katal"));
    sbmlUnitIdentifierHash.put("kelvin", tempVCUnitSystem.getInstance("K"));
    sbmlUnitIdentifierHash.put("kilogram", tempVCUnitSystem.getInstance("kg"));
    sbmlUnitIdentifierHash.put("litre", tempVCUnitSystem.getInstance("litre"));
    // sbmlUnitIdentifierHash.put("lumen",
    // tempVCUnitSystem.getInstance("lumen"));
    // sbmlUnitIdentifierHash.put("lux",
    // tempVCUnitSystem.getInstance("lux"));
    sbmlUnitIdentifierHash.put("metre", tempVCUnitSystem.getInstance("m"));
    sbmlUnitIdentifierHash.put("mole", tempVCUnitSystem.getInstance("mol"));
    sbmlUnitIdentifierHash.put("newton", tempVCUnitSystem.getInstance("N"));
    // sbmlUnitIdentifierHash.put("ohm",
    // tempVCUnitSystem.getInstance("ohm"));
    // sbmlUnitIdentifierHash.put("pascal",
    // tempVCUnitSystem.getInstance("pascal"));
    // sbmlUnitIdentifierHash.put("radian",
    // tempVCUnitSystem.getInstance("radian"));
    sbmlUnitIdentifierHash.put("second", tempVCUnitSystem.getInstance("s"));
    sbmlUnitIdentifierHash.put("siemens", tempVCUnitSystem.getInstance("S"));
    // sbmlUnitIdentifierHash.put("sievert",
    // tempVCUnitSystem.getInstance("sievert"));
    // sbmlUnitIdentifierHash.put("steradian",
    // tempVCUnitSystem.getInstance("steradian"));
    // sbmlUnitIdentifierHash.put("tesla",
    // tempVCUnitSystem.getInstance("tesla"));
    sbmlUnitIdentifierHash.put("volt", tempVCUnitSystem.getInstance("V"));
    sbmlUnitIdentifierHash.put("watt", tempVCUnitSystem.getInstance("W"));
    sbmlUnitIdentifierHash.put("weber", tempVCUnitSystem.getInstance("Wb"));
    long sbmlLevel = sbmlModel.getLevel();
    if (sbmlLevel < 3) {
        // SBML predefined unit identifiers
        sbmlUnitIdentifierHash.put(UnitDefinition.SUBSTANCE, tempVCUnitSystem.getInstance("mole"));
        sbmlUnitIdentifierHash.put(UnitDefinition.VOLUME, tempVCUnitSystem.getInstance("litre"));
        sbmlUnitIdentifierHash.put(UnitDefinition.AREA, tempVCUnitSystem.getInstance("m2"));
        sbmlUnitIdentifierHash.put(UnitDefinition.LENGTH, tempVCUnitSystem.getInstance("m"));
        sbmlUnitIdentifierHash.put(UnitDefinition.TIME, tempVCUnitSystem.getInstance("s"));
    }
    if (sbmlModel.isSetSubstanceUnits()) {
        UnitDefinition ud = sbmlModel.getSubstanceUnitsInstance();
        VCUnitDefinition vcUnitDef = SBMLUnitTranslator.getVCUnitDefinition(ud, tempVCUnitSystem);
        sbmlUnitIdentifierHash.put(UnitDefinition.SUBSTANCE, vcUnitDef);
    }
    if (sbmlModel.isSetVolumeUnits()) {
        UnitDefinition ud = sbmlModel.getVolumeUnitsInstance();
        VCUnitDefinition vcUnitDef = SBMLUnitTranslator.getVCUnitDefinition(ud, tempVCUnitSystem);
        sbmlUnitIdentifierHash.put(UnitDefinition.VOLUME, vcUnitDef);
    }
    if (sbmlModel.isSetAreaUnits()) {
        UnitDefinition ud = sbmlModel.getAreaUnitsInstance();
        VCUnitDefinition vcUnitDef = SBMLUnitTranslator.getVCUnitDefinition(ud, tempVCUnitSystem);
        sbmlUnitIdentifierHash.put(UnitDefinition.AREA, vcUnitDef);
    }
    if (sbmlModel.isSetLengthUnits()) {
        UnitDefinition ud = sbmlModel.getLengthUnitsInstance();
        VCUnitDefinition vcUnitDef = SBMLUnitTranslator.getVCUnitDefinition(ud, tempVCUnitSystem);
        sbmlUnitIdentifierHash.put(UnitDefinition.LENGTH, vcUnitDef);
    }
    if (sbmlModel.isSetTimeUnits()) {
        UnitDefinition ud = sbmlModel.getTimeUnitsInstance();
        VCUnitDefinition vcUnitDef = SBMLUnitTranslator.getVCUnitDefinition(ud, tempVCUnitSystem);
        sbmlUnitIdentifierHash.put(UnitDefinition.TIME, vcUnitDef);
    }
    // read unit definition (identifiers) declared in SBML model
    for (int i = 0; i < sbmlModel.getNumUnitDefinitions(); i++) {
        UnitDefinition ud = (org.sbml.jsbml.UnitDefinition) listofUnitDefns.get(i);
        String unitName = ud.getId();
        VCUnitDefinition vcUnitDef = SBMLUnitTranslator.getVCUnitDefinition(ud, tempVCUnitSystem);
        sbmlUnitIdentifierHash.put(unitName, vcUnitDef);
    }
    // For SBML level 2
    // default units
    VCUnitDefinition defaultSubstanceUnit = sbmlUnitIdentifierHash.get(UnitDefinition.SUBSTANCE);
    VCUnitDefinition defaultVolumeUnit = sbmlUnitIdentifierHash.get(UnitDefinition.VOLUME);
    VCUnitDefinition defaultAreaUnit = sbmlUnitIdentifierHash.get(UnitDefinition.AREA);
    VCUnitDefinition defaultLengthUnit = sbmlUnitIdentifierHash.get(UnitDefinition.LENGTH);
    VCUnitDefinition defaultTimeUnit = sbmlUnitIdentifierHash.get(UnitDefinition.TIME);
    VCUnitDefinition modelSubstanceUnit = null;
    VCUnitDefinition modelVolumeUnit = null;
    VCUnitDefinition modelAreaUnit = null;
    VCUnitDefinition modelLengthUnit = null;
    VCUnitDefinition modelTimeUnit = null;
    // units in SBML model
    // compartments
    ListOf<Compartment> listOfCompartments = sbmlModel.getListOfCompartments();
    for (int i = 0; i < listOfCompartments.size(); i++) {
        Compartment sbmlComp = listOfCompartments.get(i);
        double dim = 3;
        if (sbmlComp.isSetSpatialDimensions()) {
            dim = sbmlComp.getSpatialDimensions();
        }
        String unitStr = sbmlComp.getUnits();
        VCUnitDefinition sbmlUnitDefinition = null;
        if (unitStr != null && unitStr.length() > 0) {
            sbmlUnitDefinition = sbmlUnitIdentifierHash.get(unitStr);
        } else {
            // applying default unit if not defined for this compartment
            if (dim == 3) {
                sbmlUnitDefinition = defaultVolumeUnit;
            } else if (dim == 2) {
                sbmlUnitDefinition = defaultAreaUnit;
            } else if (dim == 1) {
                sbmlUnitDefinition = defaultLengthUnit;
            }
        }
        if (dim == 3) {
            if (sbmlUnitDefinition == null) {
                sbmlUnitDefinition = defaultVolumeUnit;
            }
            if (modelVolumeUnit == null) {
                modelVolumeUnit = sbmlUnitDefinition;
            } else if (!sbmlUnitDefinition.isEquivalent(modelVolumeUnit)) {
                localIssueList.add(new Issue(new SBMLIssueSource(sbmlComp), issueContext, IssueCategory.Units, "unit for compartment '" + sbmlComp.getId() + "' (" + unitStr + ") : (" + sbmlUnitDefinition.getSymbol() + ") not compatible with current vol unit (" + modelVolumeUnit.getSymbol() + ")", Issue.SEVERITY_WARNING));
            // logger.sendMessage(VCLogger.Priority.MediumPriority,
            // VCLogger.ErrorType.UnitError, "unit for compartment '" +
            // sbmlComp.getId() + "' (" + unitStr + ") : (" +
            // sbmlUnitDefinition.getSymbol() +
            // ") not compatible with current vol unit (" +
            // modelVolumeUnit.getSymbol() + ")");
            }
        } else if (dim == 2) {
            if (modelAreaUnit == null) {
                modelAreaUnit = sbmlUnitDefinition;
            } else if (!sbmlUnitDefinition.isEquivalent(modelAreaUnit)) {
                localIssueList.add(new Issue(new SBMLIssueSource(sbmlComp), issueContext, IssueCategory.Units, "unit for compartment '" + sbmlComp.getId() + "' (" + unitStr + ") : (" + sbmlUnitDefinition.getSymbol() + ") not compatible with current area unit (" + modelAreaUnit.getSymbol() + ")", Issue.SEVERITY_WARNING));
            // logger.sendMessage(VCLogger.Priority.MediumPriority,
            // VCLogger.ErrorType.UnitError, "unit for compartment '" +
            // sbmlComp.getId() + "' (" + unitStr + ") : (" +
            // sbmlUnitDefinition.getSymbol() +
            // ") not compatible with current area unit (" +
            // modelAreaUnit.getSymbol() + ")");
            }
        }
    }
    // species
    ListOf<org.sbml.jsbml.Species> listOfSpecies = sbmlModel.getListOfSpecies();
    for (int i = 0; i < listOfSpecies.size(); i++) {
        org.sbml.jsbml.Species sbmlSpecies = listOfSpecies.get(i);
        String unitStr = sbmlSpecies.getSubstanceUnits();
        VCUnitDefinition sbmlUnitDefinition = null;
        if (unitStr != null && unitStr.length() > 0) {
            sbmlUnitDefinition = sbmlUnitIdentifierHash.get(unitStr);
        } else {
            // apply default substance unit
            sbmlUnitDefinition = defaultSubstanceUnit;
        }
        if (modelSubstanceUnit == null) {
            modelSubstanceUnit = sbmlUnitDefinition;
        } else if (!sbmlUnitDefinition.isEquivalent(modelSubstanceUnit)) {
            localIssueList.add(new Issue(new SBMLIssueSource(sbmlSpecies), issueContext, IssueCategory.Units, "unit for species '" + sbmlSpecies.getId() + "' (" + unitStr + ") : (" + sbmlUnitDefinition.getSymbol() + ") not compatible with current substance unit (" + modelSubstanceUnit.getSymbol() + ")", Issue.SEVERITY_WARNING));
        // logger.sendMessage(VCLogger.Priority.MediumPriority,
        // VCLogger.ErrorType.UnitError, "unit for species '" +
        // sbmlSpecies.getId() + "' (" + unitStr + ") : (" +
        // sbmlUnitDefinition.getSymbol() +
        // ") not compatible with current substance unit (" +
        // modelSubstanceUnit.getSymbol() + ")");
        }
    }
    // reactions for SBML level 2 version < 3
    long sbmlVersion = sbmlModel.getVersion();
    if (sbmlVersion < 3) {
        ListOf<Reaction> listOfReactions = sbmlModel.getListOfReactions();
        for (int i = 0; i < listOfReactions.size(); i++) {
            Reaction sbmlReaction = listOfReactions.get(i);
            KineticLaw kineticLaw = sbmlReaction.getKineticLaw();
            if (kineticLaw != null) {
                // first check substance unit
                String unitStr = kineticLaw.getSubstanceUnits();
                VCUnitDefinition sbmlUnitDefinition = null;
                if (unitStr != null && unitStr.length() > 0) {
                    sbmlUnitDefinition = sbmlUnitIdentifierHash.get(unitStr);
                } else {
                    // apply default substance unit
                    sbmlUnitDefinition = defaultSubstanceUnit;
                }
                if (modelSubstanceUnit == null) {
                    modelSubstanceUnit = sbmlUnitDefinition;
                } else if (!sbmlUnitDefinition.isEquivalent(modelSubstanceUnit)) {
                    localIssueList.add(new Issue(new SBMLIssueSource(sbmlReaction), issueContext, IssueCategory.Units, "substance unit for reaction '" + sbmlReaction.getId() + "' (" + unitStr + ") : (" + sbmlUnitDefinition.getSymbol() + ") not compatible with current substance unit (" + modelSubstanceUnit.getSymbol() + ")", Issue.SEVERITY_WARNING));
                // logger.sendMessage(VCLogger.Priority.MediumPriority,
                // VCLogger.ErrorType.UnitError,
                // "substance unit for reaction '" +
                // sbmlReaction.getId() + "' (" + unitStr + ") : (" +
                // sbmlUnitDefinition.getSymbol() +
                // ") not compatible with current substance unit (" +
                // modelSubstanceUnit.getSymbol() + ")");
                }
                // check time unit
                unitStr = kineticLaw.getTimeUnits();
                if (unitStr != null && unitStr.length() > 0) {
                    sbmlUnitDefinition = sbmlUnitIdentifierHash.get(unitStr);
                } else {
                    // apply default time unit
                    sbmlUnitDefinition = defaultTimeUnit;
                }
                if (modelTimeUnit == null) {
                    modelTimeUnit = sbmlUnitDefinition;
                } else if (!sbmlUnitDefinition.isEquivalent(modelTimeUnit)) {
                    localIssueList.add(new Issue(new SBMLIssueSource(sbmlReaction), issueContext, IssueCategory.Units, "time unit for reaction '" + sbmlReaction.getId() + "' (" + unitStr + ") : (" + sbmlUnitDefinition.getSymbol() + ") not compatible with current time unit (" + modelTimeUnit.getSymbol() + ")", Issue.SEVERITY_WARNING));
                // logger.sendMessage(VCLogger.Priority.MediumPriority,
                // VCLogger.ErrorType.UnitError,
                // "time unit for reaction '" + sbmlReaction.getId() +
                // "' (" + unitStr + ") : (" +
                // sbmlUnitDefinition.getSymbol() +
                // ") not compatible with current time unit (" +
                // modelTimeUnit.getSymbol() + ")");
                }
            }
        }
    }
    if (modelSubstanceUnit == null) {
        modelSubstanceUnit = defaultSubstanceUnit;
    }
    if (modelVolumeUnit == null) {
        modelVolumeUnit = defaultVolumeUnit;
    }
    if (modelAreaUnit == null) {
        modelAreaUnit = defaultAreaUnit;
    }
    if (modelLengthUnit == null) {
        modelLengthUnit = defaultLengthUnit;
    }
    if (modelTimeUnit == null) {
        modelTimeUnit = defaultTimeUnit;
    }
    if (modelSubstanceUnit == null && modelVolumeUnit == null && modelAreaUnit == null && modelLengthUnit == null && modelTimeUnit == null) {
        // default (VC)modelUnitSystem
        return ModelUnitSystem.createDefaultVCModelUnitSystem();
    } else {
        return ModelUnitSystem.createSBMLUnitSystem(modelSubstanceUnit, modelVolumeUnit, modelAreaUnit, modelLengthUnit, modelTimeUnit);
    }
}
Also used : VCUnitSystem(cbit.vcell.units.VCUnitSystem) Issue(org.vcell.util.Issue) Compartment(org.sbml.jsbml.Compartment) Reaction(org.sbml.jsbml.Reaction) SimpleReaction(cbit.vcell.model.SimpleReaction) FluxReaction(cbit.vcell.model.FluxReaction) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) ListOf(org.sbml.jsbml.ListOf) Species(cbit.vcell.model.Species) KineticLaw(org.sbml.jsbml.KineticLaw) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) UnitDefinition(org.sbml.jsbml.UnitDefinition)

Aggregations

KineticLaw (org.sbml.jsbml.KineticLaw)4 Element (org.jdom.Element)3 InteriorPoint (org.sbml.jsbml.ext.spatial.InteriorPoint)3 BioModel (cbit.vcell.biomodel.BioModel)2 FluxReaction (cbit.vcell.model.FluxReaction)2 KineticsParameter (cbit.vcell.model.Kinetics.KineticsParameter)2 KineticsProxyParameter (cbit.vcell.model.Kinetics.KineticsProxyParameter)2 UnresolvedParameter (cbit.vcell.model.Kinetics.UnresolvedParameter)2 Model (cbit.vcell.model.Model)2 ModelParameter (cbit.vcell.model.Model.ModelParameter)2 SimpleReaction (cbit.vcell.model.SimpleReaction)2 Structure (cbit.vcell.model.Structure)2 Expression (cbit.vcell.parser.Expression)2 VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)2 HashSet (java.util.HashSet)2 Compartment (org.sbml.jsbml.Compartment)2 ListOf (org.sbml.jsbml.ListOf)2 LocalParameter (org.sbml.jsbml.LocalParameter)2 Reaction (org.sbml.jsbml.Reaction)2 ReactionContext (cbit.vcell.mapping.ReactionContext)1