Search in sources :

Example 86 with ReactionStep

use of cbit.vcell.model.ReactionStep 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 87 with ReactionStep

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

the class AbstractMathMapping method refreshLocalNameCount.

protected void refreshLocalNameCount() {
    localNameCountHash.clear();
    ReactionStep[] reactionSteps = simContext.getModel().getReactionSteps();
    for (int j = 0; j < reactionSteps.length; j++) {
        KineticsParameter[] params = reactionSteps[j].getKinetics().getKineticsParameters();
        for (KineticsParameter kp : params) {
            String name = kp.getName();
            if (localNameCountHash.containsKey(name)) {
                localNameCountHash.put(name, localNameCountHash.get(name) + 1);
            } else {
                localNameCountHash.put(name, 1);
            }
        }
    }
    List<ReactionRule> reactionRules = simContext.getModel().getRbmModelContainer().getReactionRuleList();
    for (ReactionRule reactionRule : reactionRules) {
        LocalParameter[] params = reactionRule.getKineticLaw().getLocalParameters();
        for (LocalParameter kp : params) {
            String name = kp.getName();
            if (localNameCountHash.containsKey(name)) {
                localNameCountHash.put(name, localNameCountHash.get(name) + 1);
            } else {
                localNameCountHash.put(name, 1);
            }
        }
    }
    SpeciesContext[] scs = simContext.getModel().getSpeciesContexts();
    for (SpeciesContext sc : scs) {
        String name = sc.getName();
        if (localNameCountHash.containsKey(name)) {
            localNameCountHash.put(name, localNameCountHash.get(name) + 1);
        } else {
            localNameCountHash.put(name, 1);
        }
    }
    ModelParameter[] mps = simContext.getModel().getModelParameters();
    for (ModelParameter mp : mps) {
        String name = mp.getName();
        if (localNameCountHash.containsKey(name)) {
            localNameCountHash.put(name, localNameCountHash.get(name) + 1);
        } else {
            localNameCountHash.put(name, 1);
        }
    }
}
Also used : ReactionRule(cbit.vcell.model.ReactionRule) SpeciesContext(cbit.vcell.model.SpeciesContext) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) ReactionStep(cbit.vcell.model.ReactionStep)

Example 88 with ReactionStep

use of cbit.vcell.model.ReactionStep 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 89 with ReactionStep

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

the class Xmlproducer method getXML.

/**
 * Outputs a XML version of a Model object
 * Creation date: (2/15/2001 11:39:27 AM)
 * @return Element
 * @param param cbit.vcell.model.Model
 */
