Search in sources :

Example 6 with ReactantPattern

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

the class RulebasedMathMapping method addSpeciesPatterns.

private HashMap<SpeciesPattern, VolumeParticleSpeciesPattern> addSpeciesPatterns(Domain domain, List<ReactionRule> rrList) throws MathException {
    // Particle Molecular Types
    // 
    Model model = getSimulationContext().getModel();
    List<RbmObservable> observableList = model.getRbmModelContainer().getObservableList();
    List<MolecularType> molecularTypeList = model.getRbmModelContainer().getMolecularTypeList();
    for (MolecularType molecularType : molecularTypeList) {
        ParticleMolecularType particleMolecularType = new ParticleMolecularType(molecularType.getName());
        for (MolecularComponent molecularComponent : molecularType.getComponentList()) {
            String pmcName = molecularComponent.getName();
            String pmcId = particleMolecularType.getName() + "_" + molecularComponent.getName();
            ParticleMolecularComponent particleMolecularComponent = new ParticleMolecularComponent(pmcId, pmcName);
            for (ComponentStateDefinition componentState : molecularComponent.getComponentStateDefinitions()) {
                ParticleComponentStateDefinition pcsd = particleMolecularComponent.getComponentStateDefinition(componentState.getName());
                if (pcsd == null) {
                    particleMolecularComponent.addComponentStateDefinition(new ParticleComponentStateDefinition(componentState.getName()));
                }
            }
            particleMolecularType.addMolecularComponent(particleMolecularComponent);
        }
        if (!molecularType.isAnchorAll()) {
            List<String> anchorList = new ArrayList<>();
            for (Structure struct : molecularType.getAnchors()) {
                anchorList.add(struct.getName());
            }
            particleMolecularType.setAnchorList(anchorList);
        }
        mathDesc.addParticleMolecularType(particleMolecularType);
    }
    // 
    // Assemble list of all Species Patterns (from observables, reaction rules, and seed species).
    // 
    // linked hash set maintains insertion order
    LinkedHashMap<SpeciesPattern, Structure> speciesPatternStructureMap = new LinkedHashMap<SpeciesPattern, Structure>();
    for (RbmObservable observable : observableList) {
        for (SpeciesPattern speciesPattern : observable.getSpeciesPatternList()) {
            speciesPatternStructureMap.put(speciesPattern, observable.getStructure());
        }
    }
    for (ReactionRule reactionRule : rrList) {
        for (ReactantPattern rp : reactionRule.getReactantPatterns()) {
            speciesPatternStructureMap.put(rp.getSpeciesPattern(), rp.getStructure());
        }
        for (ProductPattern pp : reactionRule.getProductPatterns()) {
            speciesPatternStructureMap.put(pp.getSpeciesPattern(), pp.getStructure());
        }
    }
    for (SpeciesContext sc : model.getSpeciesContexts()) {
        if (!sc.hasSpeciesPattern()) {
            continue;
        }
        speciesPatternStructureMap.put(sc.getSpeciesPattern(), sc.getStructure());
    }
    // 
    // add list of unique speciesPatterns
    // 
    HashMap<String, VolumeParticleSpeciesPattern> speciesPatternVCMLMap = new HashMap<String, VolumeParticleSpeciesPattern>();
    HashMap<SpeciesPattern, VolumeParticleSpeciesPattern> speciesPatternMap = new HashMap<SpeciesPattern, VolumeParticleSpeciesPattern>();
    String speciesPatternName = "speciesPattern0";
    for (SpeciesPattern speciesPattern : speciesPatternStructureMap.keySet()) {
        VolumeParticleSpeciesPattern volumeParticleSpeciesPattern = new VolumeParticleSpeciesPattern(speciesPatternName, domain, speciesPatternStructureMap.get(speciesPattern).getName());
        for (MolecularTypePattern molecularTypePattern : speciesPattern.getMolecularTypePatterns()) {
            ParticleMolecularType particleMolecularType = mathDesc.getParticleMolecularType(molecularTypePattern.getMolecularType().getName());
            ParticleMolecularTypePattern particleMolecularTypePattern = new ParticleMolecularTypePattern(particleMolecularType);
            String participantMatchLabel = molecularTypePattern.getParticipantMatchLabel();
            if (molecularTypePattern.getParticipantMatchLabel() != null) {
                particleMolecularTypePattern.setMatchLabel(participantMatchLabel);
            }
            for (MolecularComponentPattern molecularComponentPattern : molecularTypePattern.getComponentPatternList()) {
                MolecularComponent molecularComponent = molecularComponentPattern.getMolecularComponent();
                ParticleMolecularComponent particleMolecularComponent = particleMolecularType.getMolecularComponent(molecularComponent.getName());
                ParticleMolecularComponentPattern particleMolecularComponentPattern = new ParticleMolecularComponentPattern(particleMolecularComponent);
                ComponentStatePattern componentState = molecularComponentPattern.getComponentStatePattern();
                if (componentState != null) {
                    if (componentState.isAny()) {
                        ParticleComponentStatePattern pcsp = new ParticleComponentStatePattern();
                        particleMolecularComponentPattern.setComponentStatePattern(pcsp);
                    } else {
                        String name = componentState.getComponentStateDefinition().getName();
                        ParticleComponentStateDefinition pcsd = particleMolecularComponent.getComponentStateDefinition(name);
                        // ParticleComponentStateDefinition pcsd = new ParticleComponentStateDefinition(componentState.getComponentStateDefinition().getName());
                        // particleMolecularComponent.addComponentStateDefinition(pcsd);
                        ParticleComponentStatePattern pcsp = new ParticleComponentStatePattern(pcsd);
                        particleMolecularComponentPattern.setComponentStatePattern(pcsp);
                    }
                } else {
                    ParticleComponentStatePattern pcsp = new ParticleComponentStatePattern();
                    particleMolecularComponentPattern.setComponentStatePattern(pcsp);
                }
                switch(molecularComponentPattern.getBondType()) {
                    case Specified:
                        {
                            particleMolecularComponentPattern.setBondType(ParticleBondType.Specified);
                            particleMolecularComponentPattern.setBondId(molecularComponentPattern.getBondId());
                            break;
                        }
                    case Exists:
                        {
                            particleMolecularComponentPattern.setBondType(ParticleBondType.Exists);
                            particleMolecularComponentPattern.setBondId(-1);
                            break;
                        }
                    case None:
                        {
                            particleMolecularComponentPattern.setBondType(ParticleBondType.None);
                            particleMolecularComponentPattern.setBondId(-1);
                            break;
                        }
                    case Possible:
                        {
                            particleMolecularComponentPattern.setBondType(ParticleBondType.Possible);
                            particleMolecularComponentPattern.setBondId(-1);
                            break;
                        }
                }
                particleMolecularTypePattern.addMolecularComponentPattern(particleMolecularComponentPattern);
            }
            volumeParticleSpeciesPattern.addMolecularTypePattern(particleMolecularTypePattern);
        }
        String speciesPatternVCML = volumeParticleSpeciesPattern.getVCML("tempName");
        VolumeParticleSpeciesPattern uniqueVolumeParticleSpeciesPattern = speciesPatternVCMLMap.get(speciesPatternVCML);
        if (uniqueVolumeParticleSpeciesPattern == null) {
            speciesPatternVCMLMap.put(speciesPatternVCML, volumeParticleSpeciesPattern);
            speciesPatternName = TokenMangler.getNextEnumeratedToken(speciesPatternName);
            speciesPatternMap.put(speciesPattern, volumeParticleSpeciesPattern);
        } else {
            speciesPatternMap.put(speciesPattern, uniqueVolumeParticleSpeciesPattern);
        }
    }
    return speciesPatternMap;
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) ParticleMolecularComponent(cbit.vcell.math.ParticleMolecularComponent) SpeciesContext(cbit.vcell.model.SpeciesContext) VolumeParticleSpeciesPattern(cbit.vcell.math.VolumeParticleSpeciesPattern) SpeciesPattern(org.vcell.model.rbm.SpeciesPattern) ComponentStateDefinition(org.vcell.model.rbm.ComponentStateDefinition) ParticleComponentStateDefinition(cbit.vcell.math.ParticleComponentStateDefinition) LinkedHashMap(java.util.LinkedHashMap) ParticleMolecularComponent(cbit.vcell.math.ParticleMolecularComponent) MolecularComponent(org.vcell.model.rbm.MolecularComponent) ParticleComponentStateDefinition(cbit.vcell.math.ParticleComponentStateDefinition) ParticleMolecularComponentPattern(cbit.vcell.math.ParticleMolecularComponentPattern) Structure(cbit.vcell.model.Structure) ParticleMolecularType(cbit.vcell.math.ParticleMolecularType) ReactantPattern(cbit.vcell.model.ReactantPattern) ReactionRule(cbit.vcell.model.ReactionRule) ProductPattern(cbit.vcell.model.ProductPattern) ParticleMolecularComponentPattern(cbit.vcell.math.ParticleMolecularComponentPattern) MolecularComponentPattern(org.vcell.model.rbm.MolecularComponentPattern) ParticleComponentStatePattern(cbit.vcell.math.ParticleComponentStatePattern) RbmObservable(cbit.vcell.model.RbmObservable) ComponentStatePattern(org.vcell.model.rbm.ComponentStatePattern) ParticleComponentStatePattern(cbit.vcell.math.ParticleComponentStatePattern) VolumeParticleSpeciesPattern(cbit.vcell.math.VolumeParticleSpeciesPattern) ParticleMolecularTypePattern(cbit.vcell.math.ParticleMolecularTypePattern) ParticleMolecularType(cbit.vcell.math.ParticleMolecularType) MolecularType(org.vcell.model.rbm.MolecularType) Model(cbit.vcell.model.Model) ParticleMolecularTypePattern(cbit.vcell.math.ParticleMolecularTypePattern) MolecularTypePattern(org.vcell.model.rbm.MolecularTypePattern)

