Search in sources :

Example 1 with ProductPattern

use of cbit.vcell.model.ProductPattern in project vcell by virtualcell.

the class ViewGeneratedReactionsPanel method updateShape.

public void updateShape(int selectedRow) {
    GeneratedReactionTableRow reactionTableRow = tableModel.getValueAt(selectedRow);
    String inputString = reactionTableRow.getExpression();
    System.out.println(selectedRow + ": " + inputString);
    // ReactionRule newReactionRule = (ReactionRule)RbmUtils.parseReactionRule(inputString, bioModel);
    Model tempModel = null;
    try {
        tempModel = new Model("MyTempModel");
        tempModel.addFeature("c0");
    } catch (ModelException | PropertyVetoException e1) {
        e1.printStackTrace();
    }
    if (owner != null && owner.getSimulationContext() != null) {
        List<MolecularType> mtList = owner.getSimulationContext().getModel().getRbmModelContainer().getMolecularTypeList();
        try {
            tempModel.getRbmModelContainer().setMolecularTypeList(mtList);
        } catch (PropertyVetoException e1) {
            e1.printStackTrace();
            throw new RuntimeException("Unexpected exception setting " + MolecularType.typeName + " list: " + e1.getMessage(), e1);
        }
    } else {
        // This should not be possible
        throw new RuntimeException("Owner or SimulationContext are null.");
    }
    int arrowIndex = inputString.indexOf("<->");
    boolean bReversible = true;
    if (arrowIndex < 0) {
        arrowIndex = inputString.indexOf("->");
        bReversible = false;
    }
    String left = inputString.substring(0, arrowIndex).trim();
    String right = inputString.substring(arrowIndex + (bReversible ? 3 : 2)).trim();
    if (left.length() == 0 && right.length() == 0) {
        return;
    }
    // we recover the original rule that generated the flattened reaction we now try to transform back into a fake rule
    BNGReaction reactionObject = reactionTableRow.getReactionObject();
    String name = reactionObject.getRuleName();
    if (name.contains(GeneratedReactionTableModel.reverse)) {
        name = name.substring(GeneratedReactionTableModel.reverse.length());
    }
    if (name.endsWith(ReactionRule.DirectHalf)) {
        name = name.substring(0, name.indexOf(ReactionRule.DirectHalf));
    }
    if (name.endsWith(ReactionRule.InverseHalf)) {
        name = name.substring(0, name.indexOf(ReactionRule.InverseHalf));
    }
    // get the name of the original structure from the original rule and make here another structure with the same name
    String strStructure = null;
    Structure ruleStructure;
    SimulationContext sc = owner.getSimulationContext();
    ReactionRule rr = sc.getModel().getRbmModelContainer().getReactionRule(name);
    if (rr != null && rr.getStructure() != null) {
        strStructure = rr.getStructure().getName();
    }
    if (strStructure != null) {
        if (tempModel.getStructure(strStructure) == null) {
            try {
                if (rr.getStructure().getTypeName().equals(Structure.TYPE_NAME_MEMBRANE)) {
                    tempModel.addMembrane(strStructure);
                } else {
                    tempModel.addFeature(strStructure);
                }
            } catch (ModelException | PropertyVetoException e) {
                e.printStackTrace();
            }
        }
        ruleStructure = tempModel.getStructure(strStructure);
    } else {
        throw new RuntimeException("Failed to recover a Structure name from the Reaction Rule: " + name);
    }
    // making the fake rules just for display purpose, actually they are the flattened reactions resulted from bngl
    // the name is probably not unique, it's likely that many flattened reactions are derived from the same rule
    ReactionRule reactionRule = tempModel.getRbmModelContainer().createReactionRule(name, ruleStructure, bReversible);
    String regex = "[^!]\\+";
    String[] patterns = left.split(regex);
    for (String spString : patterns) {
        try {
            spString = spString.trim();
            // if compartments are present, we're cheating big time making some fake compartments just for compartment name display purposes
            SpeciesPattern speciesPattern = (SpeciesPattern) RbmUtils.parseSpeciesPattern(spString, tempModel);
            strStructure = RbmUtils.parseCompartment(spString, tempModel);
            speciesPattern.resolveBonds();
            Structure structure;
            if (strStructure != null) {
                if (tempModel.getStructure(strStructure) == null) {
                    if (sc.getModel().getStructure(strStructure).getTypeName().equals(Structure.TYPE_NAME_MEMBRANE)) {
                        tempModel.addMembrane(strStructure);
                    } else {
                        tempModel.addFeature(strStructure);
                    }
                }
                structure = tempModel.getStructure(strStructure);
            } else {
                // if nothing explicit for a participant, we use by default the structure of the rule
                structure = ruleStructure;
            }
            reactionRule.addReactant(new ReactantPattern(speciesPattern, structure));
        } catch (Throwable ex) {
            ex.printStackTrace();
            // error (red circle)
            SpeciesPatternLargeShape spls = new SpeciesPatternLargeShape(20, 20, -1, shapePanel, true, issueManager);
            reactantPatternShapeList.clear();
            productPatternShapeList.clear();
            reactantPatternShapeList.add(spls);
            shapePanel.repaint();
            return;
        }
    }
    patterns = right.split(regex);
    for (String spString : patterns) {
        try {
            spString = spString.trim();
            SpeciesPattern speciesPattern = (SpeciesPattern) RbmUtils.parseSpeciesPattern(spString, tempModel);
            strStructure = RbmUtils.parseCompartment(spString, tempModel);
            speciesPattern.resolveBonds();
            Structure structure;
            if (strStructure != null) {
                if (tempModel.getStructure(strStructure) == null) {
                    if (sc.getModel().getStructure(strStructure).getTypeName().equals(Structure.TYPE_NAME_MEMBRANE)) {
                        tempModel.addMembrane(strStructure);
                    } else {
                        tempModel.addFeature(strStructure);
                    }
                }
                structure = tempModel.getStructure(strStructure);
            } else {
                structure = ruleStructure;
            }
            // BNGLParser parser = new BNGLParser(new StringReader(sp));
            // ASTSpeciesPattern astSpeciesPattern = parser.SpeciesPattern();
            // BnglObjectConstructionVisitor constructionVisitor = new BnglObjectConstructionVisitor(tempModel, null, false);
            // SpeciesPattern speciesPattern = (SpeciesPattern) astSpeciesPattern.jjtAccept(constructionVisitor, null);
            // for(MolecularTypePattern mtp : speciesPattern.getMolecularTypePatterns()) {
            // mtp.setParticipantMatchLabel("*");
            // }
            // System.out.println(speciesPattern.toString());
            reactionRule.addProduct(new ProductPattern(speciesPattern, structure));
        } catch (Throwable ex) {
            ex.printStackTrace();
            // error (red circle)
            SpeciesPatternLargeShape spls = new SpeciesPatternLargeShape(20, 20, -1, shapePanel, true, issueManager);
            reactantPatternShapeList.clear();
            productPatternShapeList.clear();
            reactantPatternShapeList.add(spls);
            shapePanel.repaint();
            return;
        }
    }
    // ----------------------------------------------------------------------------------------------------
    List<ReactantPattern> rpList = reactionRule.getReactantPatterns();
    reactantPatternShapeList.clear();
    int xOffset = 20;
    int xOffsetRound = 20;
    if (rpList != null && rpList.size() > 0) {
        for (int i = 0; i < rpList.size(); i++) {
            SpeciesPattern sp = rpList.get(i).getSpeciesPattern();
            for (MolecularTypePattern mtp : sp.getMolecularTypePatterns()) {
                mtp.setParticipantMatchLabel("*");
            }
            SpeciesPatternLargeShape sps = new SpeciesPatternLargeShape(xOffset, 20, -1, sp, shapePanel, reactionRule, issueManager);
            // SpeciesPatternRoundShape sps = new SpeciesPatternRoundShape(xOffsetRound, 20, -1, sp, shapePanel, reactionRule);
            if (i < rpList.size() - 1) {
                sps.addEndText("+");
            } else {
                if (reactionRule.isReversible()) {
                    sps.addEndText("<->");
                } else {
                    sps.addEndText("->");
                }
            }
            xOffset = sps.getRightEnd() + 45;
            xOffsetRound = sps.getRightEnd() + 45;
            reactantPatternShapeList.add(sps);
        }
    }
    // space for the <-> sign
    xOffset += 15;
    List<ProductPattern> ppList = reactionRule.getProductPatterns();
    productPatternShapeList.clear();
    if (ppList != null && ppList.size() > 0) {
        for (int i = 0; i < ppList.size(); i++) {
            SpeciesPattern sp = ppList.get(i).getSpeciesPattern();
            for (MolecularTypePattern mtp : sp.getMolecularTypePatterns()) {
                mtp.setParticipantMatchLabel("*");
            }
            SpeciesPatternLargeShape sps = new SpeciesPatternLargeShape(xOffset, 20, -1, sp, shapePanel, reactionRule, issueManager);
            // SpeciesPatternRoundShape sps = new SpeciesPatternRoundShape(xOffset, 20, -1, sp, shapePanel, reactionRule);
            if (i < ppList.size() - 1) {
                sps.addEndText("+");
            }
            xOffset = sps.getRightEnd() + 45;
            productPatternShapeList.add(sps);
        }
    }
    Dimension preferredSize = new Dimension(xOffset + 90, 50);
    shapePanel.setPreferredSize(preferredSize);
    shapePanel.repaint();
}
Also used : SpeciesPatternLargeShape(cbit.vcell.graph.SpeciesPatternLargeShape) SpeciesPattern(org.vcell.model.rbm.SpeciesPattern) Structure(cbit.vcell.model.Structure) ReactantPattern(cbit.vcell.model.ReactantPattern) ModelException(cbit.vcell.model.ModelException) ReactionRule(cbit.vcell.model.ReactionRule) ProductPattern(cbit.vcell.model.ProductPattern) Dimension(java.awt.Dimension) SimulationContext(cbit.vcell.mapping.SimulationContext) Point(java.awt.Point) PropertyVetoException(java.beans.PropertyVetoException) MolecularType(org.vcell.model.rbm.MolecularType) BNGReaction(cbit.vcell.bionetgen.BNGReaction) Model(cbit.vcell.model.Model) VCellSortTableModel(cbit.vcell.client.desktop.biomodel.VCellSortTableModel) BioModel(cbit.vcell.biomodel.BioModel) MolecularTypePattern(org.vcell.model.rbm.MolecularTypePattern)

