Search in sources :

Example 31 with SimpleReaction

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

the class StructureAnalyzer method refreshTotalMatrices.

/**
 * This method was created in VisualAge.
 */
private void refreshTotalMatrices() throws Exception {
    // System.out.println("StructureAnalyzer.refreshTotalMatrices()");
    // 
    // update scheme matrix for full system (slow and fast)
    // 
    ReactionSpec[] reactionSpecs = new ReactionSpec[reactionSteps.length];
    for (int j = 0; j < reactionSteps.length; j++) {
        reactionSpecs[j] = mathMapping_4_8.getSimulationContext().getReactionContext().getReactionSpec(reactionSteps[j]);
    }
    // 
    // initialize rate expressions for speciesContext's due to scheme matrix
    // 
    totalSchemeMatrix = new RationalNumberMatrix(speciesContextMappings.length, reactionSteps.length);
    for (int i = 0; i < speciesContextMappings.length; i++) {
        SpeciesContextMapping scm = speciesContextMappings[i];
        SpeciesContext sc = scm.getSpeciesContext();
        // 
        // collect slow rate expression (fast handled by FastSystem)
        // 
        Expression exp = new Expression(0.0);
        for (int j = 0; j < reactionSteps.length; j++) {
            int stoichiometry = reactionSteps[j].getStoichiometry(sc);
            totalSchemeMatrix.set_elem(i, j, stoichiometry);
            if (stoichiometry != 0) {
                if (!(reactionSteps[j] instanceof DummyReactionStep) && !reactionSpecs[j].isFast() && !reactionSpecs[j].isExcluded()) {
                    ReactionParticipant[] rps1 = reactionSteps[j].getReactionParticipants();
                    ReactionParticipant rp0 = null;
                    for (ReactionParticipant rp : rps1) {
                        if (rp.getSpeciesContext() == sc) {
                            rp0 = rp;
                            break;
                        }
                    }
                    Structure structure = reactionSteps[j].getStructure();
                    // 
                    if (rp0 != null) {
                        Expression reactRateExp = getReactionRateExpression(reactionSteps[j], rp0).renameBoundSymbols(mathMapping_4_8.getNameScope());
                        if ((structure instanceof Membrane) && (sc.getStructure() != structure)) {
                            Membrane membrane = (Membrane) structure;
                            MembraneMapping membraneMapping = (MembraneMapping) mathMapping_4_8.getSimulationContext().getGeometryContext().getStructureMapping(membrane);
                            Parameter fluxCorrectionParameter = mathMapping_4_8.getFluxCorrectionParameter(membraneMapping, (Feature) sc.getStructure());
                            Expression fluxCorrection = new Expression(fluxCorrectionParameter, mathMapping_4_8.getNameScope());
                            if (reactionSteps[j] instanceof FluxReaction) {
                                exp = Expression.add(exp, Expression.mult(fluxCorrection, reactRateExp));
                            // Expression.add(exp,new Expression(fluxCorrectionParameterSymbolName+"*"+expInfix));
                            } else if (reactionSteps[j] instanceof SimpleReaction) {
                                ModelUnitSystem unitSystem = mathMapping_4_8.getSimulationContext().getModel().getUnitSystem();
                                Expression unitFactor = mathMapping_4_8.getUnitFactor(unitSystem.getVolumeSubstanceUnit().divideBy(unitSystem.getMembraneSubstanceUnit()));
                                exp = Expression.add(exp, Expression.mult(fluxCorrection, unitFactor, reactRateExp));
                            // exp = Expression.add(exp,new Expression(fluxCorrectionParameterSymbolName+"*"+ReservedSymbol.KMOLE.getName()+"*"+expInfix));
                            } else {
                                throw new RuntimeException("Internal Error: expected ReactionStep " + reactionSteps[j] + " to be of type SimpleReaction or FluxReaction");
                            }
                        } else {
                            exp = Expression.add(exp, reactRateExp);
                        }
                    }
                }
            }
        }
        // exp.bindExpression(mathMapping);
        scm.setRate(exp.flatten());
    }
    // 
    if (totalSchemeMatrix.getNumRows() > 1) {
        totalNullSpaceMatrix = (RationalMatrix) totalSchemeMatrix.findNullSpace();
    } else {
        totalNullSpaceMatrix = null;
    }
// if (totalNullSpaceMatrix==null){
// System.out.println("total system has full rank");
// }else{
// System.out.println("StructureAnalyzer.refreshTotalMatrices(), nullSpace matrix:");
// totalNullSpaceMatrix.show();
// }
}
Also used : MembraneMapping(cbit.vcell.mapping.MembraneMapping) SimpleReaction(cbit.vcell.model.SimpleReaction) SpeciesContextMapping(cbit.vcell.mapping.SpeciesContextMapping) ReactionSpec(cbit.vcell.mapping.ReactionSpec) RationalNumberMatrix(cbit.vcell.matrix.RationalNumberMatrix) DummyReactionStep(cbit.vcell.mapping.DummyReactionStep) EventDummyReactionStep(cbit.vcell.mapping.EventDummyReactionStep) ParticleDummyReactionStep(cbit.vcell.mapping.ParticleDummyReactionStep) DiffusionDummyReactionStep(cbit.vcell.mapping.DiffusionDummyReactionStep) HybridDummyReactionStep(cbit.vcell.mapping.HybridDummyReactionStep) FluxReaction(cbit.vcell.model.FluxReaction) SpeciesContext(cbit.vcell.model.SpeciesContext) Expression(cbit.vcell.parser.Expression) Membrane(cbit.vcell.model.Membrane) Parameter(cbit.vcell.model.Parameter) Structure(cbit.vcell.model.Structure) ReactionParticipant(cbit.vcell.model.ReactionParticipant) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem)

