Search in sources :

Example 16 with LocalParameter

use of cbit.vcell.mapping.ParameterContext.LocalParameter in project vcell by virtualcell.

the class RulebasedTransformer method transform.

private void transform(SimulationContext originalSimContext, SimulationContext transformedSimulationContext, ArrayList<ModelEntityMapping> entityMappings, MathMappingCallback mathMappingCallback) throws PropertyVetoException {
    Model newModel = transformedSimulationContext.getModel();
    Model originalModel = originalSimContext.getModel();
    ModelEntityMapping em = null;
    // list of rules created from the reactions; we apply the symmetry factor computed by bionetgen only to these
    Set<ReactionRule> fromReactions = new HashSet<>();
    for (SpeciesContext newSpeciesContext : newModel.getSpeciesContexts()) {
        final SpeciesContext originalSpeciesContext = originalModel.getSpeciesContext(newSpeciesContext.getName());
        // map new and old species contexts
        em = new ModelEntityMapping(originalSpeciesContext, newSpeciesContext);
        entityMappings.add(em);
        if (newSpeciesContext.hasSpeciesPattern()) {
            // it's perfect already and can't be improved
            continue;
        }
        try {
            MolecularType newmt = newModel.getRbmModelContainer().createMolecularType();
            newModel.getRbmModelContainer().addMolecularType(newmt, false);
            MolecularTypePattern newmtp_sc = new MolecularTypePattern(newmt);
            SpeciesPattern newsp_sc = new SpeciesPattern();
            newsp_sc.addMolecularTypePattern(newmtp_sc);
            newSpeciesContext.setSpeciesPattern(newsp_sc);
            RbmObservable newo = new RbmObservable(newModel, "O0_" + newmt.getName() + "_tot", newSpeciesContext.getStructure(), RbmObservable.ObservableType.Molecules);
            MolecularTypePattern newmtp_ob = new MolecularTypePattern(newmt);
            SpeciesPattern newsp_ob = new SpeciesPattern();
            newsp_ob.addMolecularTypePattern(newmtp_ob);
            newo.addSpeciesPattern(newsp_ob);
            newModel.getRbmModelContainer().addObservable(newo);
            // map new observable to old species context
            em = new ModelEntityMapping(originalSpeciesContext, newo);
            entityMappings.add(em);
        } catch (ModelException e) {
            e.printStackTrace();
            throw new RuntimeException("unable to transform species context: " + e.getMessage());
        } catch (PropertyVetoException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    ReactionSpec[] reactionSpecs = transformedSimulationContext.getReactionContext().getReactionSpecs();
    for (ReactionSpec reactionSpec : reactionSpecs) {
        if (reactionSpec.isExcluded()) {
            // we create rules only from those reactions which are not excluded
            continue;
        }
        ReactionStep rs = reactionSpec.getReactionStep();
        String name = rs.getName();
        String mangled = TokenMangler.fixTokenStrict(name);
        mangled = newModel.getReactionName(mangled);
        Kinetics k = rs.getKinetics();
        if (!(k instanceof MassActionKinetics)) {
            throw new RuntimeException("Only Mass Action Kinetics supported at this time, reaction \"" + rs.getName() + "\" uses kinetic law type \"" + rs.getKinetics().getName() + "\"");
        }
        boolean bReversible = rs.isReversible();
        ReactionRule rr = new ReactionRule(newModel, mangled, rs.getStructure(), bReversible);
        fromReactions.add(rr);
        MassActionKinetics massActionKinetics = (MassActionKinetics) k;
        List<Reactant> rList = rs.getReactants();
        List<Product> pList = rs.getProducts();
        // counting the stoichiometry - 2A+B means 3 reactants
        int numReactants = 0;
        for (Reactant r : rList) {
            numReactants += r.getStoichiometry();
            if (numReactants > 2) {
                String message = "NFSim doesn't support more than 2 reactants within a reaction: " + name;
                throw new RuntimeException(message);
            }
        }
        int numProducts = 0;
        for (Product p : pList) {
            numProducts += p.getStoichiometry();
            if (bReversible && numProducts > 2) {
                String message = "NFSim doesn't support more than 2 products within a reversible reaction: " + name;
                throw new RuntimeException(message);
            }
        }
        RateLawType rateLawType = RateLawType.MassAction;
        RbmKineticLaw kineticLaw = new RbmKineticLaw(rr, rateLawType);
        try {
            String forwardRateName = massActionKinetics.getForwardRateParameter().getName();
            Expression forwardRateExp = massActionKinetics.getForwardRateParameter().getExpression();
            String reverseRateName = massActionKinetics.getReverseRateParameter().getName();
            Expression reverseRateExp = massActionKinetics.getReverseRateParameter().getExpression();
            LocalParameter fR = kineticLaw.getLocalParameter(RbmKineticLawParameterType.MassActionForwardRate);
            fR.setName(forwardRateName);
            LocalParameter rR = kineticLaw.getLocalParameter(RbmKineticLawParameterType.MassActionReverseRate);
            rR.setName(reverseRateName);
            if (rs.hasReactant()) {
                kineticLaw.setParameterValue(fR, forwardRateExp, true);
            }
            if (rs.hasProduct()) {
                kineticLaw.setParameterValue(rR, reverseRateExp, true);
            }
            // 
            for (KineticsParameter reaction_p : massActionKinetics.getKineticsParameters()) {
                if (reaction_p.getRole() == Kinetics.ROLE_UserDefined) {
                    LocalParameter rule_p = kineticLaw.getLocalParameter(reaction_p.getName());
                    if (rule_p == null) {
                        // 
                        // after lazy parameter creation we didn't find a user-defined rule parameter with this same name.
                        // 
                        // there must be a global symbol with the same name, that the local reaction parameter has overridden.
                        // 
                        ParameterContext.LocalProxyParameter rule_proxy_parameter = null;
                        for (ProxyParameter proxyParameter : kineticLaw.getProxyParameters()) {
                            if (proxyParameter.getName().equals(reaction_p.getName())) {
                                rule_proxy_parameter = (LocalProxyParameter) proxyParameter;
                            }
                        }
                        if (rule_proxy_parameter != null) {
                            // we want to convert to local
                            boolean bConvertToGlobal = false;
                            kineticLaw.convertParameterType(rule_proxy_parameter, bConvertToGlobal);
                        } else {
                            // could find neither local parameter nor proxy parameter
                            throw new RuntimeException("user defined parameter " + reaction_p.getName() + " from reaction " + rs.getName() + " didn't map to a reactionRule parameter");
                        }
                    } else if (rule_p.getRole() == RbmKineticLawParameterType.UserDefined) {
                        kineticLaw.setParameterValue(rule_p, reaction_p.getExpression(), true);
                        rule_p.setUnitDefinition(reaction_p.getUnitDefinition());
                    } else {
                        throw new RuntimeException("user defined parameter " + reaction_p.getName() + " from reaction " + rs.getName() + " mapped to a reactionRule parameter with unexpected role " + rule_p.getRole().getDescription());
                    }
                }
            }
        } catch (ExpressionException e) {
            e.printStackTrace();
            throw new RuntimeException("Problem attempting to set RbmKineticLaw expression: " + e.getMessage());
        }
        rr.setKineticLaw(kineticLaw);
        KineticsParameter[] kpList = k.getKineticsParameters();
        ModelParameter[] mpList = rs.getModel().getModelParameters();
        ModelParameter mp = rs.getModel().getModelParameter(kpList[0].getName());
        ReactionParticipant[] rpList = rs.getReactionParticipants();
        for (ReactionParticipant p : rpList) {
            if (p instanceof Reactant) {
                int stoichiometry = p.getStoichiometry();
                for (int i = 0; i < stoichiometry; i++) {
                    SpeciesPattern speciesPattern = new SpeciesPattern(rs.getModel(), p.getSpeciesContext().getSpeciesPattern());
                    ReactantPattern reactantPattern = new ReactantPattern(speciesPattern, p.getStructure());
                    rr.addReactant(reactantPattern);
                }
            } else if (p instanceof Product) {
                int stoichiometry = p.getStoichiometry();
                for (int i = 0; i < stoichiometry; i++) {
                    SpeciesPattern speciesPattern = new SpeciesPattern(rs.getModel(), p.getSpeciesContext().getSpeciesPattern());
                    ProductPattern productPattern = new ProductPattern(speciesPattern, p.getStructure());
                    rr.addProduct(productPattern);
                }
            }
        }
        // commented code below is probably obsolete, we verify (above) in the reaction the number of participants,
        // no need to do it again in the corresponding rule
        // if(rr.getReactantPatterns().size() > 2) {
        // String message = "NFSim doesn't support more than 2 reactants within a reaction: " + name;
        // throw new RuntimeException(message);
        // }
        // if(rr.getProductPatterns().size() > 2) {
        // String message = "NFSim doesn't support more than 2 products within a reaction: " + name;
        // throw new RuntimeException(message);
        // }
        newModel.removeReactionStep(rs);
        newModel.getRbmModelContainer().addReactionRule(rr);
    }
    for (ReactionRuleSpec rrs : transformedSimulationContext.getReactionContext().getReactionRuleSpecs()) {
        if (rrs == null) {
            continue;
        }
        ReactionRule rr = rrs.getReactionRule();
        if (rrs.isExcluded()) {
            // delete those rules which are disabled (excluded) in the Specifications / Reaction table
            newModel.getRbmModelContainer().removeReactionRule(rr);
            continue;
        }
    }
    // now that we generated the rules we can delete the reaction steps they're coming from
    for (ReactionStep rs : newModel.getReactionSteps()) {
        newModel.removeReactionStep(rs);
    }
    try {
        // we invoke bngl just for the purpose of generating the xml file, which we'll then use to extract the symmetry factor
        generateNetwork(transformedSimulationContext, fromReactions, mathMappingCallback);
    } catch (ClassNotFoundException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Finished RuleBased Transformer.");
}
Also used : Product(cbit.vcell.model.Product) SpeciesContext(cbit.vcell.model.SpeciesContext) Reactant(cbit.vcell.model.Reactant) LocalProxyParameter(cbit.vcell.mapping.ParameterContext.LocalProxyParameter) SpeciesPattern(org.vcell.model.rbm.SpeciesPattern) ExpressionException(cbit.vcell.parser.ExpressionException) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) RateLawType(cbit.vcell.model.RbmKineticLaw.RateLawType) HashSet(java.util.HashSet) ReactantPattern(cbit.vcell.model.ReactantPattern) ReactionRule(cbit.vcell.model.ReactionRule) ModelException(cbit.vcell.model.ModelException) ProductPattern(cbit.vcell.model.ProductPattern) RbmObservable(cbit.vcell.model.RbmObservable) RbmKineticLaw(cbit.vcell.model.RbmKineticLaw) IOException(java.io.IOException) MolecularType(org.vcell.model.rbm.MolecularType) PropertyVetoException(java.beans.PropertyVetoException) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) ProxyParameter(cbit.vcell.model.ProxyParameter) LocalProxyParameter(cbit.vcell.mapping.ParameterContext.LocalProxyParameter) Expression(cbit.vcell.parser.Expression) ReactionStep(cbit.vcell.model.ReactionStep) Model(cbit.vcell.model.Model) MassActionKinetics(cbit.vcell.model.MassActionKinetics) Kinetics(cbit.vcell.model.Kinetics) MassActionKinetics(cbit.vcell.model.MassActionKinetics) MolecularTypePattern(org.vcell.model.rbm.MolecularTypePattern) ReactionParticipant(cbit.vcell.model.ReactionParticipant)

Example 17 with LocalParameter

use of cbit.vcell.mapping.ParameterContext.LocalParameter in project vcell by virtualcell.

the class ITextWriter method writeMembraneMapping.

protected void writeMembraneMapping(Section simContextSection, SimulationContext simContext) throws DocumentException {
    GeometryContext geoContext = simContext.getGeometryContext();
    if (geoContext == null) {
        return;
    }
    Section memMapSection = null;
    Table memMapTable = null;
    StructureMapping[] structMappings = geoContext.getStructureMappings();
    for (int i = 0; i < structMappings.length; i++) {
        MembraneMapping memMapping = null;
        if (structMappings[i] instanceof FeatureMapping) {
            continue;
        } else {
            memMapping = (MembraneMapping) structMappings[i];
        }
        String structName = memMapping.getStructure().getName();
        String initVoltage = "";
        Expression tempExp = memMapping.getInitialVoltageParameter().getExpression();
        VCUnitDefinition tempUnit = memMapping.getInitialVoltageParameter().getUnitDefinition();
        if (tempExp != null) {
            initVoltage = tempExp.infix();
            if (tempUnit != null) {
                initVoltage += "   " + tempUnit.getSymbolUnicode();
            }
        }
        String spCap = "";
        tempExp = memMapping.getSpecificCapacitanceParameter().getExpression();
        tempUnit = memMapping.getSpecificCapacitanceParameter().getUnitDefinition();
        if (tempExp != null) {
            spCap = tempExp.infix();
            if (tempUnit != null) {
                spCap += "   " + tempUnit.getSymbolUnicode();
            }
        }
        if (memMapTable == null) {
            memMapTable = getTable(4, 100, 1, 3, 3);
            memMapTable.addCell(createCell("Electrical Mapping - Membrane Potential", getBold(DEF_HEADER_FONT_SIZE), 4, 1, Element.ALIGN_CENTER, true));
            memMapTable.addCell(createHeaderCell("Membrane", getBold(), 1));
            memMapTable.addCell(createHeaderCell("Calculate V (T/F)", getBold(), 1));
            memMapTable.addCell(createHeaderCell("V initial", getBold(), 1));
            memMapTable.addCell(createHeaderCell("Specific Capacitance", getBold(), 1));
            memMapTable.endHeaders();
        }
        memMapTable.addCell(createCell(structName, getFont()));
        memMapTable.addCell(createCell((memMapping.getCalculateVoltage() ? " T " : " F "), getFont()));
        memMapTable.addCell(createCell(initVoltage, getFont()));
        memMapTable.addCell(createCell(spCap, getFont()));
    }
    if (memMapTable != null) {
        memMapSection = simContextSection.addSection("Membrane Mapping For " + simContext.getName(), simContextSection.numberDepth() + 1);
        memMapSection.add(memMapTable);
    }
    int[] widths = { 1, 1, 1, 5, 8 };
    Table electTable = null;
    ElectricalStimulus[] electricalStimuli = simContext.getElectricalStimuli();
    for (int j = 0; j < electricalStimuli.length; j++) {
        if (j == 0) {
            electTable = getTable(5, 100, 1, 3, 3);
            electTable.addCell(createCell("Electrical Mapping - Electrical Stimulus", getBold(DEF_HEADER_FONT_SIZE), 5, 1, Element.ALIGN_CENTER, true));
            electTable.addCell(createHeaderCell("Stimulus Name", getBold(), 1));
            electTable.addCell(createHeaderCell("Current Name", getBold(), 1));
            electTable.addCell(createHeaderCell("Clamp Type", getBold(), 1));
            electTable.addCell(createHeaderCell("Voltage/Current Density", getBold(), 1));
            electTable.addCell(createHeaderCell("Clamp Device", getBold(), 1));
            electTable.endHeaders();
        }
        String stimName = electricalStimuli[j].getName();
        String currName = "";
        String clampType = "", expStr = "";
        Expression tempExp = null;
        VCUnitDefinition tempUnit = null;
        if (electricalStimuli[j] instanceof CurrentDensityClampStimulus) {
            CurrentDensityClampStimulus stimulus = (CurrentDensityClampStimulus) electricalStimuli[j];
            LocalParameter currentDensityParameter = stimulus.getCurrentDensityParameter();
            tempExp = currentDensityParameter.getExpression();
            tempUnit = currentDensityParameter.getUnitDefinition();
            clampType = "Current Density (deprecated)";
        } else if (electricalStimuli[j] instanceof TotalCurrentClampStimulus) {
            TotalCurrentClampStimulus stimulus = (TotalCurrentClampStimulus) electricalStimuli[j];
            LocalParameter totalCurrentParameter = stimulus.getCurrentParameter();
            tempExp = totalCurrentParameter.getExpression();
            tempUnit = totalCurrentParameter.getUnitDefinition();
            clampType = "Current";
        } else if (electricalStimuli[j] instanceof VoltageClampStimulus) {
            VoltageClampStimulus stimulus = (VoltageClampStimulus) electricalStimuli[j];
            Parameter voltageParameter = stimulus.getVoltageParameter();
            tempExp = voltageParameter.getExpression();
            tempUnit = voltageParameter.getUnitDefinition();
            clampType = "Voltage";
        }
        if (tempExp != null) {
            expStr = tempExp.infix();
            if (tempUnit != null) {
                expStr += "   " + tempUnit.getSymbolUnicode();
            }
        }
        electTable.addCell(createCell(stimName, getFont()));
        electTable.addCell(createCell(currName, getFont()));
        electTable.addCell(createCell(clampType, getFont()));
        electTable.addCell(createCell(expStr, getFont()));
        // add electrode info
        Electrode electrode = electricalStimuli[j].getElectrode();
        if (electrode == null) {
            electTable.addCell(createCell("N/A", getFont()));
        } else {
            Coordinate c = electrode.getPosition();
            String location = c.getX() + ", " + c.getY() + ", " + c.getZ();
            String featureName = electrode.getFeature().getName();
            electTable.addCell(createCell("(" + location + ") in " + featureName, getFont()));
        }
    }
    if (electTable != null) {
        if (memMapSection == null) {
            memMapSection = simContextSection.addSection("Membrane Mapping For " + simContext.getName(), 1);
        }
        electTable.setWidths(widths);
        memMapSection.add(electTable);
    }
    // add temperature
    Table tempTable = getTable(1, 75, 1, 3, 3);
    tempTable.setAlignment(Table.ALIGN_LEFT);
    tempTable.addCell(createCell("Temperature: " + simContext.getTemperatureKelvin() + " K", getFont()));
    if (memMapSection != null) {
        memMapSection.add(tempTable);
    }
}
Also used : MembraneMapping(cbit.vcell.mapping.MembraneMapping) Table(com.lowagie.text.Table) Electrode(cbit.vcell.mapping.Electrode) CurrentDensityClampStimulus(cbit.vcell.mapping.CurrentDensityClampStimulus) Section(com.lowagie.text.Section) StructureMapping(cbit.vcell.mapping.StructureMapping) TotalCurrentClampStimulus(cbit.vcell.mapping.TotalCurrentClampStimulus) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) ElectricalStimulus(cbit.vcell.mapping.ElectricalStimulus) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) FeatureMapping(cbit.vcell.mapping.FeatureMapping) Expression(cbit.vcell.parser.Expression) Coordinate(org.vcell.util.Coordinate) VoltageClampStimulus(cbit.vcell.mapping.VoltageClampStimulus) Parameter(cbit.vcell.model.Parameter) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) GeometryContext(cbit.vcell.mapping.GeometryContext)

