Search in sources :

Example 1 with Membrane

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

the class StructureSizeSolver method updateRelativeStructureSizes.

/**
 * Insert the method's description here.
 * Creation date: (5/17/2006 10:33:38 AM)
 * @return double[]
 * @param structName java.lang.String
 * @param structSize double
 */
public static void updateRelativeStructureSizes(SimulationContext simContext) throws Exception {
    if (simContext.getGeometry().getDimension() > 0) {
        throw new RuntimeException("not yet supported for spatial applications");
    }
    StructureMapping[] structureMappings = simContext.getGeometryContext().getStructureMappings();
    try {
        // This is rewritten in Feb 2008. Siblings and children are correctly taken into account when calculating the volume fractions.
        StructureTopology structTopology = simContext.getModel().getStructureTopology();
        for (int i = 0; i < structureMappings.length; i++) {
            if (structureMappings[i] instanceof MembraneMapping) {
                // calculate the sum of features' sizes inside this membrane, this is used for calculating both surface volume ratio and volume fraction.
                double sumOfSubFeatures = 0;
                Membrane membrane = ((MembraneMapping) structureMappings[i]).getMembrane();
                Enumeration<Feature> subFeatures = structTopology.getSubFeatures(structTopology.getInsideFeature(membrane));
                while (subFeatures.hasMoreElements()) {
                    Feature feature = subFeatures.nextElement();
                    sumOfSubFeatures = sumOfSubFeatures + simContext.getGeometryContext().getStructureMapping(feature).getSizeParameter().getExpression().evaluateConstant();
                }
                // calculate the sum of features's sizes inside the membrance's parent feature, this is used for calculating the volume fraction.
                double sumOfParentMemSubFeatures = 0;
                Feature parentFeature = structTopology.getOutsideFeature(membrane);
                if (parentFeature != null) {
                    Enumeration<Feature> parentSubFeatures = structTopology.getSubFeatures(parentFeature);
                    while (parentSubFeatures.hasMoreElements()) {
                        Feature feature = parentSubFeatures.nextElement();
                        sumOfParentMemSubFeatures = sumOfParentMemSubFeatures + simContext.getGeometryContext().getStructureMapping(feature).getSizeParameter().getExpression().evaluateConstant();
                    }
                    // set surface volume ratio
                    ((MembraneMapping) structureMappings[i]).getSurfaceToVolumeParameter().setExpression(new Expression(((MembraneMapping) structureMappings[i]).getSizeParameter().getExpression().evaluateConstant() / sumOfSubFeatures));
                    // set volume fraction
                    ((MembraneMapping) structureMappings[i]).getVolumeFractionParameter().setExpression(new Expression(sumOfSubFeatures / sumOfParentMemSubFeatures));
                }
            }
        }
    } catch (NullPointerException e) {
        e.printStackTrace(System.out);
        // DialogUtils.showErrorDialog("structure sizes must all be specified");
        throw new Exception("structure sizes must all be specified");
    } catch (ExpressionException e) {
        e.printStackTrace(System.out);
        throw new Exception(e.getMessage());
    }
}
Also used : MembraneMapping(cbit.vcell.mapping.MembraneMapping) StructureTopology(cbit.vcell.model.Model.StructureTopology) StructureMapping(cbit.vcell.mapping.StructureMapping) Feature(cbit.vcell.model.Feature) AbstractConstraint(cbit.vcell.constraints.AbstractConstraint) GeneralConstraint(cbit.vcell.constraints.GeneralConstraint) ExpressionException(cbit.vcell.parser.ExpressionException) ExpressionException(cbit.vcell.parser.ExpressionException) Expression(cbit.vcell.parser.Expression) Membrane(cbit.vcell.model.Membrane)

Example 2 with Membrane

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

the class StructureSizeSolver method updateAbsoluteStructureSizes.

