Search in sources :

Example 66 with ReactionRule

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

the class ModelUnitConverter method createBioModelWithNewUnitSystem.

public static BioModel createBioModelWithNewUnitSystem(BioModel oldBioModel, ModelUnitSystem newUnitSystem) throws ExpressionException, XmlParseException {
    // new BioModel has new unit system applied to all built-in units ... but expressions still need to be corrected (see below).
    String biomodelXMLString = XmlHelper.bioModelToXML(oldBioModel);
    XMLSource newXMLSource = new XMLSource(biomodelXMLString);
    BioModel newBioModel = XmlHelper.XMLToBioModel(newXMLSource, true, newUnitSystem);
    Model newModel = newBioModel.getModel();
    Model oldModel = oldBioModel.getModel();
    for (Parameter p : newBioModel.getModel().getModelParameters()) {
        convertVarsWithUnitFactors(oldBioModel.getModel(), newBioModel.getModel(), p);
    }
    for (ReactionStep reactionStep : newBioModel.getModel().getReactionSteps()) {
        SymbolTable oldSymbolTable = oldBioModel.getModel().getReactionStep(reactionStep.getName());
        SymbolTable newSymbolTable = reactionStep;
        for (Parameter p : reactionStep.getKinetics().getUnresolvedParameters()) {
            convertVarsWithUnitFactors(oldSymbolTable, newSymbolTable, p);
        }
        for (Parameter p : reactionStep.getKinetics().getKineticsParameters()) {
            convertVarsWithUnitFactors(oldSymbolTable, newSymbolTable, p);
        }
        Kinetics kinetics = reactionStep.getKinetics();
        KineticsParameter kineticsParameter = null;
        if (kinetics.getKineticsParameterFromRole(Kinetics.ROLE_ReactionRate) != null) {
            kineticsParameter = kinetics.getKineticsParameterFromRole(Kinetics.ROLE_ReactionRate);
        } else if (kinetics.getKineticsParameterFromRole(Kinetics.ROLE_LumpedReactionRate) != null) {
            kineticsParameter = kinetics.getKineticsParameterFromRole(Kinetics.ROLE_LumpedReactionRate);
        } else {
            throw new RuntimeException("Role 'reaction rate' or role 'lumped reaction rate' expected");
        }
        Expression rateExpression = kineticsParameter.getExpression();
        jscl.math.Expression jsclExpression = null;
        String jsclExpressionString = rateExpression.infix_JSCL();
        try {
            jsclExpression = jscl.math.Expression.valueOf(jsclExpressionString);
        } catch (jscl.text.ParseException e) {
            e.printStackTrace(System.out);
            System.out.println("JSCL couldn't parse \"" + jsclExpressionString + "\"");
            return null;
        }
        jscl.math.Generic g1 = jsclExpression.expand().simplify();
        Expression newRate = new Expression(SymbolUtils.getRestoredStringJSCL(g1.toString()));
        newRate.bindExpression(reactionStep);
        // reactionStep.getKinetics().getKineticsParameterFromRole(Kinetics.ROLE_ReactionRate).setExpression(newRate.flatten());
        if (reactionStep.getKinetics().getKineticsParameterFromRole(Kinetics.ROLE_ReactionRate) != null) {
            reactionStep.getKinetics().getKineticsParameterFromRole(Kinetics.ROLE_ReactionRate).setExpression(newRate.flatten());
        }
    }
    for (ReactionRule reactionRule : newBioModel.getModel().getRbmModelContainer().getReactionRuleList()) {
        SymbolTable oldSymbolTable = oldBioModel.getModel().getRbmModelContainer().getReactionRule(reactionRule.getName()).getKineticLaw().getScopedSymbolTable();
        SymbolTable newSymbolTable = reactionRule.getKineticLaw().getScopedSymbolTable();
        for (Parameter p : reactionRule.getKineticLaw().getUnresolvedParameters()) {
            convertVarsWithUnitFactors(oldSymbolTable, newSymbolTable, p);
        }
        for (Parameter p : reactionRule.getKineticLaw().getLocalParameters()) {
            convertVarsWithUnitFactors(oldSymbolTable, newSymbolTable, p);
        }
    }
    for (SimulationContext simContext : newBioModel.getSimulationContexts()) {
        SimulationContext oldSimContext = oldBioModel.getSimulationContext(simContext.getName());
        // ArrayList<Parameter> parameterList = new ArrayList<Parameter>();
        for (StructureMapping mapping : simContext.getGeometryContext().getStructureMappings()) {
            Structure oldStructure = oldModel.getStructure(mapping.getStructure().getName());
            StructureMapping oldMapping = oldSimContext.getGeometryContext().getStructureMapping(oldStructure);
            for (Parameter p : mapping.computeApplicableParameterList()) {
                convertVarsWithUnitFactors(oldMapping, mapping, p);
            }
        }
        for (SpeciesContextSpec spec : simContext.getReactionContext().getSpeciesContextSpecs()) {
            SpeciesContext oldSpeciesContext = oldModel.getSpeciesContext(spec.getSpeciesContext().getName());
            SpeciesContextSpec oldSpec = oldSimContext.getReactionContext().getSpeciesContextSpec(oldSpeciesContext);
            for (Parameter p : spec.computeApplicableParameterList()) {
                convertVarsWithUnitFactors(oldSpec, spec, p);
            }
        }
        for (int i = 0; i < simContext.getElectricalStimuli().length; i++) {
            ElectricalStimulus newElectricalStimulus = simContext.getElectricalStimuli()[i];
            ElectricalStimulus oldElectricalStimulus = oldSimContext.getElectricalStimuli()[i];
            for (Parameter p : newElectricalStimulus.getParameters()) {
                convertVarsWithUnitFactors(oldElectricalStimulus.getNameScope().getScopedSymbolTable(), newElectricalStimulus.getNameScope().getScopedSymbolTable(), p);
            }
        }
        // convert events : trigger and delay parameters and event assignments
        for (int i = 0; simContext.getBioEvents() != null && oldSimContext.getBioEvents() != null && i < simContext.getBioEvents().length; i++) {
            BioEvent newBioEvent = simContext.getBioEvents()[i];
            BioEvent oldBioEvent = oldSimContext.getBioEvent(newBioEvent.getName());
            for (Parameter p : newBioEvent.getEventParameters()) {
                convertVarsWithUnitFactors(oldBioEvent.getNameScope().getScopedSymbolTable(), newBioEvent.getNameScope().getScopedSymbolTable(), p);
            }
            // for each event assignment expression
            for (int e = 0; e < newBioEvent.getEventAssignments().size(); e++) {
                ScopedSymbolTable newSymbolTable = newBioEvent.getNameScope().getScopedSymbolTable();
                ScopedSymbolTable oldSymbolTable = oldBioEvent.getNameScope().getScopedSymbolTable();
                EventAssignment newEventAssignment = newBioEvent.getEventAssignments().get(e);
                EventAssignment oldEventAssignment = oldBioEvent.getEventAssignments().get(e);
                VCUnitDefinition oldTargetUnit = oldEventAssignment.getTarget().getUnitDefinition();
                VCUnitDefinition newTargetUnit = newEventAssignment.getTarget().getUnitDefinition();
                Expression eventAssgnExpr = newEventAssignment.getAssignmentExpression();
                convertExprWithUnitFactors(oldSymbolTable, newSymbolTable, oldTargetUnit, newTargetUnit, eventAssgnExpr);
            }
        }
        /**
         * @TODO: If rate rule variable unit is TBD, we still need to handle the rate expression unit.
         */
        // convert rate rules
        RateRule[] rateRules = simContext.getRateRules();
        if (rateRules != null && rateRules.length > 0) {
            for (RateRule rateRule : rateRules) {
                RateRule oldRateRule = oldSimContext.getRateRule(rateRule.getName());
                ScopedSymbolTable oldSymbolTable = oldRateRule.getSimulationContext();
                ScopedSymbolTable newSymbolTable = rateRule.getSimulationContext();
                VCUnitDefinition oldTargetUnit = oldRateRule.getRateRuleVar().getUnitDefinition();
                VCUnitDefinition newTargetUnit = rateRule.getRateRuleVar().getUnitDefinition();
                Expression rateRuleExpr = rateRule.getRateRuleExpression();
                convertExprWithUnitFactors(oldSymbolTable, newSymbolTable, oldTargetUnit, newTargetUnit, rateRuleExpr);
            }
        }
        AssignmentRule[] assignmentRules = simContext.getAssignmentRules();
        if (assignmentRules != null && assignmentRules.length > 0) {
            for (AssignmentRule assignmentRule : assignmentRules) {
                AssignmentRule oldAssignRule = oldSimContext.getAssignmentRule(assignmentRule.getName());
                ScopedSymbolTable oldSymbolTable = oldAssignRule.getSimulationContext();
                ScopedSymbolTable newSymbolTable = assignmentRule.getSimulationContext();
                VCUnitDefinition oldTargetUnit = oldAssignRule.getAssignmentRuleVar().getUnitDefinition();
                VCUnitDefinition newTargetUnit = assignmentRule.getAssignmentRuleVar().getUnitDefinition();
                Expression assignmentRuleExpr = assignmentRule.getAssignmentRuleExpression();
                convertExprWithUnitFactors(oldSymbolTable, newSymbolTable, oldTargetUnit, newTargetUnit, assignmentRuleExpr);
            }
        }
    }
    // end  for - simulationContext
    return newBioModel;
}
Also used : SpeciesContext(cbit.vcell.model.SpeciesContext) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) StructureMapping(cbit.vcell.mapping.StructureMapping) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) RateRule(cbit.vcell.mapping.RateRule) ScopedSymbolTable(cbit.vcell.parser.ScopedSymbolTable) SimulationContext(cbit.vcell.mapping.SimulationContext) SpeciesContext(cbit.vcell.model.SpeciesContext) Structure(cbit.vcell.model.Structure) ReactionRule(cbit.vcell.model.ReactionRule) EventAssignment(cbit.vcell.mapping.BioEvent.EventAssignment) AssignmentRule(cbit.vcell.mapping.AssignmentRule) ScopedSymbolTable(cbit.vcell.parser.ScopedSymbolTable) SymbolTable(cbit.vcell.parser.SymbolTable) SimulationContext(cbit.vcell.mapping.SimulationContext) ElectricalStimulus(cbit.vcell.mapping.ElectricalStimulus) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) ReactionStep(cbit.vcell.model.ReactionStep) Model(cbit.vcell.model.Model) Parameter(cbit.vcell.model.Parameter) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) Kinetics(cbit.vcell.model.Kinetics) BioEvent(cbit.vcell.mapping.BioEvent) XMLSource(cbit.vcell.xml.XMLSource)

