Search in sources :

Example 26 with KineticsParameter

use of cbit.vcell.model.Kinetics.KineticsParameter in project vcell by virtualcell.

the class MembraneStructureAnalyzer method refreshResolvedFluxes.

/**
 * This method was created in VisualAge.
 */
private void refreshResolvedFluxes() throws Exception {
    // System.out.println("MembraneStructureAnalyzer.refreshResolvedFluxes()");
    ModelUnitSystem unitSystem = mathMapping.getSimulationContext().getModel().getUnitSystem();
    GeometryContext geoContext = mathMapping.getSimulationContext().getGeometryContext();
    Vector<ResolvedFlux> resolvedFluxList = new Vector<ResolvedFlux>();
    // 
    // for each reaction, get all fluxReactions associated with this membrane
    // 
    Vector<FluxReaction> fluxList = new Vector<FluxReaction>();
    ReactionSpec[] reactionSpecs = mathMapping.getSimulationContext().getReactionContext().getReactionSpecs();
    for (int j = 0; j < reactionSpecs.length; j++) {
        if (reactionSpecs[j].isExcluded()) {
            continue;
        }
        ReactionStep rs = reactionSpecs[j].getReactionStep();
        if (rs.getStructure() != null && geoContext.getStructureMapping(rs.getStructure()).getGeometryClass() == surfaceClass) {
            if (rs instanceof FluxReaction) {
                fluxList.addElement((FluxReaction) rs);
            }
        }
    }
    // 
    for (int i = 0; i < fluxList.size(); i++) {
        FluxReaction fr = fluxList.elementAt(i);
        ReactionParticipant[] reactionParticipants = fr.getReactionParticipants();
        for (int j = 0; j < reactionParticipants.length; j++) {
            if (!(reactionParticipants[j] instanceof Reactant) && !(reactionParticipants[j] instanceof Product)) {
                continue;
            }
            ResolvedFlux rf = null;
            SpeciesContext speciesContext = reactionParticipants[j].getSpeciesContext();
            for (int k = 0; k < resolvedFluxList.size(); k++) {
                ResolvedFlux rf_tmp = resolvedFluxList.elementAt(k);
                if (rf_tmp.getSpeciesContext() == reactionParticipants[j].getSpeciesContext()) {
                    rf = rf_tmp;
                }
            }
            // 
            // if speciesContext is not "fixed" and is mapped to a volume, add flux to ResolvedFlux
            // 
            StructureMapping structureMapping = mathMapping.getSimulationContext().getGeometryContext().getStructureMapping(reactionParticipants[j].getStructure());
            if (structureMapping.getGeometryClass() == surfaceClass) {
                // flux within surface
                continue;
            }
            if (structureMapping.getGeometryClass() instanceof SubVolume && surfaceClass.isAdjacentTo((SubVolume) structureMapping.getGeometryClass())) {
                SpeciesContextSpec speciesContextSpec = mathMapping.getSimulationContext().getReactionContext().getSpeciesContextSpec(speciesContext);
                if (!speciesContextSpec.isConstant()) {
                    if (rf == null) {
                        VCUnitDefinition speciesFluxUnit = speciesContext.getUnitDefinition().multiplyBy(unitSystem.getLengthUnit()).divideBy(unitSystem.getTimeUnit());
                        rf = new ResolvedFlux(speciesContext, speciesFluxUnit);
                        resolvedFluxList.addElement(rf);
                    }
                    FeatureMapping featureMapping = (FeatureMapping) structureMapping;
                    Expression insideFluxCorrection = Expression.invert(new Expression(featureMapping.getVolumePerUnitVolumeParameter(), mathMapping.getNameScope()));
                    // 
                    if (fr.getKinetics() instanceof DistributedKinetics) {
                        KineticsParameter reactionRateParameter = ((DistributedKinetics) fr.getKinetics()).getReactionRateParameter();
                        Expression correctedReactionRate = Expression.mult(new Expression(reactionRateParameter, mathMapping.getNameScope()), insideFluxCorrection);
                        if (reactionParticipants[j] instanceof Product) {
                            if (rf.getFluxExpression().isZero()) {
                                rf.setFluxExpression(correctedReactionRate.flatten());
                            } else {
                                rf.setFluxExpression(Expression.add(rf.getFluxExpression(), correctedReactionRate.flatten()));
                            }
                        } else if (reactionParticipants[j] instanceof Reactant) {
                            if (rf.getFluxExpression().isZero()) {
                                rf.setFluxExpression(Expression.negate(correctedReactionRate).flatten());
                            } else {
                                rf.setFluxExpression(Expression.add(rf.getFluxExpression(), Expression.negate(correctedReactionRate).flatten()));
                            }
                        } else {
                            throw new RuntimeException("expected either FluxReactant or FluxProduct");
                        }
                    } else if (fr.getKinetics() instanceof LumpedKinetics) {
                        throw new RuntimeException("Lumped Kinetics for fluxes not yet supported");
                    } else {
                        throw new RuntimeException("unexpected Kinetic type in MembraneStructureAnalyzer.refreshResolvedFluxes()");
                    }
                    rf.getFluxExpression().bindExpression(mathMapping);
                }
            }
        }
    }
    // 
    for (int i = 0; i < reactionSpecs.length; i++) {
        if (reactionSpecs[i].isExcluded()) {
            continue;
        }
        ReactionStep rs = reactionSpecs[i].getReactionStep();
        if (rs.getStructure() != null && geoContext.getStructureMapping(rs.getStructure()).getGeometryClass() == surfaceClass) {
            if (rs instanceof SimpleReaction) {
                SimpleReaction sr = (SimpleReaction) rs;
                ReactionParticipant[] rp_Array = sr.getReactionParticipants();
                for (int k = 0; k < rp_Array.length; k++) {
                    if (rp_Array[k] instanceof Reactant || rp_Array[k] instanceof Product) {
                        SpeciesContextSpec rpSCS = mathMapping.getSimulationContext().getReactionContext().getSpeciesContextSpec(rp_Array[k].getSpeciesContext());
                        StructureMapping rpSM = mathMapping.getSimulationContext().getGeometryContext().getStructureMapping(rp_Array[k].getStructure());
                        if (rpSM.getGeometryClass() instanceof SubVolume && !rpSCS.isConstant()) {
                            // 
                            // get ResolvedFlux for this species
                            // 
                            ResolvedFlux rf = null;
                            for (int j = 0; j < resolvedFluxList.size(); j++) {
                                ResolvedFlux rf_tmp = (ResolvedFlux) resolvedFluxList.elementAt(j);
                                if (rf_tmp.getSpeciesContext() == rp_Array[k].getSpeciesContext()) {
                                    rf = rf_tmp;
                                }
                            }
                            if (rf == null) {
                                VCUnitDefinition speciesFluxUnit = rp_Array[k].getSpeciesContext().getUnitDefinition().multiplyBy(unitSystem.getLengthUnit()).divideBy(unitSystem.getTimeUnit());
                                rf = new ResolvedFlux(rp_Array[k].getSpeciesContext(), speciesFluxUnit);
                                resolvedFluxList.addElement(rf);
                            }
                            if (rpSM.getGeometryClass() instanceof SubVolume && surfaceClass.isAdjacentTo((SubVolume) rpSM.getGeometryClass())) {
                                // 
                                // for binding on inside or outside, add to ResolvedFlux.flux
                                // 
                                Expression fluxRateExpression = getCorrectedRateExpression(sr, rp_Array[k], RateType.ResolvedFluxRate).renameBoundSymbols(mathMapping.getNameScope());
                                if (rf.getFluxExpression().isZero()) {
                                    rf.setFluxExpression(fluxRateExpression);
                                } else {
                                    rf.setFluxExpression(Expression.add(rf.getFluxExpression(), fluxRateExpression));
                                }
                                rf.getFluxExpression().bindExpression(mathMapping);
                            } else {
                                String structureName = ((rs.getStructure() != null) ? (rs.getStructure().getName()) : ("<null>"));
                                throw new Exception("In Application '" + mathMapping.getSimulationContext().getName() + "', SpeciesContext '" + rp_Array[k].getSpeciesContext().getName() + "' is not mapped adjacent to structure '" + structureName + "' but reacts there");
                            }
                        }
                    }
                }
            }
        }
    }
    // 
    if (resolvedFluxList.size() > 0) {
        resolvedFluxes = new ResolvedFlux[resolvedFluxList.size()];
        resolvedFluxList.copyInto(resolvedFluxes);
    } else {
        resolvedFluxes = null;
    }
}
Also used : LumpedKinetics(cbit.vcell.model.LumpedKinetics) Product(cbit.vcell.model.Product) FluxReaction(cbit.vcell.model.FluxReaction) SpeciesContext(cbit.vcell.model.SpeciesContext) Reactant(cbit.vcell.model.Reactant) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) SubVolume(cbit.vcell.geometry.SubVolume) Vector(java.util.Vector) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem) DistributedKinetics(cbit.vcell.model.DistributedKinetics) SimpleReaction(cbit.vcell.model.SimpleReaction) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) ReactionStep(cbit.vcell.model.ReactionStep) ReactionParticipant(cbit.vcell.model.ReactionParticipant)