public Element getXML(Model param) throws XmlParseException /*, cbit.vcell.parser.ExpressionException */
{
    Element modelnode = new Element(XMLTags.ModelTag);
    String versionName = (param.getName() != null) ? mangle(param.getName()) : "unnamed_model";
    // get Attributes
    modelnode.setAttribute(XMLTags.NameAttrTag, versionName);
    // modelnode.setAttribute(XMLTags.AnnotationAttrTag, this.mangle(param.getDescription()));
    if (param.getDescription() != null && param.getDescription().length() > 0) {
        Element annotationElem = new Element(XMLTags.AnnotationTag);
        annotationElem.setText(mangle(param.getDescription()));
        modelnode.addContent(annotationElem);
    }
    // get global parameters
    ModelParameter[] modelGlobals = param.getModelParameters();
    if (modelGlobals != null && modelGlobals.length > 0) {
        modelnode.addContent(getXML(modelGlobals));
    }
    // Get Species
    Species[] array = param.getSpecies();
    for (int i = 0; i < array.length; i++) {
        modelnode.addContent(getXML(array[i]));
    }
    // Get Structures(Features and Membranes). Add them in an ordered fashion, but it does not matter who comes first.
    try {
        ArrayList<Element> list = new ArrayList<Element>();
        Structure[] structarray = param.getStructures();
        for (int i = 0; i < structarray.length; i++) {
            Element structure = getXML(structarray[i], param);
            if (structarray[i] instanceof Feature)
                modelnode.addContent(structure);
            else
                list.add(structure);
        }
        for (int i = 0; i < list.size(); i++) {
            modelnode.addContent((Element) list.get(i));
        }
    } catch (XmlParseException e) {
        e.printStackTrace();
        throw new XmlParseException("An error occurred while procesing a Structure for the model " + versionName, e);
    }
    // Process SpeciesContexts
    SpeciesContext[] specarray = param.getSpeciesContexts();
    for (int i = 0; i < specarray.length; i++) {
        modelnode.addContent(getXML(specarray[i]));
    }
    // Get reaction Steps(Simple Reactions and Fluxtep)
    ReactionStep[] reactarray = param.getReactionSteps();
    for (int i = 0; i < reactarray.length; i++) {
        modelnode.addContent(getXML(reactarray[i]));
    }
    // add the rbmModelContainer elements
    RbmModelContainer rbmModelContainer = param.getRbmModelContainer();
    if (rbmModelContainer != null && !rbmModelContainer.isEmpty()) {
        Element rbmModelContainerElement = getXML(rbmModelContainer);
        {
            // for testing purposes only
            Document doc = new Document();
            Element clone = (Element) rbmModelContainerElement.clone();
            doc.setRootElement(clone);
            String xmlString = XmlUtil.xmlToString(doc, false);
            System.out.println(xmlString);
        }
        modelnode.addContent(rbmModelContainerElement);
    }
    // // Add rate rules
    // if (param.getRateRuleVariables()!=null && param.getRateRuleVariables().length>0){
    // modelnode.addContent( getXML(param.getRateRuleVariables()) );
    // }
    // Get Diagrams
    Diagram[] diagarray = param.getDiagrams();
    for (int i = 0; i < diagarray.length; i++) {
        modelnode.addContent(getXML(diagarray[i]));
    }
    // Add Metadata information
    if (param.getVersion() != null) {
        modelnode.addContent(getXML(param.getVersion(), param));
    }
    // add model UnitSystem
    ModelUnitSystem unitSystem = param.getUnitSystem();
    if (unitSystem != null) {
        modelnode.addContent(getXML(unitSystem));
    }
    return modelnode;
}
Also used : Element(org.jdom.Element) ArrayList(java.util.ArrayList) SpeciesContext(cbit.vcell.model.SpeciesContext) Document(org.jdom.Document) Feature(cbit.vcell.model.Feature) Diagram(cbit.vcell.model.Diagram) ModelParameter(cbit.vcell.model.Model.ModelParameter) RbmModelContainer(cbit.vcell.model.Model.RbmModelContainer) ReactionStep(cbit.vcell.model.ReactionStep) Structure(cbit.vcell.model.Structure) DBFormalSpecies(cbit.vcell.model.DBFormalSpecies) Species(cbit.vcell.model.Species) DBSpecies(cbit.vcell.model.DBSpecies) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem)

Example 90 with ReactionStep

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

Aggregations

ReactionStep (cbit.vcell.model.ReactionStep)111 SpeciesContext (cbit.vcell.model.SpeciesContext)55 Structure (cbit.vcell.model.Structure)37 ReactionParticipant (cbit.vcell.model.ReactionParticipant)33 Expression (cbit.vcell.parser.Expression)33 Model (cbit.vcell.model.Model)32 KineticsParameter (cbit.vcell.model.Kinetics.KineticsParameter)30 ArrayList (java.util.ArrayList)29 ReactionRule (cbit.vcell.model.ReactionRule)26 ModelParameter (cbit.vcell.model.Model.ModelParameter)25 Reactant (cbit.vcell.model.Reactant)25 Kinetics (cbit.vcell.model.Kinetics)24 Product (cbit.vcell.model.Product)23 PropertyVetoException (java.beans.PropertyVetoException)23 SimpleReaction (cbit.vcell.model.SimpleReaction)20 ExpressionException (cbit.vcell.parser.ExpressionException)20 Vector (java.util.Vector)19 SimulationContext (cbit.vcell.mapping.SimulationContext)18 Membrane (cbit.vcell.model.Membrane)18 BioModel (cbit.vcell.biomodel.BioModel)17