Search in sources :

Example 71 with Variable

use of cbit.vcell.math.Variable in project vcell by virtualcell.

the class MathSymbolMapping method reconcileVarNames.

/**
 * Insert the method's description here.
 * Creation date: (5/3/2006 4:03:51 PM)
 * @param mathDesc cbit.vcell.math.MathDescription
 */
public void reconcileVarNames(MathDescription mathDesc) {
    // 
    // clear secondary hashmaps in case called multiple times.
    // 
    biologicalToMathHash.clear();
    mathToBiologicalHash.clear();
    java.util.Set<SymbolTableEntry> keyset = biologicalToMathSymbolNameHash.keySet();
    java.util.Iterator<SymbolTableEntry> keysetIter = keyset.iterator();
    while (keysetIter.hasNext()) {
        SymbolTableEntry biologicalSymbol = keysetIter.next();
        String mathVarName = (String) biologicalToMathSymbolNameHash.get(biologicalSymbol);
        Variable var = mathDesc.getVariable(mathVarName);
        if (var != null) {
            biologicalToMathHash.put(biologicalSymbol, var);
            SymbolTableEntry[] previousBiologicalSymbolArr = (SymbolTableEntry[]) mathToBiologicalHash.put(var, new SymbolTableEntry[] { biologicalSymbol });
            if (previousBiologicalSymbolArr != null) {
                SymbolTableEntry[] steArr = (SymbolTableEntry[]) BeanUtils.addElement(previousBiologicalSymbolArr, biologicalSymbol);
                mathToBiologicalHash.put(var, steArr);
            }
        }
    }
}
Also used : SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) InsideVariable(cbit.vcell.math.InsideVariable) Variable(cbit.vcell.math.Variable) OutsideVariable(cbit.vcell.math.OutsideVariable)

Example 72 with Variable

use of cbit.vcell.math.Variable in project vcell by virtualcell.

the class ParticleMathMapping method combineHybrid.