Example 67 with ReactionRule

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

the class ReactionCartoonMolecule method refreshAll.

@Override
protected void refreshAll(boolean reallocateShapes) {
    try {
        if (getModel() == null || getStructureSuite() == null) {
            return;
        }
        System.out.println("ReactionCartoonMolecule, RefreshAll()");
        for (Structure structure : structureSuite.getStructures()) {
            Diagram diagram = getModel().getDiagram(structure);
            if (diagram != null) {
                // Maintain consistency between rule participant nodes, signatures and
                // species pattern when a molecule is being modified.
                rebindAll(diagram);
            }
        }
        // calculate species context weight (number of reactions for which it's a participant)
        Map<SpeciesContext, Integer> scWeightMap = new HashMap<>();
        // all the species contexts that are catalysts
        Set<SpeciesContext> scCatalystSet = new HashSet<>();
        // calculate species context length (number of species patterns it contains, 1 if has no species patterns)
        for (ReactionStep rs : getModel().getReactionSteps()) {
            ReactionParticipant[] rpList = rs.getReactionParticipants();
            for (int i = 0; i < rpList.length; i++) {
                ReactionParticipant rp = rpList[i];
                SpeciesContext sc = rp.getSpeciesContext();
                int increment = 1;
                if (rp instanceof Catalyst) {
                    scCatalystSet.add(sc);
                }
                if (scWeightMap.containsKey(sc)) {
                    int weight = scWeightMap.get(sc);
                    weight += increment;
                    scWeightMap.put(sc, weight);
                } else {
                    scWeightMap.put(sc, increment);
                }
            }
        }
        Set<Shape> unwantedShapes = new HashSet<Shape>();
        Set<RuleParticipantSignature> unwantedSignatures = new HashSet<RuleParticipantSignature>();
        unwantedShapes.addAll(getShapes());
        unwantedSignatures.addAll(ruleParticipantSignatures);
        ContainerContainerShape containerShape = (ContainerContainerShape) getShapeFromModelObject(getModel());
        List<ReactionContainerShape> reactionContainerShapeList = new ArrayList<ReactionContainerShape>();
        List<Structure> structureList = new ArrayList<Structure>(getStructureSuite().getStructures());
        // create all ReactionContainerShapes (one for each Structure)
        for (Structure structure : structureList) {
            if (structure instanceof Membrane) {
                Membrane membrane = (Membrane) structure;
                ReactionContainerShape membraneShape = (ReactionContainerShape) getShapeFromModelObject(membrane);
                if (membraneShape == null) {
                    membraneShape = new ReactionContainerShape(membrane, structureSuite, this);
                    addShape(membraneShape);
                    membrane.getMembraneVoltage().removePropertyChangeListener(this);
                    membrane.getMembraneVoltage().addPropertyChangeListener(this);
                } else {
                    membraneShape.setStructureSuite(structureSuite);
                }
                membrane.removePropertyChangeListener(this);
                membrane.addPropertyChangeListener(this);
                membraneShape.refreshLabel();
                unwantedShapes.remove(membraneShape);
                reactionContainerShapeList.add(membraneShape);
            } else if (structure instanceof Feature) {
                Feature feature = (Feature) structure;
                ReactionContainerShape featureShape = (ReactionContainerShape) getShapeFromModelObject(feature);
                if (featureShape == null) {
                    featureShape = new ReactionContainerShape(feature, structureSuite, this);
                    addShape(featureShape);
                } else {
                    featureShape.setStructureSuite(structureSuite);
                }
                feature.removePropertyChangeListener(this);
                feature.addPropertyChangeListener(this);
                featureShape.refreshLabel();
                unwantedShapes.remove(featureShape);
                reactionContainerShapeList.add(featureShape);
            }
        }
        if (containerShape == null) {
            containerShape = new ContainerContainerShape(this, getModel(), reactionContainerShapeList);
            addShape(containerShape);
        } else {
            containerShape.setReactionContainerShapeList(reactionContainerShapeList);
        }
        containerShape.refreshLabel();
        unwantedShapes.remove(containerShape);
        // add all species context shapes within the structures
        for (Structure structure : getStructureSuite().getStructures()) {
            ReactionContainerShape reactionContainerShape = (ReactionContainerShape) getShapeFromModelObject(structure);
            structure.removePropertyChangeListener(this);
            structure.addPropertyChangeListener(this);
            for (SpeciesContext structSpeciesContext : getModel().getSpeciesContexts(structure)) {
                SpeciesContextShape ss = (SpeciesContextShape) getShapeFromModelObject(structSpeciesContext);
                if (ss == null) {
                    ss = new SpeciesContextShape(structSpeciesContext, this);
                    ss.truncateLabelName(false);
                    structSpeciesContext.getSpecies().removePropertyChangeListener(this);
                    structSpeciesContext.getSpecies().addPropertyChangeListener(this);
                    reactionContainerShape.addChildShape(ss);
                    addShape(ss);
                    ss.getSpaceManager().setRelPos(reactionContainerShape.getRandomPosition());
                }
                if (speciesSizeOption == SpeciesSizeOptions.weight) {
                    // this number sets the diameter of the shape
                    Integer weight = scWeightMap.get(structSpeciesContext);
                    if (weight != null) {
                        // we cap the diameter of the shape to something reasonable
                        weight = Math.min(weight, 16);
                    }
                    ss.setFilters(highlightCatalystOption ? scCatalystSet.contains(structSpeciesContext) : false, weight);
                } else if (speciesSizeOption == SpeciesSizeOptions.length) {
                    Integer length = null;
                    if (structSpeciesContext.getSpeciesPattern() != null && !structSpeciesContext.getSpeciesPattern().getMolecularTypePatterns().isEmpty()) {
                        length = structSpeciesContext.getSpeciesPattern().getMolecularTypePatterns().size() * 2;
                        length = Math.min(length, 16);
                    }
                    ss.setFilters(highlightCatalystOption ? scCatalystSet.contains(structSpeciesContext) : false, length);
                } else {
                    ss.setFilters(highlightCatalystOption ? scCatalystSet.contains(structSpeciesContext) : false, null);
                }
                structSpeciesContext.removePropertyChangeListener(this);
                structSpeciesContext.addPropertyChangeListener(this);
                ss.refreshLabel();
                unwantedShapes.remove(ss);
            }
        }
        // add all reactionSteps that are in this structure (ReactionContainerShape), and draw the lines
        getModel().removePropertyChangeListener(this);
        getModel().addPropertyChangeListener(this);
        // 
        for (ReactionRule rr : getModel().getRbmModelContainer().getReactionRuleList()) {
            rr.removePropertyChangeListener(this);
            rr.addPropertyChangeListener(this);
            Structure structure = rr.getStructure();
            if (getStructureSuite().areReactionsShownFor(structure)) {
                ReactionContainerShape reactionContainerShape = (ReactionContainerShape) getShapeFromModelObject(structure);
                ReactionRuleFullDiagramShape rrShape = (ReactionRuleFullDiagramShape) getShapeFromModelObject(rr);
                if (rrShape == null) {
                    rrShape = new ReactionRuleFullDiagramShape(rr, this);
                    addShape(rrShape);
                    rrShape.getSpaceManager().setRelPos(reactionContainerShape.getRandomPosition());
                    reactionContainerShape.addChildShape(rrShape);
                    rrShape.getSpaceManager().setRelPos(reactionContainerShape.getRandomPosition());
                }
                rrShape.refreshLabel();
                unwantedShapes.remove(rrShape);
                // 
                // add reaction participants as edges and SignatureShapes as needed
                // 
                List<ReactionRuleParticipant> participants = rr.getReactionRuleParticipants();
                List<RuleParticipantEdgeDiagramShape> ruleEdges = new ArrayList<>();
                for (ReactionRuleParticipant participant : participants) {
                    participant.getSpeciesPattern().removePropertyChangeListener(this);
                    participant.getSpeciesPattern().addPropertyChangeListener(this);
                    Structure speciesStructure = participant.getStructure();
                    Structure reactionStructure = rr.getStructure();
                    if (getStructureSuite().getStructures().contains(speciesStructure) && getStructureSuite().areReactionsShownFor(reactionStructure)) {
                        // 
                        // find existing RuleParticipantSignatureShape in cartoon
                        // 
                        RuleParticipantShortSignature ruleParticipantShortSignature = null;
                        for (RuleParticipantSignature signature : ruleParticipantSignatures) {
                            if (signature instanceof RuleParticipantLongSignature && signature.getStructure() == participant.getStructure()) {
                                System.out.println("ReactionCartoonMolecule, refreshAll(), RuleParticipantLongSignature");
                                break;
                            }
                        }
                        for (RuleParticipantSignature signature : ruleParticipantSignatures) {
                            if (signature instanceof RuleParticipantShortSignature && signature.getStructure() == participant.getStructure() && signature.compareByCriteria(participant.getSpeciesPattern(), GroupingCriteria.molecule)) {
                                ruleParticipantShortSignature = (RuleParticipantShortSignature) signature;
                                break;
                            }
                        }
                        // 
                        // if didn't find signature in cartoons list of signatures, then create one (and create a shape for it).
                        // 
                        RuleParticipantSignatureShortDiagramShape signatureShape = null;
                        if (ruleParticipantShortSignature == null) {
                            ruleParticipantShortSignature = RuleParticipantShortSignature.fromReactionRuleParticipant(participant, this);
                            ruleParticipantSignatures.add(ruleParticipantShortSignature);
                            signatureShape = new RuleParticipantSignatureShortDiagramShape(ruleParticipantShortSignature, this);
                            addShape(signatureShape);
                            ReactionContainerShape participantContainerShape = (ReactionContainerShape) getShapeFromModelObject(participant.getStructure());
                            signatureShape.getSpaceManager().setRelPos(participantContainerShape.getRandomPosition());
                            participantContainerShape.addChildShape(signatureShape);
                            signatureShape.getSpaceManager().setRelPos(participantContainerShape.getRandomPosition());
                        } else {
                            signatureShape = (RuleParticipantSignatureShortDiagramShape) getShapeFromModelObject(ruleParticipantShortSignature);
                        }
                        unwantedShapes.remove(signatureShape);
                        unwantedSignatures.remove(ruleParticipantShortSignature);
                        signatureShape.refreshLabel();
                        signatureShape.setVisible(true);
                        // 
                        // add edge for ReactionRuleParticipant if not already present.
                        // 
                        RuleParticipantEdgeDiagramShape ruleParticipantShape = (RuleParticipantEdgeDiagramShape) getShapeFromModelObject(participant);
                        if (ruleParticipantShape == null || ruleParticipantShape.getRuleParticipantSignatureShape() != signatureShape) {
                            if (participant instanceof ReactantPattern && signatureShape.isVisible()) {
                                ruleParticipantShape = new ReactantPatternEdgeDiagramShape((ReactantPattern) participant, rrShape, signatureShape, this);
                            } else if (participant instanceof ProductPattern && signatureShape.isVisible()) {
                                ruleParticipantShape = new ProductPatternEdgeDiagramShape((ProductPattern) participant, rrShape, signatureShape, this);
                            } else {
                                throw new RuntimeException("unsupported ReactionRuleParticipant " + participant.getClass());
                            }
                            addShape(ruleParticipantShape);
                        }
                        if (!containerShape.getChildren().contains(ruleParticipantShape)) {
                            containerShape.addChildShape(ruleParticipantShape);
                        }
                        unwantedShapes.remove(ruleParticipantShape);
                        ruleParticipantShape.refreshLabel();
                        // all the edges for this rule
                        ruleEdges.add(ruleParticipantShape);
                    }
                }
                // a product edge (a closed loop) between the rule diagram shape and the signature diagram shape
                for (RuleParticipantEdgeDiagramShape ours : ruleEdges) {
                    // reset them all
                    ours.setSibling(false);
                }
                for (RuleParticipantEdgeDiagramShape ours : ruleEdges) {
                    for (RuleParticipantEdgeDiagramShape theirs : ruleEdges) {
                        if (ours == theirs) {
                            // don't compare with self
                            continue;
                        }
                        if (ours.getRuleParticipantSignatureShape() == theirs.getRuleParticipantSignatureShape()) {
                            ours.setSibling(true);
                            theirs.setSibling(true);
                        }
                    }
                }
            }
        }
        ruleParticipantSignatures.removeAll(unwantedSignatures);
        for (ReactionStep reactionStep : getModel().getReactionSteps()) {
            reactionStep.removePropertyChangeListener(this);
            reactionStep.addPropertyChangeListener(this);
            Structure structure = reactionStep.getStructure();
            if (getStructureSuite().areReactionsShownFor(structure)) {
                ReactionContainerShape reactionContainerShape = (ReactionContainerShape) getShapeFromModelObject(structure);
                if (reactionContainerShape == null) {
                    System.out.println("Reaction container shape is null for structure " + structure + " for reaction step " + reactionStep);
                }
                ReactionStepShape reactionStepShape = (ReactionStepShape) getShapeFromModelObject(reactionStep);
                if (reactionStepShape == null) {
                    if (reactionStep instanceof SimpleReaction) {
                        reactionStepShape = new SimpleReactionShape((SimpleReaction) reactionStep, this);
                    } else if (reactionStep instanceof FluxReaction) {
                        reactionStepShape = new FluxReactionShape((FluxReaction) reactionStep, this);
                    } else {
                        throw new RuntimeException("unknown type of ReactionStep '" + reactionStep.getClass().toString());
                    }
                    addShape(reactionStepShape);
                    reactionStepShape.getSpaceManager().setRelPos(reactionContainerShape.getRandomPosition());
                    reactionContainerShape.addChildShape(reactionStepShape);
                    reactionStepShape.getSpaceManager().setRelPos(reactionContainerShape.getRandomPosition());
                }
                reactionStepShape.refreshLabel();
                unwantedShapes.remove(reactionStepShape);
                // add reaction participants as edges
                for (ReactionParticipant participant : reactionStep.getReactionParticipants()) {
                    participant.removePropertyChangeListener(this);
                    participant.addPropertyChangeListener(this);
                    Structure speciesStructure = participant.getStructure();
                    Structure reactionStructure = reactionStep.getStructure();
                    if (getStructureSuite().getStructures().contains(speciesStructure) && getStructureSuite().areReactionsShownFor(reactionStructure)) {
                        SpeciesContext speciesContext = getModel().getSpeciesContext(participant.getSpecies(), speciesStructure);
                        // add speciesContextShapes that are not in this structure, but are referenced from the reactionParticipants
                        // these are only when reactionParticipants are from features that are outside of the membrane being displayed
                        SpeciesContextShape speciesContextShape = (SpeciesContextShape) getShapeFromModelObject(speciesContext);
                        if (speciesContextShape == null) {
                            speciesContextShape = new SpeciesContextShape(speciesContext, this);
                            speciesContextShape.truncateLabelName(false);
                            reactionContainerShape.addChildShape(speciesContextShape);
                            addShape(speciesContextShape);
                            speciesContextShape.getSpaceManager().setRelPos(reactionContainerShape.getRandomPosition());
                        }
                        speciesContextShape.refreshLabel();
                        unwantedShapes.remove(speciesContextShape);
                        ReactionParticipantShape reactionParticipantShape = (ReactionParticipantShape) getShapeFromModelObject(participant);
                        if (reactionParticipantShape == null) {
                            if (participant instanceof Reactant) {
                                reactionParticipantShape = new ReactantShape((Reactant) participant, reactionStepShape, speciesContextShape, this);
                            } else if (participant instanceof Product) {
                                reactionParticipantShape = new ProductShape((Product) participant, reactionStepShape, speciesContextShape, this);
                            } else if (participant instanceof Catalyst) {
                                reactionParticipantShape = new CatalystShape((Catalyst) participant, reactionStepShape, speciesContextShape, this);
                            } else {
                                throw new RuntimeException("unsupported ReactionParticipant " + participant.getClass());
                            }
                            addShape(reactionParticipantShape);
                        }
                        if (!containerShape.getChildren().contains(reactionParticipantShape)) {
                            containerShape.addChildShape(reactionParticipantShape);
                        }
                        unwantedShapes.remove(reactionParticipantShape);
                        reactionParticipantShape.refreshLabel();
                    }
                }
            }
        }
        for (Shape unwantedShape : unwantedShapes) {
            removeShape(unwantedShape);
        }
        // update diagrams
        for (Structure structure : structureSuite.getStructures()) {
            Diagram diagram = getModel().getDiagram(structure);
            if (diagram != null) {
                applyDefaults(diagram);
            }
        }
        fireGraphChanged(new GraphEvent(this));
    } catch (Throwable e) {
        handleException(e);
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Product(cbit.vcell.model.Product) FluxReaction(cbit.vcell.model.FluxReaction) SpeciesContext(cbit.vcell.model.SpeciesContext) Feature(cbit.vcell.model.Feature) Reactant(cbit.vcell.model.Reactant) HashSet(java.util.HashSet) ReactionStep(cbit.vcell.model.ReactionStep) ReactionRuleParticipant(cbit.vcell.model.ReactionRuleParticipant) ReactionParticipant(cbit.vcell.model.ReactionParticipant) Catalyst(cbit.vcell.model.Catalyst) RuleParticipantSignature(cbit.vcell.model.RuleParticipantSignature) Shape(cbit.gui.graph.Shape) GraphEvent(cbit.gui.graph.GraphEvent) RuleParticipantShortSignature(cbit.vcell.model.RuleParticipantShortSignature) Membrane(cbit.vcell.model.Membrane) Structure(cbit.vcell.model.Structure) ReactantPattern(cbit.vcell.model.ReactantPattern) RuleParticipantLongSignature(cbit.vcell.model.RuleParticipantLongSignature) SimpleReaction(cbit.vcell.model.SimpleReaction) ReactionRule(cbit.vcell.model.ReactionRule) ProductPattern(cbit.vcell.model.ProductPattern) Point(java.awt.Point) Diagram(cbit.vcell.model.Diagram)

Example 68 with ReactionRule

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

the class RbmUtils method parseReactionRule.

public static ReactionRule parseReactionRule(String inputString, String name, Structure structure, BioModel bioModel) throws ParseException {
    try {
        String label = name;
        // int labelIndex = inputString.indexOf(':');		// TODO: the way we edit reaction rules now, we have no labels here
        // String label = "";
        // if(labelIndex>=0) {
        // label = inputString.substring(0, labelIndex);
        // inputString = inputString.substring(labelIndex+1);
        // }
        // if(label.isEmpty() || (reactionRuleNames.indexOf(label) != -1)) {
        // do {	// no label or label in use, we generate new label
        // label = generateReactionRuleName();
        // } while(reactionRuleNames.indexOf(label) != -1);
        // reactionRuleNames.add(label);
        // } else {
        // reactionRuleNames.add(label);
        // }
        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 null;
        }
        // note that the constructor will try to honor the label from the editor but will generate a new one if already in use
        ReactionRule reactionRule = bioModel.getModel().getRbmModelContainer().createReactionRule(label, structure, bReversible);
        String regex = "[^!]\\+";
        String[] patterns = left.split(regex);
        for (String sp : patterns) {
            SpeciesPattern speciesPattern = parseSpeciesPattern(sp, bioModel.getModel());
            reactionRule.addReactant(new ReactantPattern(speciesPattern, reactionRule.getStructure()));
        }
        patterns = right.split(regex);
        for (String sp : patterns) {
            SpeciesPattern speciesPattern = parseSpeciesPattern(sp, bioModel.getModel());
            reactionRule.addProduct(new ProductPattern(speciesPattern, reactionRule.getStructure()));
        }
        return reactionRule;
    } catch (Throwable ex) {
        ex.printStackTrace();
        throw new ParseException(ex.getMessage());
    }
}
Also used : ReactionRule(cbit.vcell.model.ReactionRule) ASTReactionRule(org.vcell.model.bngl.ASTReactionRule) ProductPattern(cbit.vcell.model.ProductPattern) ParseException(org.vcell.model.bngl.ParseException) ParticleSpeciesPattern(cbit.vcell.math.ParticleSpeciesPattern) ASTSpeciesPattern(org.vcell.model.bngl.ASTSpeciesPattern) ReactantPattern(cbit.vcell.model.ReactantPattern)

Example 69 with ReactionRule

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

the class RbmNetworkGenerator method writeBngl_internal.

public static void writeBngl_internal(SimulationContext simulationContext, PrintWriter writer, Map<FakeReactionRuleRateParameter, LocalParameter> kineticsParameterMap, Map<FakeSeedSpeciesInitialConditionsParameter, Pair<SpeciesContext, Expression>> speciesEquivalenceMap, NetworkGenerationRequirements networkGenerationRequirements, CompartmentMode compartmentMode) {
    String callerClassName = new Exception().getStackTrace()[1].getClassName();
    String networkTransformerClassName = NetworkTransformer.class.getName();
    String rulebasedTransformerClassName = RulebasedTransformer.class.getName();
    if (!callerClassName.equals(networkTransformerClassName) && !callerClassName.equals(rulebasedTransformerClassName)) {
        throw new UnsupportedOperationException("This method may only be called from within a " + networkTransformerClassName + " or " + rulebasedTransformerClassName + " instance.");
    }
    Model model = simulationContext.getModel();
    RbmModelContainer rbmModelContainer = model.getRbmModelContainer();
    checkConsistency(model);
    // first we prepare the fake parameters we need to maintain the relationship between the species context and the seed species
    List<FakeSeedSpeciesInitialConditionsParameter> fakeParameterList = new ArrayList<FakeSeedSpeciesInitialConditionsParameter>();
    List<String> seedSpeciesList = new ArrayList<String>();
    SpeciesContext[] speciesContexts = model.getSpeciesContexts();
    for (int i = 0; i < speciesContexts.length; i++) {
        SpeciesContext sc = speciesContexts[i];
        if (!sc.hasSpeciesPattern()) {
            continue;
        }
        SpeciesContextSpec scs = simulationContext.getReactionContext().getSpeciesContextSpec(sc);
        Expression initialConcentration = scs.getParameter(SpeciesContextSpec.ROLE_InitialConcentration).getExpression();
        // fake initial values for the seed species, we need to present them to bngl as parameters
        FakeSeedSpeciesInitialConditionsParameter fakeSeedSpeciesParam = new FakeSeedSpeciesInitialConditionsParameter(sc.getName());
        Pair<SpeciesContext, Expression> p = new Pair<SpeciesContext, Expression>(sc, initialConcentration);
        speciesEquivalenceMap.put(fakeSeedSpeciesParam, p);
        String modified;
        if (compartmentMode == CompartmentMode.show) {
            modified = RbmUtils.toBnglString(sc.getSpeciesPattern(), null, CompartmentMode.hide, 0);
            modified = "@" + sc.getStructure().getName() + ":" + modified;
        } else if (compartmentMode == CompartmentMode.asSite) {
            modified = RbmUtils.toBnglString(sc.getSpeciesPattern(), sc.getStructure(), CompartmentMode.asSite, 0);
        } else {
            // CompartmentMode.hide
            modified = RbmUtils.toBnglString(sc.getSpeciesPattern(), null, CompartmentMode.hide, 0);
        }
        modified += " " + fakeSeedSpeciesParam.fakeParameterName;
        // we label the seed species with the index
        modified = (i + 1) + " " + modified;
        // we build the seed species list now, we write it later (in the BEGIN SPECIES block)
        seedSpeciesList.add(modified);
        fakeParameterList.add(fakeSeedSpeciesParam);
    }
    // second we produce the bngl file
    writer.println(BEGIN_MODEL);
    writer.println();
    for (ReactionRuleSpec rrs : simulationContext.getReactionContext().getReactionRuleSpecs()) {
        if (!rrs.isExcluded()) {
            ReactionRule reactionRule = rrs.getReactionRule();
            RbmKineticLaw kineticLaw = reactionRule.getKineticLaw();
            switch(kineticLaw.getRateLawType()) {
                case MassAction:
                    {
                        FakeReactionRuleRateParameter fakeRateParameterForward = new FakeReactionRuleRateParameter(reactionRule, RbmKineticLawParameterType.MassActionForwardRate);
                        LocalParameter origForwardRateParameter = kineticLaw.getLocalParameter(RbmKineticLawParameterType.MassActionForwardRate);
                        kineticsParameterMap.put(fakeRateParameterForward, origForwardRateParameter);
                        if (reactionRule.isReversible()) {
                            FakeReactionRuleRateParameter fakeRateParameterReverse = new FakeReactionRuleRateParameter(reactionRule, RbmKineticLawParameterType.MassActionReverseRate);
                            LocalParameter origReverseRateParameter = kineticLaw.getLocalParameter(RbmKineticLawParameterType.MassActionReverseRate);
                            kineticsParameterMap.put(fakeRateParameterReverse, origReverseRateParameter);
                        }
                        break;
                    }
                case MichaelisMenten:
                    {
                        FakeReactionRuleRateParameter fakeParameterVmax = new FakeReactionRuleRateParameter(reactionRule, RbmKineticLawParameterType.MichaelisMentenVmax);
                        FakeReactionRuleRateParameter fakeParameterKm = new FakeReactionRuleRateParameter(reactionRule, RbmKineticLawParameterType.MichaelisMentenKm);
                        LocalParameter origVmaxParameter = kineticLaw.getLocalParameter(RbmKineticLawParameterType.MichaelisMentenVmax);
                        LocalParameter origKmParameter = kineticLaw.getLocalParameter(RbmKineticLawParameterType.MichaelisMentenKm);
                        kineticsParameterMap.put(fakeParameterVmax, origVmaxParameter);
                        kineticsParameterMap.put(fakeParameterKm, origKmParameter);
                        break;
                    }
                default:
                    {
                        throw new RuntimeException("kinetic law type " + kineticLaw.getRateLawType().name() + " not yet implemented");
                    }
            }
        }
    }
    if (compartmentMode == CompartmentMode.show) {
        RbmNetworkGenerator.writeCompartments(writer, model, simulationContext);
    }
    writer.println(BEGIN_PARAMETERS);
    int speciesLimit = simulationContext.getNetworkConstraints().getSpeciesLimit();
    int reactionsLimit = simulationContext.getNetworkConstraints().getReactionsLimit();
    writer.println(NetworkConstraints.SPECIES_LIMIT_PARAMETER + "\t\t" + speciesLimit);
    writer.println(NetworkConstraints.REACTIONS_LIMIT_PARAMETER + "\t\t" + reactionsLimit);
    // the fake parameters used for reaction rule kinetics
    for (FakeReactionRuleRateParameter p : kineticsParameterMap.keySet()) {
        writer.println(p.fakeParameterName + "\t\t1");
    }
    // the fake parameters used at initial values for the seed species
    for (FakeSeedSpeciesInitialConditionsParameter s : fakeParameterList) {
        writer.println(s.fakeParameterName + "\t\t1");
    }
    writer.println(END_PARAMETERS);
    writer.println();
    RbmNetworkGenerator.writeMolecularTypes(writer, model, compartmentMode);
    // write modified version of seed species while maintaining the connection between the species context and the real seed species
    writer.println(BEGIN_SPECIES);
    for (String s : seedSpeciesList) {
        writer.println(s);
    }
    writer.println(END_SPECIES);
    writer.println();
    RbmNetworkGenerator.writeObservables(writer, rbmModelContainer, compartmentMode);
    RbmNetworkGenerator.writeReactions_internal(writer, simulationContext, compartmentMode);
    writer.println(END_MODEL);
    writer.println();
    if (callerClassName.equals(networkTransformerClassName)) {
        RbmNetworkGenerator.writeNetworkConstraints(writer, rbmModelContainer, simulationContext, networkGenerationRequirements);
    } else if (callerClassName.equals(rulebasedTransformerClassName)) {
        writer.println();
        writer.println("writeXML()");
    }
    writer.println();
}
Also used : ReactionRule(cbit.vcell.model.ReactionRule) ReactionRuleSpec(cbit.vcell.mapping.ReactionRuleSpec) ArrayList(java.util.ArrayList) SpeciesContext(cbit.vcell.model.SpeciesContext) RbmKineticLaw(cbit.vcell.model.RbmKineticLaw) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) RbmModelContainer(cbit.vcell.model.Model.RbmModelContainer) Expression(cbit.vcell.parser.Expression) BioModel(cbit.vcell.biomodel.BioModel) Model(cbit.vcell.model.Model) Pair(org.vcell.util.Pair)

