Search in sources :

Example 11 with SpeciesContextSpecParameter

use of cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter in project vcell by virtualcell.

the class SpeciesContextSpecsTableModel method getValueAt.

/**
 * getValueAt method comment.
 */
public Object getValueAt(int row, int col) {
    try {
        SpeciesContextSpec scSpec = getValueAt(row);
        ColumnType columnType = columns.get(col);
        switch(columnType) {
            case COLUMN_SPECIESCONTEXT:
                {
                    return scSpec.getSpeciesContext();
                }
            case COLUMN_STRUCTURE:
                {
                    return scSpec.getSpeciesContext().getStructure();
                }
            case COLUMN_DEPICTION:
                {
                    return scSpec.getSpeciesContext().getSpeciesPattern();
                }
            case COLUMN_CLAMPED:
                {
                    return new Boolean(scSpec.isConstant());
                }
            case COLUMN_WELLMIXED:
                {
                    return (scSpec.isConstant() || scSpec.isWellMixed()) && !getSimulationContext().isStoch();
                }
            case COLUMN_INITIAL:
                {
                    SpeciesContextSpecParameter initialConditionParameter = scSpec.getInitialConditionParameter();
                    if (initialConditionParameter != null) {
                        return new ScopedExpression(initialConditionParameter.getExpression(), initialConditionParameter.getNameScope(), true, true, autoCompleteSymbolFilter);
                    } else {
                        return null;
                    }
                }
            case COLUMN_DIFFUSION:
                {
                    SpeciesContextSpecParameter diffusionParameter = scSpec.getDiffusionParameter();
                    if (diffusionParameter != null && !scSpec.isConstant() && scSpec.isWellMixed() != null && !scSpec.isWellMixed()) {
                        return new ScopedExpression(diffusionParameter.getExpression(), diffusionParameter.getNameScope(), true, true, autoCompleteSymbolFilter);
                    } else {
                        return null;
                    }
                }
            case COLUMN_FORCECONTINUOUS:
                {
                    return new Boolean(scSpec.isForceContinuous());
                }
            default:
                {
                    return null;
                }
        }
    } catch (Exception ex) {
        ex.printStackTrace(System.out);
        return null;
    }
}
Also used : ScopedExpression(cbit.gui.ScopedExpression) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) ExpressionException(cbit.vcell.parser.ExpressionException) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter)

Example 12 with SpeciesContextSpecParameter

use of cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter in project vcell by virtualcell.

the class SimulationContext method copySimulationContext.

public static SimulationContext copySimulationContext(SimulationContext srcSimContext, String newSimulationContextName, boolean bSpatial, Application simContextType) throws java.beans.PropertyVetoException, ExpressionException, MappingException, GeometryException, ImageException {
    Geometry newClonedGeometry = new Geometry(srcSimContext.getGeometry());
    newClonedGeometry.precomputeAll(new GeometryThumbnailImageFactoryAWT());
    // if stoch copy to ode, we need to check is stoch is using particles. If yes, should convert particles to concentraton.
    // the other 3 cases are fine. ode->ode, ode->stoch, stoch-> stoch
    SimulationContext destSimContext = new SimulationContext(srcSimContext, newClonedGeometry, simContextType);
    if (srcSimContext.getApplicationType() == Application.NETWORK_STOCHASTIC && !srcSimContext.isUsingConcentration() && simContextType == Application.NETWORK_DETERMINISTIC) {
        try {
            destSimContext.convertSpeciesIniCondition(true);
        } catch (MappingException e) {
            e.printStackTrace();
            throw new java.beans.PropertyVetoException(e.getMessage(), null);
        }
    }
    if (srcSimContext.getGeometry().getDimension() > 0 && !bSpatial) {
        // copy the size over
        destSimContext.setGeometry(new Geometry("nonspatial", 0));
        StructureMapping[] srcStructureMappings = srcSimContext.getGeometryContext().getStructureMappings();
        StructureMapping[] destStructureMappings = destSimContext.getGeometryContext().getStructureMappings();
        for (StructureMapping destStructureMapping : destStructureMappings) {
            for (StructureMapping srcStructureMapping : srcStructureMappings) {
                if (destStructureMapping.getStructure() == srcStructureMapping.getStructure()) {
                    if (srcStructureMapping.getUnitSizeParameter() != null) {
                        Expression sizeRatio = srcStructureMapping.getUnitSizeParameter().getExpression();
                        GeometryClass srcGeometryClass = srcStructureMapping.getGeometryClass();
                        GeometricRegion[] srcGeometricRegions = srcSimContext.getGeometry().getGeometrySurfaceDescription().getGeometricRegions(srcGeometryClass);
                        if (srcGeometricRegions != null) {
                            double size = 0;
                            for (GeometricRegion srcGeometricRegion : srcGeometricRegions) {
                                size += srcGeometricRegion.getSize();
                            }
                            destStructureMapping.getSizeParameter().setExpression(Expression.mult(sizeRatio, new Expression(size)));
                        }
                    }
                    break;
                }
            }
        }
        // If changing spatial to non-spatial
        // set diffusion to 0, velocity and boundary to null
        // srcSimContext.getReactionContext().getspe
        Parameter[] allParameters = destSimContext.getAllParameters();
        if (allParameters != null && allParameters.length > 0) {
            for (int i = 0; i < allParameters.length; i++) {
                if (allParameters[i] instanceof SpeciesContextSpecParameter) {
                    SpeciesContextSpecParameter speciesContextSpecParameter = (SpeciesContextSpecParameter) allParameters[i];
                    int role = speciesContextSpecParameter.getRole();
                    if (role == SpeciesContextSpec.ROLE_DiffusionRate) {
                        speciesContextSpecParameter.setExpression(new Expression(0));
                    } else if (role == SpeciesContextSpec.ROLE_BoundaryValueXm || role == SpeciesContextSpec.ROLE_BoundaryValueXp || role == SpeciesContextSpec.ROLE_BoundaryValueYm || role == SpeciesContextSpec.ROLE_BoundaryValueYp || role == SpeciesContextSpec.ROLE_BoundaryValueZm || role == SpeciesContextSpec.ROLE_BoundaryValueZp) {
                        speciesContextSpecParameter.setExpression(null);
                    } else if (role == SpeciesContextSpec.ROLE_VelocityX || role == SpeciesContextSpec.ROLE_VelocityY || role == SpeciesContextSpec.ROLE_VelocityZ) {
                        speciesContextSpecParameter.setExpression(null);
                    }
                }
            }
        }
    }
    destSimContext.fixFlags();
    destSimContext.setName(newSimulationContextName);
    return destSimContext;
}
Also used : GeometryClass(cbit.vcell.geometry.GeometryClass) SurfaceGeometricRegion(cbit.vcell.geometry.surface.SurfaceGeometricRegion) VolumeGeometricRegion(cbit.vcell.geometry.surface.VolumeGeometricRegion) GeometricRegion(cbit.vcell.geometry.surface.GeometricRegion) Geometry(cbit.vcell.geometry.Geometry) PropertyVetoException(java.beans.PropertyVetoException) GeometryThumbnailImageFactoryAWT(cbit.vcell.geometry.GeometryThumbnailImageFactoryAWT) Expression(cbit.vcell.parser.Expression) Parameter(cbit.vcell.model.Parameter) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter)