private void combineHybrid() throws MappingException, ExpressionException, MatrixException, MathException, ModelException {
    ArrayList<SpeciesContext> continuousSpecies = new ArrayList<SpeciesContext>();
    ArrayList<ParticleVariable> continuousSpeciesParticleVars = new ArrayList<ParticleVariable>();
    ArrayList<SpeciesContext> stochSpecies = new ArrayList<SpeciesContext>();
    // 
    // categorize speciesContexts as continuous and stochastic
    // 
    SpeciesContextSpec[] scsArray = getSimulationContext().getReactionContext().getSpeciesContextSpecs();
    continuousSpecies = new ArrayList<SpeciesContext>();
    stochSpecies = new ArrayList<SpeciesContext>();
    for (SpeciesContextSpec speciesContextSpec : scsArray) {
        if (!getSimulationContext().isStoch() || speciesContextSpec.isForceContinuous()) {
            continuousSpecies.add(speciesContextSpec.getSpeciesContext());
            Variable variable = getMathSymbolMapping().getVariable(speciesContextSpec.getSpeciesContext());
            if (variable instanceof ParticleVariable) {
                continuousSpeciesParticleVars.add((ParticleVariable) variable);
            }
        } else {
            stochSpecies.add(speciesContextSpec.getSpeciesContext());
        }
    }
    if (continuousSpecies.isEmpty()) {
        return;
    }
    // 
    // create continuous mathDescription ... add stochastic variables and processes to the continuous Math and use this.
    // 
    DiffEquMathMapping mathMapping = new DiffEquMathMapping(getSimulationContext(), callback, networkGenerationRequirements);
    mathMapping.refresh(null);
    MathDescription contMathDesc = mathMapping.getMathDescription();
    // 
    // get list of all continuous variables
    // 
    HashMap<String, Variable> allContinuousVars = new HashMap<String, Variable>();
    Enumeration<Variable> enumVar = contMathDesc.getVariables();
    while (enumVar.hasMoreElements()) {
        Variable var = enumVar.nextElement();
        allContinuousVars.put(var.getName(), var);
    }
    // 
    // replace those continuous variables and equations for stochastic speciesContexts
    // with the particleVariables and particleProperties
    // (ParticleJumpProcesses removed later)
    // 
    ModelUnitSystem unitSystem = getSimulationContext().getModel().getUnitSystem();
    for (SpeciesContext stochSpeciesContext : stochSpecies) {
        Variable contVar = mathMapping.getMathSymbolMapping().getVariable(stochSpeciesContext);
        Variable stochVar = getMathSymbolMapping().getVariable(stochSpeciesContext);
        allContinuousVars.put(stochVar.getName(), stochVar);
        // 
        // replace continuous "concentration" VolVariable/MemVariable for this particle with a Function for concentration
        // 
        allContinuousVars.remove(contVar);
        VCUnitDefinition sizeUnit = unitSystem.getLengthUnit().raiseTo(new RationalNumber(stochSpeciesContext.getStructure().getDimension()));
        VCUnitDefinition stochasticDensityUnit = unitSystem.getStochasticSubstanceUnit().divideBy(sizeUnit);
        VCUnitDefinition continuousDensityUnit = unitSystem.getConcentrationUnit(stochSpeciesContext.getStructure());
        if (stochasticDensityUnit.isEquivalent(continuousDensityUnit)) {
            allContinuousVars.put(contVar.getName(), new Function(contVar.getName(), new Expression(stochVar, getNameScope()), contVar.getDomain()));
        } else {
            Expression conversionFactorExp = getUnitFactor(continuousDensityUnit.divideBy(stochasticDensityUnit));
            allContinuousVars.put(contVar.getName(), new Function(contVar.getName(), Expression.mult(new Expression(stochVar, getNameScope()), conversionFactorExp), contVar.getDomain()));
        }
        // 
        // remove continuous equation
        // 
        Enumeration<SubDomain> contSubDomains = contMathDesc.getSubDomains();
        while (contSubDomains.hasMoreElements()) {
            SubDomain contSubDomain = contSubDomains.nextElement();
            contSubDomain.removeEquation(contVar);
            if (contSubDomain instanceof MembraneSubDomain) {
                ((MembraneSubDomain) contSubDomain).removeJumpCondition(contVar);
            }
        }
        // 
        // remove all continuous variables for speciesContextSpec parameters (e.g. initial conditions, diffusion rates, boundary conditions, velocities)
        // 
        SpeciesContextSpec scs = getSimulationContext().getReactionContext().getSpeciesContextSpec(stochSpeciesContext);
        Parameter[] scsParameters = scs.getParameters();
        for (Parameter parameter : scsParameters) {
            Variable continuousScsParmVariable = mathMapping.getMathSymbolMapping().getVariable(parameter);
            allContinuousVars.remove(continuousScsParmVariable);
        }
        // 
        // copy ParticleJumpProcess and ParticleProperties to the continuous math
        // 
        SubDomain contSubDomain = contMathDesc.getSubDomain(contVar.getDomain().getName());
        SubDomain stochSubDomain = mathDesc.getSubDomain(stochVar.getDomain().getName());
        ParticleProperties particleProperties = stochSubDomain.getParticleProperties(stochVar);
        contSubDomain.addParticleProperties(particleProperties);
    }
    // 
    // add all ParticleJumpProcesses to the continuous model
    // 
    Enumeration<SubDomain> enumStochSubdomains = mathDesc.getSubDomains();
    while (enumStochSubdomains.hasMoreElements()) {
        SubDomain stochSubdomain = enumStochSubdomains.nextElement();
        SubDomain contSubdomain = contMathDesc.getSubDomain(stochSubdomain.getName());
        for (ParticleJumpProcess particleJumpProcess : stochSubdomain.getParticleJumpProcesses()) {
            // 
            // modify "selection list" (particleVariables), probability rate, and actions if referenced particleVariable is to be "forced continuous"
            // 
            ParticleVariable[] selectedParticles = particleJumpProcess.getParticleVariables();
            for (ParticleVariable particleVariable : selectedParticles) {
                if (continuousSpeciesParticleVars.contains(particleVariable)) {
                    particleJumpProcess.remove(particleVariable);
                    JumpProcessRateDefinition jumpProcessRateDefinition = particleJumpProcess.getParticleRateDefinition();
                    if (jumpProcessRateDefinition instanceof MacroscopicRateConstant) {
                        MacroscopicRateConstant macroscopicRateConstant = (MacroscopicRateConstant) jumpProcessRateDefinition;
                        macroscopicRateConstant.setExpression(Expression.mult(macroscopicRateConstant.getExpression(), new Expression(particleVariable, null)));
                    } else if (jumpProcessRateDefinition instanceof InteractionRadius) {
                        throw new MappingException("cannot adjust interaction radius for reaction process " + particleJumpProcess.getName() + ", particle " + particleVariable.getName() + " is continuous");
                    } else {
                        throw new MappingException("rate definition type " + jumpProcessRateDefinition.getClass().getSimpleName() + " not yet implemented for hybrid PDE/Particle math generation");
                    }
                }
                Iterator<Action> iterAction = particleJumpProcess.getActions().iterator();
                while (iterAction.hasNext()) {
                    Action action = iterAction.next();
                    if (continuousSpeciesParticleVars.contains(action.getVar())) {
                        iterAction.remove();
                    }
                }
            }
            if (!particleJumpProcess.getActions().isEmpty()) {
                contSubdomain.addParticleJumpProcess(particleJumpProcess);
            }
        }
    }
    // 
    for (MathMappingParameter mathMappingParameter : fieldMathMappingParameters) {
        if (mathMappingParameter instanceof UnitFactorParameter) {
            String name = mathMappingParameter.getName();
            if (!allContinuousVars.containsKey(name)) {
                allContinuousVars.put(name, newFunctionOrConstant(name, mathMappingParameter.getExpression(), null));
            }
        }
    }
    // 
    // add constants and functions from the particle math that aren't already defined in the continuous math
    // 
    Enumeration<Variable> enumVars = mathDesc.getVariables();
    while (enumVars.hasMoreElements()) {
        Variable var = enumVars.nextElement();
        if (var instanceof Constant || var instanceof Function) {
            String name = var.getName();
            if (!allContinuousVars.containsKey(name)) {
                allContinuousVars.put(name, var);
            }
        }
    }
    contMathDesc.setAllVariables(allContinuousVars.values().toArray(new Variable[0]));
    mathDesc = contMathDesc;
    // 
    for (int i = 0; i < fieldMathMappingParameters.length; i++) {
        if (fieldMathMappingParameters[i] instanceof UnitFactorParameter) {
            GeometryClass geometryClass = fieldMathMappingParameters[i].getGeometryClass();
            Variable variable = newFunctionOrConstant(getMathSymbol(fieldMathMappingParameters[i], geometryClass), getIdentifierSubstitutions(fieldMathMappingParameters[i].getExpression(), fieldMathMappingParameters[i].getUnitDefinition(), geometryClass), fieldMathMappingParameters[i].getGeometryClass());
            if (mathDesc.getVariable(variable.getName()) == null) {
                mathDesc.addVariable(variable);
            }
        }
    }
    if (!mathDesc.isValid()) {
        System.out.println(mathDesc.getVCML_database());
        throw new MappingException("generated an invalid mathDescription: " + mathDesc.getWarning());
    }
    System.out.println("]]]]]]]]]]]]]]]]]]]]]] VCML string begin ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]");
    System.out.println(mathDesc.getVCML());
    System.out.println("]]]]]]]]]]]]]]]]]]]]]] VCML string end ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]");
}
Also used : GeometryClass(cbit.vcell.geometry.GeometryClass) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) Action(cbit.vcell.math.Action) VolumeParticleVariable(cbit.vcell.math.VolumeParticleVariable) MembraneParticleVariable(cbit.vcell.math.MembraneParticleVariable) ParticleVariable(cbit.vcell.math.ParticleVariable) Variable(cbit.vcell.math.Variable) MathDescription(cbit.vcell.math.MathDescription) HashMap(java.util.HashMap) VolumeParticleVariable(cbit.vcell.math.VolumeParticleVariable) MembraneParticleVariable(cbit.vcell.math.MembraneParticleVariable) ParticleVariable(cbit.vcell.math.ParticleVariable) MacroscopicRateConstant(cbit.vcell.math.MacroscopicRateConstant) Constant(cbit.vcell.math.Constant) ArrayList(java.util.ArrayList) SpeciesContext(cbit.vcell.model.SpeciesContext) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SubDomain(cbit.vcell.math.SubDomain) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) Function(cbit.vcell.math.Function) MacroscopicRateConstant(cbit.vcell.math.MacroscopicRateConstant) RationalNumber(ucar.units_vcell.RationalNumber) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem) JumpProcessRateDefinition(cbit.vcell.math.JumpProcessRateDefinition) InteractionRadius(cbit.vcell.math.InteractionRadius) ParticleJumpProcess(cbit.vcell.math.ParticleJumpProcess) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) StructureMappingParameter(cbit.vcell.mapping.StructureMapping.StructureMappingParameter) Parameter(cbit.vcell.model.Parameter) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) SpeciesContextSpecProxyParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecProxyParameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) ParticleProperties(cbit.vcell.math.ParticleProperties)

