Search in sources :

Example 6 with Catalyst

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

the class StructureAnalyzer method getReactionRateExpression.

public Expression getReactionRateExpression(ReactionStep reactionStep, ReactionParticipant reactionParticipant) throws Exception {
    if (reactionParticipant instanceof Catalyst) {
        throw new Exception("Catalyst " + reactionParticipant + " doesn't have a rate for this reaction");
    // return new Expression(0.0);
    }
    double stoich = reactionStep.getStoichiometry(reactionParticipant.getSpeciesContext());
    if (stoich == 0.0) {
        return new Expression(0.0);
    }
    if (reactionStep.getKinetics() instanceof DistributedKinetics) {
        DistributedKinetics distributedKinetics = (DistributedKinetics) reactionStep.getKinetics();
        if (stoich != 1) {
            Expression exp = Expression.mult(new Expression(stoich), new Expression(distributedKinetics.getReactionRateParameter(), mathMapping_4_8.getNameScope()));
            return exp;
        } else {
            Expression exp = new Expression(distributedKinetics.getReactionRateParameter(), mathMapping_4_8.getNameScope());
            return exp;
        }
    } else if (reactionStep.getKinetics() instanceof LumpedKinetics) {
        Structure.StructureSize structureSize = reactionStep.getStructure().getStructureSize();
        // 
        // need to put this into concentration/time with respect to structure for reaction.
        // 
        LumpedKinetics lumpedKinetics = (LumpedKinetics) reactionStep.getKinetics();
        Expression factor = null;
        ModelUnitSystem unitSystem = mathMapping_4_8.getSimulationContext().getModel().getUnitSystem();
        if (reactionStep.getStructure() instanceof Feature || ((reactionStep.getStructure() instanceof Membrane) && reactionStep instanceof FluxReaction)) {
            VCUnitDefinition lumpedToVolumeSubstance = unitSystem.getVolumeSubstanceUnit().divideBy(unitSystem.getLumpedReactionSubstanceUnit());
            factor = Expression.div(new Expression(lumpedToVolumeSubstance.getDimensionlessScale()), new Expression(structureSize, mathMapping_4_8.getNameScope()));
        } else if (reactionStep.getStructure() instanceof Membrane && reactionStep instanceof SimpleReaction) {
            VCUnitDefinition lumpedToVolumeSubstance = unitSystem.getMembraneSubstanceUnit().divideBy(unitSystem.getLumpedReactionSubstanceUnit());
            factor = Expression.div(new Expression(lumpedToVolumeSubstance.getDimensionlessScale()), new Expression(structureSize, mathMapping_4_8.getNameScope()));
        } else {
            throw new RuntimeException("failed to create reaction rate expression for reaction " + reactionStep.getName() + ", with kinetic type of " + reactionStep.getKinetics().getClass().getName());
        }
        if (stoich != 1) {
            Expression exp = Expression.mult(new Expression(stoich), Expression.mult(new Expression(lumpedKinetics.getLumpedReactionRateParameter(), mathMapping_4_8.getNameScope()), factor));
            return exp;
        } else {
            Expression exp = Expression.mult(new Expression(lumpedKinetics.getLumpedReactionRateParameter(), mathMapping_4_8.getNameScope()), factor);
            return exp;
        }
    } else {
        throw new RuntimeException("unexpected kinetic type " + reactionStep.getKinetics().getClass().getName());
    }
}
Also used : DistributedKinetics(cbit.vcell.model.DistributedKinetics) SimpleReaction(cbit.vcell.model.SimpleReaction) LumpedKinetics(cbit.vcell.model.LumpedKinetics) FluxReaction(cbit.vcell.model.FluxReaction) Feature(cbit.vcell.model.Feature) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) Membrane(cbit.vcell.model.Membrane) Catalyst(cbit.vcell.model.Catalyst) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem)

Example 7 with Catalyst

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

the class DBReactionWizardPanel method bfnActionPerformed.

/**
 * Comment
 */