Example 18 with LocalParameter

use of cbit.vcell.mapping.ParameterContext.LocalParameter in project vcell by virtualcell.

the class ReactionRule method deriveDirectRule.

public static ReactionRule deriveDirectRule(ReactionRule oldRule) throws ExpressionBindingException, PropertyVetoException {
    Model m = oldRule.getModel();
    Structure s = oldRule.getStructure();
    boolean bR = false;
    String newName = oldRule.getDisplayName() + DirectHalf;
    ReactionRule newRule = new ReactionRule(m, newName, s, bR);
    RbmKineticLaw oldLaw = oldRule.getKineticLaw();
    RateLawType rateLawType = oldLaw.getRateLawType();
    if (rateLawType != RateLawType.MassAction) {
        throw new RuntimeException("Only Mass Action Kinetics supported at this time, " + ReactionRule.typeName + " \"" + oldRule.getName() + "\" uses kinetic law type \"" + rateLawType.toString() + "\"");
    }
    RbmKineticLaw newLaw = new RbmKineticLaw(newRule, rateLawType);
    newRule.setKineticLaw(newLaw);
    LocalParameter oldfr = oldLaw.getLocalParameter(RbmKineticLawParameterType.MassActionForwardRate);
    Expression exp = new Expression(oldfr.getExpression());
    newLaw.setLocalParameterValue(RbmKineticLawParameterType.MassActionForwardRate, exp);
    for (ReactantPattern oldrp : oldRule.getReactantPatterns()) {
        SpeciesPattern newsp = new SpeciesPattern(m, oldrp.getSpeciesPattern());
        ReactantPattern newrp = new ReactantPattern(newsp, oldrp.getStructure());
        // don't try to resolve matches or bonds, we want to mirror whatever is in the old rule
        newRule.addReactant(newrp, false, false);
    }
    for (ProductPattern oldpp : oldRule.getProductPatterns()) {
        SpeciesPattern newsp = new SpeciesPattern(m, oldpp.getSpeciesPattern());
        ProductPattern newpp = new ProductPattern(newsp, oldpp.getStructure());
        newRule.addProduct(newpp, false, false);
    }
    newLaw.bind(newRule);
    return newRule;
}
Also used : SpeciesPattern(org.vcell.model.rbm.SpeciesPattern) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) Expression(cbit.vcell.parser.Expression) RateLawType(cbit.vcell.model.RbmKineticLaw.RateLawType)