Example 27 with KineticsParameter

use of cbit.vcell.model.Kinetics.KineticsParameter in project vcell by virtualcell.

the class NetworkTransformer method applyKineticsExpressions.

// private Expression substituteFakeParameters(Expression paramExpression) throws ExpressionException {
// Expression newExp = new Expression(paramExpression);
// String[] fakeSymbols = paramExpression.getSymbols();
// for (String fakeSymbol : fakeSymbols){
// FakeReactionRuleRateParameter fakeParameter = FakeReactionRuleRateParameter.fromString(fakeSymbol);
// if (fakeParameter == null){
// throw new RuntimeException("unexpected identifier "+fakeSymbol+" in kinetic law during network generation");
// }
// LocalParameter localParameter = this.kineticsParameterMap.get(fakeParameter);
// Expression ruleExpression = localParameter.getExpression();
// newExp.substituteInPlace(new Expression(fakeSymbol), new Expression(ruleExpression));
// }
// return newExp;
// }
private Expression applyKineticsExpressions(BNGReaction bngReaction, KineticsParameter rateParameter, MassActionKinetics targetKinetics) throws ExpressionException {
    ReactionRule reactionRule = null;
    Expression paramExpression = bngReaction.getParamExpression();
    Expression newExp = new Expression(paramExpression);
    String[] fakeSymbols = paramExpression.getSymbols();
    for (String fakeSymbol : fakeSymbols) {
        FakeReactionRuleRateParameter fakeParameter = FakeReactionRuleRateParameter.fromString(fakeSymbol);
        if (fakeParameter == null) {
            throw new RuntimeException("unexpected identifier " + fakeSymbol + " in kinetic law during network generation");
        }
        LocalParameter localParameter = this.kineticsParameterMap.get(fakeParameter);
        System.out.println(localParameter.getNameScope());
        if (localParameter.getNameScope() instanceof ReactionRule.ReactionRuleNameScope) {
            reactionRule = ((ReactionRule.ReactionRuleNameScope) localParameter.getNameScope()).getReactionRule();
        }
        Expression ruleExpression = localParameter.getExpression();
        newExp.substituteInPlace(new Expression(fakeSymbol), new Expression(ruleExpression));
    }
    // 
    try {
        targetKinetics.setParameterValue(rateParameter, newExp);
    } catch (PropertyVetoException e) {
        e.printStackTrace();
        throw new RuntimeException("failed to set kinetics expression for reaction " + targetKinetics.getReactionStep().getName() + ": " + e.getMessage(), e);
    }
    // 
    if (reactionRule != null) {
        // try to set values from user-defined parameters into the target kinetics
        for (LocalParameter localParameter : reactionRule.getKineticLaw().getLocalParameters()) {
            if (localParameter.getRole() == RbmKineticLawParameterType.UserDefined) {
                KineticsParameter userDefinedParam = targetKinetics.getKineticsParameter(localParameter.getName());
                if (userDefinedParam != null) {
                    try {
                        targetKinetics.setParameterValue(userDefinedParam, localParameter.getExpression());
                    } catch (PropertyVetoException e) {
                        e.printStackTrace();
                        throw new RuntimeException("failed to set kinetics expression for reaction " + targetKinetics.getReactionStep().getName() + ": " + e.getMessage(), e);
                    }
                }
            }
        }
    }
    return newExp;
}
Also used : LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) PropertyVetoException(java.beans.PropertyVetoException) FakeReactionRuleRateParameter(org.vcell.model.rbm.FakeReactionRuleRateParameter) ReactionRule(cbit.vcell.model.ReactionRule) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) Expression(cbit.vcell.parser.Expression)