private void bfnActionPerformed(java.awt.event.ActionEvent actionEvent) {
    try {
        // 
        javax.swing.DefaultListModel pndlm = (javax.swing.DefaultListModel) getParameterNamesJList().getModel();
        // 
        if (actionEvent.getSource().equals(getBackJButton())) {
            if (getResolverJPanel().isVisible() && pndlm.size() == 0 && getSearchDictionaryJRadioButton().isSelected() == false) {
                // skip Parameters if there are none
                ((java.awt.CardLayout) getCardLayoutJPanel().getLayout()).previous(getCardLayoutJPanel());
            }
            ((java.awt.CardLayout) getCardLayoutJPanel().getLayout()).previous(getCardLayoutJPanel());
        } else if (actionEvent.getSource().equals(getNextJButton())) {
            if (getSearchCriteriaJPanel().isVisible()) {
                if (getSearchDictionaryJRadioButton().isSelected()) {
                    getParameterJPanel().setVisible(false);
                } else {
                    getParameterJPanel().setVisible(true);
                }
                if (!lastSearchIsSameAsCurrent()) {
                    search();
                    lastReactionSelection = null;
                    return;
                }
            } else if (getParameterJPanel().isVisible()) {
                if (lastReactStepSelection == null || !lastReactStepSelection.equals(getReactionStep0())) {
                    lastReactStepSelection = getReactionStep0();
                    ReactionType rxType = null;
                    if (getReactionStep0() instanceof FluxReaction) {
                        if (getReactionStep0().isReversible()) {
                            rxType = ReactionType.REACTTYPE_FLUX_REVERSIBLE;
                        } else {
                            rxType = ReactionType.REACTTYPE_FLUX_IRREVERSIBLE;
                        }
                    } else {
                        if (getReactionStep0().isReversible()) {
                            rxType = ReactionType.REACTTYPE_SIMPLE_REVERSIBLE;
                        } else {
                            rxType = ReactionType.REACTTYPE_SIMPLE_IRREVERSIBLE;
                        }
                    }
                    KeyValue bmid = mapRXIDtoBMIDs.get(lastReactStepSelection.getKey());
                    KeyValue structRef = mapRXIDtoStructRefIDs.get(lastReactStepSelection.getKey());
                    ReactionDescription dbfr = new ReactionDescription(getReactionStep0().getName(), rxType, getReactionStep0().getKey(), bmid, structRef);
                    // 
                    ReactionParticipant[] rpArr = getReactionStep0().getReactionParticipants();
                    for (int i = 0; i < rpArr.length; i += 1) {
                        DBNonFormalUnboundSpecies dbnfu = new DBNonFormalUnboundSpecies(rpArr[i].getSpecies().getCommonName());
                        char role;
                        if (rpArr[i] instanceof Reactant) {
                            role = ReactionDescription.RX_ELEMENT_REACTANT;
                        } else if (rpArr[i] instanceof Product) {
                            role = ReactionDescription.RX_ELEMENT_PRODUCT;
                        } else if (rpArr[i] instanceof Catalyst) {
                            role = ReactionDescription.RX_ELEMENT_CATALYST;
                        } else {
                            throw new RuntimeException("Unsupported ReationParticiapnt=" + rpArr[i].getClass().getName());
                        }
                        dbfr.addReactionElement(dbnfu, rpArr[i].getSpeciesContext().getName(), rpArr[i].getStoichiometry(), role);
                    }
                    if (dbfr.isFluxReaction()) {
                        // make sure flux is in right direction
                        Structure outsideStruct = getModel().getStructureTopology().getOutsideFeature((Membrane) getReactionStep0().getStructure());
                        String defaultOutsideSCName = dbfr.getOrigSpeciesContextName(dbfr.getFluxIndexOutside());
                        for (int i = 0; i < rpArr.length; i += 1) {
                            if (rpArr[i].getSpeciesContext().getName().equals(defaultOutsideSCName)) {
                                if (!rpArr[i].getStructure().equals(outsideStruct)) {
                                    dbfr.swapFluxSCNames();
                                }
                                break;
                            }
                        }
                    }
                    setupRX(dbfr);
                }
            }
            // 
            ((java.awt.CardLayout) getCardLayoutJPanel().getLayout()).next(getCardLayoutJPanel());
        } else if (actionEvent.getSource().equals(getFinishJButton())) {
            applySelectedReactionElements();
        }
        // 
        configureBFN();
    } catch (Exception e) {
        e.printStackTrace();
        DialogUtils.showErrorDialog(this, "DBReactionWizard failed\n" + e.getMessage(), e);
    }
}
Also used : ReactionType(cbit.vcell.model.ReactionDescription.ReactionType) KeyValue(org.vcell.util.document.KeyValue) Product(cbit.vcell.model.Product) FluxReaction(cbit.vcell.model.FluxReaction) DBNonFormalUnboundSpecies(cbit.vcell.dictionary.DBNonFormalUnboundSpecies) Reactant(cbit.vcell.model.Reactant) DataAccessException(org.vcell.util.DataAccessException) UserCancelException(org.vcell.util.UserCancelException) ReactionDescription(cbit.vcell.model.ReactionDescription) Structure(cbit.vcell.model.Structure) ReactionParticipant(cbit.vcell.model.ReactionParticipant) Catalyst(cbit.vcell.model.Catalyst)

Example 8 with Catalyst

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

the class ITextWriter method writeReactions.