public static void updateAbsoluteStructureSizes(SimulationContext simContext, Structure struct, double structSize, VCUnitDefinition structSizeUnit) throws Exception {
    StructureMapping[] structMappings = simContext.getGeometryContext().getStructureMappings();
    try {
        StructureTopology structTopology = simContext.getModel().getStructureTopology();
        SolverParameterCollection solverParameters = new SolverParameterCollection();
        ArrayList<String> unknownVars = new ArrayList<String>();
        for (StructureMapping sm : structMappings) {
            if (sm.getStructure() instanceof Membrane) {
                MembraneMapping mm = (MembraneMapping) sm;
                StructureMappingParameter svRatioParam = mm.getSurfaceToVolumeParameter();
                StructureMappingParameter volFractParam = mm.getVolumeFractionParameter();
                StructureMappingParameter sizeParam = mm.getSizeParameter();
                solverParameters.add(new SolverParameter(svRatioParam, TokenMangler.mangleToSName("sv_" + mm.getMembrane().getName()), svRatioParam.getExpression().evaluateConstant()));
                solverParameters.add(new SolverParameter(volFractParam, TokenMangler.mangleToSName("vf_" + mm.getMembrane().getName()), volFractParam.getExpression().evaluateConstant()));
            }
            StructureMappingParameter sizeParam = sm.getSizeParameter();
            Double priorKnownValue = null;
            String varName = TokenMangler.mangleToSName("size_" + sm.getStructure().getName());
            if (sizeParam.getExpression() != null) {
                priorKnownValue = sizeParam.getExpression().evaluateConstant();
            } else if (sm.getStructure() == struct) {
                priorKnownValue = structSize;
            } else {
                unknownVars.add(varName);
            }
            solverParameters.add(new SolverParameter(sizeParam, varName, priorKnownValue));
        }
        ArrayList<Expression> expressions = new ArrayList<Expression>();
        for (int i = 0; i < structMappings.length; i++) {
            if (structMappings[i] instanceof MembraneMapping) {
                MembraneMapping membraneMapping = (MembraneMapping) structMappings[i];
                Feature insideFeature = structTopology.getInsideFeature(membraneMapping.getMembrane());
                Feature outsideFeature = structTopology.getOutsideFeature(membraneMapping.getMembrane());
                StructureMappingParameter sizeParameter = membraneMapping.getSizeParameter();
                StructureMappingParameter volFractParameter = membraneMapping.getVolumeFractionParameter();
                StructureMappingParameter surfToVolParameter = membraneMapping.getSurfaceToVolumeParameter();
                // 
                // EC eclosing cyt, which contains er and golgi
                // "(cyt_size+ er_size + golgi_size) * cyt_svRatio - PM_size"  ... implicit equation, exp == 0 is implied
                // 
                Expression sumOfInsideVolumeExp = new Expression(0.0);
                for (int j = 0; j < structMappings.length; j++) {
                    if (structMappings[j] instanceof FeatureMapping && structTopology.enclosedBy(structMappings[j].getStructure(), insideFeature)) {
                        FeatureMapping childFeatureMappingOfInside = ((FeatureMapping) structMappings[j]);
                        sumOfInsideVolumeExp = Expression.add(sumOfInsideVolumeExp, new Expression(solverParameters.getName(childFeatureMappingOfInside.getSizeParameter())));
                    }
                }
                Expression tempExpr = Expression.mult(sumOfInsideVolumeExp, new Expression(solverParameters.getName(surfToVolParameter)));
                tempExpr = Expression.add(tempExpr, new Expression("-" + solverParameters.getName(sizeParameter)));
                expressions.add(tempExpr);
                // 
                // EC eclosing cyt, which contains er and golgi
                // (EC_size + cyt_size + er_size + golgi_size) * cyt_vfRatio - (cyt_size + er_size + golgi_size)  ... implicit equation, exp == 0 is implied
                // 
                Expression sumOfParentVolumeExp = new Expression(0.0);
                for (int j = 0; j < structMappings.length; j++) {
                    if (structMappings[j] instanceof FeatureMapping && structTopology.enclosedBy(structMappings[j].getStructure(), outsideFeature)) {
                        FeatureMapping childFeatureMappingOfParent = ((FeatureMapping) structMappings[j]);
                        sumOfParentVolumeExp = Expression.add(sumOfParentVolumeExp, new Expression(TokenMangler.mangleToSName(solverParameters.getName(childFeatureMappingOfParent.getSizeParameter()))));
                    }
                }
                Expression exp = Expression.mult(sumOfParentVolumeExp, new Expression(solverParameters.getName(volFractParameter)));
                exp = Expression.add(exp, Expression.negate(sumOfInsideVolumeExp));
                expressions.add(exp);
            }
        }
        if (expressions.size() != unknownVars.size()) {
            throw new RuntimeException("number of unknowns is " + unknownVars.size() + ", number of equations is " + expressions.size());
        }
        if (unknownVars.size() == 0 && expressions.size() == 0) {
            StructureMappingParameter sizeParam = simContext.getGeometryContext().getStructureMapping(struct).getSizeParameter();
            sizeParam.setExpression(new Expression(structSize));
            return;
        }
        RationalExp[][] rowColData = new RationalExp[unknownVars.size()][unknownVars.size() + 1];
        for (int row = 0; row < unknownVars.size(); row++) {
            // 
            // verify that there is no "constant" term (without an unknown)
            // 
            // System.out.println("equation("+row+"): "+expressions.get(row).infix());
            Expression constantTerm = new Expression(expressions.get(row));
            for (String var : unknownVars) {
                constantTerm.substituteInPlace(new Expression(var), new Expression(0.0));
            }
            constantTerm = constantTerm.flatten();
            // 
            for (int col = 0; col < unknownVars.size(); col++) {
                Expression equation = new Expression(expressions.get(row));
                String colVariable = unknownVars.get(col);
                Expression deriv = equation.differentiate(colVariable).flatten();
                String[] symbols = deriv.getSymbols();
                if (symbols != null) {
                    for (String symbol : symbols) {
                        if (unknownVars.contains(symbol)) {
                            throw new RuntimeException("equation is not linear in the unknowns");
                        }
                    }
                }
                rowColData[row][col] = RationalExpUtils.getRationalExp(deriv);
            }
            rowColData[row][unknownVars.size()] = RationalExpUtils.getRationalExp(constantTerm).minus();
        }
        RationalExpMatrix rationalExpMatrix = new RationalExpMatrix(rowColData);
        // rationalExpMatrix.show();
        RationalExp[] solutions = rationalExpMatrix.solveLinearExpressions();
        double[] solutionValues = new double[solutions.length];
        for (int i = 0; i < unknownVars.size(); i++) {
            Expression vcSolution = new Expression(solutions[i].infixString());
            String[] symbols = vcSolution.getSymbols();
            if (symbols != null) {
                for (String symbol : symbols) {
                    SolverParameter p = solverParameters.get(symbol);
                    if (p.knownValue == null) {
                        throw new RuntimeException("solution for var " + unknownVars.get(i) + " is a function of unknown var " + p.name);
                    }
                    vcSolution.substituteInPlace(new Expression(symbol), new Expression(p.knownValue.doubleValue()));
                }
            }
            double value = vcSolution.flatten().evaluateConstant();
            // System.out.println(unknownVars.get(i)+" = "+value+" = "+solutions[i].infixString());
            solutionValues[i] = value;
        }
        for (int i = 0; i < unknownVars.size(); i++) {
            SolverParameter p = solverParameters.get(unknownVars.get(i));
            p.parameter.setExpression(new Expression(solutionValues[i]));
        }
        // 
        // set the one known value (if not set already by the gui).
        // 
        StructureMappingParameter sizeParam = simContext.getGeometryContext().getStructureMapping(struct).getSizeParameter();
        sizeParam.setExpression(new Expression(structSize));
        System.out.println("done");
    } catch (ExpressionException e) {
        e.printStackTrace(System.out);
        throw new Exception(e.getMessage());
    }
}
Also used : MembraneMapping(cbit.vcell.mapping.MembraneMapping) ArrayList(java.util.ArrayList) StructureMappingParameter(cbit.vcell.mapping.StructureMapping.StructureMappingParameter) StructureMapping(cbit.vcell.mapping.StructureMapping) Feature(cbit.vcell.model.Feature) ExpressionException(cbit.vcell.parser.ExpressionException) FeatureMapping(cbit.vcell.mapping.FeatureMapping) RationalExpMatrix(cbit.vcell.matrix.RationalExpMatrix) Membrane(cbit.vcell.model.Membrane) StructureTopology(cbit.vcell.model.Model.StructureTopology) RationalExp(cbit.vcell.matrix.RationalExp) AbstractConstraint(cbit.vcell.constraints.AbstractConstraint) GeneralConstraint(cbit.vcell.constraints.GeneralConstraint) ExpressionException(cbit.vcell.parser.ExpressionException) Expression(cbit.vcell.parser.Expression)