Example 28 with KineticsParameter

use of cbit.vcell.model.Kinetics.KineticsParameter in project vcell by virtualcell.

the class AbstractMathMapping method getMathSymbol0.

/**
 * Substitutes appropriate variables for speciesContext bindings
 *
 * @return cbit.vcell.parser.Expression
 * @param origExp cbit.vcell.parser.Expression
 * @param structureMapping cbit.vcell.mapping.StructureMapping
 */
protected final String getMathSymbol0(SymbolTableEntry ste, GeometryClass geometryClass) throws MappingException {
    String steName = ste.getName();
    if (ste instanceof Kinetics.KineticsParameter) {
        Integer count = localNameCountHash.get(steName);
        if (count == null) {
            throw new MappingException("KineticsParameter " + steName + " not found in local name count");
        }
        if (count > 1 || steName.equals("J")) {
            return steName + "_" + ste.getNameScope().getName();
        // return getNameScope().getSymbolName(ste);
        } else {
            return steName;
        }
    }
    if (ste instanceof LocalParameter && ((LocalParameter) ste).getNameScope() instanceof ReactionRule.ReactionRuleNameScope) {
        Integer count = localNameCountHash.get(steName);
        if (count == null) {
            throw new MappingException("Reaction Rule Parameter " + steName + " not found in local name count");
        }
        if (count > 1 || steName.equals("J")) {
            return steName + "_" + ste.getNameScope().getName();
        // return getNameScope().getSymbolName(ste);
        } else {
            return steName;
        }
    }
    if (ste instanceof ProbabilityParameter) {
        // be careful here, to see if we need mangle the reaction name
        ProbabilityParameter probParm = (ProbabilityParameter) ste;
        return probParm.getName() + PARAMETER_PROBABLIITY_RATE_SUFFIX;
    }
    if (ste instanceof SpeciesConcentrationParameter) {
        SpeciesConcentrationParameter concParm = (SpeciesConcentrationParameter) ste;
        return concParm.getSpeciesContext().getName() + MATH_FUNC_SUFFIX_SPECIES_CONCENTRATION;
    }
    if (ste instanceof SpeciesCountParameter) {
        SpeciesCountParameter countParm = (SpeciesCountParameter) ste;
        return countParm.getSpeciesContext().getName() + MATH_VAR_SUFFIX_SPECIES_COUNT;
    }
    if (ste instanceof ObservableConcentrationParameter) {
        ObservableConcentrationParameter concParm = (ObservableConcentrationParameter) ste;
        return concParm.getObservable().getName() + MATH_FUNC_SUFFIX_SPECIES_CONCENTRATION;
    }
    if (ste instanceof ObservableCountParameter) {
        ObservableCountParameter countParm = (ObservableCountParameter) ste;
        return countParm.getObservable().getName() + MATH_VAR_SUFFIX_SPECIES_COUNT;
    }
    if (ste instanceof RbmObservable) {
        RbmObservable observable = (RbmObservable) ste;
        return observable.getName() + MATH_FUNC_SUFFIX_SPECIES_CONCENTRATION;
    }
    if (ste instanceof EventAssignmentOrRateRuleInitParameter) {
        EventAssignmentOrRateRuleInitParameter eventInitParm = (EventAssignmentOrRateRuleInitParameter) ste;
        // + MATH_FUNC_SUFFIX_EVENTASSIGN_OR_RATE_INIT;
        return eventInitParm.getName();
    }
    if (ste instanceof RateRuleRateParameter) {
        RateRuleRateParameter rateRuleRateParm = (RateRuleRateParameter) ste;
        // + MATH_FUNC_SUFFIX_RATERULE_RATE;
        return rateRuleRateParm.getName();
    }
    if (ste instanceof Model.ReservedSymbol) {
        return steName;
    }
    if (ste instanceof Membrane.MembraneVoltage) {
        return steName;
    }
    if (ste instanceof Structure.StructureSize) {
        Structure structure = ((Structure.StructureSize) ste).getStructure();
        StructureMapping.StructureMappingParameter sizeParameter = simContext.getGeometryContext().getStructureMapping(structure).getSizeParameter();
        return getMathSymbol(sizeParameter, geometryClass);
    }
    if (ste instanceof ProxyParameter) {
        ProxyParameter pp = (ProxyParameter) ste;
        return getMathSymbol0(pp.getTarget(), geometryClass);
    }
    // 
    if (ste instanceof ModelParameter) {
        ModelParameter mp = (ModelParameter) ste;
        return mp.getName();
    }
    if (ste instanceof SpeciesContextSpec.SpeciesContextSpecParameter) {
        SpeciesContextSpec.SpeciesContextSpecParameter scsParm = (SpeciesContextSpec.SpeciesContextSpecParameter) ste;
        SpeciesContext speciesContext = ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext();
        SpeciesContextMapping scm = getSpeciesContextMapping(speciesContext);
        String speciesContextVarName = null;
        if (scm.getVariable() != null) {
            speciesContextVarName = scm.getVariable().getName();
        } else {
            speciesContextVarName = speciesContext.getName();
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_InitialConcentration) {
            return speciesContextVarName + MATH_FUNC_SUFFIX_SPECIES_INIT_CONC_UNIT_PREFIX + TokenMangler.fixTokenStrict(scsParm.getUnitDefinition().getSymbol());
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_InitialCount) {
            return speciesContextVarName + MATH_FUNC_SUFFIX_SPECIES_INIT_COUNT;
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_DiffusionRate) {
            return speciesContextVarName + PARAMETER_DIFFUSION_RATE_SUFFIX;
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_BoundaryValueXm) {
            return speciesContextVarName + PARAMETER_BOUNDARY_XM_SUFFIX;
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_BoundaryValueXp) {
            return speciesContextVarName + PARAMETER_BOUNDARY_XP_SUFFIX;
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_BoundaryValueYm) {
            return speciesContextVarName + PARAMETER_BOUNDARY_YM_SUFFIX;
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_BoundaryValueYp) {
            return speciesContextVarName + PARAMETER_BOUNDARY_YP_SUFFIX;
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_BoundaryValueZm) {
            return speciesContextVarName + PARAMETER_BOUNDARY_ZM_SUFFIX;
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_BoundaryValueZp) {
            return speciesContextVarName + PARAMETER_BOUNDARY_ZP_SUFFIX;
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_VelocityX) {
            return speciesContextVarName + PARAMETER_VELOCITY_X_SUFFIX;
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_VelocityY) {
            return speciesContextVarName + PARAMETER_VELOCITY_Y_SUFFIX;
        }
        if (scsParm.getRole() == SpeciesContextSpec.ROLE_VelocityZ) {
            return speciesContextVarName + PARAMETER_VELOCITY_Z_SUFFIX;
        }
    }
    if (ste instanceof ElectricalDevice.ElectricalDeviceParameter) {
        ElectricalDevice.ElectricalDeviceParameter edParm = (ElectricalDevice.ElectricalDeviceParameter) ste;
        ElectricalDevice electricalDevice = (ElectricalDevice) edParm.getNameScope().getScopedSymbolTable();
        if (electricalDevice instanceof MembraneElectricalDevice) {
            String nameWithScope = ((MembraneElectricalDevice) electricalDevice).getMembraneMapping().getMembrane().getNameScope().getName();
            if (edParm.getRole() == ElectricalDevice.ROLE_TotalCurrent) {
                return PARAMETER_TOTAL_CURRENT_PREFIX + nameWithScope;
            }
            if (edParm.getRole() == ElectricalDevice.ROLE_TransmembraneCurrent) {
                return PARAMETER_TRANSMEMBRANE_CURRENT_PREFIX + nameWithScope;
            }
        // }else if (electricalDevice instanceof CurrentClampElectricalDevice) {
        // if (edParm.getRole()==ElectricalDevice.ROLE_TotalCurrentDensity){
        // return "I_"+((CurrentClampElectricalDevice)electricalDevice).getCurrentClampStimulus().getNameScope().getName();
        // }
        // if (edParm.getRole()==ElectricalDevice.ROLE_TransmembraneCurrentDensity){
        // return "F_"+((CurrentClampElectricalDevice)electricalDevice).getCurrentClampStimulus().getNameScope().getName();
        // }
        // }else if (electricalDevice instanceof VoltageClampElectricalDevice) {
        // if (edParm.getRole()==ElectricalDevice.ROLE_TotalCurrentDensity){
        // return "I_"+((VoltageClampElectricalDevice)electricalDevice).getVoltageClampStimulus().getNameScope().getName();
        // }
        // if (edParm.getRole()==ElectricalDevice.ROLE_TransmembraneCurrentDensity){
        // return "F_"+((VoltageClampElectricalDevice)electricalDevice).getVoltageClampStimulus().getNameScope().getName();
        // }
        }
    }
    if (ste instanceof LocalParameter && ((LocalParameter) ste).getNameScope() instanceof ElectricalStimulus.ElectricalStimulusNameScope) {
        LocalParameter esParm = (LocalParameter) ste;
        String nameWithScope = esParm.getNameScope().getName();
        if (esParm.getRole() == ElectricalStimulus.ElectricalStimulusParameterType.TotalCurrent) {
            return PARAMETER_TOTAL_CURRENT_PREFIX + nameWithScope;
        } else if (esParm.getRole() == ElectricalStimulus.ElectricalStimulusParameterType.Voltage) {
            return PARAMETER_VOLTAGE_PREFIX + nameWithScope;
        }
    }
    if (ste instanceof StructureMapping.StructureMappingParameter) {
        StructureMapping.StructureMappingParameter smParm = (StructureMapping.StructureMappingParameter) ste;
        Structure structure = ((StructureMapping) (smParm.getNameScope().getScopedSymbolTable())).getStructure();
        String nameWithScope = structure.getNameScope().getName();
        int role = smParm.getRole();
        if (role == StructureMapping.ROLE_InitialVoltage) {
            return smParm.getName();
        } else if (role == StructureMapping.ROLE_SpecificCapacitance) {
            return PARAMETER_SPECIFIC_CAPACITANCE_PREFIX + nameWithScope;
        } else if (role == StructureMapping.ROLE_Size) {
            if (simContext.getGeometry().getDimension() == 0) {
                // if geometry is compartmental, make sure compartment sizes are set if referenced in model.
                if (smParm.getExpression() == null || smParm.getExpression().isZero()) {
                    throw new MappingException("\nIn non-spatial application '" + getSimulationContext().getName() + "', " + "size of structure '" + structure.getName() + "' must be assigned a " + "positive value if referenced in the model.\n\nPlease go to 'Structure Mapping' tab to check the size.");
                }
            }
            return PARAMETER_SIZE_FUNCTION_PREFIX + nameWithScope;
        } else if (role == StructureMapping.ROLE_AreaPerUnitArea) {
            return "AreaPerUnitArea_" + nameWithScope;
        } else if (role == StructureMapping.ROLE_AreaPerUnitVolume) {
            return "AreaPerUnitVolume_" + nameWithScope;
        } else if (role == StructureMapping.ROLE_VolumePerUnitArea) {
            return "VolumePerUnitArea_" + nameWithScope;
        } else if (role == StructureMapping.ROLE_VolumePerUnitVolume) {
            return "VolumePerUnitVolume_" + nameWithScope;
        }
    }
    // 
    if (ste instanceof SpeciesContext) {
        SpeciesContext sc = (SpeciesContext) ste;
        SpeciesContextMapping scm = getSpeciesContextMapping(sc);
        if (scm == null) {
            throw new RuntimeException("Species '" + sc.getName() + "' is referenced in model but may have been deleted. " + "Find its references in '" + GuiConstants.DOCUMENT_EDITOR_FOLDERNAME_BIOMODEL_PARAMETERS + "'.");
        }
        // 
        if (geometryClass instanceof SubVolume) {
            // 
            if (scm.getVariable() != null && !scm.getVariable().getName().equals(steName)) {
                return scm.getVariable().getName();
            }
        // 
        // for reactions within a surface, may need "_INSIDE" or "_OUTSIDE" for jump condition
        // 
        } else if (geometryClass instanceof SurfaceClass) {
            // 
            // if the speciesContext is also within the surface, replace SpeciesContext name with Variable name
            // 
            StructureMapping sm = simContext.getGeometryContext().getStructureMapping(sc.getStructure());
            if (sm.getGeometryClass() == geometryClass) {
                if (scm.getVariable() != null && !(scm.getVariable().getName().equals(ste.getName()))) {
                    return scm.getVariable().getName();
                }
            // 
            // if the speciesContext is "inside" or "outside" the membrane
            // 
            } else if (sm.getGeometryClass() instanceof SubVolume && ((SurfaceClass) geometryClass).isAdjacentTo((SubVolume) sm.getGeometryClass())) {
                SpeciesContextSpec scs = simContext.getReactionContext().getSpeciesContextSpec(sc);
                if (!scs.isConstant()) {
                    if (!scs.isDiffusing() && !scs.isWellMixed()) {
                        throw new MappingException("Enable diffusion in Application '" + simContext.getName() + "'. This must be done for any species (e.g '" + sc.getName() + "') in flux reactions.\n\n" + "To save or run simulations, set the diffusion rate to a non-zero " + "value in Initial Conditions or disable those reactions in Specifications->Reactions.");
                    }
                }
                if (scm.getVariable() != null) {
                    return scm.getVariable().getName();
                }
            } else {
                throw new MappingException("species '" + sc.getName() + "' interacts with surface '" + geometryClass.getName() + "', but is not mapped spatially adjacent");
            }
        }
    }
    return getNameScope().getSymbolName(ste);
}
Also used : SurfaceClass(cbit.vcell.geometry.SurfaceClass) MembraneElectricalDevice(cbit.vcell.mapping.potential.MembraneElectricalDevice) SpeciesContext(cbit.vcell.model.SpeciesContext) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) SubVolume(cbit.vcell.geometry.SubVolume) CompartmentSubVolume(cbit.vcell.geometry.CompartmentSubVolume) Structure(cbit.vcell.model.Structure) ElectricalDevice(cbit.vcell.mapping.potential.ElectricalDevice) MembraneElectricalDevice(cbit.vcell.mapping.potential.MembraneElectricalDevice) ReactionRule(cbit.vcell.model.ReactionRule) RbmObservable(cbit.vcell.model.RbmObservable) StructureSize(cbit.vcell.model.Structure.StructureSize) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) ProxyParameter(cbit.vcell.model.ProxyParameter) MembraneVoltage(cbit.vcell.model.Membrane.MembraneVoltage)

