Search in sources :

Example 66 with Variable

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

the class InitialConditionsPanel method jMenuItemPaste_ActionPerformed.

/**
 * Comment
 */
private void jMenuItemPaste_ActionPerformed(final java.awt.event.ActionEvent actionEvent) {
    final Vector<String> pasteDescriptionsV = new Vector<String>();
    final Vector<Expression> newExpressionsV = new Vector<Expression>();
    final Vector<SpeciesContextSpec.SpeciesContextSpecParameter> changedParametersV = new Vector<SpeciesContextSpec.SpeciesContextSpecParameter>();
    AsynchClientTask task1 = new AsynchClientTask("validating", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            if (actionEvent.getSource() == getJMenuItemPaste() || actionEvent.getSource() == getJMenuItemPasteAll()) {
                Object pasteThis = VCellTransferable.getFromClipboard(VCellTransferable.OBJECT_FLAVOR);
                MathSymbolMapping msm = null;
                Exception mathMappingException = null;
                try {
                    MathMapping mm = null;
                    mm = getSimulationContext().createNewMathMapping();
                    msm = mm.getMathSymbolMapping();
                } catch (Exception e) {
                    mathMappingException = e;
                    e.printStackTrace(System.out);
                }
                int[] rows = null;
                if (actionEvent.getSource() == getJMenuItemPasteAll()) {
                    rows = new int[getScrollPaneTable().getRowCount()];
                    for (int i = 0; i < rows.length; i += 1) {
                        rows[i] = i;
                    }
                } else {
                    rows = getScrollPaneTable().getSelectedRows();
                }
                // 
                // Check paste
                // 
                StringBuffer errors = null;
                for (int i = 0; i < rows.length; i += 1) {
                    SpeciesContextSpec scs = tableModel.getValueAt(rows[i]);
                    try {
                        if (pasteThis instanceof VCellTransferable.ResolvedValuesSelection) {
                            VCellTransferable.ResolvedValuesSelection rvs = (VCellTransferable.ResolvedValuesSelection) pasteThis;
                            for (int j = 0; j < rvs.getPrimarySymbolTableEntries().length; j += 1) {
                                SpeciesContextSpec.SpeciesContextSpecParameter pasteDestination = null;
                                SpeciesContextSpec.SpeciesContextSpecParameter clipboardBiologicalParameter = null;
                                if (rvs.getPrimarySymbolTableEntries()[j] instanceof SpeciesContextSpec.SpeciesContextSpecParameter) {
                                    clipboardBiologicalParameter = (SpeciesContextSpec.SpeciesContextSpecParameter) rvs.getPrimarySymbolTableEntries()[j];
                                } else if (rvs.getAlternateSymbolTableEntries() != null && rvs.getAlternateSymbolTableEntries()[j] instanceof SpeciesContextSpec.SpeciesContextSpecParameter) {
                                    clipboardBiologicalParameter = (SpeciesContextSpec.SpeciesContextSpecParameter) rvs.getAlternateSymbolTableEntries()[j];
                                }
                                if (clipboardBiologicalParameter == null) {
                                    Variable pastedMathVariable = null;
                                    if (rvs.getPrimarySymbolTableEntries()[j] instanceof Variable) {
                                        pastedMathVariable = (Variable) rvs.getPrimarySymbolTableEntries()[j];
                                    } else if (rvs.getAlternateSymbolTableEntries() != null && rvs.getAlternateSymbolTableEntries()[j] instanceof Variable) {
                                        pastedMathVariable = (Variable) rvs.getAlternateSymbolTableEntries()[j];
                                    }
                                    if (pastedMathVariable != null) {
                                        if (msm == null) {
                                            throw mathMappingException;
                                        }
                                        Variable localMathVariable = msm.findVariableByName(pastedMathVariable.getName());
                                        if (localMathVariable == null) {
                                            // try if localMathVariable is a speciesContext init parameter
                                            String initSuffix = DiffEquMathMapping.MATH_FUNC_SUFFIX_SPECIES_INIT_CONC_UNIT_PREFIX + TokenMangler.fixTokenStrict(scs.getInitialConcentrationParameter().getUnitDefinition().getSymbol());
                                            localMathVariable = msm.findVariableByName(pastedMathVariable.getName() + initSuffix);
                                        }
                                        if (localMathVariable != null) {
                                            SymbolTableEntry[] localBiologicalSymbolArr = msm.getBiologicalSymbol(localMathVariable);
                                            for (int k = 0; k < localBiologicalSymbolArr.length; k += 1) {
                                                if (localBiologicalSymbolArr[k] instanceof SpeciesContext && scs.getSpeciesContext() == localBiologicalSymbolArr[k]) {
                                                    // need to change
                                                    pasteDestination = scs.getInitialConditionParameter();
                                                } else if (localBiologicalSymbolArr[k] instanceof SpeciesContextSpec.SpeciesContextSpecParameter) {
                                                    for (int l = 0; l < scs.getParameters().length; l += 1) {
                                                        if (scs.getParameters()[l] == localBiologicalSymbolArr[k]) {
                                                            pasteDestination = (SpeciesContextSpec.SpeciesContextSpecParameter) localBiologicalSymbolArr[k];
                                                            break;
                                                        }
                                                    }
                                                }
                                                if (pasteDestination != null) {
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    for (int k = 0; k < scs.getParameters().length; k += 1) {
                                        SpeciesContextSpec.SpeciesContextSpecParameter scsp = (SpeciesContextSpec.SpeciesContextSpecParameter) scs.getParameters()[k];
                                        if (scsp.getRole() == clipboardBiologicalParameter.getRole() && scs.getSpeciesContext().compareEqual(((SpeciesContextSpec) clipboardBiologicalParameter.getNameScope().getScopedSymbolTable()).getSpeciesContext())) {
                                            pasteDestination = (SpeciesContextSpec.SpeciesContextSpecParameter) scsp;
                                        }
                                    }
                                }
                                if (pasteDestination != null) {
                                    changedParametersV.add(pasteDestination);
                                    newExpressionsV.add(rvs.getExpressionValues()[j]);
                                    pasteDescriptionsV.add(VCellCopyPasteHelper.formatPasteList(scs.getSpeciesContext().getName(), pasteDestination.getName(), pasteDestination.getExpression().infix(), rvs.getExpressionValues()[j].infix()));
                                }
                            }
                        }
                    } catch (Throwable e) {
                        if (errors == null) {
                            errors = new StringBuffer();
                        }
                        errors.append(scs.getSpeciesContext().getName() + " (" + e.getClass().getName() + ") " + e.getMessage() + "\n\n");
                    }
                }
                if (errors != null) {
                    throw new Exception(errors.toString());
                }
            }
        }
    };
    AsynchClientTask task2 = new AsynchClientTask("pasting", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            // Do paste
            if (pasteDescriptionsV.size() > 0) {
                String[] pasteDescriptionArr = new String[pasteDescriptionsV.size()];
                pasteDescriptionsV.copyInto(pasteDescriptionArr);
                SpeciesContextSpec.SpeciesContextSpecParameter[] changedParametersArr = new SpeciesContextSpec.SpeciesContextSpecParameter[changedParametersV.size()];
                changedParametersV.copyInto(changedParametersArr);
                Expression[] newExpressionsArr = new Expression[newExpressionsV.size()];
                newExpressionsV.copyInto(newExpressionsArr);
                VCellCopyPasteHelper.chooseApplyPaste(InitialConditionsPanel.this, pasteDescriptionArr, changedParametersArr, newExpressionsArr);
            } else {
                PopupGenerator.showInfoDialog(InitialConditionsPanel.this, "No paste items match the destination (no changes made).");
            }
        }
    };
    ClientTaskDispatcher.dispatch(this, new Hashtable<String, Object>(), new AsynchClientTask[] { task1, task2 });
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) Variable(cbit.vcell.math.Variable) VCellTransferable(cbit.vcell.desktop.VCellTransferable) SpeciesContext(cbit.vcell.model.SpeciesContext) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) Vector(java.util.Vector) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) Hashtable(java.util.Hashtable) MathSymbolMapping(cbit.vcell.mapping.MathSymbolMapping) ScopedExpression(cbit.gui.ScopedExpression) Expression(cbit.vcell.parser.Expression) DiffEquMathMapping(cbit.vcell.mapping.DiffEquMathMapping) MathMapping(cbit.vcell.mapping.MathMapping)