Example 3 with Membrane

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

the class SBMLExporter method addCompartments.

/**
 * addCompartments comment.
 * @throws XMLStreamException
 * @throws SbmlException
 */
protected void addCompartments() throws XMLStreamException, SbmlException {
    Model vcModel = vcBioModel.getModel();
    cbit.vcell.model.Structure[] vcStructures = vcModel.getStructures();
    for (int i = 0; i < vcStructures.length; i++) {
        Compartment sbmlCompartment = sbmlModel.createCompartment();
        sbmlCompartment.setId(TokenMangler.mangleToSName(vcStructures[i].getName()));
        sbmlCompartment.setName(vcStructures[i].getName());
        VCUnitDefinition sbmlSizeUnit = null;
        StructureTopology structTopology = getSelectedSimContext().getModel().getStructureTopology();
        Structure parentStructure = structTopology.getParentStructure(vcStructures[i]);
        if (vcStructures[i] instanceof Feature) {
            sbmlCompartment.setSpatialDimensions(3);
            String outside = null;
            if (parentStructure != null) {
                outside = TokenMangler.mangleToSName(parentStructure.getName());
            }
            if (outside != null) {
                if (outside.length() > 0) {
                    sbmlCompartment.setOutside(outside);
                }
            }
            sbmlSizeUnit = sbmlExportSpec.getVolumeUnits();
            UnitDefinition unitDefn = getOrCreateSBMLUnit(sbmlSizeUnit);
            sbmlCompartment.setUnits(unitDefn);
        } else if (vcStructures[i] instanceof Membrane) {
            Membrane vcMembrane = (Membrane) vcStructures[i];
            sbmlCompartment.setSpatialDimensions(2);
            Feature outsideFeature = structTopology.getOutsideFeature(vcMembrane);
            if (outsideFeature != null) {
                sbmlCompartment.setOutside(TokenMangler.mangleToSName(outsideFeature.getName()));
                sbmlSizeUnit = sbmlExportSpec.getAreaUnits();
                UnitDefinition unitDefn = getOrCreateSBMLUnit(sbmlSizeUnit);
                sbmlCompartment.setUnits(unitDefn);
            } else if (lg.isEnabledFor(Level.WARN)) {
                lg.warn(this.sbmlModel.getName() + " membrame " + vcMembrane.getName() + " has not outside feature");
            }
        }
        sbmlCompartment.setConstant(true);
        StructureMapping vcStructMapping = getSelectedSimContext().getGeometryContext().getStructureMapping(vcStructures[i]);
        try {
            if (vcStructMapping.getSizeParameter().getExpression() != null) {
                sbmlCompartment.setSize(vcStructMapping.getSizeParameter().getExpression().evaluateConstant());
            } else {
            // really no need to set sizes of compartments in spatial ..... ????
            // throw new RuntimeException("Compartment size not set for compartment \"" + vcStructures[i].getName() + "\" ; Please set size and try exporting again.");
            }
        } catch (cbit.vcell.parser.ExpressionException e) {
            // If it is in the catch block, it means that the compartment size was probably not a double, but an assignment.
            // Check if the expression for the compartment size is not null and add it as an assignment rule.
            Expression sizeExpr = vcStructMapping.getSizeParameter().getExpression();
            if (sizeExpr != null) {
                ASTNode ruleFormulaNode = getFormulaFromExpression(sizeExpr);
                AssignmentRule assignRule = sbmlModel.createAssignmentRule();
                assignRule.setVariable(vcStructures[i].getName());
                assignRule.setMath(ruleFormulaNode);
                // If compartmentSize is specified by an assignment rule, the 'constant' field should be set to 'false' (default - true).
                sbmlCompartment.setConstant(false);
                sbmlModel.addRule(assignRule);
            }
        }
        // Add the outside compartment of given compartment as annotation to the compartment.
        // This is required later while trying to read in compartments ...
        Element sbmlImportRelatedElement = null;
        // if (parentStructure != null) {
        // sbmlImportRelatedElement = new Element(XMLTags.VCellRelatedInfoTag, sbml_vcml_ns);
        // Element compartmentElement = new Element(XMLTags.OutsideCompartmentTag, sbml_vcml_ns);
        // compartmentElement.setAttribute(XMLTags.NameAttrTag, TokenMangler.mangleToSName(parentStructure.getName()));
        // sbmlImportRelatedElement.addContent(compartmentElement);
        // }
        // Get annotation (RDF and non-RDF) for reactionStep from SBMLAnnotationUtils
        sbmlAnnotationUtil.writeAnnotation(vcStructures[i], sbmlCompartment, sbmlImportRelatedElement);
        // Now set notes,
        sbmlAnnotationUtil.writeNotes(vcStructures[i], sbmlCompartment);
    }
}
Also used : StructureTopology(cbit.vcell.model.Model.StructureTopology) Compartment(org.sbml.jsbml.Compartment) AssignmentRule(org.sbml.jsbml.AssignmentRule) Element(org.jdom.Element) ExpressionException(cbit.vcell.parser.ExpressionException) Feature(cbit.vcell.model.Feature) StructureMapping(cbit.vcell.mapping.StructureMapping) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) ASTNode(org.sbml.jsbml.ASTNode) Membrane(cbit.vcell.model.Membrane) Structure(cbit.vcell.model.Structure) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) UnitDefinition(org.sbml.jsbml.UnitDefinition)