Example 2 with ProductPattern

use of cbit.vcell.model.ProductPattern in project vcell by virtualcell.

the class ReactionRuleEditorPropertiesPanel method addProduct.

public void addProduct() {
    ProductPattern product = new ProductPattern(new SpeciesPattern(), reactionRule.getStructure());
    reactionRule.addProduct(product);
    final TreePath path = productTreeModel.findObjectPath(null, product);
    productTree.setSelectionPath(path);
    SwingUtilities.invokeLater(new Runnable() {

        public void run() {
            productTree.scrollPathToVisible(path);
        // reactantTreeModel.populateTree();
        }
    });
}
Also used : ProductPattern(cbit.vcell.model.ProductPattern) TreePath(javax.swing.tree.TreePath) SpeciesPattern(org.vcell.model.rbm.SpeciesPattern)

Example 3 with ProductPattern

use of cbit.vcell.model.ProductPattern in project vcell by virtualcell.

the class ModelProcessSpecsPanel method initConnections.

/**
 * Initializes connections
 * @exception java.lang.Exception The exception description.
 */
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void initConnections() throws java.lang.Exception {
    // user code begin {1}
    // user code end
    this.addPropertyChangeListener(ivjEventHandler);
    getScrollPaneTable().setModel(getModelProcessSpecsTableModel());
    getScrollPaneTable().setDefaultRenderer(ModelProcess.class, new DefaultScrollTableCellRenderer() {

        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            defaultToolTipText = null;
            if (value instanceof ModelProcess) {
                setText(((ModelProcess) value).getName());
                defaultToolTipText = getText();
                setToolTipText(defaultToolTipText);
            }
            TableModel tableModel = table.getModel();
            if (tableModel instanceof SortTableModel) {
                DefaultScrollTableCellRenderer.issueRenderer(this, defaultToolTipText, table, row, column, (SortTableModel) tableModel);
            }
            return this;
        }
    });
    DefaultScrollTableCellRenderer rbmReactionShapeDepictionCellRenderer = new DefaultScrollTableCellRenderer() {

        List<SpeciesPatternSmallShape> spssList = new ArrayList<SpeciesPatternSmallShape>();

        SpeciesPatternSmallShape spss = null;

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if (table.getModel() instanceof VCellSortTableModel<?>) {
                Object selectedObject = null;
                if (table.getModel() == ivjModelProcessSpecsTableModel) {
                    selectedObject = ivjModelProcessSpecsTableModel.getValueAt(row);
                }
                if (selectedObject != null) {
                    if (selectedObject instanceof ModelProcessSpec) {
                        ModelProcessSpec mps = (ModelProcessSpec) selectedObject;
                        ModelProcess mp = (ModelProcess) mps.getModelProcess();
                        if (mp instanceof ReactionRule) {
                            ReactionRule rr = (ReactionRule) mp;
                            Graphics panelContext = table.getGraphics();
                            spssList.clear();
                            List<ReactantPattern> rpList = rr.getReactantPatterns();
                            int xPos = 4;
                            for (int i = 0; i < rpList.size(); i++) {
                                SpeciesPattern sp = rr.getReactantPattern(i).getSpeciesPattern();
                                spss = new SpeciesPatternSmallShape(xPos, 2, sp, shapeManager, panelContext, rr, isSelected, issueManager);
                                if (i < rpList.size() - 1) {
                                    spss.addEndText("+");
                                } else {
                                    if (rr.isReversible()) {
                                        spss.addEndText("<->");
                                        xPos += 7;
                                    } else {
                                        spss.addEndText("->");
                                    }
                                }
                                xPos += spss.getWidth() + 15;
                                spssList.add(spss);
                            }
                            List<ProductPattern> ppList = rr.getProductPatterns();
                            xPos += 7;
                            for (int i = 0; i < ppList.size(); i++) {
                                SpeciesPattern sp = rr.getProductPattern(i).getSpeciesPattern();
                                spss = new SpeciesPatternSmallShape(xPos, 2, sp, shapeManager, panelContext, rr, isSelected, issueManager);
                                if (i < ppList.size() - 1) {
                                    spss.addEndText("+");
                                }
                                xPos += spss.getWidth() + 15;
                                spssList.add(spss);
                            }
                        } else {
                            ReactionStep rs = (ReactionStep) mp;
                            Graphics panelContext = table.getGraphics();
                            spssList.clear();
                            int xPos = 4;
                            int extraSpace = 0;
                            for (int i = 0; i < rs.getNumReactants(); i++) {
                                SpeciesPattern sp = rs.getReactant(i).getSpeciesContext().getSpeciesPattern();
                                spss = new SpeciesPatternSmallShape(xPos, 2, sp, shapeManager, panelContext, rs, isSelected, issueManager);
                                if (i < rs.getNumReactants() - 1) {
                                    spss.addEndText("+");
                                } else {
                                    if (rs.isReversible()) {
                                        spss.addEndText("<->");
                                        extraSpace += 7;
                                    } else {
                                        spss.addEndText("->");
                                    }
                                }
                                int offset = sp == null ? 17 : 15;
                                offset += extraSpace;
                                int w = spss.getWidth();
                                xPos += w + offset;
                                spssList.add(spss);
                            }
                            xPos += 8;
                            for (int i = 0; i < rs.getNumProducts(); i++) {
                                SpeciesPattern sp = rs.getProduct(i).getSpeciesContext().getSpeciesPattern();
                                if (i == 0 && rs.getNumReactants() == 0) {
                                    xPos += 14;
                                }
                                spss = new SpeciesPatternSmallShape(xPos, 2, sp, shapeManager, panelContext, rs, isSelected, issueManager);
                                if (i == 0 && rs.getNumReactants() == 0) {
                                    spss.addStartText("->");
                                }
                                if (i < rs.getNumProducts() - 1) {
                                    spss.addEndText("+");
                                }
                                int offset = sp == null ? 17 : 15;
                                int w = spss.getWidth();
                                xPos += w + offset;
                                spssList.add(spss);
                            }
                        }
                    }
                } else {
                    spssList.clear();
                }
            }
            setText("");
            return this;
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            for (SpeciesPatternSmallShape spss : spssList) {
                if (spss == null) {
                    continue;
                }
                spss.paintSelf(g);
            }
        }
    };
    getScrollPaneTable().setDefaultRenderer(SpeciesPattern.class, rbmReactionShapeDepictionCellRenderer);
    // ivjScrollPaneTable.getColumnModel().getColumn(ModelProcessSpecsTableModel.ColumnType.COLUMN_DEPICTION.ordinal()).setCellRenderer(rbmReactionShapeDepictionCellRenderer);
    // ivjScrollPaneTable.getColumnModel().getColumn(ModelProcessSpecsTableModel.ColumnType.COLUMN_DEPICTION.ordinal()).setPreferredWidth(180);
    getScrollPaneTable().getSelectionModel().addListSelectionListener(ivjEventHandler);
}
Also used : VCellSortTableModel(cbit.vcell.client.desktop.biomodel.VCellSortTableModel) SortTableModel(org.vcell.util.gui.sorttable.SortTableModel) ReactionRule(cbit.vcell.model.ReactionRule) ProductPattern(cbit.vcell.model.ProductPattern) SpeciesPatternSmallShape(cbit.vcell.graph.SpeciesPatternSmallShape) ModelProcessSpec(cbit.vcell.mapping.ModelProcessSpec) ModelProcess(cbit.vcell.model.ModelProcess) SpeciesPattern(org.vcell.model.rbm.SpeciesPattern) Graphics(java.awt.Graphics) VCellSortTableModel(cbit.vcell.client.desktop.biomodel.VCellSortTableModel) JTable(javax.swing.JTable) ReactionStep(cbit.vcell.model.ReactionStep) DefaultScrollTableCellRenderer(org.vcell.util.gui.DefaultScrollTableCellRenderer) ArrayList(java.util.ArrayList) List(java.util.List) Component(java.awt.Component) VCellSortTableModel(cbit.vcell.client.desktop.biomodel.VCellSortTableModel) TableModel(javax.swing.table.TableModel) SortTableModel(org.vcell.util.gui.sorttable.SortTableModel) ReactantPattern(cbit.vcell.model.ReactantPattern)