Example 73 with Variable

use of cbit.vcell.math.Variable 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 74 with Variable

use of cbit.vcell.math.Variable in project vcell by virtualcell.

the class PDEDataViewer method calcAutoAllTimes.

private void calcAutoAllTimes() throws Exception {
    HashSet<String> stateVarNames = null;
    Variable theVariable = null;
    boolean bStateVar = true;
    boolean isFieldData = getPdeDataContext().getVCDataIdentifier() instanceof ExternalDataIdentifier || getPdeDataContext().getVCDataIdentifier() instanceof MergedDataInfo;
    if (isFieldData) {
        // fielddata
        DataIdentifier[] dataids = getPdeDataContext().getDataIdentifiers();
        stateVarNames = new HashSet<>();
        for (int i = 0; i < dataids.length; i++) {
            if (!dataids[i].isFunction()) {
                stateVarNames.add(dataids[i].getName());
            }
        // System.out.println("name:'"+dataids[i].getName()+"' type:"+dataids[i].getVariableType()+" func:"+dataids[i].isFunction());
        }
        bStateVar = !getPdeDataContext().getDataIdentifier().isFunction();
        if (bStateVar) {
            theVariable = new VolVariable(getPdeDataContext().getDataIdentifier().getName(), getPdeDataContext().getDataIdentifier().getDomain());
        } else {
            AnnotatedFunction[] funcs = getPdeDataContext().getFunctions();
            for (int i = 0; i < funcs.length; i++) {
                if (funcs[i].getName().equals(getPdeDataContext().getDataIdentifier().getName())) {
                    theVariable = funcs[i];
                    break;
                }
            }
        }
    } else {
        stateVarNames = getSimulation().getMathDescription().getStateVariableNames();
        theVariable = getSimulation().getMathDescription().getVariable(getPdeDataContext().getVariableName());
        if (theVariable == null) {
            theVariable = ((ClientPDEDataContext) getPdeDataContext()).getDataManager().getOutputContext().getOutputFunction(getPdeDataContext().getVariableName());
        }
        if (theVariable == null) {
            DataProcessingOutputInfo dataProcessingOutputInfo = DataProcessingResultsPanel.getDataProcessingOutputInfo(getPdeDataContext());
            if (dataProcessingOutputInfo != null && Arrays.asList(dataProcessingOutputInfo.getVariableNames()).contains(getPdeDataContext().getVariableName())) {
                // PostProcess Variable
                return;
            }
        }
        bStateVar = stateVarNames.contains(getPdeDataContext().getVariableName());
    }
    if (theVariable == null) {
        throw new Exception("Unexpected Alltimes... selected variable '" + getPdeDataContext().getVariableName() + "' is not stateVariable or OutputFunction");
    }
    if (getPDEDataContextPanel1().getdisplayAdapterService1().getAllTimes()) {
        // min-max over all timepoints (allTimes)
        if (theVariable.isConstant()) {
            getPDEDataContextPanel1().getdisplayAdapterServicePanel1().changeAllTimesButtonText(DisplayAdapterServicePanel.ALL_TIMES__STATE_TEXT);
            double constVal = theVariable.getExpression().evaluateConstant();
            getPDEDataContextPanel1().setFunctionStatisticsRange(new Range(constVal, constVal));
        } else if (bStateVar) {
            getPDEDataContextPanel1().getdisplayAdapterServicePanel1().changeAllTimesButtonText(DisplayAdapterServicePanel.ALL_TIMES__STATE_TEXT);
            ArrayList<VarStatistics> varStatsArr = calcVarStat(getPdeDataContext(), new String[] { theVariable.getName() });
            if (errorAutoAllTimes(varStatsArr != null, (varStatsArr == null ? null : varStatsArr.size() > 0), isFieldData)) {
                // no postprocessinfo
                return;
            }
            FunctionStatistics functionStatistics = new FunctionStatistics(varStatsArr.get(0).minValuesOverTime, varStatsArr.get(0).maxValuesOverTime);
            getPDEDataContextPanel1().setFunctionStatisticsRange(new Range(functionStatistics.getMinOverTime(), functionStatistics.getMaxOverTime()));
        } else if (theVariable instanceof Function) {
            getPDEDataContextPanel1().getdisplayAdapterServicePanel1().changeAllTimesButtonText(DisplayAdapterServicePanel.ALL_TIMES__APPROX_TEXT);
            Function flattened = MathDescription.getFlattenedFunctions(SimulationSymbolTable.createMathSymbolTableFactory(), getSimulation().getMathDescription(), new String[] { theVariable.getName() })[0];
            if (flattened == null) {
                flattened = (Function) theVariable;
            }
            ArrayList<VarStatistics> varStatsArr = calcVarStat(getPdeDataContext(), stateVarNames.toArray(new String[0]));
            if (errorAutoAllTimes(varStatsArr != null, (varStatsArr == null ? null : varStatsArr.size() > 0), isFieldData)) {
                // check for no postprocessinfo
                return;
            }
            if (varStatsArr.size() == stateVarNames.size()) {
                if (getSimulation().getMeshSpecification().getGeometry().getGeometrySurfaceDescription().getRegionImage() == null) {
                    getSimulation().getMeshSpecification().getGeometry().getGeometrySurfaceDescription().updateAll();
                }
                FunctionStatistics functionStatistics = FunctionRangeGenerator.getFunctionStatistics(flattened.getExpression(), varStatsArr.toArray(new VarStatistics[0]), getPdeDataContext().getTimePoints(), getPdeDataContext().getCartesianMesh(), calcInDomainBitSet(), getPdeDataContext().getDataIdentifier().getVariableType());
                getPDEDataContextPanel1().setFunctionStatisticsRange(new Range(functionStatistics.getMinOverTime(), functionStatistics.getMaxOverTime()));
            } else {
                throw new Exception("Unexpectede AllTimes... calculated state var stats size != mathdescr state var size");
            }
        } else {
            throw new Exception("Unexpected AllTimes... not constant, stateVar or function");
        }
    } else {
        // min-max at each timepoint (currTime)
        if (!(theVariable instanceof Function)) {
            getPDEDataContextPanel1().getdisplayAdapterServicePanel1().changeAllTimesButtonText(DisplayAdapterServicePanel.ALL_TIMES__STATE_TEXT);
        } else {
            getPDEDataContextPanel1().getdisplayAdapterServicePanel1().changeAllTimesButtonText(DisplayAdapterServicePanel.ALL_TIMES__APPROX_TEXT);
        }
        getPDEDataContextPanel1().setFunctionStatisticsRange(null);
    }
}
Also used : VolVariable(cbit.vcell.math.VolVariable) ReservedVariable(cbit.vcell.math.ReservedVariable) Variable(cbit.vcell.math.Variable) VCSimulationDataIdentifier(cbit.vcell.solver.VCSimulationDataIdentifier) LocalVCSimulationDataIdentifier(cbit.vcell.client.ClientSimManager.LocalVCSimulationDataIdentifier) ExternalDataIdentifier(org.vcell.util.document.ExternalDataIdentifier) VCDataIdentifier(org.vcell.util.document.VCDataIdentifier) DataIdentifier(cbit.vcell.simdata.DataIdentifier) VolVariable(cbit.vcell.math.VolVariable) ArrayList(java.util.ArrayList) Range(org.vcell.util.Range) Point(java.awt.Point) SinglePoint(cbit.vcell.geometry.SinglePoint) DataAccessException(org.vcell.util.DataAccessException) PropertyVetoException(java.beans.PropertyVetoException) ImageException(cbit.image.ImageException) UserCancelException(org.vcell.util.UserCancelException) MergedDataInfo(cbit.vcell.simdata.MergedDataInfo) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) Function(cbit.vcell.math.Function) VarStatistics(cbit.vcell.util.FunctionRangeGenerator.VarStatistics) DataProcessingOutputInfo(cbit.vcell.simdata.DataOperationResults.DataProcessingOutputInfo) ExternalDataIdentifier(org.vcell.util.document.ExternalDataIdentifier) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) FunctionStatistics(cbit.vcell.util.FunctionRangeGenerator.FunctionStatistics)