Example 70 with ReactionRule

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

the class ParticipantSignatureShapePanel method hasStateChanged.

public RuleAnalysisChanged hasStateChanged(String key, MolecularComponentPattern molecularComponentPattern) {
    ReactionRule reactionRule = reactionRuleMap.get(key);
    if (reactionRule == null) {
        return RuleAnalysisChanged.ANALYSISFAILED;
    }
    ModelRuleEntry modelRuleEntry = modelRuleEntryMap.get(key);
    RuleAnalysisReport report = reportMap.get(key);
    if (modelRuleEntry == null || report == null) {
        System.out.println("modelRuleEntry == null || report == null,  NOT GOOD!");
    // refreshRuleAnalysis();
    }
    if (!bRuleAnalysisFailed && report != null) {
        MolecularComponentEntry molecularComponentEntry = modelRuleEntry.findMolecularComponentEntry(molecularComponentPattern);
        if (report.hasStateChanged(molecularComponentEntry)) {
            return RuleAnalysisChanged.CHANGED;
        } else {
            return RuleAnalysisChanged.UNCHANGED;
        }
    } else {
        return RuleAnalysisChanged.ANALYSISFAILED;
    }
}
Also used : RuleAnalysisReport(org.vcell.model.rbm.RuleAnalysisReport) ModelRuleEntry(cbit.vcell.model.ModelRuleFactory.ModelRuleEntry) ReactionRule(cbit.vcell.model.ReactionRule) MolecularComponentEntry(org.vcell.model.rbm.RuleAnalysis.MolecularComponentEntry)

Aggregations

ReactionRule (cbit.vcell.model.ReactionRule)78 ArrayList (java.util.ArrayList)29 ReactionStep (cbit.vcell.model.ReactionStep)26 SpeciesContext (cbit.vcell.model.SpeciesContext)26 Structure (cbit.vcell.model.Structure)26 MolecularType (org.vcell.model.rbm.MolecularType)20 RbmObservable (cbit.vcell.model.RbmObservable)19 ProductPattern (cbit.vcell.model.ProductPattern)17 ReactantPattern (cbit.vcell.model.ReactantPattern)17 Model (cbit.vcell.model.Model)16 SpeciesPattern (org.vcell.model.rbm.SpeciesPattern)16 PropertyVetoException (java.beans.PropertyVetoException)15 SimulationContext (cbit.vcell.mapping.SimulationContext)14 LocalParameter (cbit.vcell.mapping.ParameterContext.LocalParameter)11 Expression (cbit.vcell.parser.Expression)10 BioModel (cbit.vcell.biomodel.BioModel)9 List (java.util.List)9 ModelParameter (cbit.vcell.model.Model.ModelParameter)8 Parameter (cbit.vcell.model.Parameter)8 Product (cbit.vcell.model.Product)8