Search in sources :

Example 6 with MappingException

use of cbit.vcell.mapping.MappingException in project vcell by virtualcell.

the class PotentialMapping method determineLumpedEquations.

/**
 * Insert the method's description here.
 * Creation date: (2/20/2002 9:02:42 AM)
 * @return cbit.vcell.mathmodel.MathModel
 * @param circuitGraph cbit.vcell.mapping.potential.Graph
 */
private void determineLumpedEquations(Graph graph, double temperatureKelvin) throws ExpressionException, MatrixException, MappingException, MathException {
    // 
    // traverses graph and calculates RHS expressions for all capacitive devices (dV/dt)
    // 
    // calculate dependent voltages as functions of independent voltages.
    // 
    // 
    Graph[] spanningTrees = graph.getSpanningForest();
    if (!bSilent) {
        System.out.println("spanning tree(s):");
        for (int i = 0; i < spanningTrees.length; i++) {
            System.out.println(i + ") " + spanningTrees[i]);
        }
    }
    Path[] fundamentalCycles = graph.getFundamentalCycles();
    if (!bSilent) {
        System.out.println("fundamental cycles:");
        for (int i = 0; i < fundamentalCycles.length; i++) {
            System.out.println("   " + fundamentalCycles[i]);
        }
    }
    // 
    // print out basic device information
    // 
    fieldEdges = graph.getEdges();
    // 
    if (!bSilent) {
        System.out.println("\n\n applying KVL to <<ALL>> fundamental cycles\n");
    }
    Path[] graphCycles = graph.getFundamentalCycles();
    RationalExpMatrix voltageMatrix = new RationalExpMatrix(graphCycles.length, graph.getNumEdges());
    for (int i = 0; i < graphCycles.length; i++) {
        Edge[] cycleEdges = graphCycles[i].getEdges();
        Node[] nodesTraversed = graphCycles[i].getNodesTraversed();
        Expression exp = new Expression(0.0);
        // 
        for (int j = 0; j < cycleEdges.length; j++) {
            int edgeIndex = graph.getIndex(cycleEdges[j]);
            Expression voltage = new Expression(((ElectricalDevice) cycleEdges[j].getData()).getVoltageSymbol(), fieldMathMapping.getNameScope());
            if (cycleEdges[j].getNode1().equals(nodesTraversed[j])) {
                // going same direction
                exp = Expression.add(exp, voltage);
                voltageMatrix.set_elem(i, edgeIndex, 1);
            } else {
                // going opposite direction
                exp = Expression.add(exp, Expression.negate(voltage));
                voltageMatrix.set_elem(i, edgeIndex, -1);
            }
        }
        if (!bSilent) {
            System.out.println(exp.flatten().infix() + " = 0.0");
        }
    }
    if (!bSilent) {
        voltageMatrix.show();
    }
    if (voltageMatrix.getNumRows() > 0) {
        RationalExpMatrix vPermutationMatrix = new RationalExpMatrix(voltageMatrix.getNumRows(), voltageMatrix.getNumRows());
        voltageMatrix.gaussianElimination(vPermutationMatrix);
        if (!bSilent) {
            System.out.println("reduced matrix");
            voltageMatrix.show();
        }
    } else {
        voltageMatrix = null;
    }
    // 
    // declare dependent voltages as functions of independent voltages
    // 
    // 1) Always use Voltage-Clamps as independent voltages
    // 2) Try to use Capacitive devices as independent voltages
    // 
    // solve for current-clamp voltages and redundant/constrained capacitive voltages as function of (1) and (2).
    // 
    Expression[] dependentVoltageExpressions = new Expression[fieldEdges.length];
    // 
    // make sure assumptions hold regarding edge ordering, otherwise wrong dependent voltages will be selected
    // 
    verifyEdgeOrdering();
    for (int i = 0; voltageMatrix != null && i < voltageMatrix.getNumRows(); i++) {
        // 
        // find first '1.0' element, this column is the next 'dependent' voltage
        // 
        int column = -1;
        for (int j = i; j < voltageMatrix.getNumCols(); j++) {
            RationalExp elem = voltageMatrix.get(i, j);
            if (elem.isConstant() && elem.getConstant().doubleValue() == 1.0) {
                column = j;
                break;
            }
        }
        if (column != -1) {
            // 
            // get electrical device of dependent voltage
            // 
            ElectricalDevice device = (ElectricalDevice) fieldEdges[column].getData();
            // 
            // form dependency expression
            // 
            StringBuffer buffer = new StringBuffer();
            for (int j = column + 1; j < graph.getNumEdges(); j++) {
                if (!voltageMatrix.get_elem(i, j).isZero()) {
                    ElectricalDevice colDevice = (ElectricalDevice) fieldEdges[j].getData();
                    Expression voltage = new Expression(colDevice.getVoltageSymbol(), fieldMathMapping.getNameScope());
                    buffer.append(" + " + voltageMatrix.get(i, j).minus().infixString() + '*' + voltage.infix());
                }
            }
            dependentVoltageExpressions[column] = (new Expression(buffer.toString())).flatten();
            dependentVoltageExpressions[column].bindExpression(device);
            device.setDependentVoltageExpression(dependentVoltageExpressions[column]);
        }
    }
    if (!bSilent) {
        for (int i = 0; i < dependentVoltageExpressions.length; i++) {
            System.out.println("dependentVoltageExpressions[" + i + "] = " + dependentVoltageExpressions[i]);
        }
    }
    // 
    if (!bSilent) {
        System.out.println("\n\nSOLVE FOR TOTAL CURRENTS IN TERMS OF APPLIED CURRENTS");
        System.out.println("\n\n  1)  applying KVL to all fundamental \"capacitive\" and Voltage-clamp cycles (after current-clamp edges are removed)\n");
    }
    Graph capacitorGraph = new Graph();
    for (int i = 0; i < fieldEdges.length; i++) {
        ElectricalDevice device = (ElectricalDevice) fieldEdges[i].getData();
        if (device.hasCapacitance() || device.isVoltageSource()) {
            capacitorGraph.addEdge(fieldEdges[i]);
        }
    }
    Path[] capacitorGraphCycles = capacitorGraph.getFundamentalCycles();
    RationalExpMatrix capacitorGraphVoltageMatrix = new RationalExpMatrix(capacitorGraphCycles.length, graph.getNumEdges());
    for (int i = 0; i < capacitorGraphCycles.length; i++) {
        Edge[] cycleEdges = capacitorGraphCycles[i].getEdges();
        Node[] nodesTraversed = capacitorGraphCycles[i].getNodesTraversed();
        Expression exp = new Expression(0.0);
        // 
        for (int j = 0; j < cycleEdges.length; j++) {
            int edgeIndex = graph.getIndex(cycleEdges[j]);
            Expression voltage = new Expression(((ElectricalDevice) cycleEdges[j].getData()).getVoltageSymbol(), fieldMathMapping.getNameScope());
            if (cycleEdges[j].getNode1().equals(nodesTraversed[j])) {
                // going same direction
                exp = Expression.add(exp, voltage);
                capacitorGraphVoltageMatrix.set_elem(i, edgeIndex, 1);
            } else {
                // going opposite direction
                exp = Expression.add(exp, Expression.negate(voltage));
                capacitorGraphVoltageMatrix.set_elem(i, edgeIndex, -1);
            }
        }
        if (!bSilent) {
            System.out.println(exp.flatten().infix() + " = 0.0");
        }
    }
    if (!bSilent) {
        capacitorGraphVoltageMatrix.show();
    }
    // 
    if (!bSilent) {
        System.out.println("\n\n  2)  applying KCL to all nodes (except one) .. n-1 nodes of full graph  --- CONSERVATION OF TOTAL CURRENT\n");
    }
    Node[] nodes = graph.getNodes();
    RationalExpMatrix kclMatrix = new RationalExpMatrix(graph.getNumNodes() - 1, graph.getNumEdges());
    for (int i = 0; i < nodes.length - 1; i++) {
        if (graph.getDegree(nodes[i]) > 0) {
            Edge[] adjacentEdges = graph.getAdjacentEdges(nodes[i]);
            Expression exp = new Expression(0.0);
            // 
            for (int j = 0; j < adjacentEdges.length; j++) {
                int edgeIndex = graph.getIndex(adjacentEdges[j]);
                Expression totalCurrent = new Expression(((ElectricalDevice) adjacentEdges[j].getData()).getTotalCurrentSymbol(), fieldMathMapping.getNameScope());
                if (adjacentEdges[j].getNode1().equals(nodes[i])) {
                    exp = Expression.add(exp, Expression.negate(totalCurrent));
                    kclMatrix.set_elem(i, edgeIndex, -1);
                } else {
                    exp = Expression.add(exp, totalCurrent);
                    kclMatrix.set_elem(i, edgeIndex, 1);
                }
            }
            if (!bSilent) {
                System.out.println(exp.flatten().infix() + " = 0.0");
            }
        } else {
            throw new MappingException("compartment '" + nodes[i].getName() + "' is electrically isolated, cannot generate ciruit equations for application '" + fieldSimContext.getName() + "'.  \n\nPlease specify electrical properties for all membranes (see Structures tab in Physiology).");
        }
    }
    if (!bSilent) {
        kclMatrix.show();
    }
    // 
    if (!bSilent) {
        System.out.println("\n\n  3)  form total 'current' matrix\n");
    }
    int numNonCapacitiveEdges = 0;
    for (int i = 0; i < fieldEdges.length; i++) {
        ElectricalDevice device = (ElectricalDevice) fieldEdges[i].getData();
        if (!device.hasCapacitance()) {
            numNonCapacitiveEdges++;
        }
    }
    int cmat_rows = kclMatrix.getNumRows() + capacitorGraphVoltageMatrix.getNumRows() + numNonCapacitiveEdges;
    RationalExpMatrix currentMatrix = new RationalExpMatrix(cmat_rows, 3 * graph.getNumEdges());
    // 
    // order edges for current elimination (unknown voltage-clamp currents as well as all total currents).
    // 
    int[] cIndex = new int[fieldEdges.length];
    int ci = 0;
    for (int i = 0; i < fieldEdges.length; i++) {
        if (((ElectricalDevice) fieldEdges[i].getData()).isVoltageSource()) {
            cIndex[ci++] = i;
        }
    }
    for (int i = 0; i < fieldEdges.length; i++) {
        if (!((ElectricalDevice) fieldEdges[i].getData()).isVoltageSource()) {
            cIndex[ci++] = i;
        }
    }
    if (ci != fieldEdges.length) {
        throw new RuntimeException("error computing current indexes");
    }
    if (!bSilent) {
        System.out.println("reordered devices for current matrix elimination");
        for (int i = 0; i < cIndex.length; i++) {
            Expression voltage = new Expression(((ElectricalDevice) fieldEdges[cIndex[i]].getData()).getVoltageSymbol(), fieldMathMapping.getNameScope());
            System.out.println(i + ") = device[" + cIndex[i] + "] = " + voltage.infix());
        }
    }
    int row = 0;
    // 
    for (int i = 0; i < kclMatrix.getNumRows(); i++) {
        for (int j = 0; j < kclMatrix.getNumCols(); j++) {
            // entry for i's
            currentMatrix.set_elem(row, j, kclMatrix.get(i, cIndex[j]));
        }
        row++;
    }
    // 
    for (int i = 0; i < fieldEdges.length; i++) {
        ElectricalDevice device = (ElectricalDevice) fieldEdges[cIndex[i]].getData();
        if (!device.hasCapacitance()) {
            currentMatrix.set_elem(row, i, 1);
            currentMatrix.set_elem(row, i + graph.getNumEdges(), -1);
            row++;
        }
    }
    // 
    // add current terms of (i - F)*1000/C form using KVL relationships from "capacitor graph"
    // 
    ModelUnitSystem modelUnitSystem = fieldMathMapping.getSimulationContext().getModel().getUnitSystem();
    VCUnitDefinition potentialUnit = modelUnitSystem.getVoltageUnit();
    VCUnitDefinition timeUnit = modelUnitSystem.getTimeUnit();
    for (int i = 0; i < capacitorGraphVoltageMatrix.getNumRows(); i++) {
        for (int j = 0; j < capacitorGraphVoltageMatrix.getNumCols(); j++) {
            ElectricalDevice device = (ElectricalDevice) fieldEdges[cIndex[j]].getData();
            RationalExp coefficient = capacitorGraphVoltageMatrix.get(i, cIndex[j]);
            if (device.hasCapacitance()) {
                // 
                // replace dVi/dt  with   1000/Ci * Ii  +  1000/Ci * Fi
                // 
                SymbolTableEntry capacitanceParameter = ((MembraneElectricalDevice) device).getCapacitanceParameter();
                Expression capacitance = new Expression(capacitanceParameter, fieldMathMapping.getNameScope());
                String Cname = capacitance.infix();
                VCUnitDefinition unitFactor = potentialUnit.divideBy(timeUnit).multiplyBy(capacitanceParameter.getUnitDefinition()).divideBy(device.getTotalCurrentSymbol().getUnitDefinition());
                RationalExp unitFactorExp = fieldMathMapping.getUnitFactorAsRationalExp(unitFactor);
                // entry for i's
                currentMatrix.set_elem(row, j, coefficient.mult(unitFactorExp.div(new RationalExp(Cname))));
                // entry for F's
                currentMatrix.set_elem(row, j + graph.getNumEdges(), coefficient.minus().mult(unitFactorExp).div(new RationalExp(Cname)));
            } else if (device.isVoltageSource()) {
                // 
                // directly insert "symbolic" dVi/dt into the new matrix
                // 
                currentMatrix.set_elem(row, j + 2 * graph.getNumEdges(), coefficient);
            }
        }
        row++;
    }
    if (!bSilent) {
        currentMatrix.show();
    }
    if (currentMatrix.getNumRows() > 0) {
        RationalExpMatrix cPermutationMatrix = new RationalExpMatrix(currentMatrix.getNumRows(), currentMatrix.getNumRows());
        currentMatrix.gaussianElimination(cPermutationMatrix);
        if (!bSilent) {
            System.out.println("reduced matrix");
            currentMatrix.show();
        }
    }
    // 
    if (!bSilent) {
        System.out.println("\n\n total currents for each device\n");
    }
    Expression[] totalCurrents = new Expression[fieldEdges.length];
    for (int i = 0; i < fieldEdges.length; i++) {
        ElectricalDevice device = (ElectricalDevice) fieldEdges[cIndex[i]].getData();
        StringBuffer buffer = new StringBuffer("0.0");
        // 
        for (int j = 0; j < graph.getNumEdges(); j++) {
            RationalExp coefficient = currentMatrix.get(i, j + graph.getNumEdges());
            if (!coefficient.isZero()) {
                ElectricalDevice colDevice = (ElectricalDevice) fieldEdges[cIndex[j]].getData();
                Expression source = new Expression(colDevice.getSourceSymbol(), fieldMathMapping.getNameScope());
                buffer.append(" + " + coefficient.minus() + "*" + source.infix());
            }
        }
        // 
        for (int j = 0; j < graph.getNumEdges(); j++) {
            RationalExp coefficient = currentMatrix.get(i, j + 2 * graph.getNumEdges());
            if (!coefficient.isZero()) {
                VoltageClampElectricalDevice colDevice = (VoltageClampElectricalDevice) fieldEdges[cIndex[j]].getData();
                Expression timeDeriv = colDevice.getVoltageClampStimulus().getVoltageParameter().getExpression().differentiate("t");
                timeDeriv = timeDeriv.flatten();
                timeDeriv.bindExpression(colDevice);
                timeDeriv.renameBoundSymbols(colDevice.getNameScope().getParent());
                buffer.append(" + " + coefficient.minus() + "*" + timeDeriv.infix());
            }
        }
        totalCurrents[cIndex[i]] = (new Expression(buffer.toString())).flatten();
        totalCurrents[cIndex[i]].bindExpression(device.getNameScope().getParent().getScopedSymbolTable());
        device.getParameterFromRole(ElectricalDevice.ROLE_TotalCurrent).setExpression(totalCurrents[cIndex[i]]);
    }
    if (!bSilent) {
        for (int i = 0; i < totalCurrents.length; i++) {
            System.out.println("totalCurrents[" + i + "] = " + totalCurrents[cIndex[i]].toString());
        }
    }
    // 
    if (!bSilent) {
        System.out.println("\n\n capacitive currents for each device\n");
    }
    Expression[] capacitiveCurrents = new Expression[fieldEdges.length];
    for (int i = 0; i < fieldEdges.length; i++) {
        ElectricalDevice device = (ElectricalDevice) fieldEdges[i].getData();
        if (device instanceof MembraneElectricalDevice) {
            MembraneElectricalDevice membraneElectricalDevice = (MembraneElectricalDevice) device;
            Expression source = new Expression(membraneElectricalDevice.getSourceSymbol(), fieldMathMapping.getNameScope());
            capacitiveCurrents[i] = Expression.add(totalCurrents[i], Expression.negate(source));
            capacitiveCurrents[i].bindExpression(membraneElectricalDevice);
        // membraneElectricalDevice.setCapacitiveCurrentExpression(capacitiveCurrents[i]);
        } else {
        // device.setCapacitiveCurrentExpression(new Expression(0.0));
        }
    }
    if (!bSilent) {
        for (int i = 0; i < capacitiveCurrents.length; i++) {
            System.out.println("capacitiveCurrents[" + i + "] = " + ((capacitiveCurrents[cIndex[i]] == null) ? "0.0" : capacitiveCurrents[cIndex[i]].infix()));
        }
    }
// 
// display equations for independent voltages.
// 
// if (!bSilent){
// for (int i = 0; i < graph.getNumEdges(); i++){
// ElectricalDevice device = (ElectricalDevice)graph.getEdges()[i].getData();
// //
// // membrane ode
// //
// if (device.hasCapacitance() && dependentVoltageExpressions[i]==null){
// Expression initExp = new Expression(0.0);
// System.out.println(device.getInitialVoltageFunction().getVCML());
// System.out.println((new cbit.vcell.math.OdeEquation(new cbit.vcell.math.VolVariable(device.getVName()),new Expression(device.getInitialVoltageFunction().getName()),new Expression(fieldCapacitiveCurrent[i].flatten().toString()+"*"+cbit.vcell.model.ReservedSymbol.KMILLIVOLTS.getName()+"/"+device.getCapName()))).getVCML());
// }
// //
// // membrane forced potential
// //
// if (device.hasCapacitance() && dependentVoltageExpressions[i]!=null){
// System.out.println((new Function(device.getVName(),dependentVoltageExpressions[i])).getVCML());
// System.out.println((new Function(device.getSourceName(),device.getCurrentSourceExpression()).getVCML()));
// }
// //
// // current clamp
// //
// if (!device.hasCapacitance() && !device.isVoltageSource()){
// System.out.println((new Function(device.getSourceName(),device.getCurrentSourceExpression()).getVCML()));
// System.out.println((new Function(device.getVName(),dependentVoltageExpressions[i])).getVCML());
// }
// //
// // voltage clamp
// //
// if (!device.hasCapacitance() && device.isVoltageSource()){
// System.out.println((new Function(device.getIName(),totalCurrents[i])).getVCML());
// System.out.println((new Function(device.getVName(),device.getInitialVoltageFunction().getExpression())).getVCML());
// }
// }
// }
}
Also used : Path(cbit.util.graph.Path) Node(cbit.util.graph.Node) RationalExp(cbit.vcell.matrix.RationalExp) MappingException(cbit.vcell.mapping.MappingException) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) Graph(cbit.util.graph.Graph) RationalExpMatrix(cbit.vcell.matrix.RationalExpMatrix) Expression(cbit.vcell.parser.Expression) Edge(cbit.util.graph.Edge) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem)