Example 75 with Variable

use of cbit.vcell.math.Variable 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)

Aggregations

Variable (cbit.vcell.math.Variable)108 Expression (cbit.vcell.parser.Expression)69 VolVariable (cbit.vcell.math.VolVariable)63 MemVariable (cbit.vcell.math.MemVariable)48 ReservedVariable (cbit.vcell.math.ReservedVariable)43 MembraneRegionVariable (cbit.vcell.math.MembraneRegionVariable)38 MathException (cbit.vcell.math.MathException)37 VolumeRegionVariable (cbit.vcell.math.VolumeRegionVariable)36 FilamentVariable (cbit.vcell.math.FilamentVariable)35 InsideVariable (cbit.vcell.math.InsideVariable)34 OutsideVariable (cbit.vcell.math.OutsideVariable)34 ExpressionException (cbit.vcell.parser.ExpressionException)34 Function (cbit.vcell.math.Function)32 MathDescription (cbit.vcell.math.MathDescription)32 Constant (cbit.vcell.math.Constant)31 FilamentRegionVariable (cbit.vcell.math.FilamentRegionVariable)29 VolumeParticleVariable (cbit.vcell.math.VolumeParticleVariable)25 MembraneParticleVariable (cbit.vcell.math.MembraneParticleVariable)24 ParticleVariable (cbit.vcell.math.ParticleVariable)24 Vector (java.util.Vector)23