Example 19 with LocalParameter

use of cbit.vcell.mapping.ParameterContext.LocalParameter in project vcell by virtualcell.

the class ReactionRulePropertiesTableModel method isCellEditable.

/**
 * Insert the method's description here.
 * Creation date: (2/24/01 12:27:46 AM)
 * @return boolean
 * @param rowIndex int
 * @param columnIndex int
 */
public boolean isCellEditable(int rowIndex, int columnIndex) {
    if (!bEditable) {
        return false;
    }
    Object o = getValueAt(rowIndex);
    if (!(o instanceof Parameter)) {
        return false;
    }
    Parameter parameter = (Parameter) o;
    if (reactionRule != null && reactionRule.getKineticLaw().getLocalParameter(RbmKineticLawParameterType.MassActionReverseRate) == parameter) {
        if (!reactionRule.isReversible()) {
            // disable Kr if rule is not reversible
            return false;
        }
    }
    switch(columnIndex) {
        case COLUMN_NAME:
            return parameter.isNameEditable();
        case COLUMN_DESCRIPTION:
            return false;
        case COLUMN_IS_GLOBAL:
            // if the parameter is reaction rate param or a ReservedSymbol in the model, it should not be editable
            if ((parameter instanceof LocalParameter) && (((LocalParameter) parameter).getRole() != RbmKineticLaw.RbmKineticLawParameterType.UserDefined)) {
                return false;
            }
            if (parameter instanceof UnresolvedParameter) {
                return false;
            }
            if (parameter instanceof LocalProxyParameter) {
                LocalProxyParameter kpp = (LocalProxyParameter) parameter;
                SymbolTableEntry ste = kpp.getTarget();
                if ((ste instanceof Model.ReservedSymbol) || (ste instanceof SpeciesContext) || (ste instanceof ModelQuantity)) {
                    return false;
                }
            }
            return true;
        case COLUMN_VALUE:
            return parameter.isExpressionEditable();
        case COLUMN_UNITS:
            return parameter.isUnitEditable();
    }
    return false;
}
Also used : LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) LocalProxyParameter(cbit.vcell.mapping.ParameterContext.LocalProxyParameter) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) ModelQuantity(cbit.vcell.model.ModelQuantity) Model(cbit.vcell.model.Model) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) Parameter(cbit.vcell.model.Parameter) LocalProxyParameter(cbit.vcell.mapping.ParameterContext.LocalProxyParameter) UnresolvedParameter(cbit.vcell.mapping.ParameterContext.UnresolvedParameter) UnresolvedParameter(cbit.vcell.mapping.ParameterContext.UnresolvedParameter) SpeciesContext(cbit.vcell.model.SpeciesContext)