Example 7 with MappingException

use of cbit.vcell.mapping.MappingException in project vcell by virtualcell.

the class StochMathMapping_4_8 method refreshVariables.

/**
 * Map speciesContext to variable, used for structural analysis (slow reactions and fast reactions)
 * Creation date: (10/25/2006 8:59:43 AM)
 * @exception cbit.vcell.mapping.MappingException The exception description.
 */
private void refreshVariables() throws MappingException {
    // 
    // non-constant dependant variables(means rely on other contants/functions) require a function
    // 
    Enumeration<SpeciesContextMapping> enum1 = getSpeciesContextMappings();
    while (enum1.hasMoreElements()) {
        SpeciesContextMapping scm = enum1.nextElement();
        SpeciesContextSpec scs = getSimulationContext().getReactionContext().getSpeciesContextSpec(scm.getSpeciesContext());
        if (scm.getDependencyExpression() != null && !scs.isConstant()) {
            // scm.setVariable(new Function(scm.getSpeciesContext().getName(),scm.getDependencyExpression()));
            scm.setVariable(null);
        }
    }
    // 
    // non-constant independant variables require either a membrane or volume variable
    // 
    enum1 = getSpeciesContextMappings();
    // stochastic substance unit from modelUnitSystem
    ModelUnitSystem modelUnitSystem = getSimulationContext().getModel().getUnitSystem();
    VCUnitDefinition stochSubstanceUnit = modelUnitSystem.getStochasticSubstanceUnit();
    while (enum1.hasMoreElements()) {
        SpeciesContextMapping scm = (SpeciesContextMapping) enum1.nextElement();
        SpeciesContextSpec scs = getSimulationContext().getReactionContext().getSpeciesContextSpec(scm.getSpeciesContext());
        // stochastic variable is always a function of size.
        MathMapping_4_8.SpeciesCountParameter spCountParm = null;
        try {
            String countName = scs.getSpeciesContext().getName() + BIO_PARAM_SUFFIX_SPECIES_COUNT;
            Expression countExp = new Expression(0.0);
            spCountParm = addSpeciesCountParameter(countName, countExp, MathMapping_4_8.PARAMETER_ROLE_COUNT, stochSubstanceUnit, scs);
        } catch (PropertyVetoException pve) {
            pve.printStackTrace();
            throw new MappingException(pve.getMessage());
        }
        // add concentration of species as MathMappingParameter - this will map to species concentration function
        try {
            String concName = scs.getSpeciesContext().getName() + BIO_PARAM_SUFFIX_SPECIES_CONCENTRATION;
            Expression concExp = getExpressionAmtToConc(new Expression(spCountParm.getName()), scs.getSpeciesContext());
            concExp.bindExpression(this);
            addSpeciesConcentrationParameter(concName, concExp, MathMapping_4_8.PARAMETER_ROLE_CONCENRATION, scs.getSpeciesContext().getUnitDefinition(), scs);
        } catch (Exception e) {
            e.printStackTrace();
            throw new MappingException(e.getMessage());
        }
        if (scm.getDependencyExpression() == null && !scs.isConstant()) {
            scm.setVariable(new StochVolVariable(getMathSymbol(spCountParm, getSimulationContext().getGeometryContext().getStructureMapping(scs.getSpeciesContext().getStructure()))));
            mathSymbolMapping.put(scm.getSpeciesContext(), scm.getVariable().getName());
        }
    }
}
Also used : SpeciesContextMapping(cbit.vcell.mapping.SpeciesContextMapping) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) PropertyVetoException(java.beans.PropertyVetoException) MatrixException(cbit.vcell.matrix.MatrixException) ModelException(cbit.vcell.model.ModelException) ExpressionException(cbit.vcell.parser.ExpressionException) MappingException(cbit.vcell.mapping.MappingException) MathException(cbit.vcell.math.MathException) MappingException(cbit.vcell.mapping.MappingException) PropertyVetoException(java.beans.PropertyVetoException) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) StochVolVariable(cbit.vcell.math.StochVolVariable) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem)