Example 32 with SimpleReaction

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

the class MembraneStructureAnalyzer method refreshResolvedFluxes.

/**
 * This method was created in VisualAge.
 */
private void refreshResolvedFluxes() throws Exception {
    // System.out.println("MembraneStructureAnalyzer.refreshResolvedFluxes()");
    ModelUnitSystem unitSystem = mathMapping.getSimulationContext().getModel().getUnitSystem();
    GeometryContext geoContext = mathMapping.getSimulationContext().getGeometryContext();
    Vector<ResolvedFlux> resolvedFluxList = new Vector<ResolvedFlux>();
    // 
    // for each reaction, get all fluxReactions associated with this membrane
    // 
    Vector<FluxReaction> fluxList = new Vector<FluxReaction>();
    ReactionSpec[] reactionSpecs = mathMapping.getSimulationContext().getReactionContext().getReactionSpecs();
    for (int j = 0; j < reactionSpecs.length; j++) {
        if (reactionSpecs[j].isExcluded()) {
            continue;
        }
        ReactionStep rs = reactionSpecs[j].getReactionStep();
        if (rs.getStructure() != null && geoContext.getStructureMapping(rs.getStructure()).getGeometryClass() == surfaceClass) {
            if (rs instanceof FluxReaction) {
                fluxList.addElement((FluxReaction) rs);
            }
        }
    }
    // 
    for (int i = 0; i < fluxList.size(); i++) {
        FluxReaction fr = fluxList.elementAt(i);
        ReactionParticipant[] reactionParticipants = fr.getReactionParticipants();
        for (int j = 0; j < reactionParticipants.length; j++) {
            if (!(reactionParticipants[j] instanceof Reactant) && !(reactionParticipants[j] instanceof Product)) {
                continue;
            }
            ResolvedFlux rf = null;
            SpeciesContext speciesContext = reactionParticipants[j].getSpeciesContext();
            for (int k = 0; k < resolvedFluxList.size(); k++) {
                ResolvedFlux rf_tmp = resolvedFluxList.elementAt(k);
                if (rf_tmp.getSpeciesContext() == reactionParticipants[j].getSpeciesContext()) {
                    rf = rf_tmp;
                }
            }
            // 
            // if speciesContext is not "fixed" and is mapped to a volume, add flux to ResolvedFlux
            // 
            StructureMapping structureMapping = mathMapping.getSimulationContext().getGeometryContext().getStructureMapping(reactionParticipants[j].getStructure());
            if (structureMapping.getGeometryClass() == surfaceClass) {
                // flux within surface
                continue;
            }
            if (structureMapping.getGeometryClass() instanceof SubVolume && surfaceClass.isAdjacentTo((SubVolume) structureMapping.getGeometryClass())) {
                SpeciesContextSpec speciesContextSpec = mathMapping.getSimulationContext().getReactionContext().getSpeciesContextSpec(speciesContext);
                if (!speciesContextSpec.isConstant()) {
                    if (rf == null) {
                        VCUnitDefinition speciesFluxUnit = speciesContext.getUnitDefinition().multiplyBy(unitSystem.getLengthUnit()).divideBy(unitSystem.getTimeUnit());
                        rf = new ResolvedFlux(speciesContext, speciesFluxUnit);
                        resolvedFluxList.addElement(rf);
                    }
                    FeatureMapping featureMapping = (FeatureMapping) structureMapping;
                    Expression insideFluxCorrection = Expression.invert(new Expression(featureMapping.getVolumePerUnitVolumeParameter(), mathMapping.getNameScope()));
                    // 
                    if (fr.getKinetics() instanceof DistributedKinetics) {
                        KineticsParameter reactionRateParameter = ((DistributedKinetics) fr.getKinetics()).getReactionRateParameter();
                        Expression correctedReactionRate = Expression.mult(new Expression(reactionRateParameter, mathMapping.getNameScope()), insideFluxCorrection);
                        if (reactionParticipants[j] instanceof Product) {
                            if (rf.getFluxExpression().isZero()) {
                                rf.setFluxExpression(correctedReactionRate.flatten());
                            } else {
                                rf.setFluxExpression(Expression.add(rf.getFluxExpression(), correctedReactionRate.flatten()));
                            }
                        } else if (reactionParticipants[j] instanceof Reactant) {
                            if (rf.getFluxExpression().isZero()) {
                                rf.setFluxExpression(Expression.negate(correctedReactionRate).flatten());
                            } else {
                                rf.setFluxExpression(Expression.add(rf.getFluxExpression(), Expression.negate(correctedReactionRate).flatten()));
                            }
                        } else {
                            throw new RuntimeException("expected either FluxReactant or FluxProduct");
                        }
                    } else if (fr.getKinetics() instanceof LumpedKinetics) {
                        throw new RuntimeException("Lumped Kinetics for fluxes not yet supported");
                    } else {
                        throw new RuntimeException("unexpected Kinetic type in MembraneStructureAnalyzer.refreshResolvedFluxes()");
                    }
                    rf.getFluxExpression().bindExpression(mathMapping);
                }
            }
        }
    }
    // 
    for (int i = 0; i < reactionSpecs.length; i++) {
        if (reactionSpecs[i].isExcluded()) {
            continue;
        }
        ReactionStep rs = reactionSpecs[i].getReactionStep();
        if (rs.getStructure() != null && geoContext.getStructureMapping(rs.getStructure()).getGeometryClass() == surfaceClass) {
            if (rs instanceof SimpleReaction) {
                SimpleReaction sr = (SimpleReaction) rs;
                ReactionParticipant[] rp_Array = sr.getReactionParticipants();
                for (int k = 0; k < rp_Array.length; k++) {
                    if (rp_Array[k] instanceof Reactant || rp_Array[k] instanceof Product) {
                        SpeciesContextSpec rpSCS = mathMapping.getSimulationContext().getReactionContext().getSpeciesContextSpec(rp_Array[k].getSpeciesContext());
                        StructureMapping rpSM = mathMapping.getSimulationContext().getGeometryContext().getStructureMapping(rp_Array[k].getStructure());
                        if (rpSM.getGeometryClass() instanceof SubVolume && !rpSCS.isConstant()) {
                            // 
                            // get ResolvedFlux for this species
                            // 
                            ResolvedFlux rf = null;
                            for (int j = 0; j < resolvedFluxList.size(); j++) {
                                ResolvedFlux rf_tmp = (ResolvedFlux) resolvedFluxList.elementAt(j);
                                if (rf_tmp.getSpeciesContext() == rp_Array[k].getSpeciesContext()) {
                                    rf = rf_tmp;
                                }
                            }
                            if (rf == null) {
                                VCUnitDefinition speciesFluxUnit = rp_Array[k].getSpeciesContext().getUnitDefinition().multiplyBy(unitSystem.getLengthUnit()).divideBy(unitSystem.getTimeUnit());
                                rf = new ResolvedFlux(rp_Array[k].getSpeciesContext(), speciesFluxUnit);
                                resolvedFluxList.addElement(rf);
                            }
                            if (rpSM.getGeometryClass() instanceof SubVolume && surfaceClass.isAdjacentTo((SubVolume) rpSM.getGeometryClass())) {
                                // 
                                // for binding on inside or outside, add to ResolvedFlux.flux
                                // 
                                Expression fluxRateExpression = getCorrectedRateExpression(sr, rp_Array[k], RateType.ResolvedFluxRate).renameBoundSymbols(mathMapping.getNameScope());
                                if (rf.getFluxExpression().isZero()) {
                                    rf.setFluxExpression(fluxRateExpression);
                                } else {
                                    rf.setFluxExpression(Expression.add(rf.getFluxExpression(), fluxRateExpression));
                                }
                                rf.getFluxExpression().bindExpression(mathMapping);
                            } else {
                                String structureName = ((rs.getStructure() != null) ? (rs.getStructure().getName()) : ("<null>"));
                                throw new Exception("In Application '" + mathMapping.getSimulationContext().getName() + "', SpeciesContext '" + rp_Array[k].getSpeciesContext().getName() + "' is not mapped adjacent to structure '" + structureName + "' but reacts there");
                            }
                        }
                    }
                }
            }
        }
    }
    // 
    if (resolvedFluxList.size() > 0) {
        resolvedFluxes = new ResolvedFlux[resolvedFluxList.size()];
        resolvedFluxList.copyInto(resolvedFluxes);
    } else {
        resolvedFluxes = null;
    }
}
Also used : LumpedKinetics(cbit.vcell.model.LumpedKinetics) Product(cbit.vcell.model.Product) FluxReaction(cbit.vcell.model.FluxReaction) SpeciesContext(cbit.vcell.model.SpeciesContext) Reactant(cbit.vcell.model.Reactant) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) SubVolume(cbit.vcell.geometry.SubVolume) Vector(java.util.Vector) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem) DistributedKinetics(cbit.vcell.model.DistributedKinetics) SimpleReaction(cbit.vcell.model.SimpleReaction) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) ReactionStep(cbit.vcell.model.ReactionStep) ReactionParticipant(cbit.vcell.model.ReactionParticipant)