Example 67 with Variable

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

the class FastSystemAnalyzer method refreshInvarianceMatrix.

/**
 */
private void refreshInvarianceMatrix() throws MathException, ExpressionException {
    // 
    // the invariance's are expressed in matrix form
    // 
    // |a a a a a -1  0  0|   |x1|   |0|
    // |a a a a a  0 -1  0| * |x2| = |0|
    // |a a a a a  0  0 -1|   |x3|   |0|
    // |x4|
    // |x5|
    // |c1|
    // |c2|
    // |c3|
    // 
    Variable[] vars = new Variable[fastVarList.size()];
    fastVarList.copyInto(vars);
    int numVars = fastVarList.size();
    int rows = fastSystem.getNumFastInvariants();
    int cols = numVars + fastSystem.getNumFastInvariants();
    RationalExpMatrix matrix = new RationalExpMatrix(rows, cols);
    Enumeration<FastInvariant> fastInvariantsEnum = fastSystem.getFastInvariants();
    for (int i = 0; i < rows && fastInvariantsEnum.hasMoreElements(); i++) {
        FastInvariant fi = (FastInvariant) fastInvariantsEnum.nextElement();
        Expression function = fi.getFunction();
        for (int j = 0; j < numVars; j++) {
            Variable var = (Variable) fastVarList.elementAt(j);
            Expression exp = function.differentiate(var.getName());
            exp.bindExpression(null);
            exp = exp.flatten();
            RationalExp coeffRationalExp = RationalExpUtils.getRationalExp(exp);
            matrix.set_elem(i, j, coeffRationalExp);
        }
        matrix.set_elem(i, numVars + i, -1);
    }
    // Print
    System.out.println("origMatrix");
    matrix.show();
    // 
    // gaussian elimination on the matrix give the following representation
    // note that some column pivoting (variable re-ordering) is sometimes required to
    // determine N-r dependent vars
    // 
    // |10i0iccc|
    // |01i0iccc|  where (c)'s are the coefficients for constants of invariances
    // |00i1iccc|        (i)'s are the coefficients for dependent vars in terms of independent vars
    // 
    // Print
    System.out.println("reducedMatrix");
    if (rows > 0) {
        try {
            matrix.gaussianElimination(new RationalExpMatrix(rows, rows));
        } catch (MatrixException e) {
            e.printStackTrace(System.out);
            throw new MathException(e.getMessage());
        }
    }
    matrix.show();
    for (int i = 0; i < vars.length; i++) {
        System.out.print(vars[i].getName() + "  ");
    }
    System.out.println("");
    // 
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < rows; j++) {
            RationalExp rexp = matrix.get(i, j).simplify();
            matrix.set_elem(i, j, rexp);
        }
    }
    for (int i = 0; i < rows; i++) {
        // 
        if (!matrix.get(i, i).isConstant() || matrix.get(i, i).getConstant().doubleValue() != 1) {
            for (int j = i + 1; j < numVars; j++) {
                if (matrix.get(i, j).isConstant() && matrix.get(i, j).getConstant().doubleValue() == 1.0) {
                    for (int ii = 0; ii < rows; ii++) {
                        RationalExp temp = matrix.get(ii, i);
                        matrix.set_elem(ii, i, matrix.get(ii, j));
                        matrix.set_elem(ii, j, temp);
                    }
                    Variable tempVar = vars[i];
                    vars[i] = vars[j];
                    vars[j] = tempVar;
                    break;
                }
            }
        }
    }
    // Print
    for (int i = 0; i < vars.length; i++) {
        System.out.print(vars[i].getName() + "  ");
    }
    System.out.println("");
    matrix.show();
    // 
    // separate into dependent and indepent variables, and chop off identity matrix (left N-r columns)
    // 
    // T       |iiccc|                   T
    // [x1 x2 x4] = -1 * |iiccc| * [x3 x5 c1 c2 c3]
    // |iiccc|
    // 
    // 
    int numInvariants = fastSystem.getNumFastInvariants();
    dependentVarList.removeAllElements();
    for (int i = 0; i < numInvariants; i++) {
        dependentVarList.addElement(vars[i]);
    }
    independentVarList.removeAllElements();
    for (int i = numInvariants; i < vars.length; i++) {
        independentVarList.addElement(vars[i]);
    }
    int new_cols = independentVarList.size() + numInvariants;
    dependencyMatrix = new RationalExpMatrix(rows, new_cols);
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < new_cols; j++) {
            RationalExp rexp = matrix.get(i, j + dependentVarList.size()).simplify().minus();
            dependencyMatrix.set_elem(i, j, rexp);
        }
    }
    // Print
    System.out.println("\n\nDEPENDENCY MATRIX");
    dependencyMatrix.show();
    System.out.print("dependent vars: ");
    for (int i = 0; i < dependentVarList.size(); i++) {
        System.out.print(((Variable) dependentVarList.elementAt(i)).getName() + "  ");
    }
    System.out.println("");
    System.out.print("independent vars: ");
    for (int i = 0; i < independentVarList.size(); i++) {
        System.out.print(((Variable) independentVarList.elementAt(i)).getName() + "  ");
    }
    System.out.println("");
}
Also used : MatrixException(cbit.vcell.matrix.MatrixException) ReservedVariable(cbit.vcell.math.ReservedVariable) Variable(cbit.vcell.math.Variable) VolVariable(cbit.vcell.math.VolVariable) MemVariable(cbit.vcell.math.MemVariable) RationalExpMatrix(cbit.vcell.matrix.RationalExpMatrix) Expression(cbit.vcell.parser.Expression) MathException(cbit.vcell.math.MathException) RationalExp(cbit.vcell.matrix.RationalExp) FastInvariant(cbit.vcell.math.FastInvariant)