Example 8 with MappingException

use of cbit.vcell.mapping.MappingException in project vcell by virtualcell.

the class ModelOptimizationMapping method getRemappedReferenceData.

/**
 * Gets the constraintData property (cbit.vcell.opt.ConstraintData) value.
 * @return The constraintData property value.
 * @see #setConstraintData
 */
private ReferenceData getRemappedReferenceData(MathMapping mathMapping) throws MappingException {
    if (modelOptimizationSpec.getReferenceData() == null) {
        return null;
    }
    // 
    // make sure time is mapped
    // 
    ReferenceData refData = modelOptimizationSpec.getReferenceData();
    ReferenceDataMappingSpec[] refDataMappingSpecs = modelOptimizationSpec.getReferenceDataMappingSpecs();
    RowColumnResultSet rowColResultSet = new RowColumnResultSet();
    Vector<SymbolTableEntry> modelObjectList = new Vector<SymbolTableEntry>();
    Vector<double[]> dataList = new Vector<double[]>();
    // 
    // find bound columns, (time is always mapped to the first column)
    // 
    int mappedColumnCount = 0;
    for (int i = 0; i < refDataMappingSpecs.length; i++) {
        SymbolTableEntry modelObject = refDataMappingSpecs[i].getModelObject();
        if (modelObject != null) {
            int mappedColumnIndex = mappedColumnCount;
            if (modelObject instanceof Model.ReservedSymbol && ((ReservedSymbol) modelObject).isTime()) {
                mappedColumnIndex = 0;
            }
            String origRefDataColumnName = refDataMappingSpecs[i].getReferenceDataColumnName();
            int origRefDataColumnIndex = refData.findColumn(origRefDataColumnName);
            if (origRefDataColumnIndex < 0) {
                throw new RuntimeException("reference data column named '" + origRefDataColumnName + "' not found");
            }
            double[] columnData = refData.getDataByColumn(origRefDataColumnIndex);
            if (modelObjectList.contains(modelObject)) {
                throw new RuntimeException("multiple reference data columns mapped to same model object '" + modelObject.getName() + "'");
            }
            modelObjectList.insertElementAt(modelObject, mappedColumnIndex);
            dataList.insertElementAt(columnData, mappedColumnIndex);
            mappedColumnCount++;
        }
    }
    // 
    if (modelObjectList.size() == 0) {
        throw new RuntimeException("reference data was not associated with model");
    }
    if (modelObjectList.size() == 1) {
        throw new RuntimeException("reference data was not associated with model, must map time and at least one other column");
    }
    boolean bFoundTimeVar = false;
    for (SymbolTableEntry ste : modelObjectList) {
        if (ste instanceof Model.ReservedSymbol && ((ReservedSymbol) ste).isTime()) {
            bFoundTimeVar = true;
            break;
        }
    }
    if (!bFoundTimeVar) {
        throw new RuntimeException("must map time column of reference data to model");
    }
    // 
    for (int i = 0; i < modelObjectList.size(); i++) {
        SymbolTableEntry modelObject = (SymbolTableEntry) modelObjectList.elementAt(i);
        try {
            // Find by name because MathSybolMapping has different 'objects' than refDataMapping 'objects'
            Variable variable = mathMapping.getMathSymbolMapping().findVariableByName(modelObject.getName());
            if (variable != null) {
                String symbol = variable.getName();
                rowColResultSet.addDataColumn(new ODESolverResultSetColumnDescription(symbol));
            } else if (modelObject instanceof Model.ReservedSymbol && ((Model.ReservedSymbol) modelObject).isTime()) {
                Model.ReservedSymbol time = (Model.ReservedSymbol) modelObject;
                String symbol = time.getName();
                rowColResultSet.addDataColumn(new ODESolverResultSetColumnDescription(symbol));
            }
        } catch (MathException | MatrixException | ExpressionException | ModelException e) {
            e.printStackTrace();
            throw new MappingException(e.getMessage(), e);
        }
    }
    // 
    // populate data columns (time and rest)
    // 
    double[] weights = new double[rowColResultSet.getColumnDescriptionsCount()];
    weights[0] = 1.0;
    int numRows = ((double[]) dataList.elementAt(0)).length;
    int numColumns = modelObjectList.size();
    for (int j = 0; j < numRows; j++) {
        double[] row = new double[numColumns];
        for (int i = 0; i < numColumns; i++) {
            row[i] = ((double[]) dataList.elementAt(i))[j];
            if (i > 0) {
                weights[i] += row[i] * row[i];
            }
        }
        rowColResultSet.addRow(row);
    }
    for (int i = 0; i < numColumns; i++) {
        if (weights[i] == 0) {
            weights[i] = 1;
        } else {
            weights[i] = 1 / weights[i];
        }
    }
    SimpleReferenceData remappedRefData = new SimpleReferenceData(rowColResultSet, weights);
    return remappedRefData;
}
Also used : ParameterVariable(cbit.vcell.math.ParameterVariable) Variable(cbit.vcell.math.Variable) ReservedSymbol(cbit.vcell.model.Model.ReservedSymbol) ReservedSymbol(cbit.vcell.model.Model.ReservedSymbol) ExpressionException(cbit.vcell.parser.ExpressionException) MappingException(cbit.vcell.mapping.MappingException) MatrixException(cbit.vcell.matrix.MatrixException) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) ODESolverResultSetColumnDescription(cbit.vcell.math.ODESolverResultSetColumnDescription) Vector(java.util.Vector) RowColumnResultSet(cbit.vcell.math.RowColumnResultSet) ModelException(cbit.vcell.model.ModelException) SimpleReferenceData(cbit.vcell.opt.SimpleReferenceData) SimpleReferenceData(cbit.vcell.opt.SimpleReferenceData) ReferenceData(cbit.vcell.opt.ReferenceData) MathException(cbit.vcell.math.MathException) Model(cbit.vcell.model.Model)