Example 13 with SpeciesContextSpecParameter

use of cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter in project vcell by virtualcell.

the class ApplicationConstraintsGenerator method steadyStateFromApplication.

/**
 * Insert the method's description here.
 * Creation date: (6/26/01 8:25:55 AM)
 * @return cbit.vcell.constraints.ConstraintContainerImpl
 */
public static ConstraintContainerImpl steadyStateFromApplication(SimulationContext simContext, double tolerance) {
    try {
        ConstraintContainerImpl ccImpl = new ConstraintContainerImpl();
        // ====================
        // add physical limits
        // ====================
        // 
        // no negative concentrations
        // 
        cbit.vcell.model.Model model = simContext.getModel();
        cbit.vcell.model.SpeciesContext[] speciesContexts = model.getSpeciesContexts();
        for (int i = 0; i < speciesContexts.length; i++) {
            ccImpl.addSimpleBound(new SimpleBounds(speciesContexts[i].getName(), new RealInterval(0, Double.POSITIVE_INFINITY), AbstractConstraint.PHYSICAL_LIMIT, "non-negative concentration"));
        }
        for (int i = 0; i < speciesContexts.length; i++) {
            SpeciesContextSpecParameter initParam = (simContext.getReactionContext().getSpeciesContextSpec(speciesContexts[i])).getInitialConditionParameter();
            if (initParam != null) {
                double initialValue = initParam.getExpression().evaluateConstant();
                double lowInitialValue = Math.min(initialValue / tolerance, initialValue * tolerance);
                double highInitialValue = Math.max(initialValue / tolerance, initialValue * tolerance);
                ccImpl.addSimpleBound(new SimpleBounds(speciesContexts[i].getName(), new RealInterval(lowInitialValue, highInitialValue), AbstractConstraint.MODELING_ASSUMPTION, "close to specified \"initialCondition\""));
            }
        }
        // =========================
        // add modeling assumptions
        // =========================
        // 
        // mass action forward and reverse rates should be non-negative
        // 
        cbit.vcell.model.ReactionStep[] reactionSteps = model.getReactionSteps();
        for (int i = 0; i < reactionSteps.length; i++) {
            Kinetics kinetics = reactionSteps[i].getKinetics();
            if (kinetics instanceof MassActionKinetics) {
                Expression forwardRateConstraintExp = new Expression(((MassActionKinetics) kinetics).getForwardRateParameter().getExpression().infix() + ">=0");
                forwardRateConstraintExp = getSteadyStateExpression(forwardRateConstraintExp);
                if (!forwardRateConstraintExp.compareEqual(new Expression(1.0))) {
                    ccImpl.addGeneralConstraint(new GeneralConstraint(forwardRateConstraintExp, AbstractConstraint.MODELING_ASSUMPTION, "non-negative forward rate"));
                }
                Expression reverseRateConstraintExp = new Expression(((MassActionKinetics) kinetics).getReverseRateParameter().getExpression().infix() + ">=0");
                reverseRateConstraintExp = getSteadyStateExpression(reverseRateConstraintExp);
                if (!reverseRateConstraintExp.compareEqual(new Expression(1.0))) {
                    ccImpl.addGeneralConstraint(new GeneralConstraint(reverseRateConstraintExp, AbstractConstraint.MODELING_ASSUMPTION, "non-negative reverse rate"));
                }
            }
            KineticsParameter authoritativeParameter = kinetics.getAuthoritativeParameter();
            Expression kineticRateConstraintExp = new Expression(authoritativeParameter.getName() + "==" + authoritativeParameter.getExpression().infix());
            kineticRateConstraintExp = getSteadyStateExpression(kineticRateConstraintExp);
            if (!kineticRateConstraintExp.compareEqual(new Expression(1.0))) {
                ccImpl.addGeneralConstraint(new GeneralConstraint(kineticRateConstraintExp, AbstractConstraint.MODELING_ASSUMPTION, "definition"));
            }
        }
        // 
        try {
            simContext.setMathDescription(simContext.createNewMathMapping().getMathDescription());
        } catch (Throwable e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("cannot create mathDescription");
        }
        MathDescription mathDesc = simContext.getMathDescription();
        if (mathDesc.getGeometry().getDimension() > 0) {
            throw new RuntimeException("spatial simulations not yet supported");
        }
        CompartmentSubDomain subDomain = (CompartmentSubDomain) mathDesc.getSubDomains().nextElement();
        java.util.Enumeration<Equation> enumEquations = subDomain.getEquations();
        while (enumEquations.hasMoreElements()) {
            Equation equation = (Equation) enumEquations.nextElement();
            Expression rateConstraintExp = new Expression(equation.getRateExpression().infix() + "==0");
            rateConstraintExp = getSteadyStateExpression(rateConstraintExp);
            if (!rateConstraintExp.compareEqual(new Expression(1.0))) {
                // not a trivial constraint (always true)
                ccImpl.addGeneralConstraint(new GeneralConstraint(rateConstraintExp, AbstractConstraint.PHYSICAL_LIMIT, "definition of steady state"));
            }
        }
        // 
        for (int i = 0; i < reactionSteps.length; i++) {
            Kinetics kinetics = reactionSteps[i].getKinetics();
            Kinetics.KineticsParameter[] parameters = kinetics.getKineticsParameters();
            for (int j = 0; j < parameters.length; j++) {
                Expression exp = parameters[j].getExpression();
                if (exp.getSymbols() == null || exp.getSymbols().length == 0) {
                    // 
                    try {
                        double constantValue = exp.evaluateConstant();
                        double lowValue = Math.min(constantValue / tolerance, constantValue * tolerance);
                        double highValue = Math.max(constantValue / tolerance, constantValue * tolerance);
                        RealInterval interval = new RealInterval(lowValue, highValue);
                        ccImpl.addSimpleBound(new SimpleBounds(parameters[j].getName(), interval, AbstractConstraint.MODELING_ASSUMPTION, "parameter close to model default"));
                    } catch (cbit.vcell.parser.ExpressionException e) {
                        System.out.println("error evaluating parameter " + parameters[j].getName() + " in reaction step " + reactionSteps[i].getName());
                    }
                } else {
                    Expression parameterDefinitionExp = new Expression(parameters[j].getName() + "==" + parameters[j].getExpression().infix());
                    ccImpl.addGeneralConstraint(new GeneralConstraint(getSteadyStateExpression(parameterDefinitionExp), AbstractConstraint.MODELING_ASSUMPTION, "parameter definition"));
                }
            }
        }
        ccImpl.addSimpleBound(new SimpleBounds(model.getFARADAY_CONSTANT().getName(), new RealInterval(model.getFARADAY_CONSTANT().getExpression().evaluateConstant()), AbstractConstraint.PHYSICAL_LIMIT, "Faraday's constant"));
        ccImpl.addSimpleBound(new SimpleBounds(model.getTEMPERATURE().getName(), new RealInterval(300), AbstractConstraint.PHYSICAL_LIMIT, "Absolute Temperature Kelvin"));
        ccImpl.addSimpleBound(new SimpleBounds(model.getGAS_CONSTANT().getName(), new RealInterval(model.getGAS_CONSTANT().getExpression().evaluateConstant()), AbstractConstraint.PHYSICAL_LIMIT, "ideal gas constant"));
        ccImpl.addSimpleBound(new SimpleBounds(model.getKMILLIVOLTS().getName(), new RealInterval(model.getKMILLIVOLTS().getExpression().evaluateConstant()), AbstractConstraint.PHYSICAL_LIMIT, "ideal gas constant"));
        // 
        // add K_fluxs
        // 
        java.util.Enumeration<Variable> enumVars = mathDesc.getVariables();
        while (enumVars.hasMoreElements()) {
            Variable var = (Variable) enumVars.nextElement();
            if (var.getName().startsWith("Kflux_") && var instanceof Function) {
                Expression kfluxExp = new Expression(((Function) var).getExpression());
                kfluxExp.bindExpression(mathDesc);
                kfluxExp = MathUtilities.substituteFunctions(kfluxExp, mathDesc);
                kfluxExp = kfluxExp.flatten();
                ccImpl.addSimpleBound(new SimpleBounds(var.getName(), new RealInterval(kfluxExp.evaluateConstant()), AbstractConstraint.MODELING_ASSUMPTION, "flux conversion factor"));
            }
        }
        return ccImpl;
    } catch (cbit.vcell.parser.ExpressionException e) {
        e.printStackTrace(System.out);
        return null;
    } catch (java.beans.PropertyVetoException e) {
        e.printStackTrace(System.out);
        return null;
    }
}
Also used : Variable(cbit.vcell.math.Variable) SimpleBounds(cbit.vcell.constraints.SimpleBounds) MathDescription(cbit.vcell.math.MathDescription) GeneralConstraint(cbit.vcell.constraints.GeneralConstraint) RealInterval(net.sourceforge.interval.ia_math.RealInterval) Function(cbit.vcell.math.Function) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) ConstraintContainerImpl(cbit.vcell.constraints.ConstraintContainerImpl) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) Equation(cbit.vcell.math.Equation) AbstractConstraint(cbit.vcell.constraints.AbstractConstraint) GeneralConstraint(cbit.vcell.constraints.GeneralConstraint) Expression(cbit.vcell.parser.Expression) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) MassActionKinetics(cbit.vcell.model.MassActionKinetics) MassActionKinetics(cbit.vcell.model.MassActionKinetics) Kinetics(cbit.vcell.model.Kinetics)