Example 68 with Variable

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

the class FastSystemAnalyzer method refreshSubstitutedRateExps.

/**
 */
private void refreshSubstitutedRateExps() throws MathException, ExpressionException {
    // 
    // refresh PseudoConstants (temp constants involved with fastInvariants)
    // 
    pseudoConstantList.removeAllElements();
    Enumeration<FastInvariant> enum_fi = fastSystem.getFastInvariants();
    while (enum_fi.hasMoreElements()) {
        FastInvariant fi = enum_fi.nextElement();
        fi.getFunction().bindExpression(this);
        PseudoConstant pc = new PseudoConstant(getAvailablePseudoConstantName(), fi.getFunction(), MathMapping_4_8.nullDomain);
        pseudoConstantList.addElement(pc);
    // System.out.println("FastSystem.refreshSubstitutedRateExps() __C"+i+" = "+fi.getFunction());
    }
    // 
    // build expressions for dependent variables in terms of independent vars
    // and pseudoConstants
    // 
    dependencyExpList.removeAllElements();
    for (int row = 0; row < dependentVarList.size(); row++) {
        Expression exp = new Expression("0.0;");
        // 
        for (int col = 0; col < independentVarList.size(); col++) {
            Variable indepVar = (Variable) independentVarList.elementAt(col);
            RationalExp coefExp = dependencyMatrix.get(row, col).simplify();
            if (!coefExp.isZero()) {
                exp = Expression.add(exp, new Expression(coefExp.infixString() + "*" + indepVar.getName()));
            }
        }
        // 
        for (int col = independentVarList.size(); col < dependencyMatrix.getNumCols(); col++) {
            PseudoConstant pc = (PseudoConstant) pseudoConstantList.elementAt(col - independentVarList.size());
            RationalExp coefExp = dependencyMatrix.get(row, col);
            if (!coefExp.isZero()) {
                exp = Expression.add(exp, new Expression(coefExp.infixString() + "*" + pc.getName()));
            }
        }
        exp.bindExpression(null);
        exp = exp.flatten();
        exp.bindExpression(this);
        // System.out.println("FastSystem.refreshSubstitutedRateExps() "+((Variable)dependentVarList.elementAt(row)).getName()+" = "+exp.toString()+";");
        dependencyExpList.addElement(exp);
    }
    // 
    // flatten functions, then substitute expressions for dependent vars into rate expressions
    // 
    fastRateExpList.removeAllElements();
    // VariableSymbolTable combinedSymbolTable = getCombinedSymbolTable();
    Enumeration<FastRate> enum_fr = fastSystem.getFastRates();
    while (enum_fr.hasMoreElements()) {
        FastRate fr = enum_fr.nextElement();
        Expression exp = new Expression(MathUtilities.substituteFunctions(new Expression(fr.getFunction()), this));
        // System.out.println("FastSystem.refreshSubstitutedRateExps() fast rate before substitution = "+exp.toString());
        for (int j = 0; j < dependentVarList.size(); j++) {
            Variable depVar = (Variable) dependentVarList.elementAt(j);
            Expression subExp = new Expression((Expression) dependencyExpList.elementAt(j));
            exp.substituteInPlace(new Expression(depVar.getName()), subExp);
        }
        exp.bindExpression(null);
        exp = exp.flatten();
        // System.out.println("FastSystem.refreshSubstitutedRateExps() fast rate after substitution  = "+exp.toString());
        exp.bindExpression(this);
        fastRateExpList.addElement(exp);
    }
}
Also used : ReservedVariable(cbit.vcell.math.ReservedVariable) Variable(cbit.vcell.math.Variable) VolVariable(cbit.vcell.math.VolVariable) MemVariable(cbit.vcell.math.MemVariable) Expression(cbit.vcell.parser.Expression) PseudoConstant(cbit.vcell.math.PseudoConstant) FastRate(cbit.vcell.math.FastRate) RationalExp(cbit.vcell.matrix.RationalExp) FastInvariant(cbit.vcell.math.FastInvariant)