Example 7 with ReactantPattern

use of cbit.vcell.model.ReactantPattern 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)

Example 8 with ReactantPattern

use of cbit.vcell.model.ReactantPattern 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 9 with ReactantPattern

use of cbit.vcell.model.ReactantPattern 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 10 with ReactantPattern

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

the class GeneratedReactionTableRow method deriveRule.

private void deriveRule(String inputString, Model tempModel) {
    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;
    }
    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));
    }
    // try to 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 {
                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 = 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 making some fake compartments in the tempModel 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) {
                    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();
            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) {
                    tempModel.addFeature(strStructure);
                }
                structure = tempModel.getStructure(strStructure);
            } else {
                structure = ruleStructure;
            }
            reactionRule.addProduct(new ProductPattern(speciesPattern, structure));
        } catch (Throwable ex) {
            ex.printStackTrace();
            return;
        }
    }
}
Also used : ReactionRule(cbit.vcell.model.ReactionRule) ModelException(cbit.vcell.model.ModelException) ProductPattern(cbit.vcell.model.ProductPattern) SimulationContext(cbit.vcell.mapping.SimulationContext) SpeciesPattern(org.vcell.model.rbm.SpeciesPattern) MolecularType(org.vcell.model.rbm.MolecularType) PropertyVetoException(java.beans.PropertyVetoException) Structure(cbit.vcell.model.Structure) ReactantPattern(cbit.vcell.model.ReactantPattern)

Aggregations

ReactantPattern (cbit.vcell.model.ReactantPattern)22 ProductPattern (cbit.vcell.model.ProductPattern)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 PropertyVetoException (java.beans.PropertyVetoException)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