Example 14 with SpeciesContextSpecParameter

use of cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter in project vcell by virtualcell.

the class ApplicationConstraintsGenerator method fromApplication.

/**
 * Insert the method's description here.
 * Creation date: (6/26/01 8:25:55 AM)
 * @return cbit.vcell.constraints.ConstraintContainerImpl
 */
public static ConstraintContainerImpl fromApplication(SimulationContext simContext) {
    try {
        ConstraintContainerImpl ccImpl = new ConstraintContainerImpl();
        // ====================
        // add physical limits
        // ====================
        // 
        // no negative concentrations
        // 
        cbit.vcell.model.Model model = simContext.getModel();
        cbit.vcell.model.SpeciesContext[] speciesContexts = model.getSpeciesContexts();
        for (int i = 0; i < speciesContexts.length; i++) {
            ccImpl.addSimpleBound(new SimpleBounds(speciesContexts[i].getName(), new RealInterval(0, Double.POSITIVE_INFINITY), AbstractConstraint.PHYSICAL_LIMIT, "non-negative concentration"));
        }
        for (int i = 0; i < speciesContexts.length; i++) {
            SpeciesContextSpecParameter initParam = (simContext.getReactionContext().getSpeciesContextSpec(speciesContexts[i])).getInitialConditionParameter();
            if (initParam != null) {
                double initialValue = initParam.getExpression().evaluateConstant();
                ccImpl.addSimpleBound(new SimpleBounds(speciesContexts[i].getName(), new RealInterval(initialValue), AbstractConstraint.MODELING_ASSUMPTION, "specified \"initialCondition\""));
            }
        }
        // =========================
        // add modeling assumptions
        // =========================
        // 
        // mass action forward and reverse rates should be non-negative
        // 
        cbit.vcell.model.ReactionStep[] reactionSteps = model.getReactionSteps();
        for (int i = 0; i < reactionSteps.length; i++) {
            Kinetics kinetics = reactionSteps[i].getKinetics();
            if (kinetics instanceof MassActionKinetics) {
                Expression forwardRateConstraintExp = new Expression(((MassActionKinetics) kinetics).getForwardRateParameter().getExpression().infix() + ">=0");
                forwardRateConstraintExp = getSteadyStateExpression(forwardRateConstraintExp);
                if (!forwardRateConstraintExp.compareEqual(new Expression(1.0))) {
                    ccImpl.addGeneralConstraint(new GeneralConstraint(forwardRateConstraintExp, AbstractConstraint.MODELING_ASSUMPTION, "non-negative forward rate"));
                }
                Expression reverseRateConstraintExp = new Expression(((MassActionKinetics) kinetics).getReverseRateParameter().getExpression().infix() + ">=0");
                reverseRateConstraintExp = getSteadyStateExpression(reverseRateConstraintExp);
                if (!reverseRateConstraintExp.compareEqual(new Expression(1.0))) {
                    ccImpl.addGeneralConstraint(new GeneralConstraint(reverseRateConstraintExp, AbstractConstraint.MODELING_ASSUMPTION, "non-negative reverse rate"));
                }
            }
            KineticsParameter authoritativeParameter = kinetics.getAuthoritativeParameter();
            Expression kineticRateConstraintExp = new Expression(authoritativeParameter.getName() + "==" + authoritativeParameter.getExpression().infix());
            kineticRateConstraintExp = getSteadyStateExpression(kineticRateConstraintExp);
            if (!kineticRateConstraintExp.compareEqual(new Expression(1.0))) {
                ccImpl.addGeneralConstraint(new GeneralConstraint(kineticRateConstraintExp, AbstractConstraint.MODELING_ASSUMPTION, "definition"));
            }
        }
        // 
        for (int i = 0; i < reactionSteps.length; i++) {
            Kinetics kinetics = reactionSteps[i].getKinetics();
            Kinetics.KineticsParameter[] parameters = kinetics.getKineticsParameters();
            for (int j = 0; j < parameters.length; j++) {
                Expression exp = parameters[j].getExpression();
                if (exp.getSymbols() == null || exp.getSymbols().length == 0) {
                    // 
                    try {
                        double constantValue = exp.evaluateConstant();
                        RealInterval interval = new RealInterval(constantValue);
                        ccImpl.addSimpleBound(new SimpleBounds(parameters[j].getName(), interval, AbstractConstraint.MODELING_ASSUMPTION, "model value"));
                    } catch (cbit.vcell.parser.ExpressionException e) {
                        System.out.println("error evaluating parameter " + parameters[j].getName() + " in reaction step " + reactionSteps[i].getName());
                    }
                } else {
                    Expression parameterDefinitionExp = new Expression(parameters[j].getName() + "==" + parameters[j].getExpression().infix());
                    parameterDefinitionExp = getSteadyStateExpression(parameterDefinitionExp);
                    if (!parameterDefinitionExp.compareEqual(new Expression(1.0))) {
                        ccImpl.addGeneralConstraint(new GeneralConstraint(parameterDefinitionExp, AbstractConstraint.MODELING_ASSUMPTION, "parameter definition"));
                    }
                }
            }
        }
        ccImpl.addSimpleBound(new SimpleBounds(model.getFARADAY_CONSTANT().getName(), new RealInterval(model.getFARADAY_CONSTANT().getExpression().evaluateConstant()), AbstractConstraint.PHYSICAL_LIMIT, "Faraday's constant"));
        ccImpl.addSimpleBound(new SimpleBounds(model.getTEMPERATURE().getName(), new RealInterval(300), AbstractConstraint.PHYSICAL_LIMIT, "Absolute Temperature Kelvin"));
        ccImpl.addSimpleBound(new SimpleBounds(model.getGAS_CONSTANT().getName(), new RealInterval(model.getGAS_CONSTANT().getExpression().evaluateConstant()), AbstractConstraint.PHYSICAL_LIMIT, "ideal gas constant"));
        ccImpl.addSimpleBound(new SimpleBounds(model.getKMILLIVOLTS().getName(), new RealInterval(model.getKMILLIVOLTS().getExpression().evaluateConstant()), AbstractConstraint.PHYSICAL_LIMIT, "ideal gas constant"));
        return ccImpl;
    } catch (cbit.vcell.parser.ExpressionException e) {
        e.printStackTrace(System.out);
        return null;
    } catch (java.beans.PropertyVetoException e) {
        e.printStackTrace(System.out);
        return null;
    }
}
Also used : SimpleBounds(cbit.vcell.constraints.SimpleBounds) GeneralConstraint(cbit.vcell.constraints.GeneralConstraint) RealInterval(net.sourceforge.interval.ia_math.RealInterval) AbstractConstraint(cbit.vcell.constraints.AbstractConstraint) GeneralConstraint(cbit.vcell.constraints.GeneralConstraint) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) Expression(cbit.vcell.parser.Expression) ConstraintContainerImpl(cbit.vcell.constraints.ConstraintContainerImpl) MassActionKinetics(cbit.vcell.model.MassActionKinetics) MassActionKinetics(cbit.vcell.model.MassActionKinetics) Kinetics(cbit.vcell.model.Kinetics) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter)