// each reaction has its own table, ordered by the structures.
protected void writeReactions(Chapter physioChapter, Model model) throws DocumentException {
    if (model == null) {
        return;
    }
    Paragraph reactionParagraph = new Paragraph();
    reactionParagraph.add(new Chunk("Structures and Reactions Diagram").setLocalDestination(model.getName()));
    Section reactionDiagramSection = physioChapter.addSection(reactionParagraph, physioChapter.numberDepth() + 1);
    try {
        addImage(reactionDiagramSection, encodeJPEG(generateDocReactionsImage(model, null)));
    } catch (Exception e) {
        e.printStackTrace();
        throw new DocumentException(e.getClass().getName() + ": " + e.getMessage());
    }
    for (int i = 0; i < model.getNumStructures(); i++) {
        ReactionStep[] reactionSteps = model.getReactionSteps();
        ReactionStep rs = null;
        Table modifierTable = null;
        Table reactionTable = null;
        boolean firstTime = true;
        Section reactStructSection = null;
        for (int j = 0; j < reactionSteps.length; j++) {
            if (reactionSteps[j].getStructure() == model.getStructure(i)) {
                // can also use structureName1.equals(structureName2)
                if (firstTime) {
                    Paragraph linkParagraph = new Paragraph();
                    linkParagraph.add(new Chunk("Reaction(s) in " + model.getStructure(i).getName()).setLocalDestination(model.getStructure(i).getName()));
                    reactStructSection = physioChapter.addSection(linkParagraph, physioChapter.numberDepth() + 1);
                    firstTime = false;
                }
                rs = reactionSteps[j];
                String type;
                if (rs instanceof SimpleReaction) {
                    type = "Reaction";
                } else {
                    type = "Flux";
                }
                // write Reaction equation as a table
                // Get the image arrow cell depending on type of reactionStep : MassAction => double arrow, otherwise, forward arrow
                boolean bReversible = false;
                if (rs.getKinetics() instanceof MassActionKinetics) {
                    bReversible = true;
                }
                Cell arrowImageCell = getReactionArrowImageCell(bReversible);
                // Get reactants and products strings
                ReactionCanvas rc = new ReactionCanvas();
                rc.setReactionStep(rs);
                ReactionCanvasDisplaySpec rcdSpec = rc.getReactionCanvasDisplaySpec();
                String reactants = rcdSpec.getLeftText();
                String products = rcdSpec.getRightText();
                // Create table and add cells for reactants, arrow(s) images, products
                int[] widths = { 8, 1, 8 };
                reactionTable = getTable(3, 100, 0, 2, 2);
                // Add reactants as cell
                Cell tableCell = createCell(reactants, getBold());
                tableCell.setHorizontalAlignment(Cell.ALIGN_RIGHT);
                tableCell.setBorderColor(Color.white);
                reactionTable.addCell(tableCell);
                // add arrow(s) image as cell
                if (arrowImageCell != null) {
                    arrowImageCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
                    arrowImageCell.setBorderColor(Color.white);
                    reactionTable.addCell(arrowImageCell);
                }
                // add products as cell
                tableCell = createCell(products, getBold());
                tableCell.setBorderColor(Color.white);
                reactionTable.addCell(tableCell);
                // reactionTable.setBorderColor(Color.white);
                reactionTable.setWidths(widths);
                // Identify modifiers,
                ReactionParticipant[] rpArr = rs.getReactionParticipants();
                Vector<ReactionParticipant> modifiersVector = new Vector<ReactionParticipant>();
                for (int k = 0; k < rpArr.length; k += 1) {
                    if (rpArr[k] instanceof Catalyst) {
                        modifiersVector.add(rpArr[k]);
                    }
                }
                // Write the modifiers in a separate table, if present
                if (modifiersVector.size() > 0) {
                    modifierTable = getTable(1, 50, 0, 1, 1);
                    modifierTable.addCell(createCell("Modifiers List", getBold(DEF_HEADER_FONT_SIZE), 1, 1, Element.ALIGN_CENTER, true));
                    StringBuffer modifierNames = new StringBuffer();
                    for (int k = 0; k < modifiersVector.size(); k++) {
                        modifierNames.append(((Catalyst) modifiersVector.elementAt(k)).getName() + "\n");
                    }
                    modifierTable.addCell(createCell(modifierNames.toString().trim(), getFont()));
                    modifiersVector.removeAllElements();
                }
                Section reactionSection = reactStructSection.addSection(type + " " + rs.getName(), reactStructSection.numberDepth() + 1);
                // Annotation
                VCMetaData vcMetaData = rs.getModel().getVcMetaData();
                if (vcMetaData.getFreeTextAnnotation(rs) != null) {
                    Table annotTable = getTable(1, 100, 1, 3, 3);
                    annotTable.addCell(createCell("Reaction Annotation", getBold(DEF_HEADER_FONT_SIZE), 1, 1, Element.ALIGN_CENTER, true));
                    annotTable.addCell(createCell(vcMetaData.getFreeTextAnnotation(rs), getFont()));
                    reactionSection.add(annotTable);
                // reactionSection.add(new Paragraph("\""+rs.getAnnotation()+"\""));
                }
                // reaction table
                if (reactionTable != null) {
                    reactionSection.add(reactionTable);
                    // re-set reactionTable
                    reactionTable = null;
                }
                if (modifierTable != null) {
                    reactionSection.add(modifierTable);
                    modifierTable = null;
                }
                // Write kinetics parameters, etc. in a table
                writeKineticsParams(reactionSection, rs);
            }
        }
    }
}
Also used : Table(com.lowagie.text.Table) SimpleReaction(cbit.vcell.model.SimpleReaction) ReactionCanvasDisplaySpec(cbit.vcell.model.ReactionCanvasDisplaySpec) ReactionCanvas(cbit.vcell.model.ReactionCanvas) Chunk(com.lowagie.text.Chunk) Section(com.lowagie.text.Section) DocumentException(com.lowagie.text.DocumentException) ExpressionException(cbit.vcell.parser.ExpressionException) Paragraph(com.lowagie.text.Paragraph) VCMetaData(cbit.vcell.biomodel.meta.VCMetaData) DocumentException(com.lowagie.text.DocumentException) ReactionStep(cbit.vcell.model.ReactionStep) MassActionKinetics(cbit.vcell.model.MassActionKinetics) Cell(com.lowagie.text.Cell) ReactionParticipant(cbit.vcell.model.ReactionParticipant) Vector(java.util.Vector) Catalyst(cbit.vcell.model.Catalyst)

Example 9 with Catalyst

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

the class ReactionCartoonTool method getLineTypeFromAttachment.