Example 33 with SimpleReaction

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

the class DiffEquMathMapping method refreshSpeciesContextMappings.

/**
 * This method was created in VisualAge.
 */
private void refreshSpeciesContextMappings() throws ExpressionException, MappingException, MathException {
    // 
    // create a SpeciesContextMapping for each speciesContextSpec.
    // 
    // set initialExpression from SpeciesContextSpec.
    // set diffusing
    // set variable (only if "Constant" or "Function", else leave it as null)
    // 
    speciesContextMappingList.removeAllElements();
    SpeciesContextSpec[] speciesContextSpecs = simContext.getReactionContext().getSpeciesContextSpecs();
    for (int i = 0; i < speciesContextSpecs.length; i++) {
        SpeciesContextSpec scs = speciesContextSpecs[i];
        SpeciesContextMapping scm = new SpeciesContextMapping(scs.getSpeciesContext());
        scm.setPDERequired(simContext.isPDERequired(scs.getSpeciesContext()));
        scm.setHasEventAssignment(simContext.hasEventAssignment(scs.getSpeciesContext()));
        scm.setHasHybridReaction(false);
        for (ReactionSpec reactionSpec : getSimulationContext().getReactionContext().getReactionSpecs()) {
            if (!reactionSpec.isExcluded() && reactionSpec.hasHybrid(getSimulationContext(), scs.getSpeciesContext())) {
                scm.setHasHybridReaction(true);
            }
        }
        // scm.setAdvecting(isAdvectionRequired(scs.getSpeciesContext()));
        if (scs.isConstant()) {
            Expression initCond = scs.getInitialConditionParameter() == null ? null : new Expression(scs.getInitialConditionParameter(), getNameScope());
            scm.setDependencyExpression(initCond);
        // //
        // // determine if a Function is necessary
        // //
        // boolean bNeedFunction = false;
        // if (initCond.getSymbols()!=null){
        // bNeedFunction = true;
        // }
        // if (bNeedFunction){
        // scm.setVariable(new Function(scm.getSpeciesContext().getName(),initCond));
        // }else{
        // scm.setVariable(new Constant(scm.getSpeciesContext().getName(),initCond));
        // }
        }
        // 
        // test if participant in fast reaction step, request elimination if possible
        // 
        scm.setFastParticipant(false);
        ReactionSpec[] reactionSpecs = simContext.getReactionContext().getReactionSpecs();
        for (int j = 0; j < reactionSpecs.length; j++) {
            ReactionSpec reactionSpec = reactionSpecs[j];
            if (reactionSpec.isExcluded()) {
                continue;
            }
            ReactionStep rs = reactionSpec.getReactionStep();
            if (rs instanceof SimpleReaction && rs.countNumReactionParticipants(scs.getSpeciesContext()) > 0) {
                if (reactionSpec.isFast()) {
                    scm.setFastParticipant(true);
                }
            }
        }
        speciesContextMappingList.addElement(scm);
    }
}
Also used : SimpleReaction(cbit.vcell.model.SimpleReaction) Expression(cbit.vcell.parser.Expression) ReactionStep(cbit.vcell.model.ReactionStep)