Example 15 with SpeciesContextSpecParameter

use of cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter in project vcell by virtualcell.

the class SBMLExporter method addSpecies.

/**
 * addSpecies comment.
 * @throws XMLStreamException
 * @throws SbmlException
 */
protected void addSpecies() throws XMLStreamException, SbmlException {
    Model vcModel = vcBioModel.getModel();
    SpeciesContext[] vcSpeciesContexts = vcModel.getSpeciesContexts();
    for (int i = 0; i < vcSpeciesContexts.length; i++) {
        org.sbml.jsbml.Species sbmlSpecies = sbmlModel.createSpecies();
        sbmlSpecies.setId(vcSpeciesContexts[i].getName());
        // Assuming that at this point, the compartment(s) for the model are already filled in.
        Compartment compartment = sbmlModel.getCompartment(TokenMangler.mangleToSName(vcSpeciesContexts[i].getStructure().getName()));
        if (compartment != null) {
            sbmlSpecies.setCompartment(compartment.getId());
        }
        // 'hasSubstanceOnly' field will be 'false', since VC deals only with initial concentrations and not initial amounts.
        sbmlSpecies.setHasOnlySubstanceUnits(false);
        // Get (and set) the initial concentration value
        if (getSelectedSimContext() == null) {
            throw new RuntimeException("No simcontext (application) specified; Cannot proceed.");
        }
        // Get the speciesContextSpec in the simContext corresponding to the 'speciesContext'; and extract its initial concentration value.
        SpeciesContextSpec vcSpeciesContextsSpec = getSelectedSimContext().getReactionContext().getSpeciesContextSpec(vcSpeciesContexts[i]);
        // we need to convert concentration from uM -> molecules/um3; this can be achieved by dividing by KMOLE.
        try {
            sbmlSpecies.setInitialConcentration(vcSpeciesContextsSpec.getInitialConditionParameter().getExpression().evaluateConstant());
        } catch (cbit.vcell.parser.ExpressionException e) {
            // If exporting to L2V3, if species concentration is not an expr with x, y, z or other species, add as InitialAssignment, else complain.
            if (vcSpeciesContextsSpec.getInitialConditionParameter().getExpression() != null) {
                Expression initConcExpr = vcSpeciesContextsSpec.getInitialConditionParameter().getExpression();
                if ((sbmlLevel == 2 && sbmlVersion >= 3) || (sbmlLevel > 2)) {
                    // L2V3 and above - add expression as init assignment
                    ASTNode initAssgnMathNode = getFormulaFromExpression(initConcExpr);
                    InitialAssignment initAssignment = sbmlModel.createInitialAssignment();
                    initAssignment.setSymbol(vcSpeciesContexts[i].getName());
                    initAssignment.setMath(initAssgnMathNode);
                } else {
                    // L2V1 (or L1V2 also??)
                    // L2V1 (and L1V2?) and species is 'fixed' (constant), and not fn of x,y,z, other sp, add expr as assgn rule
                    ASTNode assgnRuleMathNode = getFormulaFromExpression(initConcExpr);
                    AssignmentRule assgnRule = sbmlModel.createAssignmentRule();
                    assgnRule.setVariable(vcSpeciesContexts[i].getName());
                    assgnRule.setMath(assgnRuleMathNode);
                }
            }
        }
        // Get (and set) the boundary condition value
        boolean bBoundaryCondition = getBoundaryCondition(vcSpeciesContexts[i]);
        sbmlSpecies.setBoundaryCondition(bBoundaryCondition);
        // mandatory for L3, optional for L2
        sbmlSpecies.setConstant(false);
        // set species substance units as 'molecules' - same as defined in the model; irrespective of it is in surface or volume.
        UnitDefinition unitDefn = getOrCreateSBMLUnit(sbmlExportSpec.getSubstanceUnits());
        sbmlSpecies.setSubstanceUnits(unitDefn);
        // need to do the following if exporting to SBML spatial
        if (bSpatial) {
            // Required for setting BoundaryConditions : structureMapping for vcSpeciesContext[i] & sbmlGeometry.coordinateComponents
            StructureMapping sm = getSelectedSimContext().getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure());
            SpatialModelPlugin mplugin = (SpatialModelPlugin) sbmlModel.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
            org.sbml.jsbml.ext.spatial.Geometry sbmlGeometry = mplugin.getGeometry();
            CoordinateComponent ccX = sbmlGeometry.getListOfCoordinateComponents().get(vcModel.getX().getName());
            CoordinateComponent ccY = sbmlGeometry.getListOfCoordinateComponents().get(vcModel.getY().getName());
            CoordinateComponent ccZ = sbmlGeometry.getListOfCoordinateComponents().get(vcModel.getZ().getName());
            // add diffusion, advection, boundary condition parameters for species, if they exist
            Parameter[] scsParams = vcSpeciesContextsSpec.getParameters();
            if (scsParams != null) {
                for (int j = 0; j < scsParams.length; j++) {
                    if (scsParams[j] != null) {
                        SpeciesContextSpecParameter scsParam = (SpeciesContextSpecParameter) scsParams[j];
                        // no need to add parameters in SBML for init conc or init count
                        int role = scsParam.getRole();
                        switch(role) {
                            case SpeciesContextSpec.ROLE_BoundaryValueXm:
                                {
                                    break;
                                }
                            case SpeciesContextSpec.ROLE_BoundaryValueXp:
                                {
                                    break;
                                }
                            case SpeciesContextSpec.ROLE_BoundaryValueYm:
                                {
                                    break;
                                }
                            case SpeciesContextSpec.ROLE_BoundaryValueYp:
                                {
                                    break;
                                }
                            case SpeciesContextSpec.ROLE_BoundaryValueZm:
                                {
                                    break;
                                }
                            case SpeciesContextSpec.ROLE_BoundaryValueZp:
                                {
                                    break;
                                }
                            case SpeciesContextSpec.ROLE_DiffusionRate:
                                {
                                    break;
                                }
                            case SpeciesContextSpec.ROLE_InitialConcentration:
                                {
                                    // done elsewhere??
                                    continue;
                                // break;
                                }
                            case SpeciesContextSpec.ROLE_InitialCount:
                                {
                                    // done elsewhere??
                                    continue;
                                // break;
                                }
                            case SpeciesContextSpec.ROLE_VelocityX:
                                {
                                    break;
                                }
                            case SpeciesContextSpec.ROLE_VelocityY:
                                {
                                    break;
                                }
                            case SpeciesContextSpec.ROLE_VelocityZ:
                                {
                                    break;
                                }
                            default:
                                {
                                    throw new RuntimeException("SpeciesContext Specification parameter with role " + SpeciesContextSpec.RoleNames[role] + " not yet supported for SBML export");
                                }
                        }
                        // if diffusion is 0 && vel terms are not specified, boundary condition not present
                        if (vcSpeciesContextsSpec.isAdvecting() || vcSpeciesContextsSpec.isDiffusing()) {
                            Expression diffExpr = vcSpeciesContextsSpec.getDiffusionParameter().getExpression();
                            boolean bDiffExprNull = (diffExpr == null);
                            boolean bDiffExprIsZero = false;
                            if (!bDiffExprNull && diffExpr.isNumeric()) {
                                try {
                                    bDiffExprIsZero = (diffExpr.evaluateConstant() == 0.0);
                                } catch (Exception e) {
                                    e.printStackTrace(System.out);
                                    throw new RuntimeException("Unable to evalute numeric value of diffusion parameter for speciesContext '" + vcSpeciesContexts[i] + "'.");
                                }
                            }
                            boolean bDiffusionZero = (bDiffExprNull || bDiffExprIsZero);
                            Expression velX_Expr = vcSpeciesContextsSpec.getVelocityXParameter().getExpression();
                            SpatialQuantity[] velX_Quantities = vcSpeciesContextsSpec.getVelocityQuantities(QuantityComponent.X);
                            boolean bVelX_ExprIsNull = (velX_Expr == null && velX_Quantities.length == 0);
                            Expression velY_Expr = vcSpeciesContextsSpec.getVelocityYParameter().getExpression();
                            SpatialQuantity[] velY_Quantities = vcSpeciesContextsSpec.getVelocityQuantities(QuantityComponent.Y);
                            boolean bVelY_ExprIsNull = (velY_Expr == null && velY_Quantities.length == 0);
                            Expression velZ_Expr = vcSpeciesContextsSpec.getVelocityZParameter().getExpression();
                            SpatialQuantity[] velZ_Quantities = vcSpeciesContextsSpec.getVelocityQuantities(QuantityComponent.Z);
                            boolean bVelZ_ExprIsNull = (velZ_Expr == null && velZ_Quantities.length == 0);
                            boolean bAdvectionNull = (bVelX_ExprIsNull && bVelY_ExprIsNull && bVelZ_ExprIsNull);
                            if (bDiffusionZero && bAdvectionNull) {
                                continue;
                            }
                        }
                        // for example, if scsParam is BC_Zm and if coordinateComponent 'ccZ' is null, no SBML parameter should be created for BC_Zm
                        if ((((role == SpeciesContextSpec.ROLE_BoundaryValueXm) || (role == SpeciesContextSpec.ROLE_BoundaryValueXp)) && (ccX == null)) || (((role == SpeciesContextSpec.ROLE_BoundaryValueYm) || (role == SpeciesContextSpec.ROLE_BoundaryValueYp)) && (ccY == null)) || (((role == SpeciesContextSpec.ROLE_BoundaryValueZm) || (role == SpeciesContextSpec.ROLE_BoundaryValueZp)) && (ccZ == null))) {
                            continue;
                        }
                        org.sbml.jsbml.Parameter sbmlParam = createSBMLParamFromSpeciesParam(vcSpeciesContexts[i], (SpeciesContextSpecParameter) scsParams[j]);
                        if (sbmlParam != null) {
                            BoundaryConditionType vcBCType_Xm = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeXm();
                            BoundaryConditionType vcBCType_Xp = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeXp();
                            BoundaryConditionType vcBCType_Ym = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeYm();
                            BoundaryConditionType vcBCType_Yp = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeYp();
                            BoundaryConditionType vcBCType_Zm = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeZm();
                            BoundaryConditionType vcBCType_Zp = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeZp();
                            SpatialParameterPlugin spplugin = (SpatialParameterPlugin) sbmlParam.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
                            if (role == SpeciesContextSpec.ROLE_DiffusionRate) {
                                // set diffusionCoefficient element in SpatialParameterPlugin for param
                                DiffusionCoefficient sbmlDiffCoeff = new DiffusionCoefficient();
                                sbmlDiffCoeff.setVariable(vcSpeciesContexts[i].getName());
                                sbmlDiffCoeff.setDiffusionKind(DiffusionKind.isotropic);
                                sbmlDiffCoeff.setSpeciesRef(vcSpeciesContexts[i].getName());
                                spplugin.setParamType(sbmlDiffCoeff);
                            }
                            if ((role == SpeciesContextSpec.ROLE_BoundaryValueXm) && (ccX != null)) {
                                // set BoundaryCondn Xm element in SpatialParameterPlugin for param
                                BoundaryCondition sbmlBCXm = new BoundaryCondition();
                                spplugin.setParamType(sbmlBCXm);
                                sbmlBCXm.setType(getBoundaryConditionKind(vcBCType_Xm));
                                sbmlBCXm.setVariable(vcSpeciesContexts[i].getName());
                                sbmlBCXm.setCoordinateBoundary(ccX.getBoundaryMinimum().getId());
                            }
                            if ((role == SpeciesContextSpec.ROLE_BoundaryValueXp) && (ccX != null)) {
                                // set BoundaryCondn Xp element in SpatialParameterPlugin for param
                                BoundaryCondition sbmlBCXp = new BoundaryCondition();
                                spplugin.setParamType(sbmlBCXp);
                                sbmlBCXp.setType(getBoundaryConditionKind(vcBCType_Xp));
                                sbmlBCXp.setVariable(vcSpeciesContexts[i].getName());
                                sbmlBCXp.setType(sm.getBoundaryConditionTypeXp().boundaryTypeStringValue());
                                sbmlBCXp.setCoordinateBoundary(ccX.getBoundaryMaximum().getId());
                            }
                            if ((role == SpeciesContextSpec.ROLE_BoundaryValueYm) && (ccY != null)) {
                                // set BoundaryCondn Ym element in SpatialParameterPlugin for param
                                BoundaryCondition sbmlBCYm = new BoundaryCondition();
                                spplugin.setParamType(sbmlBCYm);
                                sbmlBCYm.setType(getBoundaryConditionKind(vcBCType_Yp));
                                sbmlBCYm.setVariable(vcSpeciesContexts[i].getName());
                                sbmlBCYm.setType(sm.getBoundaryConditionTypeYm().boundaryTypeStringValue());
                                sbmlBCYm.setCoordinateBoundary(ccY.getBoundaryMinimum().getId());
                            }
                            if ((role == SpeciesContextSpec.ROLE_BoundaryValueYp) && (ccY != null)) {
                                // set BoundaryCondn Yp element in SpatialParameterPlugin for param
                                BoundaryCondition sbmlBCYp = new BoundaryCondition();
                                spplugin.setParamType(sbmlBCYp);
                                sbmlBCYp.setType(getBoundaryConditionKind(vcBCType_Yp));
                                sbmlBCYp.setVariable(vcSpeciesContexts[i].getName());
                                sbmlBCYp.setType(sm.getBoundaryConditionTypeYp().boundaryTypeStringValue());
                                sbmlBCYp.setCoordinateBoundary(ccY.getBoundaryMaximum().getId());
                            }
                            if ((role == SpeciesContextSpec.ROLE_BoundaryValueZm) && (ccZ != null)) {
                                // set BoundaryCondn Zm element in SpatialParameterPlugin for param
                                BoundaryCondition sbmlBCZm = new BoundaryCondition();
                                spplugin.setParamType(sbmlBCZm);
                                sbmlBCZm.setType(getBoundaryConditionKind(vcBCType_Zm));
                                sbmlBCZm.setVariable(vcSpeciesContexts[i].getName());
                                sbmlBCZm.setType(sm.getBoundaryConditionTypeZm().boundaryTypeStringValue());
                                sbmlBCZm.setCoordinateBoundary(ccZ.getBoundaryMinimum().getId());
                            }
                            if ((role == SpeciesContextSpec.ROLE_BoundaryValueZp) && (ccZ != null)) {
                                // set BoundaryCondn Zp element in SpatialParameterPlugin for param
                                BoundaryCondition sbmlBCZp = new BoundaryCondition();
                                spplugin.setParamType(sbmlBCZp);
                                sbmlBCZp.setType(getBoundaryConditionKind(vcBCType_Zp));
                                sbmlBCZp.setVariable(vcSpeciesContexts[i].getName());
                                sbmlBCZp.setType(sm.getBoundaryConditionTypeZp().boundaryTypeStringValue());
                                sbmlBCZp.setCoordinateBoundary(ccZ.getBoundaryMaximum().getId());
                            }
                            if (role == SpeciesContextSpec.ROLE_VelocityX) {
                                // set advectionCoeff X element in SpatialParameterPlugin for param
                                AdvectionCoefficient sbmlAdvCoeffX = new AdvectionCoefficient();
                                spplugin.setParamType(sbmlAdvCoeffX);
                                sbmlAdvCoeffX.setVariable(vcSpeciesContexts[i].getName());
                                sbmlAdvCoeffX.setCoordinate(CoordinateKind.cartesianX);
                            }
                            if (role == SpeciesContextSpec.ROLE_VelocityY) {
                                // set advectionCoeff Y element in SpatialParameterPlugin for param
                                AdvectionCoefficient sbmlAdvCoeffY = new AdvectionCoefficient();
                                spplugin.setParamType(sbmlAdvCoeffY);
                                sbmlAdvCoeffY.setVariable(vcSpeciesContexts[i].getName());
                                sbmlAdvCoeffY.setCoordinate(CoordinateKind.cartesianY);
                            }
                            if (role == SpeciesContextSpec.ROLE_VelocityZ) {
                                // set advectionCoeff Z element in SpatialParameterPlugin for param
                                AdvectionCoefficient sbmlAdvCoeffZ = new AdvectionCoefficient();
                                spplugin.setParamType(sbmlAdvCoeffZ);
                                sbmlAdvCoeffZ.setVariable(vcSpeciesContexts[i].getName());
                                sbmlAdvCoeffZ.setCoordinate(CoordinateKind.cartesianZ);
                            }
                        }
                    // if sbmlParam != null
                    }
                // if scsParams[j] != null
                }
            // end for scsParams
            }
        // end scsParams != null
        }
        // end if (bSpatial)
        // Add the common name of species to annotation, and add an annotation element to the species.
        // This is required later while trying to read in fluxes ...
        // new Element(XMLTags.VCellRelatedInfoTag, sbml_vcml_ns);
        Element sbmlImportRelatedElement = null;
        // Element speciesElement = new Element(XMLTags.SpeciesTag, sbml_vcml_ns);
        // speciesElement.setAttribute(XMLTags.NameAttrTag, TokenMangler.mangleToSName(vcSpeciesContexts[i].getSpecies().getCommonName()));
        // sbmlImportRelatedElement.addContent(speciesElement);
        // Get RDF annotation for species from SBMLAnnotationUtils
        sbmlAnnotationUtil.writeAnnotation(vcSpeciesContexts[i].getSpecies(), sbmlSpecies, sbmlImportRelatedElement);
        // Now set notes,
        sbmlAnnotationUtil.writeNotes(vcSpeciesContexts[i].getSpecies(), sbmlSpecies);
    }
}
Also used : Compartment(org.sbml.jsbml.Compartment) Element(org.jdom.Element) BoundaryConditionType(cbit.vcell.math.BoundaryConditionType) SpatialParameterPlugin(org.sbml.jsbml.ext.spatial.SpatialParameterPlugin) SpeciesContext(cbit.vcell.model.SpeciesContext) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) StructureMapping(cbit.vcell.mapping.StructureMapping) ASTNode(org.sbml.jsbml.ASTNode) SpatialQuantity(cbit.vcell.mapping.spatial.SpatialObject.SpatialQuantity) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) UnitDefinition(org.sbml.jsbml.UnitDefinition) CoordinateComponent(org.sbml.jsbml.ext.spatial.CoordinateComponent) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) AdvectionCoefficient(org.sbml.jsbml.ext.spatial.AdvectionCoefficient) AssignmentRule(org.sbml.jsbml.AssignmentRule) SpatialModelPlugin(org.sbml.jsbml.ext.spatial.SpatialModelPlugin) ExpressionException(cbit.vcell.parser.ExpressionException) DiffusionCoefficient(org.sbml.jsbml.ext.spatial.DiffusionCoefficient) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) ImageException(cbit.image.ImageException) SBMLException(org.sbml.jsbml.SBMLException) ExpressionException(cbit.vcell.parser.ExpressionException) InitialAssignment(org.sbml.jsbml.InitialAssignment) Expression(cbit.vcell.parser.Expression) BoundaryCondition(org.sbml.jsbml.ext.spatial.BoundaryCondition) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) StructureMappingParameter(cbit.vcell.mapping.StructureMapping.StructureMappingParameter) Parameter(cbit.vcell.model.Parameter) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter)