Example 4 with Membrane

use of cbit.vcell.model.Membrane 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 5 with Membrane

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

the class SBMLImporter method addCompartments.

protected void addCompartments(VCMetaData metaData) {
    if (sbmlModel == null) {
        throw new SBMLImportException("SBML model is NULL");
    }
    ListOf listofCompartments = sbmlModel.getListOfCompartments();
    if (listofCompartments == null) {
        throw new SBMLImportException("Cannot have 0 compartments in model");
    }
    // Using a vector here - since there can be SBML models with only
    // features and no membranes.
    // Hence keeping the datastructure flexible.
    List<Structure> structList = new ArrayList<Structure>();
    java.util.HashMap<String, Structure> structureNameMap = new java.util.HashMap<String, Structure>();
    try {
        int structIndx = 0;
        // First pass - create the structures
        for (int i = 0; i < sbmlModel.getNumCompartments(); i++) {
            org.sbml.jsbml.Compartment compartment = (org.sbml.jsbml.Compartment) listofCompartments.get(i);
            String compartmentName = compartment.getId();
            if (!compartment.isSetSpatialDimensions() || compartment.getSpatialDimensions() == 3) {
                Feature feature = new Feature(compartmentName);
                structList.add(structIndx, feature);
                structureNameMap.put(compartmentName, feature);
            } else if (compartment.getSpatialDimensions() == 2) {
                // spatial dimensions is set (see clause above)
                Membrane membrane = new Membrane(compartmentName);
                structList.add(structIndx, membrane);
                structureNameMap.put(compartmentName, membrane);
            } else {
                logger.sendMessage(VCLogger.Priority.HighPriority, VCLogger.ErrorType.CompartmentError, "Cannot deal with spatial dimension : " + compartment.getSpatialDimensions() + " for compartments at this time.");
                throw new SBMLImportException("Cannot deal with spatial dimension : " + compartment.getSpatialDimensions() + " for compartments at this time");
            }
            structIndx++;
            sbmlAnnotationUtil.readAnnotation(structList.get(i), compartment);
            sbmlAnnotationUtil.readNotes(structList.get(i), compartment);
        }
        // Second pass - connect the structures
        Model model = vcBioModel.getSimulationContext(0).getModel();
        for (int i = 0; i < sbmlModel.getNumCompartments(); i++) {
            org.sbml.jsbml.Compartment sbmlCompartment = (org.sbml.jsbml.Compartment) listofCompartments.get(i);
            String outsideCompartmentId = null;
            if (sbmlCompartment.getOutside() != null && sbmlCompartment.getOutside().length() > 0) {
                // compartment.getOutside returns the Sid of the 'outside'
                // compartment, so get the compartment from model.
                outsideCompartmentId = sbmlCompartment.getOutside();
            } else {
                Element sbmlImportRelatedElement = sbmlAnnotationUtil.readVCellSpecificAnnotation(sbmlCompartment);
                if (sbmlImportRelatedElement != null) {
                    Element embeddedVCellElement = sbmlImportRelatedElement.getChild(OUTSIDE_COMP_NAME, Namespace.getNamespace(SBMLUtils.SBML_VCELL_NS));
                    if (embeddedVCellElement != null) {
                        outsideCompartmentId = embeddedVCellElement.getAttributeValue(XMLTags.NameTag);
                    }
                }
            }
            if (outsideCompartmentId != null) {
                Compartment outsideCompartment = sbmlModel.getCompartment(outsideCompartmentId);
                Structure outsideStructure = (Structure) structureNameMap.get(outsideCompartment.getId());
                Structure struct = (Structure) structureNameMap.get(sbmlCompartment.getId());
                struct.setSbmlParentStructure(outsideStructure);
            }
        }
        // set the structures in vc vcBioModel.getSimulationContext(0)
        Structure[] structures = structList.toArray(new Structure[structList.size()]);
        model.setStructures(structures);
        // Third pass thro' the list of compartments : set the sizes on the
        // structureMappings - can be done only after setting
        // the structures on vcBioModel.getSimulationContext(0).
        boolean allSizesSet = true;
        for (int i = 0; i < sbmlModel.getNumCompartments(); i++) {
            org.sbml.jsbml.Compartment compartment = (org.sbml.jsbml.Compartment) listofCompartments.get(i);
            String compartmentName = compartment.getId();
            if (!compartment.isSetSize()) {
                // logger.sendMessage(VCLogger.Priority.MediumPriority,
                // TranslationMessage.COMPARTMENT_ERROR,
                // "compartment "+compartmentName+" size is not set in SBML document.");
                allSizesSet = false;
            } else {
                double size = compartment.getSize();
                // Check if size is specified by a rule
                Expression sizeExpr = getValueFromAssignmentRule(compartmentName);
                if (sizeExpr != null && !sizeExpr.isNumeric()) {
                    // We are NOT handling compartment sizes with assignment
                    // rules/initial Assignments that are NON-numeric at
                    // this time ...
                    logger.sendMessage(VCLogger.Priority.HighPriority, VCLogger.ErrorType.CompartmentError, "compartment " + compartmentName + " size has an assignment rule which is not a numeric value, cannot handle it at this time.");
                }
                // check if it is specified by initial assignment
                if (sizeExpr == null) {
                    InitialAssignment compInitAssgnment = sbmlModel.getInitialAssignment(compartmentName);
                    if (compInitAssgnment != null) {
                        sizeExpr = getExpressionFromFormula(compInitAssgnment.getMath());
                    }
                }
                if (sizeExpr != null && !sizeExpr.isNumeric()) {
                    // We are NOT handling compartment sizes with assignment
                    // rules/initial Assignments that are NON-numeric at
                    // this time ...
                    logger.sendMessage(VCLogger.Priority.HighPriority, VCLogger.ErrorType.CompartmentError, "compartment " + compartmentName + " size has an initial assignment which is not a numeric value, cannot handle it at this time.");
                }
                // from 'size' attribute,
                if (sizeExpr == null) {
                    sizeExpr = new Expression(size);
                }
                // Now set the size of the compartment.
                Structure struct = model.getStructure(compartmentName);
                StructureMapping.StructureMappingParameter mappingParam = vcBioModel.getSimulationContext(0).getGeometryContext().getStructureMapping(struct).getSizeParameter();
                mappingParam.setExpression(sizeExpr);
            }
        }
        // size is set
        if (allSizesSet) {
            StructureSizeSolver.updateRelativeStructureSizes(vcBioModel.getSimulationContext(0));
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new SBMLImportException("Error adding Feature to vcModel " + e.getMessage(), e);
    }
}
Also used : HashMap(java.util.HashMap) Compartment(org.sbml.jsbml.Compartment) Element(org.jdom.Element) ArrayList(java.util.ArrayList) Feature(cbit.vcell.model.Feature) StructureMapping(cbit.vcell.mapping.StructureMapping) ListOf(org.sbml.jsbml.ListOf) Membrane(cbit.vcell.model.Membrane) Structure(cbit.vcell.model.Structure) 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) InitialAssignment(org.sbml.jsbml.InitialAssignment) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) Compartment(org.sbml.jsbml.Compartment)

Aggregations

Membrane (cbit.vcell.model.Membrane)77 Feature (cbit.vcell.model.Feature)50 Structure (cbit.vcell.model.Structure)47 Expression (cbit.vcell.parser.Expression)31 SpeciesContext (cbit.vcell.model.SpeciesContext)25 MembraneMapping (cbit.vcell.mapping.MembraneMapping)20 StructureTopology (cbit.vcell.model.Model.StructureTopology)19 ExpressionException (cbit.vcell.parser.ExpressionException)18 PropertyVetoException (java.beans.PropertyVetoException)17 FluxReaction (cbit.vcell.model.FluxReaction)16 Model (cbit.vcell.model.Model)16 ReactionStep (cbit.vcell.model.ReactionStep)16 SimpleReaction (cbit.vcell.model.SimpleReaction)16 ArrayList (java.util.ArrayList)14 StructureMapping (cbit.vcell.mapping.StructureMapping)12 ModelUnitSystem (cbit.vcell.model.ModelUnitSystem)12 ReactionParticipant (cbit.vcell.model.ReactionParticipant)12 VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)12 SubVolume (cbit.vcell.geometry.SubVolume)11 SurfaceClass (cbit.vcell.geometry.SurfaceClass)11