Example 9 with MappingException

use of cbit.vcell.mapping.MappingException in project vcell by virtualcell.

the class XmlReader method getSimulationContext.

/**
 * This method returns a SimulationContext from a XML representation.
 * Creation date: (4/2/2001 3:19:01 PM)
 * @return cbit.vcell.mapping.SimulationContext
 * @param param org.jdom.Element
 */
private SimulationContext getSimulationContext(Element param, BioModel biomodel) throws XmlParseException {
    // get the attributes
    // name
    String name = unMangle(param.getAttributeValue(XMLTags.NameAttrTag));
    boolean bStoch = false;
    boolean bRuleBased = false;
    boolean bUseConcentration = true;
    boolean bRandomizeInitCondition = false;
    boolean bInsufficientIterations = false;
    boolean bInsufficientMaxMolecules = false;
    // default is true for now
    boolean bMassConservationModelReduction = true;
    NetworkConstraints nc = null;
    Element ncElement = param.getChild(XMLTags.RbmNetworkConstraintsTag, vcNamespace);
    if (ncElement != null) {
        // one network constraint element
        nc = getAppNetworkConstraints(ncElement, biomodel.getModel());
    } else {
        if (legacyNetworkConstraints != null) {
            nc = legacyNetworkConstraints;
        }
    }
    if ((param.getAttributeValue(XMLTags.StochAttrTag) != null) && (param.getAttributeValue(XMLTags.StochAttrTag).equals("true"))) {
        bStoch = true;
    }
    if (bStoch) {
        // stochastic and using concentration vs amount
        if ((param.getAttributeValue(XMLTags.ConcentrationAttrTag) != null) && (param.getAttributeValue(XMLTags.ConcentrationAttrTag).equals("false"))) {
            bUseConcentration = false;
        }
        // stochastic and randomizing initial conditions or not (for non-spatial)
        if ((param.getAttributeValue(XMLTags.RandomizeInitConditionTag) != null) && (param.getAttributeValue(XMLTags.RandomizeInitConditionTag).equals("true"))) {
            bRandomizeInitCondition = true;
        }
    }
    if ((param.getAttributeValue(XMLTags.MassConservationModelReductionTag) != null) && (param.getAttributeValue(XMLTags.MassConservationModelReductionTag).equals("false"))) {
        bMassConservationModelReduction = false;
    }
    if ((param.getAttributeValue(XMLTags.InsufficientIterationsTag) != null) && (param.getAttributeValue(XMLTags.InsufficientIterationsTag).equals("true"))) {
        bInsufficientIterations = true;
    }
    if ((param.getAttributeValue(XMLTags.InsufficientMaxMoleculesTag) != null) && (param.getAttributeValue(XMLTags.InsufficientMaxMoleculesTag).equals("true"))) {
        bInsufficientMaxMolecules = true;
    }
    if ((param.getAttributeValue(XMLTags.RuleBasedAttrTag) != null) && (param.getAttributeValue(XMLTags.RuleBasedAttrTag).equals("true"))) {
        bRuleBased = true;
        if ((param.getAttributeValue(XMLTags.ConcentrationAttrTag) != null) && (param.getAttributeValue(XMLTags.ConcentrationAttrTag).equals("false"))) {
            bUseConcentration = false;
        }
        if ((param.getAttributeValue(XMLTags.RandomizeInitConditionTag) != null) && (param.getAttributeValue(XMLTags.RandomizeInitConditionTag).equals("true"))) {
            // we propagate the flag but we don't use it for now
            bRandomizeInitCondition = true;
        }
    }
    // Retrieve Geometry
    Geometry newgeometry = null;
    try {
        newgeometry = getGeometry(param.getChild(XMLTags.GeometryTag, vcNamespace));
    } catch (Throwable e) {
        e.printStackTrace();
        String stackTrace = null;
        try {
            java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
            java.io.PrintStream ps = new java.io.PrintStream(bos);
            e.printStackTrace(ps);
            ps.flush();
            bos.flush();
            stackTrace = new String(bos.toByteArray());
            ps.close();
            bos.close();
        } catch (Exception e2) {
        // do Nothing
        }
        throw new XmlParseException("A Problem occurred while retrieving the geometry for the simulationContext " + name, e);
    }
    // Retrieve MathDescription(if there is no MathDescription skip it)
    MathDescription newmathdesc = null;
    Element xmlMathDescription = param.getChild(XMLTags.MathDescriptionTag, vcNamespace);
    if (xmlMathDescription != null) {
        newmathdesc = getMathDescription(xmlMathDescription, newgeometry);
        if (biomodel.getVersion() != null && biomodel.getVersion().getVersionKey() != null) {
            Long lpcBMKey = Long.valueOf(biomodel.getVersion().getVersionKey().toString());
            // MathDescription.originalHasLowPrecisionConstants.remove(lpcBMKey);
            try {
                Enumeration<Constant> myenum = newmathdesc.getConstants();
                while (myenum.hasMoreElements()) {
                    Constant nextElement = myenum.nextElement();
                    String name2 = nextElement.getName();
                    ReservedSymbol reservedSymbolByName = biomodel.getModel().getReservedSymbolByName(name2);
                    if (reservedSymbolByName != null && nextElement.getExpression() != null && reservedSymbolByName.getExpression() != null) {
                        // System.out.println(name2);
                        boolean equals = nextElement.getExpression().infix().equals(reservedSymbolByName.getExpression().infix());
                        // System.out.println("--"+" "+nextElement.getExpression().infix() +" "+reservedSymbolByName.getExpression().infix()+" "+equals);
                        if (!equals) {
                            TreeSet<String> treeSet = MathDescription.originalHasLowPrecisionConstants.get(lpcBMKey);
                            if (treeSet == null) {
                                treeSet = new TreeSet<>();
                                MathDescription.originalHasLowPrecisionConstants.put(lpcBMKey, treeSet);
                            }
                            treeSet.add(newmathdesc.getVersion().getVersionKey().toString());
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    // Retrieve Version (Metada)
    Version version = getVersion(param.getChild(XMLTags.VersionTag, vcNamespace));
    // ------ Create SimContext ------
    SimulationContext newsimcontext = null;
    try {
        newsimcontext = new SimulationContext(biomodel.getModel(), newgeometry, newmathdesc, version, bStoch, bRuleBased);
    } catch (java.beans.PropertyVetoException e) {
        e.printStackTrace(System.out);
        throw new XmlParseException("A propertyveto exception was generated when creating the new SimulationContext " + name, e);
    }
    // set attributes
    try {
        newsimcontext.setName(name);
        // Add annotation
        String annotation = param.getChildText(XMLTags.AnnotationTag, vcNamespace);
        if (annotation != null) /* && annotation.length()>0*/
        {
            newsimcontext.setDescription(unMangle(annotation));
        }
        // set if using concentration
        newsimcontext.setUsingConcentration(bUseConcentration);
        // set mass conservation model reduction flag
        newsimcontext.setUsingMassConservationModelReduction(bMassConservationModelReduction);
        // set if randomizing init condition or not (for stochastic applications
        if (bStoch) {
            newsimcontext.setRandomizeInitConditions(bRandomizeInitCondition);
        }
        if (bInsufficientIterations) {
            newsimcontext.setInsufficientIterations(bInsufficientIterations);
        }
        if (bInsufficientMaxMolecules) {
            newsimcontext.setInsufficientMaxMolecules(bInsufficientMaxMolecules);
        }
        if (nc != null) {
            newsimcontext.setNetworkConstraints(nc);
        }
    } catch (java.beans.PropertyVetoException e) {
        e.printStackTrace(System.out);
        throw new XmlParseException("Exception", e);
    }
    String tempchar = param.getAttributeValue(XMLTags.CharacteristicSizeTag);
    if (tempchar != null) {
        try {
            newsimcontext.setCharacteristicSize(Double.valueOf(tempchar));
        } catch (java.beans.PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new XmlParseException("A PropertyVetoException was fired when setting the CharacteristicSize " + tempchar, e);
        }
    }
    // Retrieve DataContext
    Element dataContextElement = param.getChild(XMLTags.DataContextTag, vcNamespace);
    if (dataContextElement != null) {
        DataContext dataContext = newsimcontext.getDataContext();
        ArrayList<DataSymbol> dataSymbols = getDataSymbols(dataContextElement, dataContext, newsimcontext.getModel().getUnitSystem());
        for (int i = 0; i < dataSymbols.size(); i++) {
            dataContext.addDataSymbol(dataSymbols.get(i));
        }
    }
    // Retrieve spatialObjects and add to simContext
    Element spatialObjectsElement = param.getChild(XMLTags.SpatialObjectsTag, vcNamespace);
    if (spatialObjectsElement != null) {
        SpatialObject[] spatialObjects = getSpatialObjects(newsimcontext, spatialObjectsElement);
        try {
            newsimcontext.setSpatialObjects(spatialObjects);
        } catch (PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Error adding spatialObjects to simulationContext", e);
        }
    }
    // Retrieve application parameters and add to simContext
    Element appParamsElement = param.getChild(XMLTags.ApplicationParametersTag, vcNamespace);
    if (appParamsElement != null) {
        SimulationContextParameter[] appParameters = getSimulationContextParams(appParamsElement, newsimcontext);
        try {
            newsimcontext.setSimulationContextParameters(appParameters);
        } catch (PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Error adding application parameters to simulationContext", e);
        }
    }
    // 
    // -Process the GeometryContext-
    // 
    Element tempelement = param.getChild(XMLTags.GeometryContextTag, vcNamespace);
    LinkedList<StructureMapping> maplist = new LinkedList<StructureMapping>();
    // Retrieve FeatureMappings
    Iterator<Element> iterator = tempelement.getChildren(XMLTags.FeatureMappingTag, vcNamespace).iterator();
    while (iterator.hasNext()) {
        maplist.add(getFeatureMapping((Element) (iterator.next()), newsimcontext));
    }
    // Retrieve MembraneMappings
    iterator = tempelement.getChildren(XMLTags.MembraneMappingTag, vcNamespace).iterator();
    while (iterator.hasNext()) {
        maplist.add(getMembraneMapping((Element) (iterator.next()), newsimcontext));
    }
    // Add these mappings to the internal geometryContext of this simcontext
    StructureMapping[] structarray = new StructureMapping[maplist.size()];
    maplist.toArray(structarray);
    try {
        newsimcontext.getGeometryContext().setStructureMappings(structarray);
        newsimcontext.getGeometryContext().refreshStructureMappings();
        newsimcontext.refreshSpatialObjects();
    } catch (MappingException e) {
        e.printStackTrace();
        throw new XmlParseException("A MappingException was fired when trying to set the StructureMappings array to the Geometrycontext of the SimContext " + name, e);
    } catch (java.beans.PropertyVetoException e) {
        e.printStackTrace(System.out);
        throw new XmlParseException("A PopertyVetoException was fired when trying to set the StructureMappings array to the Geometrycontext of the SimContext " + name, e);
    }
    // 
    // -Process the ReactionContext-
    // 
    tempelement = param.getChild(XMLTags.ReactionContextTag, vcNamespace);
    // Retrieve ReactionSpecs
    List<Element> children = tempelement.getChildren(XMLTags.ReactionSpecTag, vcNamespace);
    if (children.size() != 0) {
        if (children.size() != biomodel.getModel().getReactionSteps().length) {
            throw new XmlParseException("The number of reactions is not consistent.\n" + "Model reactions=" + biomodel.getModel().getReactionSteps().length + ", Reaction specs=" + children.size());
        }
        // *NOTE: Importing a model from other languages does not generates reaction specs.
        // A more robust code will read the reactions in the source file and replace the ones created by the default by the VirtualCell framework.
        ReactionSpec[] reactionSpecs = new ReactionSpec[children.size()];
        int rSpecCounter = 0;
        for (Element rsElement : children) {
            reactionSpecs[rSpecCounter] = getReactionSpec(rsElement, newsimcontext);
            rSpecCounter++;
        }
        try {
            newsimcontext.getReactionContext().setReactionSpecs(reactionSpecs);
        } catch (java.beans.PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new XmlParseException("A PropertyVetoException occurred while setting the ReactionSpecs to the SimContext " + name, e);
        }
    }
    // Retrieve ReactionRuleSpecs
    Element reactionRuleSpecsElement = tempelement.getChild(XMLTags.ReactionRuleSpecsTag, vcNamespace);
    if (reactionRuleSpecsElement != null) {
        ReactionRuleSpec[] reactionRuleSpecs = getReactionRuleSpecs(newsimcontext, reactionRuleSpecsElement);
        try {
            newsimcontext.getReactionContext().setReactionRuleSpecs(reactionRuleSpecs);
        } catch (PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new XmlParseException("A PropertyVetoException occurred while setting the ReactionRuleSpecs to the SimContext " + name, e);
        }
    }
    children = tempelement.getChildren(XMLTags.SpeciesContextSpecTag, vcNamespace);
    getSpeciesContextSpecs(children, newsimcontext.getReactionContext(), biomodel.getModel());
    // Retrieve output functions
    Element outputFunctionsElement = param.getChild(XMLTags.OutputFunctionsTag, vcNamespace);
    if (outputFunctionsElement != null) {
        ArrayList<AnnotatedFunction> outputFunctions = getOutputFunctions(outputFunctionsElement);
        try {
            // construct OutputFnContext from mathDesc in newSimContext and add output functions that were read in from XML.
            OutputFunctionContext outputFnContext = newsimcontext.getOutputFunctionContext();
            for (AnnotatedFunction outputFunction : outputFunctions) {
                outputFnContext.addOutputFunction(outputFunction);
            }
        } catch (PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new XmlParseException(e);
        }
    }
    // Retrieve Electrical context
    org.jdom.Element electElem = param.getChild(XMLTags.ElectricalContextTag, vcNamespace);
    // this information is optional!
    if (electElem != null) {
        if (electElem.getChild(XMLTags.ClampTag, vcNamespace) != null) {
            // read clamp
            ElectricalStimulus[] electArray = new ElectricalStimulus[1];
            electArray[0] = getElectricalStimulus(electElem.getChild(XMLTags.ClampTag, vcNamespace), newsimcontext);
            try {
                newsimcontext.setElectricalStimuli(electArray);
            } catch (java.beans.PropertyVetoException e) {
                e.printStackTrace(System.out);
                throw new XmlParseException(e);
            }
        }
        // read ground electrode
        if (electElem.getChild(XMLTags.ElectrodeTag, vcNamespace) != null) {
            Electrode groundElectrode = getElectrode(electElem.getChild(XMLTags.ElectrodeTag, vcNamespace), newsimcontext);
            try {
                newsimcontext.setGroundElectrode(groundElectrode);
            } catch (java.beans.PropertyVetoException e) {
                e.printStackTrace(System.out);
                throw new XmlParseException(e);
            }
        }
    }
    // Retrieve (bio)events and add to simContext
    tempelement = param.getChild(XMLTags.BioEventsTag, vcNamespace);
    if (tempelement != null) {
        BioEvent[] bioEvents = getBioEvents(newsimcontext, tempelement);
        try {
            newsimcontext.setBioEvents(bioEvents);
        } catch (PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Error adding events to simulationContext", e);
        }
    }
    // Retrieve spatialProcesses and add to simContext
    tempelement = param.getChild(XMLTags.SpatialProcessesTag, vcNamespace);
    if (tempelement != null) {
        SpatialProcess[] spatialProcesses = getSpatialProcesses(newsimcontext, tempelement);
        try {
            newsimcontext.setSpatialProcesses(spatialProcesses);
        } catch (PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Error adding spatialProcesses to simulationContext", e);
        }
    }
    // Retrieve rate rules and add to simContext
    tempelement = param.getChild(XMLTags.RateRulesTag, vcNamespace);
    if (tempelement != null) {
        RateRule[] rateRules = getRateRules(newsimcontext, tempelement);
        try {
            newsimcontext.setRateRules(rateRules);
        } catch (PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Error adding rate rules to simulationContext", e);
        }
    }
    tempelement = param.getChild(XMLTags.AssignmentRulesTag, vcNamespace);
    if (tempelement != null) {
        AssignmentRule[] assignmentRules = getAssignmentRules(newsimcontext, tempelement);
        try {
            newsimcontext.setAssignmentRules(assignmentRules);
        } catch (PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Error adding assignment rules to simulationContext", e);
        }
    }
    org.jdom.Element analysisTaskListElement = param.getChild(XMLTags.AnalysisTaskListTag, vcNamespace);
    if (analysisTaskListElement != null) {
        children = analysisTaskListElement.getChildren(XMLTags.ParameterEstimationTaskTag, vcNamespace);
        if (children.size() != 0) {
            Vector<ParameterEstimationTask> analysisTaskList = new Vector<ParameterEstimationTask>();
            for (Element parameterEstimationTaskElement : children) {
                try {
                    ParameterEstimationTask parameterEstimationTask = ParameterEstimationTaskXMLPersistence.getParameterEstimationTask(parameterEstimationTaskElement, newsimcontext);
                    analysisTaskList.add(parameterEstimationTask);
                } catch (Exception e) {
                    e.printStackTrace(System.out);
                    throw new XmlParseException("An Exception occurred when parsing AnalysisTasks of SimContext " + name, e);
                }
            }
            try {
                AnalysisTask[] analysisTasks = (AnalysisTask[]) BeanUtils.getArray(analysisTaskList, AnalysisTask.class);
                newsimcontext.setAnalysisTasks(analysisTasks);
            } catch (java.beans.PropertyVetoException e) {
                e.printStackTrace(System.out);
                throw new XmlParseException("A PropertyVetoException occurred when setting the AnalysisTasks of the SimContext " + name, e);
            }
        }
    }
    // Microscope Measurement
    org.jdom.Element element = param.getChild(XMLTags.MicroscopeMeasurement, vcNamespace);
    if (element != null) {
        getMicroscopeMeasurement(element, newsimcontext);
    }
    for (GeometryClass gc : newsimcontext.getGeometry().getGeometryClasses()) {
        try {
            StructureSizeSolver.updateUnitStructureSizes(newsimcontext, gc);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    newsimcontext.getGeometryContext().enforceHierarchicalBoundaryConditions(newsimcontext.getModel().getStructureTopology());
    return newsimcontext;
}
Also used : MathDescription(cbit.vcell.math.MathDescription) MappingException(cbit.vcell.mapping.MappingException) PropertyVetoException(java.beans.PropertyVetoException) Version(org.vcell.util.document.Version) RedistributionVersion(cbit.vcell.solvers.mb.MovingBoundarySolverOptions.RedistributionVersion) SimulationVersion(org.vcell.util.document.SimulationVersion) VCellSoftwareVersion(org.vcell.util.document.VCellSoftwareVersion) SpatialProcess(cbit.vcell.mapping.spatial.processes.SpatialProcess) RateRule(cbit.vcell.mapping.RateRule) Vector(java.util.Vector) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) Electrode(cbit.vcell.mapping.Electrode) ReactionSpec(cbit.vcell.mapping.ReactionSpec) ReactionRuleSpec(cbit.vcell.mapping.ReactionRuleSpec) AssignmentRule(cbit.vcell.mapping.AssignmentRule) LinkedList(java.util.LinkedList) PropertyVetoException(java.beans.PropertyVetoException) OutputFunctionContext(cbit.vcell.solver.OutputFunctionContext) FieldDataSymbol(cbit.vcell.data.FieldDataSymbol) DataSymbol(cbit.vcell.data.DataSymbol) ParameterEstimationTask(cbit.vcell.modelopt.ParameterEstimationTask) AnalysisTask(cbit.vcell.modelopt.AnalysisTask) NetworkConstraints(org.vcell.model.rbm.NetworkConstraints) GeometryClass(cbit.vcell.geometry.GeometryClass) MacroscopicRateConstant(cbit.vcell.math.MacroscopicRateConstant) Constant(cbit.vcell.math.Constant) Element(org.jdom.Element) ReservedSymbol(cbit.vcell.model.Model.ReservedSymbol) StructureMapping(cbit.vcell.mapping.StructureMapping) SpatialObject(cbit.vcell.mapping.spatial.SpatialObject) DataContext(cbit.vcell.data.DataContext) SimulationContext(cbit.vcell.mapping.SimulationContext) SimulationContextParameter(cbit.vcell.mapping.SimulationContext.SimulationContextParameter) GeometryException(cbit.vcell.geometry.GeometryException) MathFormatException(cbit.vcell.math.MathFormatException) MappingException(cbit.vcell.mapping.MappingException) PropertyVetoException(java.beans.PropertyVetoException) ImageException(cbit.image.ImageException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ModelException(cbit.vcell.model.ModelException) DataConversionException(org.jdom.DataConversionException) ExpressionException(cbit.vcell.parser.ExpressionException) MathException(cbit.vcell.math.MathException) Geometry(cbit.vcell.geometry.Geometry) ElectricalStimulus(cbit.vcell.mapping.ElectricalStimulus) BioEvent(cbit.vcell.mapping.BioEvent) Element(org.jdom.Element)

Example 10 with MappingException

use of cbit.vcell.mapping.MappingException in project vcell by virtualcell.

the class MathVerifier method testMathGeneration.

public MathGenerationResults testMathGeneration(KeyValue simContextKey) throws SQLException, ObjectNotFoundException, DataAccessException, XmlParseException, MappingException, MathException, MatrixException, ExpressionException, ModelException, PropertyVetoException {
    User adminUser = new User(PropertyLoader.ADMINISTRATOR_ACCOUNT, new org.vcell.util.document.KeyValue(PropertyLoader.ADMINISTRATOR_ID));
    if (lg.isTraceEnabled())
        lg.trace("Testing SimContext with key '" + simContextKey + "'");
    // get biomodel refs
    java.sql.Connection con = null;
    java.sql.Statement stmt = null;
    con = conFactory.getConnection(new Object());
    cbit.vcell.modeldb.BioModelSimContextLinkTable bmscTable = cbit.vcell.modeldb.BioModelSimContextLinkTable.table;
    cbit.vcell.modeldb.BioModelTable bmTable = cbit.vcell.modeldb.BioModelTable.table;
    cbit.vcell.modeldb.UserTable userTable = cbit.vcell.modeldb.UserTable.table;
    String sql = "SELECT " + bmscTable.bioModelRef.getQualifiedColName() + "," + bmTable.ownerRef.getQualifiedColName() + "," + userTable.userid.getQualifiedColName() + " FROM " + bmscTable.getTableName() + "," + bmTable.getTableName() + "," + userTable.getTableName() + " WHERE " + bmscTable.simContextRef.getQualifiedColName() + " = " + simContextKey + " AND " + bmTable.id.getQualifiedColName() + " = " + bmscTable.bioModelRef.getQualifiedColName() + " AND " + bmTable.ownerRef.getQualifiedColName() + " = " + userTable.id.getQualifiedColName();
    ArrayList<KeyValue> bioModelKeys = new ArrayList<KeyValue>();
    stmt = con.createStatement();
    User owner = null;
    try {
        ResultSet rset = stmt.executeQuery(sql);
        while (rset.next()) {
            KeyValue key = new KeyValue(rset.getBigDecimal(bmscTable.bioModelRef.getUnqualifiedColName()));
            bioModelKeys.add(key);
            KeyValue ownerRef = new KeyValue(rset.getBigDecimal(bmTable.ownerRef.getUnqualifiedColName()));
            String userid = rset.getString(userTable.userid.getUnqualifiedColName());
            owner = new User(userid, ownerRef);
        }
    } finally {
        if (stmt != null) {
            stmt.close();
        }
        con.close();
    }
    // use the first biomodel...
    if (bioModelKeys.size() == 0) {
        throw new RuntimeException("zombie simContext ... no biomodels");
    }
    BioModelInfo bioModelInfo = dbServerImpl.getBioModelInfo(owner, bioModelKeys.get(0));
    // 
    // read in the BioModel from the database
    // 
    BigString bioModelXML = dbServerImpl.getBioModelXML(owner, bioModelInfo.getVersion().getVersionKey());
    BioModel bioModelFromDB = XmlHelper.XMLToBioModel(new XMLSource(bioModelXML.toString()));
    BioModel bioModelNewMath = XmlHelper.XMLToBioModel(new XMLSource(bioModelXML.toString()));
    bioModelFromDB.refreshDependencies();
    bioModelNewMath.refreshDependencies();
    // 
    // get all Simulations for this model
    // 
    Simulation[] modelSimsFromDB = bioModelFromDB.getSimulations();
    // 
    // ---> only for the SimContext we started with...
    // recompute mathDescription, and verify it is equivalent
    // then check each associated simulation to ensure math overrides are applied in an equivalent manner also.
    // 
    SimulationContext[] simContextsFromDB = bioModelFromDB.getSimulationContexts();
    SimulationContext[] simContextsNewMath = bioModelNewMath.getSimulationContexts();
    SimulationContext simContextFromDB = null;
    SimulationContext simContextNewMath = null;
    for (int k = 0; k < simContextsFromDB.length; k++) {
        // find it...
        if (simContextsFromDB[k].getKey().equals(simContextKey)) {
            simContextFromDB = simContextsFromDB[k];
            simContextNewMath = simContextsNewMath[k];
            break;
        }
    }
    if (simContextFromDB == null) {
        throw new RuntimeException("BioModel referred to by this SimContext does not contain this SimContext");
    } else {
        MathDescription origMathDesc = simContextFromDB.getMathDescription();
        // 
        try {
            if (simContextNewMath.getGeometry().getDimension() > 0 && simContextNewMath.getGeometry().getGeometrySurfaceDescription().getGeometricRegions() == null) {
                simContextNewMath.getGeometry().getGeometrySurfaceDescription().updateAll();
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
        // 
        // updated mathDescription loaded into copy of bioModel, then test for equivalence.
        // 
        cbit.vcell.mapping.MathMapping mathMapping = simContextNewMath.createNewMathMapping();
        MathDescription mathDesc_latest = mathMapping.getMathDescription();
        MathMapping_4_8 mathMapping_4_8 = new MathMapping_4_8(simContextNewMath);
        MathDescription mathDesc_4_8 = mathMapping_4_8.getMathDescription();
        String issueString = null;
        org.vcell.util.Issue[] issues = mathMapping.getIssues();
        if (issues != null && issues.length > 0) {
            StringBuffer buffer = new StringBuffer("Issues(" + issues.length + "):\n");
            for (int l = 0; l < issues.length; l++) {
                buffer.append(" <<" + issues[l].toString() + ">>\n");
            }
            issueString = buffer.toString();
        }
        simContextNewMath.setMathDescription(mathDesc_latest);
        MathCompareResults mathCompareResults_latest = MathDescription.testEquivalency(SimulationSymbolTable.createMathSymbolTableFactory(), origMathDesc, mathDesc_latest);
        MathCompareResults mathCompareResults_4_8 = null;
        try {
            mathCompareResults_4_8 = MathDescription.testEquivalency(SimulationSymbolTable.createMathSymbolTableFactory(), origMathDesc, mathDesc_4_8);
        } catch (Exception e) {
            e.printStackTrace(System.out);
            mathCompareResults_4_8 = new MathCompareResults(Decision.MathDifferent_FAILURE_UNKNOWN, e.getMessage());
        }
        return new MathGenerationResults(bioModelFromDB, simContextFromDB, origMathDesc, mathDesc_latest, mathCompareResults_latest, mathDesc_4_8, mathCompareResults_4_8);
    }
}
Also used : User(org.vcell.util.document.User) Connection(java.sql.Connection) KeyValue(org.vcell.util.document.KeyValue) MathDescription(cbit.vcell.math.MathDescription) ArrayList(java.util.ArrayList) BigString(org.vcell.util.BigString) BigString(org.vcell.util.BigString) MathCompareResults(cbit.vcell.math.MathCompareResults) ResultSet(java.sql.ResultSet) BioModelInfo(org.vcell.util.document.BioModelInfo) MathMapping_4_8(cbit.vcell.mapping.vcell_4_8.MathMapping_4_8) SimulationContext(cbit.vcell.mapping.SimulationContext) PropertyVetoException(java.beans.PropertyVetoException) MatrixException(cbit.vcell.matrix.MatrixException) ModelException(cbit.vcell.model.ModelException) ObjectNotFoundException(org.vcell.util.ObjectNotFoundException) SQLException(java.sql.SQLException) XmlParseException(cbit.vcell.xml.XmlParseException) DataAccessException(org.vcell.util.DataAccessException) ExpressionException(cbit.vcell.parser.ExpressionException) MappingException(cbit.vcell.mapping.MappingException) MathException(cbit.vcell.math.MathException) KeyValue(org.vcell.util.document.KeyValue) Simulation(cbit.vcell.solver.Simulation) BioModel(cbit.vcell.biomodel.BioModel) XMLSource(cbit.vcell.xml.XMLSource)

Aggregations

MappingException (cbit.vcell.mapping.MappingException)25 ExpressionException (cbit.vcell.parser.ExpressionException)20 PropertyVetoException (java.beans.PropertyVetoException)17 MathException (cbit.vcell.math.MathException)13 ModelException (cbit.vcell.model.ModelException)13 Expression (cbit.vcell.parser.Expression)13 MathDescription (cbit.vcell.math.MathDescription)11 MatrixException (cbit.vcell.matrix.MatrixException)11 SimulationContext (cbit.vcell.mapping.SimulationContext)10 StructureMapping (cbit.vcell.mapping.StructureMapping)9 DataAccessException (org.vcell.util.DataAccessException)9 BioModel (cbit.vcell.biomodel.BioModel)8 SpeciesContextSpec (cbit.vcell.mapping.SpeciesContextSpec)8 XmlParseException (cbit.vcell.xml.XmlParseException)8 Model (cbit.vcell.model.Model)7 VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)7 XMLSource (cbit.vcell.xml.XMLSource)7 Structure (cbit.vcell.model.Structure)6 Vector (java.util.Vector)6 ImageException (cbit.image.ImageException)5