Example 20 with LocalParameter

use of cbit.vcell.mapping.ParameterContext.LocalParameter in project vcell by virtualcell.

the class ReactionRulePropertiesTableModel method setValueAt.

public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    Object o = getValueAt(rowIndex);
    if (!(o instanceof Parameter)) {
        return;
    }
    Parameter parameter = (Parameter) o;
    // try {
    switch(columnIndex) {
        case COLUMN_NAME:
            {
                try {
                    if (aValue instanceof String) {
                        String newName = (String) aValue;
                        if (!parameter.getName().equals(newName)) {
                            if (parameter instanceof LocalParameter) {
                                reactionRule.getKineticLaw().renameParameter(parameter.getName(), newName);
                            } else if (parameter instanceof LocalProxyParameter) {
                                parameter.setName(newName);
                            }
                            fireTableRowsUpdated(rowIndex, rowIndex);
                        }
                    }
                } catch (ExpressionException e) {
                    e.printStackTrace(System.out);
                    PopupGenerator.showErrorDialog(ownerTable, "Error changing parameter name:\n" + e.getMessage());
                } catch (PropertyVetoException e) {
                    e.printStackTrace(System.out);
                    PopupGenerator.showErrorDialog(ownerTable, "Error changing parameter name:\n" + e.getMessage());
                }
                break;
            }
        case COLUMN_IS_GLOBAL:
            {
                if (aValue.equals(Boolean.FALSE)) {
                    // check box has been <unset> (<true> to <false>) : change param from global to local
                    if ((parameter instanceof LocalProxyParameter) && ((((LocalProxyParameter) parameter).getTarget() instanceof Model.ReservedSymbol) || (((LocalProxyParameter) parameter).getTarget() instanceof SpeciesContext) || (((LocalProxyParameter) parameter).getTarget() instanceof ModelQuantity))) {
                        PopupGenerator.showErrorDialog(ownerTable, "Parameter : \'" + parameter.getName() + "\' is a " + ((LocalProxyParameter) parameter).getTarget().getClass() + " in the model; cannot convert it to a local kinetic parameter.");
                    } else {
                        try {
                            reactionRule.getKineticLaw().convertParameterType(parameter, false);
                        } catch (PropertyVetoException pve) {
                            pve.printStackTrace(System.out);
                            PopupGenerator.showErrorDialog(ownerTable, "Unable to convert parameter : \'" + parameter.getName() + "\' to local kinetics parameter : " + pve.getMessage());
                        } catch (ExpressionBindingException e) {
                            e.printStackTrace(System.out);
                            PopupGenerator.showErrorDialog(ownerTable, "Unable to convert parameter : \'" + parameter.getName() + "\' to local kinetics parameter : " + e.getMessage());
                        }
                    }
                } else {
                    // check box has been <set> (<false> to <true>) : change param from local to global
                    if ((parameter instanceof LocalParameter) && (((LocalParameter) parameter).getRole() != RbmKineticLaw.RbmKineticLawParameterType.UserDefined)) {
                        PopupGenerator.showErrorDialog(ownerTable, "Parameter : \'" + parameter.getName() + "\' is a pre-defined kinetics parameter (not user-defined); cannot convert it to a model level (global) parameter.");
                    } else {
                        ModelParameter mp = reactionRule.getModel().getModelParameter(parameter.getName());
                        // model already had the model parameter 'param', but check if 'param' value is different from
                        // model parameter with same name. If it is, the local value will be overridden by global (model) param
                        // value, and user should be warned.
                        String choice = "Ok";
                        if (mp != null && !(mp.getExpression().compareEqual(parameter.getExpression()))) {
                            String msgStr = "Model already has a global parameter named : \'" + parameter.getName() + "\'; with value = \'" + mp.getExpression().infix() + "\'; This local parameter \'" + parameter.getName() + "\' with value = \'" + parameter.getExpression().infix() + "\' will be overridden by the global value. \nPress \'Ok' to override " + "local value with global value of \'" + parameter.getName() + "\'. \nPress \'Cancel\' to retain new local value.";
                            choice = PopupGenerator.showWarningDialog(ownerTable, msgStr, new String[] { "Ok", "Cancel" }, "Ok");
                        }
                        if (choice.equals("Ok")) {
                            try {
                                // Now 'parameter' is a local kinetic parameter. If it is not numeric, and if its expression
                                // contains other local kinetic parameters, warn user that 'parameter' cannot be promoted because
                                // of its expression containing other local parameters.
                                boolean bPromoteable = true;
                                if (!parameter.getExpression().isNumeric()) {
                                    String[] symbols = parameter.getExpression().getSymbols();
                                    for (int i = 0; i < symbols.length; i++) {
                                        if (reactionRule.getKineticLaw().getLocalParameter(symbols[i]) != null) {
                                            PopupGenerator.showErrorDialog(ownerTable, "Parameter \'" + parameter.getName() + "\' contains other local kinetic parameters; Cannot convert it to global until the referenced parameters are global.");
                                            bPromoteable = false;
                                        }
                                    }
                                }
                                if (bPromoteable) {
                                    reactionRule.getKineticLaw().convertParameterType(parameter, true);
                                }
                            } catch (PropertyVetoException pve) {
                                pve.printStackTrace(System.out);
                                PopupGenerator.showErrorDialog(ownerTable, "Cannot convert parameter \'" + parameter.getName() + "\' to global parameter : " + pve.getMessage());
                            } catch (ExpressionBindingException e) {
                                e.printStackTrace(System.out);
                                PopupGenerator.showErrorDialog(ownerTable, "Cannot convert parameter \'" + parameter.getName() + "\' to global parameter : " + e.getMessage());
                            }
                        }
                    }
                }
                fireTableRowsUpdated(rowIndex, rowIndex);
                break;
            }
        case COLUMN_VALUE:
            {
                try {
                    if (aValue instanceof ScopedExpression) {
                        // }
                        throw new RuntimeException("unexpected value type ScopedExpression");
                    } else if (aValue instanceof String) {
                        String newExpressionString = (String) aValue;
                        if (parameter instanceof LocalParameter) {
                            LocalParameter localParameter = (LocalParameter) parameter;
                            reactionRule.getKineticLaw().setParameterValue(localParameter, new Expression(newExpressionString), true);
                        } else if (parameter instanceof LocalProxyParameter) {
                            parameter.setExpression(new Expression(newExpressionString));
                        }
                    }
                    reactionRule.getKineticLaw().resolveUndefinedUnits();
                    fireTableRowsUpdated(rowIndex, rowIndex);
                } catch (java.beans.PropertyVetoException e) {
                    e.printStackTrace(System.out);
                    PopupGenerator.showErrorDialog(ownerTable, "Error:\n" + e.getMessage());
                } catch (ExpressionException e) {
                    e.printStackTrace(System.out);
                    PopupGenerator.showErrorDialog(ownerTable, "Expression error:\n" + e.getMessage());
                }
                break;
            }
        case COLUMN_UNITS:
            {
                try {
                    if (aValue instanceof String && parameter instanceof LocalParameter && ((LocalParameter) parameter).getRole() == RbmKineticLaw.RbmKineticLawParameterType.UserDefined) {
                        String newUnitString = (String) aValue;
                        LocalParameter kineticsParm = (LocalParameter) parameter;
                        ModelUnitSystem modelUnitSystem = reactionRule.getModel().getUnitSystem();
                        if (!kineticsParm.getUnitDefinition().getSymbol().equals(newUnitString)) {
                            kineticsParm.setUnitDefinition(modelUnitSystem.getInstance(newUnitString));
                            reactionRule.getKineticLaw().resolveUndefinedUnits();
                            fireTableRowsUpdated(rowIndex, rowIndex);
                        }
                    }
                } catch (VCUnitException e) {
                    e.printStackTrace(System.out);
                    PopupGenerator.showErrorDialog(ownerTable, "Error changing parameter unit:\n" + e.getMessage());
                }
                break;
            }
    }