Example 69 with Variable

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

the class FastSystemAnalyzer method refreshFastVarList.

/**
 * @return java.util.Vector
 */
private void refreshFastVarList() throws MathException, ExpressionException {
    fastVarList.clear();
    // 
    // get list of unique (VolVariables and MemVariables) in fastRate expressions
    // 
    Enumeration<FastRate> fastRatesEnum = fastSystem.getFastRates();
    while (fastRatesEnum.hasMoreElements()) {
        FastRate fr = fastRatesEnum.nextElement();
        Expression exp = fr.getFunction();
        Enumeration<Variable> enum1 = MathUtilities.getRequiredVariables(exp, this);
        while (enum1.hasMoreElements()) {
            Variable var = enum1.nextElement();
            if (var instanceof VolVariable || var instanceof MemVariable) {
                if (!fastVarList.contains(var)) {
                    fastVarList.addElement(var);
                // System.out.println("FastSystemImplicit.refreshFastVarList(), FAST RATE VARIABLE: "+var.getName());
                }
            }
        }
    }
    // 
    // get list of all variables used in invariant expressions that are not used in fast rates
    // 
    Enumeration<FastInvariant> fastInvariantsEnum = fastSystem.getFastInvariants();
    while (fastInvariantsEnum.hasMoreElements()) {
        FastInvariant fi = (FastInvariant) fastInvariantsEnum.nextElement();
        Expression exp = fi.getFunction();
        // System.out.println("FastSystemImplicit.refreshFastVarList(), ORIGINAL FAST INVARIANT: "+exp);
        Enumeration<Variable> enum1 = MathUtilities.getRequiredVariables(exp, this);
        while (enum1.hasMoreElements()) {
            Variable var = enum1.nextElement();
            if (var instanceof VolVariable || var instanceof MemVariable) {
                if (!fastVarList.contains(var)) {
                    fastVarList.addElement(var);
                }
            }
        }
    }
    // 
    // verify that there are N equations (rates+invariants) and N unknowns (fastVariables)
    // 
    int numBoundFunctions = fastSystem.getNumFastInvariants() + fastSystem.getNumFastRates();
    if (fastVarList.size() != numBoundFunctions) {
        throw new MathException("FastSystem.checkDimension(), there are " + fastVarList.size() + " variables and " + numBoundFunctions + " FastInvariant's & FastRates");
    }
}
Also used : ReservedVariable(cbit.vcell.math.ReservedVariable) Variable(cbit.vcell.math.Variable) VolVariable(cbit.vcell.math.VolVariable) MemVariable(cbit.vcell.math.MemVariable) MemVariable(cbit.vcell.math.MemVariable) Expression(cbit.vcell.parser.Expression) VolVariable(cbit.vcell.math.VolVariable) MathException(cbit.vcell.math.MathException) FastRate(cbit.vcell.math.FastRate) FastInvariant(cbit.vcell.math.FastInvariant)