Aggregations

SpeciesContextSpecParameter (cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter)16 Expression (cbit.vcell.parser.Expression)10 KineticsParameter (cbit.vcell.model.Kinetics.KineticsParameter)9 ModelParameter (cbit.vcell.model.Model.ModelParameter)8 SpeciesContext (cbit.vcell.model.SpeciesContext)8 SpeciesContextSpec (cbit.vcell.mapping.SpeciesContextSpec)7 VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)7 StructureMappingParameter (cbit.vcell.mapping.StructureMapping.StructureMappingParameter)6 Model (cbit.vcell.model.Model)6 Parameter (cbit.vcell.model.Parameter)6 Structure (cbit.vcell.model.Structure)6 CompartmentSubDomain (cbit.vcell.math.CompartmentSubDomain)4 MathDescription (cbit.vcell.math.MathDescription)4 Variable (cbit.vcell.math.Variable)4 ModelUnitSystem (cbit.vcell.model.ModelUnitSystem)4 ReactionStep (cbit.vcell.model.ReactionStep)4 SymbolTableEntry (cbit.vcell.parser.SymbolTableEntry)4 ArrayList (java.util.ArrayList)4 ScopedExpression (cbit.gui.ScopedExpression)3 GeometryClass (cbit.vcell.geometry.GeometryClass)3