Example 29 with KineticsParameter

use of cbit.vcell.model.Kinetics.KineticsParameter in project vcell by virtualcell.

the class AbstractMathMapping method refreshLocalNameCount.

protected void refreshLocalNameCount() {
    localNameCountHash.clear();
    ReactionStep[] reactionSteps = simContext.getModel().getReactionSteps();
    for (int j = 0; j < reactionSteps.length; j++) {
        KineticsParameter[] params = reactionSteps[j].getKinetics().getKineticsParameters();
        for (KineticsParameter kp : params) {
            String name = kp.getName();
            if (localNameCountHash.containsKey(name)) {
                localNameCountHash.put(name, localNameCountHash.get(name) + 1);
            } else {
                localNameCountHash.put(name, 1);
            }
        }
    }
    List<ReactionRule> reactionRules = simContext.getModel().getRbmModelContainer().getReactionRuleList();
    for (ReactionRule reactionRule : reactionRules) {
        LocalParameter[] params = reactionRule.getKineticLaw().getLocalParameters();
        for (LocalParameter kp : params) {
            String name = kp.getName();
            if (localNameCountHash.containsKey(name)) {
                localNameCountHash.put(name, localNameCountHash.get(name) + 1);
            } else {
                localNameCountHash.put(name, 1);
            }
        }
    }
    SpeciesContext[] scs = simContext.getModel().getSpeciesContexts();
    for (SpeciesContext sc : scs) {
        String name = sc.getName();
        if (localNameCountHash.containsKey(name)) {
            localNameCountHash.put(name, localNameCountHash.get(name) + 1);
        } else {
            localNameCountHash.put(name, 1);
        }
    }
    ModelParameter[] mps = simContext.getModel().getModelParameters();
    for (ModelParameter mp : mps) {
        String name = mp.getName();
        if (localNameCountHash.containsKey(name)) {
            localNameCountHash.put(name, localNameCountHash.get(name) + 1);
        } else {
            localNameCountHash.put(name, 1);
        }
    }
}
Also used : ReactionRule(cbit.vcell.model.ReactionRule) SpeciesContext(cbit.vcell.model.SpeciesContext) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) ReactionStep(cbit.vcell.model.ReactionStep)