private LineType getLineTypeFromAttachment(SpeciesContext speciesContext, Point worldPoint) throws Exception {
    Shape mouseOverShape = getReactionCartoon().pickWorld(worldPoint);
    if (mouseOverShape instanceof ReactionStepShape) {
        // check if the ReactionStep already has a ReactionParticipant for
        // this SpeciesContext
        ReactionStep reactionStep = (ReactionStep) mouseOverShape.getModelObject();
        ReactionParticipant[] rps = reactionStep.getReactionParticipants();
        if (mouseOverShape instanceof SimpleReactionShape) {
            switch(mouseOverShape.getAttachmentFromAbs(worldPoint)) {
                case Shape.ATTACH_LEFT:
                    {
                        for (int i = 0; i < rps.length; i++) {
                            if (rps[i] instanceof Reactant && rps[i].getSpeciesContext() == speciesContext) {
                                return LineType.NULL;
                            }
                        }
                        return LineType.REACTANT;
                    }
                case Shape.ATTACH_CENTER:
                    {
                        for (int i = 0; i < rps.length; i++) {
                            if (rps[i] instanceof Catalyst && rps[i].getSpeciesContext() == speciesContext) {
                                return LineType.NULL;
                            }
                        }
                        return LineType.CATALYST;
                    }
                case Shape.ATTACH_RIGHT:
                    {
                        for (int i = 0; i < rps.length; i++) {
                            if (rps[i] instanceof Product && rps[i].getSpeciesContext() == speciesContext) {
                                return LineType.NULL;
                            }
                        }
                        return LineType.PRODUCT;
                    }
            }
        } else if (mouseOverShape instanceof FluxReactionShape) {
            switch(mouseOverShape.getAttachmentFromAbs(worldPoint)) {
                case Shape.ATTACH_LEFT:
                    {
                        // return LineType.FLUX;
                        for (int i = 0; i < rps.length; i++) {
                            if (rps[i] instanceof Reactant && rps[i].getSpeciesContext() == speciesContext) {
                                return LineType.NULL;
                            }
                        }
                        return LineType.REACTANT;
                    }
                case Shape.ATTACH_CENTER:
                    {
                        for (int i = 0; i < rps.length; i++) {
                            if (rps[i] instanceof Catalyst && rps[i].getSpeciesContext() == speciesContext) {
                                return LineType.NULL;
                            }
                        }
                        return LineType.CATALYST;
                    }
                case Shape.ATTACH_RIGHT:
                    {
                        for (int i = 0; i < rps.length; i++) {
                            // return LineType.FLUX;
                            if (rps[i] instanceof Product && rps[i].getSpeciesContext() == speciesContext) {
                                return LineType.NULL;
                            }
                        }
                        return LineType.PRODUCT;
                    }
            }
        }
    }
    return LineType.NULL;
}
Also used : SpeciesContextShape(cbit.vcell.graph.SpeciesContextShape) RubberBandRectShape(cbit.gui.graph.RubberBandRectShape) ProductShape(cbit.vcell.graph.ProductShape) ContainerShape(cbit.gui.graph.ContainerShape) CatalystShape(cbit.vcell.graph.CatalystShape) FluxReactionShape(cbit.vcell.graph.FluxReactionShape) ContainerContainerShape(cbit.vcell.graph.ContainerContainerShape) ReactantShape(cbit.vcell.graph.ReactantShape) ElipseShape(cbit.gui.graph.ElipseShape) SimpleReactionShape(cbit.vcell.graph.SimpleReactionShape) ReactionStepShape(cbit.vcell.graph.ReactionStepShape) ReactionContainerShape(cbit.vcell.graph.ReactionContainerShape) Shape(cbit.gui.graph.Shape) RuleParticipantSignatureDiagramShape(cbit.vcell.graph.RuleParticipantSignatureDiagramShape) ReactionRuleDiagramShape(cbit.vcell.graph.ReactionRuleDiagramShape) RubberBandEdgeShape(cbit.gui.graph.RubberBandEdgeShape) ReactionParticipantShape(cbit.vcell.graph.ReactionParticipantShape) ReactionStep(cbit.vcell.model.ReactionStep) SimpleReactionShape(cbit.vcell.graph.SimpleReactionShape) Product(cbit.vcell.model.Product) ReactionStepShape(cbit.vcell.graph.ReactionStepShape) ReactionParticipant(cbit.vcell.model.ReactionParticipant) Reactant(cbit.vcell.model.Reactant) Catalyst(cbit.vcell.model.Catalyst) Point(java.awt.Point) FluxReactionShape(cbit.vcell.graph.FluxReactionShape)

Example 10 with Catalyst

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

the class BioCartoonTool method pasteReactionSteps0.

/**
 * pasteReactionSteps0 : does the actual pasting. First called with a cloned model, to track issues. If user still wants to proceed, the paste
 * is performed on the original model.
 *
 * Insert the method's description here.
 * Creation date: (5/10/2003 3:55:25 PM)
 * @param pasteToModel cbit.vcell.model.Model
 * @param pasteToStructure cbit.vcell.model.Structure
 * @param bNew boolean
 */
