Search in sources :

Example 11 with MassActionKinetics

use of cbit.vcell.model.MassActionKinetics 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 12 with MassActionKinetics

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

the class BNGOutputPanel method getCollapsedReactionSteps.

private ReactionStep[] getCollapsedReactionSteps(ReactionStep[] reactionSteps) {
    Vector<ReactionStep> collapsedRxnStepsVector = new Vector<ReactionStep>();
    Vector<ReactionStep> rxnStepsVector = new Vector<ReactionStep>();
    for (int i = 0; i < reactionSteps.length; i++) {
        rxnStepsVector.addElement(reactionSteps[i]);
    }
    for (int i = 0; i < rxnStepsVector.size(); i++) {
        ReactionStep fwdRStep = rxnStepsVector.elementAt(i);
        // Get the reactionParticipants and the corresponding reactants and products in an array
        ReactionParticipant[] rps = fwdRStep.getReactionParticipants();
        Vector<SpeciesContext> fwdReactantsVector = new Vector<SpeciesContext>();
        Vector<SpeciesContext> fwdProductsVector = new Vector<SpeciesContext>();
        for (int j = 0; j < rps.length; j++) {
            if (rps[j] instanceof Reactant) {
                fwdReactantsVector.addElement(rps[j].getSpeciesContext());
            } else if (rps[j] instanceof Product) {
                fwdProductsVector.addElement(rps[j].getSpeciesContext());
            }
        }
        SpeciesContext[] fwdReactants = (SpeciesContext[]) BeanUtils.getArray(fwdReactantsVector, SpeciesContext.class);
        SpeciesContext[] fwdProducts = (SpeciesContext[]) BeanUtils.getArray(fwdProductsVector, SpeciesContext.class);
        boolean bReverseReactionFound = false;
        // Loop through all the reactions to find the corresponding reverse reaction
        for (int ii = 0; ii < reactionSteps.length; ii++) {
            ReactionStep revRStep = reactionSteps[ii];
            // Get the reactionParticipants and the corresponding reactants and products in an array
            ReactionParticipant[] revRps = revRStep.getReactionParticipants();
            Vector<SpeciesContext> revReactantsVector = new Vector<SpeciesContext>();
            Vector<SpeciesContext> revProductsVector = new Vector<SpeciesContext>();
            for (int j = 0; j < revRps.length; j++) {
                if (revRps[j] instanceof Reactant) {
                    revReactantsVector.addElement(revRps[j].getSpeciesContext());
                } else if (revRps[j] instanceof Product) {
                    revProductsVector.addElement(revRps[j].getSpeciesContext());
                }
            }
            SpeciesContext[] revReactants = (SpeciesContext[]) BeanUtils.getArray(revReactantsVector, SpeciesContext.class);
            SpeciesContext[] revProducts = (SpeciesContext[]) BeanUtils.getArray(revProductsVector, SpeciesContext.class);
            // Check if reactants of reaction in outer 'for' loop match products in inner 'for' loop and vice versa.
            if (BeanUtils.arrayEquals(fwdReactants, revProducts) && BeanUtils.arrayEquals(fwdProducts, revReactants)) {
                // Set the reverse kinetic rate expression for the reaction in outer loop with the forward rate from reactionStep in inner loop
                // inner 'for' loop
                MassActionKinetics revMAKinetics = (MassActionKinetics) revRStep.getKinetics();
                // outer 'for' loop
                MassActionKinetics fwdMAKinetics = (MassActionKinetics) fwdRStep.getKinetics();
                try {
                    fwdMAKinetics.setParameterValue(fwdMAKinetics.getReverseRateParameter(), revMAKinetics.getForwardRateParameter().getExpression());
                    Kinetics.KineticsParameter param = revMAKinetics.getKineticsParameter(revMAKinetics.getForwardRateParameter().getExpression().infix());
                    fwdMAKinetics.setParameterValue(param, param.getExpression());
                } catch (Exception e) {
                    e.printStackTrace(System.out);
                    throw new RuntimeException(e.getMessage());
                }
                // Add this to the collapsedRxnStepsVector
                collapsedRxnStepsVector.addElement(fwdRStep);
                rxnStepsVector.removeElement(revRStep);
                bReverseReactionFound = true;
                break;
            }
        }
        // Add it as is to the 'collapsedRxnStepsVector'
        if (!bReverseReactionFound) {
            collapsedRxnStepsVector.addElement(fwdRStep);
        }
    }
    // Convert the vector into an array of reactionSteps and return
    ReactionStep[] collapsedRxnSteps = (ReactionStep[]) BeanUtils.getArray(collapsedRxnStepsVector, ReactionStep.class);
    return collapsedRxnSteps;
}
Also used : Product(cbit.vcell.model.Product) SpeciesContext(cbit.vcell.model.SpeciesContext) Reactant(cbit.vcell.model.Reactant) SbmlTransformException(cbit.vcell.xml.sbml_transform.SbmlTransformException) IOException(java.io.IOException) ReactionStep(cbit.vcell.model.ReactionStep) MassActionKinetics(cbit.vcell.model.MassActionKinetics) Kinetics(cbit.vcell.model.Kinetics) MassActionKinetics(cbit.vcell.model.MassActionKinetics) Vector(java.util.Vector) ReactionParticipant(cbit.vcell.model.ReactionParticipant)