// }catch (java.beans.PropertyVetoException e){
// e.printStackTrace(System.out);
// }
}
Also used : LocalProxyParameter(cbit.vcell.mapping.ParameterContext.LocalProxyParameter) SpeciesContext(cbit.vcell.model.SpeciesContext) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ExpressionException(cbit.vcell.parser.ExpressionException) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) PropertyVetoException(java.beans.PropertyVetoException) VCUnitException(cbit.vcell.units.VCUnitException) ModelParameter(cbit.vcell.model.Model.ModelParameter) ScopedExpression(cbit.gui.ScopedExpression) ModelQuantity(cbit.vcell.model.ModelQuantity) ScopedExpression(cbit.gui.ScopedExpression) Expression(cbit.vcell.parser.Expression) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) Parameter(cbit.vcell.model.Parameter) LocalProxyParameter(cbit.vcell.mapping.ParameterContext.LocalProxyParameter) UnresolvedParameter(cbit.vcell.mapping.ParameterContext.UnresolvedParameter) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem)

Aggregations

LocalParameter (cbit.vcell.mapping.ParameterContext.LocalParameter)45 Expression (cbit.vcell.parser.Expression)31 VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)17 PropertyVetoException (java.beans.PropertyVetoException)12 ModelParameter (cbit.vcell.model.Model.ModelParameter)11 SpeciesContext (cbit.vcell.model.SpeciesContext)11 ExpressionException (cbit.vcell.parser.ExpressionException)11 ModelUnitSystem (cbit.vcell.model.ModelUnitSystem)9 Parameter (cbit.vcell.model.Parameter)9 ArrayList (java.util.ArrayList)9 SymbolTableEntry (cbit.vcell.parser.SymbolTableEntry)8 Element (org.jdom.Element)8 ProxyParameter (cbit.vcell.model.ProxyParameter)7 CurrentDensityClampStimulus (cbit.vcell.mapping.CurrentDensityClampStimulus)6 LocalProxyParameter (cbit.vcell.mapping.ParameterContext.LocalProxyParameter)6 TotalCurrentClampStimulus (cbit.vcell.mapping.TotalCurrentClampStimulus)6 Model (cbit.vcell.model.Model)6 ElectricalStimulus (cbit.vcell.mapping.ElectricalStimulus)5 CompartmentSubDomain (cbit.vcell.math.CompartmentSubDomain)5 Domain (cbit.vcell.math.Variable.Domain)5