private static final PasteHelper pasteReactionSteps0(HashMap<String, HashMap<ReactionParticipant, Structure>> rxPartMapStructure, Component parent, IssueContext issueContext, ReactionStep[] copyFromRxSteps, Model pasteToModel, Structure pasteToStructure, boolean bNew, /*boolean bUseDBSpecies,*/
UserResolvedRxElements userResolvedRxElements) throws Exception {
    HashMap<BioModelEntityObject, BioModelEntityObject> reactionsAndSpeciesContexts = new HashMap<>();
    if (copyFromRxSteps == null || copyFromRxSteps.length == 0 || pasteToModel == null || pasteToStructure == null) {
        throw new IllegalArgumentException("CartoonTool.pasteReactionSteps Error " + (copyFromRxSteps == null || copyFromRxSteps.length == 0 ? "reactionStepsArr empty " : "") + (pasteToModel == null ? "model is null " : "") + (pasteToStructure == null ? "struct is null " : ""));
    }
    if (!pasteToModel.contains(pasteToStructure)) {
        throw new IllegalArgumentException("CartoonTool.pasteReactionSteps model " + pasteToModel.getName() + " does not contain structure " + pasteToStructure.getName());
    }
    // Check PasteToModel has preferred targets if set
    if (userResolvedRxElements != null) {
        for (int i = 0; i < userResolvedRxElements.toSpeciesArr.length; i++) {
            if (userResolvedRxElements.toSpeciesArr[i] != null) {
                if (!pasteToModel.contains(userResolvedRxElements.toSpeciesArr[i])) {
                    throw new RuntimeException("PasteToModel does not contain preferred Species " + userResolvedRxElements.toSpeciesArr[i]);
                }
            }
            if (userResolvedRxElements.toStructureArr[i] != null) {
                if (!pasteToModel.contains(userResolvedRxElements.toStructureArr[i])) {
                    throw new RuntimeException("PasteToModel does not contain preferred Structure " + userResolvedRxElements.toStructureArr[i]);
                }
            }
        }
    }
    int counter = 0;
    Structure currentStruct = pasteToStructure;
    String copiedStructName = copyFromRxSteps[counter].getStructure().getName();
    StructureTopology structTopology = (copyFromRxSteps[counter].getModel() == null ? pasteToModel.getStructureTopology() : copyFromRxSteps[counter].getModel().getStructureTopology());
    IdentityHashMap<Species, Species> speciesHash = new IdentityHashMap<Species, Species>();
    IdentityHashMap<SpeciesContext, SpeciesContext> speciesContextHash = new IdentityHashMap<SpeciesContext, SpeciesContext>();
    Vector<Issue> issueVector = new Vector<Issue>();
    do {
        // create a new reaction, instead of cloning the old one; set struc
        ReactionStep copyFromReactionStep = copyFromRxSteps[counter];
        String newName = copyFromReactionStep.getName();
        while (pasteToModel.getReactionStep(newName) != null) {
            newName = org.vcell.util.TokenMangler.getNextEnumeratedToken(newName);
        }
        ReactionStep newReactionStep = null;
        if (copyFromReactionStep instanceof SimpleReaction) {
            newReactionStep = new SimpleReaction(pasteToModel, currentStruct, newName, copyFromReactionStep.isReversible());
        } else if (copyFromReactionStep instanceof FluxReaction && currentStruct instanceof Membrane) {
            newReactionStep = new FluxReaction(pasteToModel, (Membrane) currentStruct, null, newName, copyFromReactionStep.isReversible());
        }
        pasteToModel.addReactionStep(newReactionStep);
        reactionsAndSpeciesContexts.put(newReactionStep, copyFromReactionStep);
        Structure toRxnStruct = newReactionStep.getStructure();
        Structure fromRxnStruct = copyFromReactionStep.getStructure();
        if (!fromRxnStruct.getClass().equals(pasteToStructure.getClass())) {
            throw new Exception("Cannot copy reaction from " + fromRxnStruct.getTypeName() + " to " + pasteToStructure.getTypeName() + ".");
        }
        // add appropriate reactionParticipants to newReactionStep.
        StructureTopology toStructureTopology = pasteToModel.getStructureTopology();
        ReactionParticipant[] copyFromRxParticipantArr = copyFromReactionStep.getReactionParticipants();
        if (rxPartMapStructure == null) {
            // null during 'issues' trial
            rxPartMapStructure = new HashMap<String, HashMap<ReactionParticipant, Structure>>();
        }
        if (rxPartMapStructure.get(copyFromReactionStep.getName()) == null) {
            // Ask user to assign species to compartments for each reaction to be pasted
            rxPartMapStructure.put(copyFromReactionStep.getName(), askUserResolveMembraneConnections(parent, pasteToModel.getStructures(), currentStruct, fromRxnStruct, toRxnStruct, copyFromRxParticipantArr, toStructureTopology, structTopology));
        }
        for (int i = 0; i < copyFromRxParticipantArr.length; i += 1) {
            Structure pasteToStruct = currentStruct;
            // if(toRxnStruct instanceof Membrane){
            pasteToStruct = rxPartMapStructure.get(copyFromReactionStep.getName()).get(copyFromRxParticipantArr[i]);
            // if(pasteToStruct == null){
            // for(ReactionParticipant myRXPart:rxPartMapStructure.get(copyFromReactionStep.getName()).keySet()){
            // if(myRXPart.getSpeciesContext().getName().equals(copyFromRxParticipantArr[i].getSpeciesContext().getName())){
            // pasteToStruct = rxPartMapStructure.get(copyFromReactionStep.getName()).get(myRXPart);
            // break;
            // }
            // }
            // }
            // }
            // this adds the speciesContexts and species (if any) to the model)
            String rootSC = ReactionCartoonTool.speciesContextRootFinder(copyFromRxParticipantArr[i].getSpeciesContext());
            SpeciesContext newSc = null;
            SpeciesContext[] matchSC = pasteToModel.getSpeciesContexts();
            for (int j = 0; matchSC != null && j < matchSC.length; j++) {
                String matchRoot = ReactionCartoonTool.speciesContextRootFinder(matchSC[j]);
                if (matchRoot != null && matchRoot.equals(rootSC) && matchSC[j].getStructure().getName().equals(pasteToStruct.getName())) {
                    newSc = matchSC[j];
                    reactionsAndSpeciesContexts.put(newSc, matchSC[j]);
                    break;
                }
            }
            if (newSc == null) {
                newSc = pasteSpecies(parent, copyFromRxParticipantArr[i].getSpecies(), rootSC, pasteToModel, pasteToStruct, bNew, /*bUseDBSpecies,*/
                speciesHash, UserResolvedRxElements.getPreferredReactionElement(userResolvedRxElements, copyFromRxParticipantArr[i]));
                reactionsAndSpeciesContexts.put(newSc, copyFromRxParticipantArr[i].getSpeciesContext());
            }
            // record the old-new speciesContexts (reactionparticipants) in the IdHashMap, this is useful, esp for 'Paste new', while replacing proxyparams.
            SpeciesContext oldSc = copyFromRxParticipantArr[i].getSpeciesContext();
            if (speciesContextHash.get(oldSc) == null) {
                speciesContextHash.put(oldSc, newSc);
            }
            if (copyFromRxParticipantArr[i] instanceof Reactant) {
                newReactionStep.addReactionParticipant(new Reactant(null, newReactionStep, newSc, copyFromRxParticipantArr[i].getStoichiometry()));
            } else if (copyFromRxParticipantArr[i] instanceof Product) {
                newReactionStep.addReactionParticipant(new Product(null, newReactionStep, newSc, copyFromRxParticipantArr[i].getStoichiometry()));
            } else if (copyFromRxParticipantArr[i] instanceof Catalyst) {
                newReactionStep.addCatalyst(newSc);
            }
        }
        // // If 'newReactionStep' is a fluxRxn, set its fluxCarrier
        // if (newReactionStep instanceof FluxReaction) {
        // if (fluxCarrierSp != null) {
        // ((FluxReaction)newReactionStep).setFluxCarrier(fluxCarrierSp, pasteToModel);
        // } else {
        // throw new RuntimeException("Could not set FluxCarrier species for the flux reaction to be pasted");
        // }
        // }
        // For each kinetic parameter expression for new kinetics, replace the proxyParams from old kinetics with proxyParams in new kinetics
        // i.e., if the proxyParams are speciesContexts, replace with corresponding speciesContext in newReactionStep;
        // if the proxyParams are structureSizes or MembraneVoltages, replace with corresponding structure quantity in newReactionStep
        Kinetics oldKinetics = copyFromReactionStep.getKinetics();
        KineticsParameter[] oldKps = oldKinetics.getKineticsParameters();
        KineticsProxyParameter[] oldKprps = oldKinetics.getProxyParameters();
        Hashtable<String, Expression> paramExprHash = new Hashtable<String, Expression>();
        for (int i = 0; oldKps != null && i < oldKps.length; i++) {
            Expression newExpression = new Expression(oldKps[i].getExpression());
            for (int j = 0; oldKprps != null && j < oldKprps.length; j++) {
                // check if kinetic proxy parameter is in kinetic parameter expression
                if (newExpression.hasSymbol(oldKprps[j].getName())) {
                    SymbolTableEntry ste = oldKprps[j].getTarget();
                    Model pasteFromModel = copyFromReactionStep.getModel();
                    if (ste instanceof SpeciesContext) {
                        // if newRxnStruct is a feature/membrane, get matching spContexts from old reaction and replace them in new rate expr.
                        SpeciesContext oldSC = (SpeciesContext) ste;
                        SpeciesContext newSC = speciesContextHash.get(oldSC);
                        if (newSC == null) {
                            // check if oldSc is present in paste-model; if not, add it.
                            if (!pasteToModel.equals(pasteFromModel)) {
                                if (pasteToModel.getSpeciesContext(oldSC.getName()) == null) {
                                    // if paste-model has oldSc struct, paste it there,
                                    Structure newSCStruct = pasteToModel.getStructure(oldSC.getStructure().getName());
                                    if (newSCStruct != null) {
                                        newSC = pasteSpecies(parent, oldSC.getSpecies(), null, pasteToModel, newSCStruct, bNew, /*bUseDBSpecies,*/
                                        speciesHash, UserResolvedRxElements.getPreferredReactionElement(userResolvedRxElements, oldSC));
                                        speciesContextHash.put(oldSC, newSC);
                                    } else {
                                        // oldStruct wasn't found in paste-model, paste it in newRxnStruct and add warning to issues list
                                        newSC = pasteSpecies(parent, oldSC.getSpecies(), null, pasteToModel, toRxnStruct, bNew, /*bUseDBSpecies,*/
                                        speciesHash, UserResolvedRxElements.getPreferredReactionElement(userResolvedRxElements, oldSC));
                                        speciesContextHash.put(oldSC, newSC);
                                        Issue issue = new Issue(oldSC, issueContext, IssueCategory.CopyPaste, "SpeciesContext '" + oldSC.getSpecies().getCommonName() + "' was not found in compartment '" + oldSC.getStructure().getName() + "' in the model; the species was added to the compartment '" + toRxnStruct.getName() + "' where the reaction was pasted.", Issue.SEVERITY_WARNING);
                                        issueVector.add(issue);
                                    }
                                }
                            }
                        // if models are the same and newSc is null, then oldSc is not a rxnParticipant. Leave it as is in the expr.
                        }
                        if (newSC != null) {
                            reactionsAndSpeciesContexts.put(newSC, oldSC);
                            newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(newSC.getName()));
                        }
                    // SpeciesContext sc = null;
                    // Species newSp = model.getSpecies(oldSc.getSpecies().getCommonName());
                    // if  (oldSc.getStructure() == (oldRxnStruct)) {
                    // sc = model.getSpeciesContext(newSp, newRxnStruct);
                    // } else {
                    // if (newRxnStruct instanceof Membrane) {
                    // // for a membrane, we need to make sure that inside-outside spContexts used are appropriately replaced.
                    // if (oldSc.getStructure() == ((Membrane)oldRxnStruct).getOutsideFeature()) {
                    // // old speciesContext is outside (old) membrane, new spContext should be outside new membrane
                    // sc = model.getSpeciesContext(newSp, ((Membrane)newRxnStruct).getOutsideFeature());
                    // } else if (oldSc.getStructure() == ((Membrane)oldRxnStruct).getInsideFeature()) {
                    // // old speciesContext is inside (old) membrane, new spContext should be inside new membrane
                    // sc = model.getSpeciesContext(newSp, ((Membrane)newRxnStruct).getInsideFeature());
                    // }
                    // }
                    // }
                    // if (sc != null) {
                    // newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(sc.getName()));
                    // }
                    } else if (ste instanceof StructureSize) {
                        Structure str = ((StructureSize) ste).getStructure();
                        // if the structure size used is same as the structure in which the reaction is present, change the structSize to appropriate new struct
                        if (str.compareEqual(fromRxnStruct)) {
                            newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(toRxnStruct.getStructureSize().getName()));
                        } else {
                            if (fromRxnStruct instanceof Membrane) {
                                if (str.equals(structTopology.getOutsideFeature((Membrane) fromRxnStruct))) {
                                    newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(structTopology.getOutsideFeature((Membrane) toRxnStruct).getStructureSize().getName()));
                                } else if (str.equals(structTopology.getInsideFeature((Membrane) fromRxnStruct))) {
                                    newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(structTopology.getInsideFeature((Membrane) toRxnStruct).getStructureSize().getName()));
                                }
                            }
                        }
                    } else if (ste instanceof MembraneVoltage) {
                        Membrane membr = ((MembraneVoltage) ste).getMembrane();
                        // if the MembraneVoltage used is same as that of the membrane in which the reaction is present, change the MemVoltage
                        if ((fromRxnStruct instanceof Membrane) && (membr.compareEqual(fromRxnStruct))) {
                            newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(((Membrane) toRxnStruct).getMembraneVoltage().getName()));
                        }
                    } else if (ste instanceof ModelParameter) {
                        // see if model has this global parameter (if rxn is being pasted into another model, it won't)
                        if (!pasteToModel.equals(pasteFromModel)) {
                            ModelParameter oldMp = (ModelParameter) ste;
                            ModelParameter mp = pasteToModel.getModelParameter(oldMp.getName());
                            boolean bNonNumeric = false;
                            String newMpName = oldMp.getName();
                            if (mp != null) {
                                // new model has a model parameter with same name - are they the same param?
                                if (!mp.getExpression().equals(oldMp.getExpression())) {
                                    // no, they are not the same param, so mangle the 'ste' name and add as global in the other model
                                    while (pasteToModel.getModelParameter(newMpName) != null) {
                                        newMpName = TokenMangler.getNextEnumeratedToken(newMpName);
                                    }
                                    // if expression if numeric, add it as such. If not, set it to 0.0 and add it as global
                                    Expression exp = oldMp.getExpression();
                                    if (!exp.flatten().isNumeric()) {
                                        exp = new Expression(0.0);
                                        bNonNumeric = true;
                                    }
                                    ModelParameter newMp = pasteToModel.new ModelParameter(newMpName, exp, Model.ROLE_UserDefined, oldMp.getUnitDefinition());
                                    String annotation = "Copied from model : " + pasteFromModel.getNameScope();
                                    newMp.setModelParameterAnnotation(annotation);
                                    pasteToModel.addModelParameter(newMp);
                                    // if global param name had to be changed, make sure newExpr is updated as well.
                                    if (!newMpName.equals(oldMp.getName())) {
                                        newExpression.substituteInPlace(new Expression(oldMp.getName()), new Expression(newMpName));
                                    }
                                }
                            } else {
                                // no global param with same name was found in other model, so add it to other model.
                                // if expression if numeric, add it as such. If not, set it to 0.0 and add it as global
                                Expression exp = oldMp.getExpression();
                                if (!exp.flatten().isNumeric()) {
                                    exp = new Expression(0.0);
                                    bNonNumeric = true;
                                }
                                ModelParameter newMp = pasteToModel.new ModelParameter(newMpName, exp, Model.ROLE_UserDefined, oldMp.getUnitDefinition());
                                String annotation = "Copied from model : " + pasteFromModel.getNameScope();
                                newMp.setModelParameterAnnotation(annotation);
                                pasteToModel.addModelParameter(newMp);
                            }
                            // if a non-numeric parameter was encountered in the old model, it was added as a numeric (0.0), warn user of change.
                            if (bNonNumeric) {
                                Issue issue = new Issue(oldMp, issueContext, IssueCategory.CopyPaste, "Global parameter '" + oldMp.getName() + "' was non-numeric; it has been added " + "as global parameter '" + newMpName + "' in the new model with value = 0.0. " + "Please update its value, if required, before using it.", Issue.SEVERITY_WARNING);
                                issueVector.add(issue);
                            }
                        }
                    }
                }
            // end - if newExpr.hasSymbol(ProxyParam)
            }
            // now if store <param names, new expression> in hashTable
            if (paramExprHash.get(oldKps[i].getName()) == null) {
                paramExprHash.put(oldKps[i].getName(), newExpression);
            }
        }
        // end for - oldKps (old kinetic parameters)
        // use this new expression to generate 'vcml' for the (new) kinetics (easier way to transfer all kinetic parameters)
        String newKineticsStr = oldKinetics.writeTokensWithReplacingProxyParams(paramExprHash);
        // convert the kinetics 'vcml' to tokens.
        CommentStringTokenizer kineticsTokens = new CommentStringTokenizer(newKineticsStr);
        // skip the first token;
        kineticsTokens.nextToken();
        // second token is the kinetic type; use this to create a dummy kinetics
        String kineticType = kineticsTokens.nextToken();
        Kinetics newkinetics = KineticsDescription.fromVCMLKineticsName(kineticType).createKinetics(newReactionStep);
        // use the remaining tokens to construct the new kinetics
        newkinetics.fromTokens(newKineticsStr);
        // bind newkinetics to newReactionStep and add it to newReactionStep
        newkinetics.bind(newReactionStep);
        newReactionStep.setKinetics(newkinetics);
        counter += 1;
        if (counter == copyFromRxSteps.length) {
            break;
        }
        if (!copiedStructName.equals(fromRxnStruct.getName())) {
            if (currentStruct instanceof Feature) {
                currentStruct = structTopology.getMembrane((Feature) currentStruct);
            } else if (currentStruct instanceof Membrane) {
                currentStruct = structTopology.getInsideFeature((Membrane) currentStruct);
            }
        }
        copiedStructName = fromRxnStruct.getName();
    } while (true);
    return new PasteHelper(issueVector, rxPartMapStructure, reactionsAndSpeciesContexts);
}
Also used : Issue(org.vcell.util.Issue) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) IdentityHashMap(java.util.IdentityHashMap) Product(cbit.vcell.model.Product) FluxReaction(cbit.vcell.model.FluxReaction) SpeciesContext(cbit.vcell.model.SpeciesContext) Reactant(cbit.vcell.model.Reactant) Feature(cbit.vcell.model.Feature) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) Membrane(cbit.vcell.model.Membrane) Structure(cbit.vcell.model.Structure) Species(cbit.vcell.model.Species) Vector(java.util.Vector) SimpleReaction(cbit.vcell.model.SimpleReaction) KineticsProxyParameter(cbit.vcell.model.Kinetics.KineticsProxyParameter) StructureTopology(cbit.vcell.model.Model.StructureTopology) Hashtable(java.util.Hashtable) BioModelEntityObject(cbit.vcell.model.BioModelEntityObject) StructureSize(cbit.vcell.model.Structure.StructureSize) PropertyVetoException(java.beans.PropertyVetoException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ModelException(cbit.vcell.model.ModelException) UserCancelException(org.vcell.util.UserCancelException) ModelParameter(cbit.vcell.model.Model.ModelParameter) Expression(cbit.vcell.parser.Expression) MembraneVoltage(cbit.vcell.model.Membrane.MembraneVoltage) ReactionStep(cbit.vcell.model.ReactionStep) Model(cbit.vcell.model.Model) CommentStringTokenizer(org.vcell.util.CommentStringTokenizer) Kinetics(cbit.vcell.model.Kinetics) ReactionParticipant(cbit.vcell.model.ReactionParticipant) Catalyst(cbit.vcell.model.Catalyst)

Aggregations

Catalyst (cbit.vcell.model.Catalyst)19 ReactionParticipant (cbit.vcell.model.ReactionParticipant)14 Product (cbit.vcell.model.Product)10 Reactant (cbit.vcell.model.Reactant)10 ReactionStep (cbit.vcell.model.ReactionStep)9 FluxReaction (cbit.vcell.model.FluxReaction)7 SimpleReaction (cbit.vcell.model.SimpleReaction)7 SpeciesContext (cbit.vcell.model.SpeciesContext)7 Expression (cbit.vcell.parser.Expression)6 KineticsParameter (cbit.vcell.model.Kinetics.KineticsParameter)5 Structure (cbit.vcell.model.Structure)5 Shape (cbit.gui.graph.Shape)4 Feature (cbit.vcell.model.Feature)4 Membrane (cbit.vcell.model.Membrane)4 ExpressionException (cbit.vcell.parser.ExpressionException)4 Point (java.awt.Point)4 ArrayList (java.util.ArrayList)4 ModelParameter (cbit.vcell.model.Model.ModelParameter)3 VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)3 UserCancelException (org.vcell.util.UserCancelException)3