Example 13 with MassActionKinetics

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

the class XmlReader method getKinetics.

/**
 * This method returns a Kinetics object from a XML Element based on the value of the kinetics type attribute.
 * Creation date: (3/19/2001 4:42:04 PM)
 * @return cbit.vcell.model.Kinetics
 * @param param org.jdom.Element
 */
private Kinetics getKinetics(Element param, ReactionStep reaction, Model model) throws XmlParseException {
    VariableHash varHash = new VariableHash();
    addResevedSymbols(varHash, model);
    String type = param.getAttributeValue(XMLTags.KineticsTypeAttrTag);
    Kinetics newKinetics = null;
    try {
        if (type.equalsIgnoreCase(XMLTags.KineticsTypeGeneralKinetics)) {
            // create a general kinetics
            newKinetics = new GeneralKinetics(reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeGeneralCurrentKinetics)) {
            // Create GeneralCurrentKinetics
            newKinetics = new GeneralCurrentKinetics(reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeMassAction) && reaction instanceof SimpleReaction) {
            // create a Mass Action kinetics
            newKinetics = new MassActionKinetics((SimpleReaction) reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeNernst) && reaction instanceof FluxReaction) {
            // create NernstKinetics
            newKinetics = new NernstKinetics((FluxReaction) reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeGHK) && reaction instanceof FluxReaction) {
            // create GHKKinetics
            newKinetics = new GHKKinetics((FluxReaction) reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeHMM_Irr) && reaction instanceof SimpleReaction) {
            // create HMM_IrrKinetics
            newKinetics = new HMM_IRRKinetics((SimpleReaction) reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeHMM_Rev) && reaction instanceof SimpleReaction) {
            // create HMM_RevKinetics
            newKinetics = new HMM_REVKinetics((SimpleReaction) reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeGeneralTotal_oldname)) {
            // create GeneralTotalKinetics
            newKinetics = new GeneralLumpedKinetics(reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeGeneralLumped)) {
            // create GeneralLumpedKinetics
            newKinetics = new GeneralLumpedKinetics(reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeGeneralCurrentLumped)) {
            // create GeneralCurrentLumpedKinetics
            newKinetics = new GeneralCurrentLumpedKinetics(reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeGeneralPermeability) && reaction instanceof FluxReaction) {
            // create GeneralPermeabilityKinetics
            newKinetics = new GeneralPermeabilityKinetics((FluxReaction) reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeMacroscopic_Irr) && reaction instanceof SimpleReaction) {
            // create Macroscopic_IRRKinetics
            newKinetics = new Macroscopic_IRRKinetics((SimpleReaction) reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeMicroscopic_Irr) && reaction instanceof SimpleReaction) {
            // create Microscopic_IRRKinetics
            newKinetics = new Microscopic_IRRKinetics((SimpleReaction) reaction);
        } else {
            throw new XmlParseException("Unknown kinetics type: " + type);
        }
    } catch (ExpressionException e) {
        e.printStackTrace();
        throw new XmlParseException("Error creating the kinetics for reaction: " + reaction.getName(), e);
    }
    try {
        // transaction begin flag ... yeah, this is a hack
        newKinetics.reading(true);
        // Read all of the parameters
        List<Element> list = param.getChildren(XMLTags.ParameterTag, vcNamespace);
        // add constants that may be used in kinetics.
        // VariableHash varHash = getVariablesHash();
        ArrayList<String> reserved = new ArrayList<String>();
        ReservedSymbol[] reservedSymbols = reaction.getModel().getReservedSymbols();
        for (ReservedSymbol rs : reservedSymbols) {
            reserved.add(rs.getName());
        }
        try {
            if (reaction.getStructure() instanceof Membrane) {
                Membrane membrane = (Membrane) reaction.getStructure();
                varHash.addVariable(new Constant(membrane.getMembraneVoltage().getName(), new Expression(0.0)));
                reserved.add(membrane.getMembraneVoltage().getName());
            }
            // 
            // add Reactants, Products, and Catalysts (ReactionParticipants)
            // 
            ReactionParticipant[] rp = reaction.getReactionParticipants();
            for (int i = 0; i < rp.length; i++) {
                varHash.addVariable(new Constant(rp[i].getName(), new Expression(0.0)));
            }
        } catch (MathException e) {
            e.printStackTrace(System.out);
            throw new XmlParseException("error reordering parameters according to dependencies: ", e);
        }
        // 
        for (Element xmlParam : list) {
            String paramName = unMangle(xmlParam.getAttributeValue(XMLTags.NameAttrTag));
            String role = xmlParam.getAttributeValue(XMLTags.ParamRoleAttrTag);
            String paramExpStr = xmlParam.getText();
            Expression paramExp = unMangleExpression(paramExpStr);
            try {
                if (varHash.getVariable(paramName) == null) {
                    varHash.addVariable(new Function(paramName, paramExp, null));
                } else {
                    if (reserved.contains(paramName)) {
                        varHash.removeVariable(paramName);
                        varHash.addVariable(new Function(paramName, paramExp, null));
                    }
                }
            } catch (MathException e) {
                e.printStackTrace(System.out);
                throw new XmlParseException("error reordering parameters according to dependencies: ", e);
            }
            Kinetics.KineticsParameter tempParam = null;
            if (!role.equals(XMLTags.ParamRoleUserDefinedTag)) {
                tempParam = newKinetics.getKineticsParameterFromRole(Kinetics.getParamRoleFromDefaultDesc(role));
            } else {
                continue;
            }
            // hack for bringing in General Total kinetics without breaking.
            if (tempParam == null && newKinetics instanceof GeneralLumpedKinetics) {
                if (role.equals(Kinetics.GTK_AssumedCompartmentSize_oldname) || role.equals(Kinetics.GTK_ReactionRate_oldname) || role.equals(Kinetics.GTK_CurrentDensity_oldname)) {
                    continue;
                } else if (role.equals(VCMODL.TotalRate_oldname)) {
                    tempParam = newKinetics.getKineticsParameterFromRole(Kinetics.ROLE_LumpedReactionRate);
                }
            }
            // hack from bringing in chargeValence parameters without breaking
            if (tempParam == null && Kinetics.getParamRoleFromDefaultDesc(role) == Kinetics.ROLE_ChargeValence) {
                tempParam = newKinetics.getChargeValenceParameter();
            }
            if (tempParam == null) {
                throw new XmlParseException("parameter with role '" + role + "' not found in kinetics type '" + type + "'");
            }
            // 
            if (!tempParam.getName().equals(paramName)) {
                Kinetics.KineticsParameter multNameParam = newKinetics.getKineticsParameter(paramName);
                int n = 0;
                while (multNameParam != null) {
                    String tempName = paramName + "_" + n++;
                    newKinetics.renameParameter(paramName, tempName);
                    multNameParam = newKinetics.getKineticsParameter(tempName);
                }
                newKinetics.renameParameter(tempParam.getName(), paramName);
            }
        }
        // 
        // create unresolved parameters for all unresolved symbols
        // 
        String unresolvedSymbol = varHash.getFirstUnresolvedSymbol();
        while (unresolvedSymbol != null) {
            try {
                // will turn into an UnresolvedParameter.
                varHash.addVariable(new Function(unresolvedSymbol, new Expression(0.0), null));
            } catch (MathException e) {
                e.printStackTrace(System.out);
                throw new XmlParseException(e);
            }
            newKinetics.addUnresolvedParameter(unresolvedSymbol);
            unresolvedSymbol = varHash.getFirstUnresolvedSymbol();
        }
        Variable[] sortedVariables = varHash.getTopologicallyReorderedVariables();
        ModelUnitSystem modelUnitSystem = reaction.getModel().getUnitSystem();
        for (int i = sortedVariables.length - 1; i >= 0; i--) {
            if (sortedVariables[i] instanceof Function) {
                Function paramFunction = (Function) sortedVariables[i];
                Element xmlParam = null;
                for (int j = 0; j < list.size(); j++) {
                    Element tempParam = (Element) list.get(j);
                    if (paramFunction.getName().equals(unMangle(tempParam.getAttributeValue(XMLTags.NameAttrTag)))) {
                        xmlParam = tempParam;
                        break;
                    }
                }
                if (xmlParam == null) {
                    // must have been an unresolved parameter
                    continue;
                }
                String symbol = xmlParam.getAttributeValue(XMLTags.VCUnitDefinitionAttrTag);
                VCUnitDefinition unit = null;
                if (symbol != null) {
                    unit = modelUnitSystem.getInstance(symbol);
                }
                Kinetics.KineticsParameter tempParam = newKinetics.getKineticsParameter(paramFunction.getName());
                if (tempParam == null) {
                    newKinetics.addUserDefinedKineticsParameter(paramFunction.getName(), paramFunction.getExpression(), unit);
                } else {
                    newKinetics.setParameterValue(tempParam, paramFunction.getExpression());
                    tempParam.setUnitDefinition(unit);
                }
            }
        }
    } catch (java.beans.PropertyVetoException e) {
        e.printStackTrace(System.out);
        throw new XmlParseException("Exception while setting parameters for Reaction : " + reaction.getName(), e);
    } catch (ExpressionException e) {
        e.printStackTrace(System.out);
        throw new XmlParseException("Exception while settings parameters for Reaction : " + reaction.getName(), e);
    } finally {
        newKinetics.reading(false);
    }
    return newKinetics;
}
Also used : FilamentVariable(cbit.vcell.math.FilamentVariable) OutsideVariable(cbit.vcell.math.OutsideVariable) StochVolVariable(cbit.vcell.math.StochVolVariable) RandomVariable(cbit.vcell.math.RandomVariable) VolumeRandomVariable(cbit.vcell.math.VolumeRandomVariable) VolumeParticleVariable(cbit.vcell.math.VolumeParticleVariable) VolumeRegionVariable(cbit.vcell.math.VolumeRegionVariable) InsideVariable(cbit.vcell.math.InsideVariable) VolVariable(cbit.vcell.math.VolVariable) MembraneRegionVariable(cbit.vcell.math.MembraneRegionVariable) PointVariable(cbit.vcell.math.PointVariable) MembraneRandomVariable(cbit.vcell.math.MembraneRandomVariable) MembraneParticleVariable(cbit.vcell.math.MembraneParticleVariable) ParticleVariable(cbit.vcell.math.ParticleVariable) MemVariable(cbit.vcell.math.MemVariable) FilamentRegionVariable(cbit.vcell.math.FilamentRegionVariable) Variable(cbit.vcell.math.Variable) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) VariableHash(cbit.vcell.math.VariableHash) HMM_IRRKinetics(cbit.vcell.model.HMM_IRRKinetics) MacroscopicRateConstant(cbit.vcell.math.MacroscopicRateConstant) Constant(cbit.vcell.math.Constant) Element(org.jdom.Element) ReservedSymbol(cbit.vcell.model.Model.ReservedSymbol) NernstKinetics(cbit.vcell.model.NernstKinetics) ArrayList(java.util.ArrayList) FluxReaction(cbit.vcell.model.FluxReaction) GeneralKinetics(cbit.vcell.model.GeneralKinetics) GeneralLumpedKinetics(cbit.vcell.model.GeneralLumpedKinetics) ExpressionException(cbit.vcell.parser.ExpressionException) PropertyVetoException(java.beans.PropertyVetoException) GeneralCurrentKinetics(cbit.vcell.model.GeneralCurrentKinetics) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) Function(cbit.vcell.math.Function) GeneralCurrentLumpedKinetics(cbit.vcell.model.GeneralCurrentLumpedKinetics) Membrane(cbit.vcell.model.Membrane) Macroscopic_IRRKinetics(cbit.vcell.model.Macroscopic_IRRKinetics) GeneralPermeabilityKinetics(cbit.vcell.model.GeneralPermeabilityKinetics) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem) SimpleReaction(cbit.vcell.model.SimpleReaction) GHKKinetics(cbit.vcell.model.GHKKinetics) HMM_REVKinetics(cbit.vcell.model.HMM_REVKinetics) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) MathException(cbit.vcell.math.MathException) MassActionKinetics(cbit.vcell.model.MassActionKinetics) Macroscopic_IRRKinetics(cbit.vcell.model.Macroscopic_IRRKinetics) Kinetics(cbit.vcell.model.Kinetics) NernstKinetics(cbit.vcell.model.NernstKinetics) GeneralKinetics(cbit.vcell.model.GeneralKinetics) GeneralLumpedKinetics(cbit.vcell.model.GeneralLumpedKinetics) GeneralPermeabilityKinetics(cbit.vcell.model.GeneralPermeabilityKinetics) GHKKinetics(cbit.vcell.model.GHKKinetics) MassActionKinetics(cbit.vcell.model.MassActionKinetics) Microscopic_IRRKinetics(cbit.vcell.model.Microscopic_IRRKinetics) GeneralCurrentKinetics(cbit.vcell.model.GeneralCurrentKinetics) HMM_REVKinetics(cbit.vcell.model.HMM_REVKinetics) HMM_IRRKinetics(cbit.vcell.model.HMM_IRRKinetics) GeneralCurrentLumpedKinetics(cbit.vcell.model.GeneralCurrentLumpedKinetics) Microscopic_IRRKinetics(cbit.vcell.model.Microscopic_IRRKinetics) ReactionParticipant(cbit.vcell.model.ReactionParticipant)