Example 30 with KineticsParameter

use of cbit.vcell.model.Kinetics.KineticsParameter 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)

Aggregations

KineticsParameter (cbit.vcell.model.Kinetics.KineticsParameter)46 Expression (cbit.vcell.parser.Expression)31 SpeciesContext (cbit.vcell.model.SpeciesContext)23 ModelParameter (cbit.vcell.model.Model.ModelParameter)19 ReactionStep (cbit.vcell.model.ReactionStep)18 Kinetics (cbit.vcell.model.Kinetics)15 ExpressionException (cbit.vcell.parser.ExpressionException)14 Model (cbit.vcell.model.Model)12 PropertyVetoException (java.beans.PropertyVetoException)12 VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)11 MassActionKinetics (cbit.vcell.model.MassActionKinetics)10 ReactionParticipant (cbit.vcell.model.ReactionParticipant)9 SimpleReaction (cbit.vcell.model.SimpleReaction)9 Structure (cbit.vcell.model.Structure)9 LocalParameter (cbit.vcell.mapping.ParameterContext.LocalParameter)8 SpeciesContextSpecParameter (cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter)6 ModelUnitSystem (cbit.vcell.model.ModelUnitSystem)6 ReactionRule (cbit.vcell.model.ReactionRule)6 Species (cbit.vcell.model.Species)6 Vector (java.util.Vector)6