Example 34 with SimpleReaction

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

the class ReactionCartoonFull method refreshAll.

@Override
protected void refreshAll(boolean reallocateShapes) {
    try {
        if (getModel() == null || getStructureSuite() == null) {
            return;
        }
        System.out.println("ReactionCartoonFull, 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 = rp.getStoichiometry();
                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
                        // 
                        RuleParticipantLongSignature ruleParticipantLongSignature = null;
                        for (RuleParticipantSignature signature : ruleParticipantSignatures) {
                            if (signature instanceof RuleParticipantLongSignature && signature.getStructure() == participant.getStructure() && signature.compareByCriteria(participant.getSpeciesPattern(), GroupingCriteria.full)) {
                                ruleParticipantLongSignature = (RuleParticipantLongSignature) signature;
                                break;
                            }
                        }
                        for (RuleParticipantSignature signature : ruleParticipantSignatures) {
                            if (signature instanceof RuleParticipantShortSignature && signature.getStructure() == participant.getStructure()) {
                                System.out.println("ReactionCartoonFull, refreshAll(), RuleParticipantShortSignature");
                            }
                        }
                        // 
                        // if didn't find signature in cartoons list of signatures, then create one (and create a shape for it).
                        // 
                        RuleParticipantSignatureFullDiagramShape signatureShape = null;
                        if (ruleParticipantLongSignature == null) {
                            ruleParticipantLongSignature = RuleParticipantLongSignature.fromReactionRuleParticipant(participant, this);
                            ruleParticipantSignatures.add(ruleParticipantLongSignature);
                            signatureShape = new RuleParticipantSignatureFullDiagramShape(ruleParticipantLongSignature, this);
                            addShape(signatureShape);
                            ReactionContainerShape participantContainerShape = (ReactionContainerShape) getShapeFromModelObject(participant.getStructure());
                            signatureShape.getSpaceManager().setRelPos(participantContainerShape.getRandomPosition());
                            participantContainerShape.addChildShape(signatureShape);
                            signatureShape.getSpaceManager().setRelPos(participantContainerShape.getRandomPosition());
                        } else {
                            signatureShape = (RuleParticipantSignatureFullDiagramShape) getShapeFromModelObject(ruleParticipantLongSignature);
                        }
                        unwantedShapes.remove(signatureShape);
                        unwantedSignatures.remove(ruleParticipantLongSignature);
                        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 35 with SimpleReaction

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

the class ReactionCartoonMolecule method applyDefaults.

public void applyDefaults(Diagram diagram) {
    List<NodeReference> nodeList = diagram.getNodeMoleculeList();
    List<NodeReference> orphansList = new ArrayList<NodeReference>();
    for (int i = 0; i < nodeList.size(); i++) {
        NodeReference node = nodeList.get(i);
        Object obj = null;
        Structure struct = diagram.getStructure();
        boolean found = false;
        switch(node.nodeType) {
            case NodeReference.SIMPLE_REACTION_NODE:
                obj = getModel().getReactionStep(node.name);
                if (!(obj instanceof SimpleReaction)) {
                    System.out.println("ReactionCartoon.applyDefaults(), diagram reaction " + node.name + " type mismatch in model, using location anyway");
                }
                break;
            case NodeReference.FLUX_REACTION_NODE:
                obj = getModel().getReactionStep(node.name);
                if (!(obj instanceof FluxReaction)) {
                    System.out.println("ReactionCartoon.applyDefaults(), diagram flux " + node.name + " type mismatch in model, using location anyway");
                }
                break;
            case NodeReference.SPECIES_CONTEXT_NODE:
                obj = getModel().getSpeciesContext(node.name);
                break;
            case NodeReference.REACTION_RULE_NODE:
                obj = getModel().getRbmModelContainer().getReactionRule(node.name);
                break;
            case // obj is a RuleParticipantSignature
            NodeReference.RULE_PARTICIPANT_SIGNATURE_FULL_NODE:
                System.out.println("ReactionCartoonMolecule, RULE_PARTICIPANT_SIGNATURE_FULL_NODE detected");
                for (RuleParticipantSignature signature : ruleParticipantSignatures) {
                    if (signature instanceof RuleParticipantLongSignature && signature.getStructure() == struct && signature.compareByCriteria(node.getName(), GroupingCriteria.full)) {
                        obj = signature;
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    orphansList.add(node);
                }
                break;
            case NodeReference.RULE_PARTICIPANT_SIGNATURE_SHORT_NODE:
                for (RuleParticipantSignature signature : ruleParticipantSignatures) {
                    if (signature instanceof RuleParticipantShortSignature && signature.getStructure() == struct && signature.compareByCriteria(node.getName(), GroupingCriteria.full)) {
                        obj = signature;
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    orphansList.add(node);
                }
                break;
        }
        // -- switch
        Shape shape = getShapeFromModelObject(obj);
        if (shape != null) {
            Point relPosOld = shape.getRelPos();
            Point relPosNew = node.location;
            // In old models, the same node can appear in multiple diagrams.
            // Now, we have only one diagram, so if a node has multiple positions,
            // some would overwrite others.
            // This attempts to prevent overwriting a position with a worse one.
            // if(relPosOld.x + relPosOld.y < relPosNew.x + relPosNew.y) {
            shape.setRelPos(relPosNew);
        // }
        }
    }
    if (!orphansList.isEmpty()) {
        diagram.removeNodeReferences(NodeReference.Mode.molecule, orphansList);
    }
}
Also used : RuleParticipantSignature(cbit.vcell.model.RuleParticipantSignature) RuleParticipantLongSignature(cbit.vcell.model.RuleParticipantLongSignature) SimpleReaction(cbit.vcell.model.SimpleReaction) Shape(cbit.gui.graph.Shape) NodeReference(cbit.vcell.model.NodeReference) ArrayList(java.util.ArrayList) FluxReaction(cbit.vcell.model.FluxReaction) Point(java.awt.Point) Point(java.awt.Point) RuleParticipantShortSignature(cbit.vcell.model.RuleParticipantShortSignature) Structure(cbit.vcell.model.Structure)

Aggregations

SimpleReaction (cbit.vcell.model.SimpleReaction)49 FluxReaction (cbit.vcell.model.FluxReaction)26 SpeciesContext (cbit.vcell.model.SpeciesContext)22 ReactionParticipant (cbit.vcell.model.ReactionParticipant)20 ReactionStep (cbit.vcell.model.ReactionStep)19 Structure (cbit.vcell.model.Structure)19 Expression (cbit.vcell.parser.Expression)19 Membrane (cbit.vcell.model.Membrane)16 Feature (cbit.vcell.model.Feature)15 Reactant (cbit.vcell.model.Reactant)15 ArrayList (java.util.ArrayList)14 KineticsParameter (cbit.vcell.model.Kinetics.KineticsParameter)13 Product (cbit.vcell.model.Product)12 PropertyVetoException (java.beans.PropertyVetoException)12 Model (cbit.vcell.model.Model)10 Kinetics (cbit.vcell.model.Kinetics)9 MassActionKinetics (cbit.vcell.model.MassActionKinetics)9 Point (java.awt.Point)9 Shape (cbit.gui.graph.Shape)8 BioModel (cbit.vcell.biomodel.BioModel)7