Example 14 with MassActionKinetics

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

the class ReactionPropertiesPanel method setReversible.

private void setReversible(boolean bReversible) {
    reactionStep.setReversible(bReversible);
    if (reactionStep.getKinetics() instanceof MassActionKinetics) {
        KineticsParameter kp = reactionStep.getKinetics().getKineticsParameterFromRole(Kinetics.ROLE_KReverse);
        kp.setExpression(new Expression(0.0d));
    }
    getParameterTableModel().refreshData();
}
Also used : KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) Expression(cbit.vcell.parser.Expression) MassActionKinetics(cbit.vcell.model.MassActionKinetics)

Example 15 with MassActionKinetics

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

the class FRAPStudy method createNewSimBioModel.

public static BioModel createNewSimBioModel(FRAPStudy sourceFrapStudy, Parameter[] params, TimeStep tStep, KeyValue simKey, User owner, int startingIndexForRecovery) throws Exception {
    if (owner == null) {
        throw new Exception("Owner is not defined");
    }
    ROI cellROI_2D = sourceFrapStudy.getFrapData().getRoi(FRAPData.VFRAP_ROI_ENUM.ROI_CELL.name());
    double df = params[FRAPModel.INDEX_PRIMARY_DIFF_RATE].getInitialGuess();
    double ff = params[FRAPModel.INDEX_PRIMARY_FRACTION].getInitialGuess();
    double bwmRate = params[FRAPModel.INDEX_BLEACH_MONITOR_RATE].getInitialGuess();
    double dc = 0;
    double fc = 0;
    double bs = 0;
    double onRate = 0;
    double offRate = 0;
    if (params.length == FRAPModel.NUM_MODEL_PARAMETERS_TWO_DIFF) {
        dc = params[FRAPModel.INDEX_SECONDARY_DIFF_RATE].getInitialGuess();
        fc = params[FRAPModel.INDEX_SECONDARY_FRACTION].getInitialGuess();
    } else if (params.length == FRAPModel.NUM_MODEL_PARAMETERS_BINDING) {
        dc = params[FRAPModel.INDEX_SECONDARY_DIFF_RATE].getInitialGuess();
        fc = params[FRAPModel.INDEX_SECONDARY_FRACTION].getInitialGuess();
        bs = params[FRAPModel.INDEX_BINDING_SITE_CONCENTRATION].getInitialGuess();
        onRate = params[FRAPModel.INDEX_ON_RATE].getInitialGuess();
        offRate = params[FRAPModel.INDEX_OFF_RATE].getInitialGuess();
    }
    // immobile fraction
    double fimm = 1 - ff - fc;
    if (fimm < FRAPOptimizationUtils.epsilon && fimm > (0 - FRAPOptimizationUtils.epsilon)) {
        fimm = 0;
    }
    if (fimm < (1 + FRAPOptimizationUtils.epsilon) && fimm > (1 - FRAPOptimizationUtils.epsilon)) {
        fimm = 1;
    }
    Extent extent = sourceFrapStudy.getFrapData().getImageDataset().getExtent();
    double[] timeStamps = sourceFrapStudy.getFrapData().getImageDataset().getImageTimeStamps();
    TimeBounds timeBounds = new TimeBounds(0.0, timeStamps[timeStamps.length - 1] - timeStamps[startingIndexForRecovery]);
    double timeStepVal = timeStamps[startingIndexForRecovery + 1] - timeStamps[startingIndexForRecovery];
    int numX = cellROI_2D.getRoiImages()[0].getNumX();
    int numY = cellROI_2D.getRoiImages()[0].getNumY();
    int numZ = cellROI_2D.getRoiImages().length;
    short[] shortPixels = cellROI_2D.getRoiImages()[0].getPixels();
    byte[] bytePixels = new byte[numX * numY * numZ];
    final byte EXTRACELLULAR_PIXVAL = 0;
    final byte CYTOSOL_PIXVAL = 1;
    for (int i = 0; i < bytePixels.length; i++) {
        if (shortPixels[i] != 0) {
            bytePixels[i] = CYTOSOL_PIXVAL;
        }
    }
    VCImage maskImage;
    try {
        maskImage = new VCImageUncompressed(null, bytePixels, extent, numX, numY, numZ);
    } catch (ImageException e) {
        e.printStackTrace();
        throw new RuntimeException("failed to create mask image for geometry");
    }
    Geometry geometry = new Geometry("geometry", maskImage);
    if (geometry.getGeometrySpec().getNumSubVolumes() != 2) {
        throw new Exception("Cell ROI has no ExtraCellular.");
    }
    int subVolume0PixVal = ((ImageSubVolume) geometry.getGeometrySpec().getSubVolume(0)).getPixelValue();
    geometry.getGeometrySpec().getSubVolume(0).setName((subVolume0PixVal == EXTRACELLULAR_PIXVAL ? EXTRACELLULAR_NAME : CYTOSOL_NAME));
    int subVolume1PixVal = ((ImageSubVolume) geometry.getGeometrySpec().getSubVolume(1)).getPixelValue();
    geometry.getGeometrySpec().getSubVolume(1).setName((subVolume1PixVal == CYTOSOL_PIXVAL ? CYTOSOL_NAME : EXTRACELLULAR_NAME));
    geometry.getGeometrySurfaceDescription().updateAll();
    BioModel bioModel = new BioModel(null);
    bioModel.setName("unnamed");
    Model model = new Model("model");
    bioModel.setModel(model);
    model.addFeature(EXTRACELLULAR_NAME);
    Feature extracellular = (Feature) model.getStructure(EXTRACELLULAR_NAME);
    model.addFeature(CYTOSOL_NAME);
    Feature cytosol = (Feature) model.getStructure(CYTOSOL_NAME);
    // Membrane mem = model.addMembrane(EXTRACELLULAR_CYTOSOL_MEM_NAME);
    // model.getStructureTopology().setInsideFeature(mem, cytosol);
    // model.getStructureTopology().setOutsideFeature(mem, extracellular);
    String roiDataName = FRAPStudy.ROI_EXTDATA_NAME;
    final int SPECIES_COUNT = 4;
    final int FREE_SPECIES_INDEX = 0;
    final int BS_SPECIES_INDEX = 1;
    final int COMPLEX_SPECIES_INDEX = 2;
    final int IMMOBILE_SPECIES_INDEX = 3;
    Expression[] diffusionConstants = null;
    Species[] species = null;
    SpeciesContext[] speciesContexts = null;
    Expression[] initialConditions = null;
    diffusionConstants = new Expression[SPECIES_COUNT];
    species = new Species[SPECIES_COUNT];
    speciesContexts = new SpeciesContext[SPECIES_COUNT];
    initialConditions = new Expression[SPECIES_COUNT];
    // total initial condition
    FieldFunctionArguments postBleach_first = new FieldFunctionArguments(roiDataName, "postbleach_first", new Expression(0), VariableType.VOLUME);
    FieldFunctionArguments prebleach_avg = new FieldFunctionArguments(roiDataName, "prebleach_avg", new Expression(0), VariableType.VOLUME);
    Expression expPostBleach_first = new Expression(postBleach_first.infix());
    Expression expPreBleach_avg = new Expression(prebleach_avg.infix());
    Expression totalIniCondition = Expression.div(expPostBleach_first, expPreBleach_avg);
    // Free Species
    diffusionConstants[FREE_SPECIES_INDEX] = new Expression(df);
    species[FREE_SPECIES_INDEX] = new Species(FRAPStudy.SPECIES_NAME_PREFIX_MOBILE, "Mobile bleachable species");
    speciesContexts[FREE_SPECIES_INDEX] = new SpeciesContext(null, species[FREE_SPECIES_INDEX].getCommonName(), species[FREE_SPECIES_INDEX], cytosol);
    initialConditions[FREE_SPECIES_INDEX] = Expression.mult(new Expression(ff), totalIniCondition);
    // Immobile Species (No diffusion)
    // Set very small diffusion rate on immobile to force evaluation as state variable (instead of FieldData function)
    // If left as a function errors occur because functions involving FieldData require a database connection
    final String IMMOBILE_DIFFUSION_KLUDGE = "1e-14";
    diffusionConstants[IMMOBILE_SPECIES_INDEX] = new Expression(IMMOBILE_DIFFUSION_KLUDGE);
    species[IMMOBILE_SPECIES_INDEX] = new Species(FRAPStudy.SPECIES_NAME_PREFIX_IMMOBILE, "Immobile bleachable species");
    speciesContexts[IMMOBILE_SPECIES_INDEX] = new SpeciesContext(null, species[IMMOBILE_SPECIES_INDEX].getCommonName(), species[IMMOBILE_SPECIES_INDEX], cytosol);
    initialConditions[IMMOBILE_SPECIES_INDEX] = Expression.mult(new Expression(fimm), totalIniCondition);
    // BS Species
    diffusionConstants[BS_SPECIES_INDEX] = new Expression(IMMOBILE_DIFFUSION_KLUDGE);
    species[BS_SPECIES_INDEX] = new Species(FRAPStudy.SPECIES_NAME_PREFIX_BINDING_SITE, "Binding Site species");
    speciesContexts[BS_SPECIES_INDEX] = new SpeciesContext(null, species[BS_SPECIES_INDEX].getCommonName(), species[BS_SPECIES_INDEX], cytosol);
    initialConditions[BS_SPECIES_INDEX] = Expression.mult(new Expression(bs), totalIniCondition);
    // Complex species
    diffusionConstants[COMPLEX_SPECIES_INDEX] = new Expression(dc);
    species[COMPLEX_SPECIES_INDEX] = new Species(FRAPStudy.SPECIES_NAME_PREFIX_SLOW_MOBILE, "Slower mobile bleachable species");
    speciesContexts[COMPLEX_SPECIES_INDEX] = new SpeciesContext(null, species[COMPLEX_SPECIES_INDEX].getCommonName(), species[COMPLEX_SPECIES_INDEX], cytosol);
    initialConditions[COMPLEX_SPECIES_INDEX] = Expression.mult(new Expression(fc), totalIniCondition);
    // add reactions to species if there is bleachWhileMonitoring rate.
    for (int i = 0; i < initialConditions.length; i++) {
        model.addSpecies(species[i]);
        model.addSpeciesContext(speciesContexts[i]);
        // reaction with BMW rate, which should not be applied to binding site
        if (!(species[i].getCommonName().equals(FRAPStudy.SPECIES_NAME_PREFIX_BINDING_SITE))) {
            SimpleReaction simpleReaction = new SimpleReaction(model, cytosol, speciesContexts[i].getName() + "_bleach", true);
            model.addReactionStep(simpleReaction);
            simpleReaction.addReactant(speciesContexts[i], 1);
            MassActionKinetics massActionKinetics = new MassActionKinetics(simpleReaction);
            simpleReaction.setKinetics(massActionKinetics);
            KineticsParameter kforward = massActionKinetics.getForwardRateParameter();
            simpleReaction.getKinetics().setParameterValue(kforward, new Expression(new Double(bwmRate)));
        }
    }
    // add the binding reaction: F + BS <-> C
    SimpleReaction simpleReaction2 = new SimpleReaction(model, cytosol, "reac_binding", true);
    model.addReactionStep(simpleReaction2);
    simpleReaction2.addReactant(speciesContexts[FREE_SPECIES_INDEX], 1);
    simpleReaction2.addReactant(speciesContexts[BS_SPECIES_INDEX], 1);
    simpleReaction2.addProduct(speciesContexts[COMPLEX_SPECIES_INDEX], 1);
    MassActionKinetics massActionKinetics = new MassActionKinetics(simpleReaction2);
    simpleReaction2.setKinetics(massActionKinetics);
    KineticsParameter kforward = massActionKinetics.getForwardRateParameter();
    KineticsParameter kreverse = massActionKinetics.getReverseRateParameter();
    simpleReaction2.getKinetics().setParameterValue(kforward, new Expression(new Double(onRate)));
    simpleReaction2.getKinetics().setParameterValue(kreverse, new Expression(new Double(offRate)));
    // create simulation context
    SimulationContext simContext = new SimulationContext(bioModel.getModel(), geometry);
    bioModel.addSimulationContext(simContext);
    FeatureMapping cytosolFeatureMapping = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(cytosol);
    FeatureMapping extracellularFeatureMapping = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(extracellular);
    // Membrane plasmaMembrane = model.getStructureTopology().getMembrane(cytosol, extracellular);
    // MembraneMapping plasmaMembraneMapping = (MembraneMapping)simContext.getGeometryContext().getStructureMapping(plasmaMembrane);
    SubVolume cytSubVolume = geometry.getGeometrySpec().getSubVolume(CYTOSOL_NAME);
    SubVolume exSubVolume = geometry.getGeometrySpec().getSubVolume(EXTRACELLULAR_NAME);
    SurfaceClass pmSurfaceClass = geometry.getGeometrySurfaceDescription().getSurfaceClass(exSubVolume, cytSubVolume);
    cytosolFeatureMapping.setGeometryClass(cytSubVolume);
    extracellularFeatureMapping.setGeometryClass(exSubVolume);
    // plasmaMembraneMapping.setGeometryClass(pmSurfaceClass);
    cytosolFeatureMapping.getUnitSizeParameter().setExpression(new Expression(1.0));
    extracellularFeatureMapping.getUnitSizeParameter().setExpression(new Expression(1.0));
    for (int i = 0; i < speciesContexts.length; i++) {
        SpeciesContextSpec scs = simContext.getReactionContext().getSpeciesContextSpec(speciesContexts[i]);
        scs.getInitialConditionParameter().setExpression(initialConditions[i]);
        scs.getDiffusionParameter().setExpression(diffusionConstants[i]);
    }
    MathMapping mathMapping = simContext.createNewMathMapping();
    MathDescription mathDesc = mathMapping.getMathDescription();
    // Add total fluorescence as function of mobile(optional: and slower mobile) and immobile fractions
    mathDesc.addVariable(new Function(FRAPStudy.SPECIES_NAME_PREFIX_COMBINED, new Expression(species[FREE_SPECIES_INDEX].getCommonName() + "+" + species[COMPLEX_SPECIES_INDEX].getCommonName() + "+" + species[IMMOBILE_SPECIES_INDEX].getCommonName()), null));
    simContext.setMathDescription(mathDesc);
    SimulationVersion simVersion = new SimulationVersion(simKey, "sim1", owner, new GroupAccessNone(), new KeyValue("0"), new BigDecimal(0), new Date(), VersionFlag.Current, "", null);
    Simulation newSimulation = new Simulation(simVersion, mathDesc);
    simContext.addSimulation(newSimulation);
    newSimulation.getSolverTaskDescription().setTimeBounds(timeBounds);
    newSimulation.getMeshSpecification().setSamplingSize(cellROI_2D.getISize());
    // newSimulation.getSolverTaskDescription().setTimeStep(timeStep); // Sundials doesn't need time step
    newSimulation.getSolverTaskDescription().setSolverDescription(SolverDescription.SundialsPDE);
    // use exp time step as output time spec
    newSimulation.getSolverTaskDescription().setOutputTimeSpec(new UniformOutputTimeSpec(timeStepVal));
    return bioModel;
}
Also used : ImageException(cbit.image.ImageException) KeyValue(org.vcell.util.document.KeyValue) Extent(org.vcell.util.Extent) SurfaceClass(cbit.vcell.geometry.SurfaceClass) MathDescription(cbit.vcell.math.MathDescription) VCImage(cbit.image.VCImage) SpeciesContext(cbit.vcell.model.SpeciesContext) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) Feature(cbit.vcell.model.Feature) TimeBounds(cbit.vcell.solver.TimeBounds) Function(cbit.vcell.math.Function) GroupAccessNone(org.vcell.util.document.GroupAccessNone) SimulationVersion(org.vcell.util.document.SimulationVersion) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) FeatureMapping(cbit.vcell.mapping.FeatureMapping) SubVolume(cbit.vcell.geometry.SubVolume) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) Species(cbit.vcell.model.Species) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) SimpleReaction(cbit.vcell.model.SimpleReaction) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) FieldFunctionArguments(cbit.vcell.field.FieldFunctionArguments) VCImageUncompressed(cbit.image.VCImageUncompressed) SimulationContext(cbit.vcell.mapping.SimulationContext) ROI(cbit.vcell.VirtualMicroscopy.ROI) ImageException(cbit.image.ImageException) UserCancelException(org.vcell.util.UserCancelException) BigDecimal(java.math.BigDecimal) Date(java.util.Date) Geometry(cbit.vcell.geometry.Geometry) Simulation(cbit.vcell.solver.Simulation) Expression(cbit.vcell.parser.Expression) BioModel(cbit.vcell.biomodel.BioModel) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) MathMapping(cbit.vcell.mapping.MathMapping) MassActionKinetics(cbit.vcell.model.MassActionKinetics)

Aggregations

MassActionKinetics (cbit.vcell.model.MassActionKinetics)16 KineticsParameter (cbit.vcell.model.Kinetics.KineticsParameter)11 Expression (cbit.vcell.parser.Expression)11 Kinetics (cbit.vcell.model.Kinetics)8 SimpleReaction (cbit.vcell.model.SimpleReaction)8 SpeciesContext (cbit.vcell.model.SpeciesContext)6 Model (cbit.vcell.model.Model)5 ReactionParticipant (cbit.vcell.model.ReactionParticipant)5 ReactionStep (cbit.vcell.model.ReactionStep)5 Function (cbit.vcell.math.Function)4 VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)4 BioModel (cbit.vcell.biomodel.BioModel)3 MathDescription (cbit.vcell.math.MathDescription)3 Product (cbit.vcell.model.Product)3 Reactant (cbit.vcell.model.Reactant)3 ExpressionException (cbit.vcell.parser.ExpressionException)3 ArrayList (java.util.ArrayList)3 ImageException (cbit.image.ImageException)2 VCImage (cbit.image.VCImage)2 VCImageUncompressed (cbit.image.VCImageUncompressed)2