Example 70 with Variable

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

the class MathMapping_4_8 method getResolvedVolVariable.

/**
 * Find the defined variable (VolVariable) for the resolved compartments.
 * This method is used to assure only one variable is created.
 * @return cbit.vcell.math.VolVariable
 * @param species cbit.vcell.model.Species
 */
private VolVariable getResolvedVolVariable(Species species) {
    Enumeration<SpeciesContextMapping> enum1 = getSpeciesContextMappings();
    while (enum1.hasMoreElements()) {
        SpeciesContextMapping scm = enum1.nextElement();
        if (scm.getSpeciesContext().getSpecies() == species) {
            Variable var = scm.getVariable();
            if (var instanceof VolVariable) {
                Structure structure = scm.getSpeciesContext().getStructure();
                StructureMapping sm = simContext.getGeometryContext().getStructureMapping(structure);
                if (structure instanceof Feature && getResolved(sm)) {
                    return (VolVariable) var;
                }
            }
        }
    }
    return new VolVariable(TokenMangler.fixTokenStrict(species.getCommonName()), nullDomain);
}
Also used : MembraneRegionVariable(cbit.vcell.math.MembraneRegionVariable) VolVariable(cbit.vcell.math.VolVariable) MemVariable(cbit.vcell.math.MemVariable) Variable(cbit.vcell.math.Variable) SpeciesContextMapping(cbit.vcell.mapping.SpeciesContextMapping) VolVariable(cbit.vcell.math.VolVariable) Structure(cbit.vcell.model.Structure) StructureMapping(cbit.vcell.mapping.StructureMapping) Feature(cbit.vcell.model.Feature)

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