Example 4 with ProductPattern

use of cbit.vcell.model.ProductPattern 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 5 with ProductPattern

use of cbit.vcell.model.ProductPattern in project vcell by virtualcell.

the class RulebasedMathMapping method addParticleJumpProcesses.

private void addParticleJumpProcesses(VariableHash varHash, GeometryClass geometryClass, SubDomain subDomain, HashMap<SpeciesPattern, VolumeParticleSpeciesPattern> speciesPatternMap) throws ExpressionException, MappingException, MathException, PropertyVetoException {
    ArrayList<ReactionRule> rrList = new ArrayList<>();
    for (ReactionRuleSpec rrSpec : getSimulationContext().getReactionContext().getReactionRuleSpecs()) {
        if (!rrSpec.isExcluded()) {
            rrList.add(rrSpec.getReactionRule());
        }
    }
    for (ReactionRule reactionRule : rrList) {
        String jpName = TokenMangler.mangleToSName(reactionRule.getName());
        ArrayList<ParticleVariable> reactantParticles = new ArrayList<ParticleVariable>();
        for (ReactantPattern reactantSpeciesPattern : reactionRule.getReactantPatterns()) {
            reactantParticles.add(speciesPatternMap.get(reactantSpeciesPattern.getSpeciesPattern()));
        }
        ArrayList<ParticleVariable> productParticles = new ArrayList<ParticleVariable>();
        for (ProductPattern productSpeciesPattern : reactionRule.getProductPatterns()) {
            productParticles.add(speciesPatternMap.get(productSpeciesPattern.getSpeciesPattern()));
        }
        ArrayList<Action> forwardActions = new ArrayList<Action>();
        ArrayList<Action> reverseActions = new ArrayList<Action>();
        for (ParticleVariable reactant : reactantParticles) {
            forwardActions.add(new Action(reactant, Action.ACTION_DESTROY, new Expression(1.0)));
            reverseActions.add(new Action(reactant, Action.ACTION_CREATE, new Expression(1.0)));
        }
        for (ParticleVariable product : productParticles) {
            forwardActions.add(new Action(product, Action.ACTION_CREATE, new Expression(1.0)));
            reverseActions.add(new Action(product, Action.ACTION_DESTROY, new Expression(1.0)));
        }
        RbmKineticLaw kinetics = reactionRule.getKineticLaw();
        if (kinetics.getRateLawType() == RbmKineticLaw.RateLawType.MassAction) {
            boolean constantMassActionKineticCoefficients = true;
            StringBuffer errorMessage = new StringBuffer();
            Parameter forward_rateParameter = kinetics.getLocalParameter(RbmKineticLawParameterType.MassActionForwardRate);
            Expression substitutedForwardRate = MathUtilities.substituteModelParameters(forward_rateParameter.getExpression(), reactionRule.getNameScope().getScopedSymbolTable());
            if (!substitutedForwardRate.flatten().isNumeric()) {
                errorMessage.append("flattened Kf for reactionRule(" + reactionRule.getName() + ") is not numeric, exp = '" + substitutedForwardRate.flatten().infix() + "'");
                constantMassActionKineticCoefficients = false;
            }
            if (reactionRule.isReversible()) {
                Parameter reverse_rateParameter = kinetics.getLocalParameter(RbmKineticLawParameterType.MassActionReverseRate);
                if (reverse_rateParameter == null || reverse_rateParameter.getExpression() == null) {
                    throw new MappingException("reverse rate constant for reaction rule " + reactionRule.getName() + " is missing");
                }
                Expression substitutedReverseRate = MathUtilities.substituteModelParameters(reverse_rateParameter.getExpression(), reactionRule.getNameScope().getScopedSymbolTable());
                if (!substitutedReverseRate.flatten().isNumeric()) {
                    errorMessage.append("flattened Kr for reactionRule(" + reactionRule.getName() + ") is not numeric, exp = '" + substitutedReverseRate.flatten().infix() + "'");
                    constantMassActionKineticCoefficients = false;
                }
            }
            if (constantMassActionKineticCoefficients) {
                addStrictMassActionParticleJumpProcess(varHash, geometryClass, subDomain, reactionRule, jpName, reactantParticles, productParticles, forwardActions, reverseActions);
            } else {
                throw new MappingException("not mass action: " + errorMessage.toString());
            // addGeneralParticleJumpProcess(varHash, geometryClass, subDomain,
            // reactionRule, jpName,
            // reactantParticles, productParticles,
            // forwardActions, reverseActions);
            }
        } else {
            throw new MappingException("rule-based math generation unsupported for Kinetic Law: " + kinetics.getRateLawType());
        }
    }
// end reactionRules
}
Also used : Action(cbit.vcell.math.Action) ReactionRule(cbit.vcell.model.ReactionRule) ProductPattern(cbit.vcell.model.ProductPattern) VolumeParticleVariable(cbit.vcell.math.VolumeParticleVariable) ParticleVariable(cbit.vcell.math.ParticleVariable) ArrayList(java.util.ArrayList) RbmKineticLaw(cbit.vcell.model.RbmKineticLaw) Expression(cbit.vcell.parser.Expression) Parameter(cbit.vcell.model.Parameter) UnresolvedParameter(cbit.vcell.mapping.ParameterContext.UnresolvedParameter) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) ReactantPattern(cbit.vcell.model.ReactantPattern)

Aggregations

ProductPattern (cbit.vcell.model.ProductPattern)22 ReactantPattern (cbit.vcell.model.ReactantPattern)20 ReactionRule (cbit.vcell.model.ReactionRule)17 SpeciesPattern (org.vcell.model.rbm.SpeciesPattern)12 Structure (cbit.vcell.model.Structure)10 ArrayList (java.util.ArrayList)8 SpeciesContext (cbit.vcell.model.SpeciesContext)7 MolecularType (org.vcell.model.rbm.MolecularType)6 MolecularTypePattern (org.vcell.model.rbm.MolecularTypePattern)6 RbmObservable (cbit.vcell.model.RbmObservable)5 ReactionStep (cbit.vcell.model.ReactionStep)5 ModelException (cbit.vcell.model.ModelException)4 RbmKineticLaw (cbit.vcell.model.RbmKineticLaw)4 Point (java.awt.Point)4 List (java.util.List)4 SpeciesPatternSmallShape (cbit.vcell.graph.SpeciesPatternSmallShape)3 Model (cbit.vcell.model.Model)3 Product (cbit.vcell.model.Product)3 Reactant (cbit.vcell.model.Reactant)3 Graphics (java.awt.Graphics)3