[Bio] / ModelEditor / RecoElempanel.py Repository:
ViewVC logotype

View of /ModelEditor/RecoElempanel.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.19 - (download) (as text) (annotate)
Tue Jan 17 17:12:47 2006 UTC (13 years, 7 months ago) by efrank
Branch: MAIN
CVS Tags: lwc, HEAD
Changes since 1.18: +24 -23 lines
persistence for dynamics stuff
bunch of flux modelinig stuff including flux model building in modeleditor

from ModelEditor.DoubleTextEntryDialog import DoubleTextEntryDialog
from ModelEditor.DynParamsDialog import DynParamsDialog
from ModelEditor.GloParamsDialog import GloParamsDialog
from ModelEditor.RunSpecieInfoDialog import RunSpecieInfoDialog
import copy
from wxPython.wx         import *
from KahApp.KahConfigMgr import KahConfigMgr
from FaST.BssFactory     import BssFactory
from KahOM.RecoElem      import RecoElem
from KahOM.Model         import Model
from KahOM.RxDynAssoc    import RxDynAssoc
import os

from MeSharedEditServer  import putOnClipboard
from MeSharedEditServer  import getCbDescriptor
from KahDataServices.ModelFromText  import doModelFromText

#------------------------------------------------------------------------
class TreeData:
#------------------------------------------------------------------------
    """
    TreeData instances are associated with wxTree nodes via
    SetPyData(). TreeData is just a struct to keep us sane
    when fetching things back. It holds a RecoElem and the
    CatalogEntry that owns it.
    """

    def __init__(self, itemId, model, aRecoElem, aCatalogEntry):
        self.model    = model
        self.re       = aRecoElem
        self.ce       = aCatalogEntry
        self.itemId   = itemId
        return

        


#------------------------------------------------------------------------
class RecoElempanel:
#------------------------------------------------------------------------
    #------------------------------------------------------------------
    def __init__(self, parent):
    #------------------------------------------------------------------
        self.selectedItem    = None      # last thing selected. Instance of TreeItem
        self.cutOrCopiedRx         = None
        self.cutOrCopiedTreeData   = None # ref to TreeData instance
        self._pluginDict      = {}        # used to dispatch calls to plugins.
        self.parent = parent

        self.parent.rootId = self.parent.tree_ctr.AddRoot("top item")

 
        #set up menu for editing recoelem
        self.recoElemEditMenu = wxMenu()
        self.recoElemNewKidId = wxNewId()
        self.recoElemCopyREBranchId = wxNewId()
        self.recoElemCutREBranchId = wxNewId()
        self.recoElemDelREChildrenId = wxNewId()
        self.recoElemPasteREBranchId = wxNewId()
        self.recoElemMergeREBranchId = wxNewId()

        self.recoElemPasteRxId = wxNewId()
        self.recoElemPasteFromSelectedRxGridId = wxNewId()
        self.recoElemAppendFromTextFileId = wxNewId()
        self.recoElemVizWithCytoScapeId = wxNewId()
        self.recoElemWriteToBssId = wxNewId()

        self.recoElemWriteToCbId= wxNewId()
        self.recoElemEditParamsId = wxNewId()
        self.recoElemSetRunSpeciesInfoId = wxNewId()
        self.setupRecoElemEditMenu()

        #set up menu for list
        self.recoElemRxListEditMenu = wxMenu()
        self.recoElemRxListCutId = wxNewId()
        self.recoElemRxListCopyId = wxNewId()
        self.recoElemRxListPasteId = wxNewId()
        self.recoElemRxListAddDynId = wxNewId()
        self.setupRecoElemRxListEditMenu()

        self.initEvents()
        return

    #------------------------------------------------------------------
    def initEvents(self):
    #------------------------------------------------------------------

        #button1= self.parent.OK_button
        # select in list of reactions
        EVT_LISTBOX(self.parent, self.parent.list_box.GetId(),
                    self.onSelectReaction)

        # hit the button that loads a RecoElem id
        #EVT_BUTTON(self.parent, button1.GetId(), self.ID_NUM)

        # select in tree
        EVT_TREE_SEL_CHANGED(self.parent.tree_ctr, 
                             self.parent.tree_ctr.GetId(), self.onSelect)

        # Right click on tree (presumably after selection)
        EVT_RIGHT_DOWN(self.parent.tree_ctr, self.rightTreeClick)

        # Right click on List (presumably after selection)
        EVT_RIGHT_DOWN(self.parent.list_box, self.onRightListClick)

        # this does not work for some reason.
        #EVT_LISTBOX(self.parent.list_box, self.parent.list_box.GetId(),
        #  self.onRightListClick)
        
        
        return


    #------------------------------------------------------------------
    def addRecoElemTree( self, treeItemId, aModel, aRecoElem, aCatalogEntry ):
    #------------------------------------------------------------------
        """
        @type treeItemId:  wx tree item id
        @type aModel:      KahOM.Model
        @type aRecoElem:   KahOM.RecoElem
        @type aCatalogEntry: CatalogServices.CatalogEntry

        Attach aRecoElem at node treeItemId, recording the catalogEntry.
        Also, recursively attach all childern AND force all children to
        have the same catalogEntry and same Model.
        """
        
        itemLabel = ""
        
        if (treeItemId == self.parent.rootId):
            if (aCatalogEntry == None):
                #it's a clipboard item.  just use the model name as label.
                itemLabel = aModel.getName()
            else:
                #itemLabel = aCatalogEntry.factory.getFoundryName()+"::"
                itemLabel = aCatalogEntry.path()+ "::"
        
        numrx= aRecoElem.nReactions()
        if numrx > 0:
            itemLabel += "(" + str(numrx) + "rx"+ ") " + aRecoElem.getName()
        else:
            itemLabel += aRecoElem.getName()

        itemId=self.parent.tree_ctr.AppendItem(treeItemId, itemLabel )
        self.parent.tree_ctr.SetPyData(itemId,
                                       TreeData( itemId, aModel, aRecoElem, aCatalogEntry))
        
        for kid in aRecoElem.getRawSubElems():
            self.addRecoElemTree( itemId, aModel, kid, aCatalogEntry )
            
        return itemId

    #------------------------------------------------------------------
    def onSelectReaction(self,event):
    #------------------------------------------------------------------
        return

        pt=self.parent.list_box.GetPosition()
        item =self.parent.list_box.HitTest(pt)

        selectedlist=self.parent.list_box.GetSelections()

        for count in selectedlist:
            rx = self.parent.list_boxData[count]

        return

    #------------------------------------------------------------------
    def onSelect(self, treeEvent):
    #------------------------------------------------------------------
        item = treeEvent.GetItem()
        d    = self.parent.tree_ctr.GetPyData(item)
        if (None==d):
            print "RecoElemPanel::onSelect PyData=None error"
            return
            
        re = d.re
        self.selectedItem=item
      
        self.redrawRecoElemRxList( re, d.model )
        return

    #------------------------------------------------------------------
    def redrawRecoElemRxList(self, re, m):
    #------------------------------------------------------------------
        """
        @type re: KahOM.RecoElem
        @type m: KahOM.Model
        @rtype: none
        """
        wxBeginBusyCursor()
        self.parent.list_box.Clear()
        offset = 0
        self.parent.list_boxData.clear()
        for rx in re.getRawReactions():
            #item = rx.asString()

            #
            rxDynAssoc = m.getRxDynAssoc()
            try:
                dyn = rxDynAssoc.getDyn( rx )
                dynName= "[" + dyn.__module__ + "] "
            except KeyError:
                dynName= "[No Dyn] "                

            item = dynName + rx.asString()
            #
            listnum = self.parent.list_box.Append(item)
            itemNo =  self.parent.list_box.GetCount()-1
            # we store the recoElem ptr too in case we have to rm the rx
            self.parent.list_boxData[itemNo] = (rx, offset, re, m)
            offset += 1
           
        wxEndBusyCursor()

        return

    #------------------------------------------------------------------
    def onRightListClick( self, event):
    #------------------------------------------------------------------
                
        listBoxObject = event.GetEventObject()
        listBoxObject.PopupMenu(self.recoElemRxListEditMenu, event.GetPosition())
        
        return
    
    #------------------------------------------------------------------
    def setupRecoElemRxListEditMenu(self):
    #------------------------------------------------------------------
        self.recoElemRxListEditMenu.Append( self.recoElemRxListCutId, 
                                          "Cut", "Cut" )
        EVT_MENU(self.parent, self.recoElemRxListCutId, self.recoElemRxListCut)
        

        self.recoElemRxListEditMenu.Append( self.recoElemRxListCopyId,
                                          "Copy","Copy")
        EVT_MENU(self.parent, self.recoElemRxListCopyId,self.recoElemRxListCopy)
        self.recoElemRxListEditMenu.Append( self.recoElemRxListPasteId,
                                          "Paste", "Paste")
        EVT_MENU(self.parent, self.recoElemRxListPasteId,
                 self.recoElemRxListPaste)
        self.recoElemRxListEditMenu.Append( self.recoElemPasteFromSelectedRxGridId,
                                            "Paste From Selected Rx Table", 
                                            "Paste From Selected Rx Table")
        EVT_MENU(self.parent, self.recoElemPasteFromSelectedRxGridId,
                 self.recoElemPasteFromSelectedRxGrid)
        self.recoElemRxListEditMenu.Append( self.recoElemRxListAddDynId,
                                            "Edit Dynamics For Rx",
                                            "Edit Dynamics For Rx")
        EVT_MENU(self.parent, self.recoElemRxListAddDynId,
                 self.recoElemRxListAddDyn)

        return

    #------------------------------------------------------------------
    def rightTreeClick( self, event):
    #------------------------------------------------------------------
        #pt=event.GetPosition()
        #if self.selectedItem != None:
        if 1:
            treeObject = event.GetEventObject()
            treeObject.PopupMenu(self.recoElemEditMenu, event.GetPosition() )

        return
    
    #------------------------------------------------------------------
    def setupRecoElemEditMenu(self):
    #------------------------------------------------------------------
        self.recoElemEditMenu.Append( self.recoElemNewKidId,
                                      "New Sub Element", "New kid arg3" )
        EVT_MENU(self.parent, self.recoElemNewKidId, self.recoElemNewKid)
        #
        self.recoElemEditMenu.Append( self.recoElemCopyREBranchId,
                                      "Copy Tree Branch", "Copy Tree Branch" )
        EVT_MENU(self.parent, self.recoElemCopyREBranchId, self.recoElemCopyREBranch)
        #
        self.recoElemEditMenu.Append( self.recoElemCutREBranchId,
                                      "Cut Tree Branch", "Cut Tree Branch" )
        EVT_MENU(self.parent, self.recoElemCutREBranchId, self.recoElemCutREBranch)
        #
        self.recoElemEditMenu.Append( self.recoElemDelREChildrenId,
                                      "Delete all children", "Delete all children")
        EVT_MENU(self.parent, self.recoElemDelREChildrenId,
                 self.recoElemDelREChildren)
        #
        self.recoElemEditMenu.Append( self.recoElemPasteREBranchId,
                                      "Paste Tree Branch", "Paste Tree Branch" )
        EVT_MENU(self.parent, self.recoElemPasteREBranchId, self.recoElemPasteREBranch)

        self.recoElemEditMenu.Append( self.recoElemMergeREBranchId,
                                      "Merge into Tree Branch",
                                      "Merge into Tree Branch" )
        EVT_MENU(self.parent, self.recoElemMergeREBranchId, self.recoElemMergeREBranch)

        self.recoElemEditMenu.Append( self.recoElemEditParamsId,
                                      "Set Global Parameters",
                                      "Set Global Parameters")
        EVT_MENU(self.parent, self.recoElemEditParamsId, self.editParams)
        
        self.recoElemEditMenu.Append( self.recoElemSetRunSpeciesInfoId,
                                      "Set per Species info for a Run",
                                      "Set per Species info for a Run")
        EVT_MENU(self.parent, self.recoElemSetRunSpeciesInfoId, self.setRunSpeciesInfo)
        #
        # Rx related
        #

        #
        self.recoElemEditMenu.AppendSeparator()
        #

        self.recoElemEditMenu.Append( self.recoElemPasteRxId,
                                      "Paste Rx", "Add kid arg3" )
        EVT_MENU(self.parent, self.recoElemPasteRxId, self.recoElemPasteRx)
        #
        self.recoElemEditMenu.Append( self.recoElemPasteFromSelectedRxGridId,
                                      "Paste From Selected Rx Table", 
                                      "Paste From Selected Rx Table")
        EVT_MENU(self.parent, self.recoElemPasteFromSelectedRxGridId,
                 self.recoElemPasteFromSelectedRxGrid)
        #
        self.recoElemEditMenu.AppendSeparator()
        #

        self.recoElemEditMenu.Append( self.recoElemAppendFromTextFileId,
                                      "Append from text file",
                                      "Append from text file")
        EVT_MENU(self.parent, self.recoElemAppendFromTextFileId,
                 self.recoElemAppendFromTextFile)

        self.recoElemEditMenu.Append( self.recoElemWriteToBssId,
                                      "Write new version",
                                      "Write new version")
        EVT_MENU(self.parent, self.recoElemWriteToBssId,
                 self.recoElemWriteToBss)
        

        #
        # Shared editing
        
        self.recoElemEditMenu.AppendSeparator()
        self.recoElemEditMenu.Append( self.recoElemWriteToCbId,
                                      "Copy Branch to shared clipboard",
                                      "Copy Branch to shared clipboard")
        EVT_MENU(self.parent, self.recoElemWriteToCbId, self.recoElemWriteToCb)
        

        #
        # plug-ins will be added beyond here via extendRecoElemEditMenu.
        #

        self.recoElemEditMenu.AppendSeparator()

        """
        self.recoElemEditMenu.Append( self.recoElemVizWithCytoScapeId,
                                      "Visualize in CytoScape",
                                      "Visualize in CytoScape")
        EVT_MENU(self.parent, self.recoElemVizWithCytoScapeId,
                 self.recoElemVizWithCytoScape)
        """
                                      
        return

    #------------------------------------------------------------------
    def extendRecoElemEditMenu(self, menuText, helpText,  theModule):
    #------------------------------------------------------------------
        """
        Used for plugins.  Adds them to the RecoElemEditMenu

        @type menuText: string   The text to be shown in the menu.
        @type helpText: string   The help text for the item.
        @type theModule:  Instance of KahModule
        """

        # is there already a module with this name?  Name must be unique.
        #

        mgr       = self.parent.getConfigMgr()

        try:
            cfg = mgr.getSection( theModule.name() )
            self.parent.error("extendRecoelemEditMenu: Already have a module with name %s. Abort loading new plugin." % theModule.name())
            return
        except KeyError:
            pass
            
        # Make new menu item
        #

        theNewId = wxNewId()
        self._pluginDict[theNewId] = theModule

        # Configure the new module.  Don't reread config script...just
        # allows its values to be used.

        try:
            cfg = mgr.newSection( theModule.name() )
        except ValueError:
            # should never get here....
            self.parent.error( "extendRecoelemEditMenu: program error.")
            return

        theModule.config( cfg )
        mgr.redoOverrides()

        #
        self.recoElemEditMenu.Append( theNewId, menuText, helpText )
        EVT_MENU(self.parent, theNewId, self.pluginHandler)

        return
    
    #------------------------------------------------------------------
    def pluginHandler(self, event):
    #------------------------------------------------------------------
        """
        Dispatches a wxCommandEvent that arose from an EVT_MENU
        registration to the actual plugin.
        """

        if (self.selectedItem == None):
            self.parent.error( "Select a RecoElem first" )
            return
        
        # form the arg list to the plugin

        treeData = self.parent.tree_ctr.GetPyData( self.selectedItem)
        re    = treeData.re
        model = treeData.model

        ##
        # find and call the plugin
        #
        # this is a little wonky right now.  we'r exposing the execution
        # rules and have the config file hardwired.  its a start.  don't
        # copy this code.
        ##

        theModule = self._pluginDict[ event.GetId() ]
        mgr       = self.parent.getConfigMgr()
        cfg       = mgr.getSection( theModule.name() )
        theModule.process( model, re, cfg )
        theModule.finish( cfg )

        # the plugin may have changed the recoelem, so we have to
        # bring the display up to date.  this is really inefficient,
        # but we're going to destroy everything for the recoelem
        # and rebuilt from scratch to make sure we get it right.
        
        id       = treeData.itemId
        parentId = self.parent.tree_ctr.GetItemParent( id )

        self.parent.tree_ctr.DeleteChildren( id )
        self.parent.tree_ctr.Delete( id )
        #parentId = self.parent.tree_ctr.GetItemParent( id )

        newId = self.addRecoElemTree( parentId, treeData.model, re, treeData.ce )

        self.parent.tree_ctr.SelectItem( newId )

        return

    #------------------------------------------------------------------
    def updateTreeBranchText(self, sourceRXNum, recoElemName):
    #------------------------------------------------------------------

        rxPrevName = self.parent.tree_ctr.GetItemText(self.selectedItem)
        newLabel = "(" + str(sourceRXNum) + "rx" ") " + recoElemName

        #sylistic purposes get rid of (0 rx) if it exist
        if newLabel[1] == '0':
            newLabel = newLabel[6:]
        

        self.parent.tree_ctr.SetItemText(self.selectedItem, newLabel)
        return
    
    #------------------------------------------------------------------
    def recoElemNewKid(self, event):
    #------------------------------------------------------------------
        if (self.selectedItem == None): return
        treeData = self.parent.tree_ctr.GetPyData( self.selectedItem)
        re = treeData.re
        
        prompt = "Name of new child for " + re.getName()
        dlg = wxTextEntryDialog(self.parent, message=prompt, style=wxOK)

        if ( dlg.ShowModal() == wxID_OK):
            kidName = dlg.GetValue()
            if ( kidName=="" ): return
            dlg.Destroy()
        else:
            #didn't get a kid name
            dlg.Destroy()
            return

        newKid = RecoElem( kidName )
        re.appendSubElems( newKid )
        self.addRecoElemTree( self.selectedItem, treeData.model, newKid, treeData.ce)
        
        return
    
    #------------------------------------------------------------------
    def __setCutCopyBuffer(self, treeItem):
    #------------------------------------------------------------------
        """
        Used for cut/copy and paste.  Upon cut/copy, stash a reference
        to the treeData instance of that tree item.  Pull back later
        via getTreeDataRef.  Note: we keep a reference, not a copy.

        @type treeItem: wxTreeItem
        @rtype: None
        """

        self.cutOrCopiedTreeData = self.parent.tree_ctr.GetPyData( treeItem )

        return

    #------------------------------------------------------------------
    def __getCutCopyBuffer(self):
    #------------------------------------------------------------------
        """
        Used for cut/copy and paste.  Upon cut/copy, stash a reference
        to the treeData instance of that tree item.  Pull back later
        via getTreeDataRef.  Note: we keep a reference, not a copy.
        """

        return self.cutOrCopiedTreeData

    #------------------------------------------------------------------
    def recoElemCopyREBranch(self, event):
    #------------------------------------------------------------------

        if (self.selectedItem == None): return
        self.__setCutCopyBuffer(self.selectedItem)

        return

    #------------------------------------------------------------------
    def recoElemCutREBranch(self, event):
    #------------------------------------------------------------------
        if (self.selectedItem == None): return
        
        # first, squirrel away a copy of the associated TreeData
        # in case someone later wants a paste

        self.__setCutCopyBuffer(self.selectedItem)

        # modify the actual recoElem tree.

        parentItem   = self.parent.tree_ctr.GetItemParent(self.selectedItem)
        parentRe     = self.parent.tree_ctr.GetPyData( parentItem ).re
        selectedRe   = self.parent.tree_ctr.GetPyData(self.selectedItem ).re

        # if we have a parent, i.e., if we are not the top of the tree,
        # then remove ourself from our parents kid-list
        
        if (parentRe != None):
            parentRe.getRawSubElems().remove( selectedRe )
            parentRe.setDirty()

        # this no longer points anyplace valid
        self.selectedItem == None
        
        # now modify the display
        self.parent.tree_ctr.Delete(self.selectedItem)
        return
    #------------------------------------------------------------------
    def recoElemDelREChildren(self, event):
    #------------------------------------------------------------------
        """
        Delete all children of this node
        """

        if (self.selectedItem == None): return
        
        # first, modify the actual recoElem.
        selectedRe   = self.parent.tree_ctr.GetPyData(self.selectedItem ).re
        selectedRe.clearSubElems()

        # modify the display
        self.parent.tree_ctr.DeleteChildren(self.selectedItem)
        return
    
        kid,cookie = self.parent.tree_ctr.GetFirstChild(self.selectedItem)
        print kid, kid.IsOk(), cookie
        while ( kid.IsOk() ):
            self.parent.tree_ctr.Delete(kid)
            kid,cookie = self.parent.tree_ctr.GetNextChild(self.selectedItem, cookie)
            print kid, kid.IsOk(), cookie


        return

    #------------------------------------------------------------------
    def __deepCopyReactions(self, srcRecoElem, tgtRecoElem):
    #------------------------------------------------------------------
        """
        caller must call buildMaps() in target's SeedReco when all done
        with everything.  set self.__srcModel and self.tgtModel. gak.
        Meant for use with RecoElem.cloneSpine().
        """

        
        mapSrc  = self.srcModel.getReactionSeedEntryMap().getDict()
        rsemTgt = self.tgtModel.getReactionSeedEntryMap()
        srTgt   = self.tgtModel.getSeedReco()

        for rx in srcRecoElem.getRawReactions():
            # copy the reaction and stick it in new
            newRx = copy.deepcopy(rx)
            tgtRecoElem.appendReactions( newRx )

            # bring over the history info too.
            try:
                l =mapSrc[ rx ]
            except:
                l=[]
                print "No rsem entry for ", rx.asString()

            for se in l:
                srTgt.appendEntry( se )
                rsemTgt.addRelation( newRx, copy.deepcopy( se ) )

        return
        
    #------------------------------------------------------------------
    def __shallowCopyReactions(self, srcRecoElem, tgtRecoElem):
    #------------------------------------------------------------------
        """ meant for use with RecoElem.cloneSpine()  """
        for rx in srcRecoElem.getRawReactions():
            tgtRecoElem.appendReactions( rx )

        return

    #------------------------------------------------------------------
    def recoElemPasteREBranch(self, event):
    #------------------------------------------------------------------
        return self.__recoElemPasteREBranchCore(event, merge=0)
        

        if (self.selectedItem == None):
            self.parent.error( "Select a tree branch first as target.")
            return


        srcTreeData = self.__getCutCopyBuffer()

        if (srcTreeData == None):
            self.parent.error( "Select and copy a tree branch first.")
            return

        targetTreeData = self.parent.tree_ctr.GetPyData( self.selectedItem)

        reTarget = targetTreeData.re
        ceTarget = targetTreeData.ce

        # if source and target models differ, have to jump extra hoops to
        # preserve reco linkages.

        self.srcModel = srcTreeData.model        #need for call to __deepCopyREactions
        self.tgtModel = targetTreeData.model
        
        if ( not (targetTreeData.model == self.srcModel) ):
            if (srcTreeData.re.getName() == "SeedReco"):
                print "copying SeedReco"
                nSeedReco = self.srcModel.getSeedReco().clone()
                targetTreeData.model.setSeedReco( nSeedReco )
            #
            reSourceCopy = srcTreeData.re.cloneSpine( self.__deepCopyReactions)
            
        else:
            #deep copy the recoElem backbone so that editing new/old doesn't change
            #old/new, but BORROW the reactions from the old recoElem...the underlying
            #ReactionSeedRecoMap owns them.

            reSourceCopy = srcTreeData.re.cloneSpine( self.__shallowCopyReactions)

        reTarget.appendSubElems( reSourceCopy )
        self.addRecoElemTree( self.selectedItem, targetTreeData.model, 
                              reSourceCopy, ceTarget )

        return

    #------------------------------------------------------------------
    def recoElemMergeREBranch(self, event):
    #------------------------------------------------------------------
        return self.__recoElemPasteREBranchCore(event, merge=1)

        if (self.selectedItem == None):
            self.parent.error( "Select a tree branch first as target.")
            return

        srcTreeData = self.__getCutCopyBuffer()
        if (srcTreeData == None):
            self.parent.error( "Select and copy a tree branch first.")
            return

        reSource = srcTreeData.re
        reTarget = self.parent.tree_ctr.GetPyData( self.selectedItem).re
        ceTarget = self.parent.tree_ctr.GetPyData( self.selectedItem).ce
        mTarget  = self.parent.tree_ctr.GetPyData( self.selectedItem).model

        for k in reSource.getRawSubElems():
            kCopy = copy.deepcopy( k )
            reTarget.appendSubElems( kCopy )
            self.addRecoElemTree( self.selectedItem, srcTreeData.model, kCopy, ceTarget )


        # unlike pasting the whole branch in, we must drain any
        # reactions out of the cut/copied branch

        for rx in reSource.getRawReactions():
            reTarget.appendReactions( copy.deepcopy(rx ) )
        
        rxListNum = reTarget.nReactions()
        self.updateTreeBranchText(rxListNum, reTarget.getName())
        self.redrawRecoElemRxList(reTarget,mTarget )

        return

    #------------------------------------------------------------------
    def __recoElemPasteREBranchCore(self, event, merge):
    #------------------------------------------------------------------
        """ handles both Paste and Merge """
        
        if (self.selectedItem == None):
            self.parent.error( "Select a tree branch first as target.")
            return

        srcTreeData = self.__getCutCopyBuffer()

        if (srcTreeData == None):
            self.parent.error( "Select and copy a tree branch first.")
            return

        targetTreeData = self.parent.tree_ctr.GetPyData( self.selectedItem)

        reTarget = targetTreeData.re
        ceTarget = targetTreeData.ce
        mTarget  = targetTreeData.model

        # if source and target models differ, have to jump extra hoops to
        # preserve reco linkages.

        self.srcModel = srcTreeData.model        #need for call to __deepCopyREactions
        self.tgtModel = targetTreeData.model
        
        if ( not (targetTreeData.model == self.srcModel ) ):
            if (srcTreeData.re.getName() == "SeedReco"):
                print "copying SeedReco"
                nSeedReco = self.srcModel.getSeedReco().clone()
                targetTreeData.model.setSeedReco( nSeedReco )
            #
            reSourceCopy = srcTreeData.re.cloneSpine( self.__deepCopyReactions)
            
        else:
            #deep copy the recoElem backbone so that editing new/old doesn't change
            #old/new, but BORROW the reactions from the old recoElem...the underlying
            #ReactionSeedRecoMap owns them.

            reSourceCopy = srcTreeData.re.cloneSpine( self.__shallowCopyReactions)

        #-- Now glom copy onto target.  Note that the reactions in the top node of
        #   reSourceCopy have been deepcopied or not already, as appropriate.  So
        #   don't have to worry about this the merge

        if (not merge):
            reTarget.appendSubElems( reSourceCopy )
            self.addRecoElemTree( self.selectedItem, targetTreeData.model, 
                                  reSourceCopy, ceTarget )
        else:
            # shove in the kids, but not the source recoElem itself
            for kid in reSourceCopy.getRawSubElems():
                reTarget.appendSubElems( kid )
                self.addRecoElemTree( self.selectedItem, targetTreeData.model, 
                                      kid, ceTarget )

            # unlike pasting the whole branch in, we must drain any
            # reactions out of the cut/copied branch

            for rx in reSourceCopy.getRawReactions():
                reTarget.appendReactions( rx )
        
            rxListNum = reTarget.nReactions()
            self.updateTreeBranchText(rxListNum, reTarget.getName())
            self.redrawRecoElemRxList(reTarget, mTarget)

        return


    #------------------------------------------------------------------
    def recoElemPasteRx(self, event):
    #------------------------------------------------------------------

        if ( None == self.selectedItem ): return
        if ( None == self.cutOrCopiedRx ): return
        
        
        re = self.parent.tree_ctr.GetPyData( self.selectedItem).re
        model = self.parent.tree_ctr.GetPyData( self.selectedItem).model

        rxNew =  copy.deepcopy(self.cutOrCopiedRx  )
        re.appendReactions( rxNew )

        rxListNum = re.nReactions()
        
        self.updateTreeBranchText(rxListNum, re.getName())
        self.redrawRecoElemRxList(re, model)

        return


    #------------------------------------------------------------------
    def recoElemPasteFromSelectedRxGrid(self, event):
    #------------------------------------------------------------------
        if (self.selectedItem == None): return

        re = self.parent.tree_ctr.GetPyData( self.selectedItem).re
        model = self.parent.tree_ctr.GetPyData( self.selectedItem).model

        rxList = self.parent.rx.getSelectedRx()
        rxListNum = re.nReactions()

        for rx in rxList:
            re.appendReactions(copy.deepcopy(rx))

        self.updateTreeBranchText(rxListNum, re.getName())
        self.redrawRecoElemRxList(re, model)
                
        return

    #------------------------------------------------------------------
    def recoElemAppendFromTextFile(self, event):
    #------------------------------------------------------------------
        """
        Read contents of a text file, convert to recoElem and append
        as child to the selected item.
        """

        if (self.selectedItem == None):
            self.parent.error( "Select an item first.")
            return
        
        prompt = "Choose a file"
        dlg = wxFileDialog(self.parent, message=prompt, style=wxOPEN)
        if ( dlg.ShowModal() == wxID_OK):
            path = dlg.GetPath()
            print "using path ", path
            dlg.Destroy()
        else:
            #didn't get a kid name
            dlg.Destroy()
            return
        
        treeData = self.parent.tree_ctr.GetPyData( self.selectedItem)
        model = treeData.model
        re = treeData.re

        try:
            #read in whats in the text file
            readRE = doModelFromText(path, model,verbose=1)

            #transfer all of readRE (a temp top node) kids to re
            for k in readRE.getRawSubElems():
                self.addRecoElemTree( self.selectedItem, treeData.model,
                                      k, treeData.ce)

                re.appendSubElems( k )

            # just in case rx were assoc. w/ top node in the file, move
            # those over too.
            
            for rx in readRE.getRawReactions():
                re.appendReactions( rx )
        except Exception, e:
            print e

        print "snarfed:"

        re.dump()
    
        #for k in reTemp.getRawSubElems():
            # we don't deepcopy here because  we've taken ownership
            #re.appendSubElems( k )

        print "[1]"

        rxListNum = re.nReactions()
        print "[3]"
        self.updateTreeBranchText(rxListNum, re.getName())
        print "[4]"
        self.redrawRecoElemRxList(re, model)

        return
    
    #------------------------------------------------------------------
    def recoElemWriteToBss(self, event):
    #------------------------------------------------------------------
        # there are so many problems here it's not funny.  We _will_
        # corrupt the DB with this but have to start somewhere.  Example:
        # How do we know we've not been passed a REcoElem that is
        # owned by a higher entity?  The system needs to be extended to
        # understand the ownership model and catalog arch.

        if (self.selectedItem == None): return

        model = self.parent.tree_ctr.GetPyData( self.selectedItem).model
        catalogEntry = self.parent.tree_ctr.GetPyData( self.selectedItem).ce

        if (None == catalogEntry):
            # clipboard item.  can't write that.
            self.parent.error( "No catalog entry. Copy this item into a loaded model before writing")
            return

        wxBeginBusyCursor()

        foundryItemKey = catalogEntry.write( model )

        if (foundryItemKey == None ):
            self.parent.error( "Write failed.")
        else:
            self.parent.error( "Write succeeded" )
            #update catalog panel
            

        wxEndBusyCursor()
        return

    #------------------------------------------------------------------
    def recoElemWriteToCb(self, event):
    #------------------------------------------------------------------
        """ Copy the current recoElem to the clipboard """

        if not self.parent.cat.cbStarted:
            self.parent.error( "Shared editing not started.")
            return

        if (self.selectedItem == None): 
            self.parent.error( "Make a selection first.")
            return

        re0 = self.parent.tree_ctr.GetPyData( self.selectedItem).re
        re  = copy.deepcopy(re0)        #$$.deepCopy()

        print "copying to clipboard ", re0.getName(), re.getName()
        intId = putOnClipboard( re )
        print "deep copied to clipboard:"


        # tell everyone about it

        descriptor = getCbDescriptor()
        print "descriptor is ", descriptor

        self.parent.meAGMgr.cbChanged(descriptor)

        return

    #------------------------------------------------------------------
    def editParams(self, evt):
    #------------------------------------------------------------------
        """
        Popup dialog to allow user to add, delete, and modify global
        parameters for the model.
        """
        treeData = self.parent.tree_ctr.GetPyData( self.selectedItem)
        model = treeData.model
        d = model.getParamDict()

        dlg = GloParamsDialog(self.parent, -1, "Set Global Parameters",
                              d, allow=1)
        
        if (dlg.ShowModal() == wxID_OK):
            model.setParamDict(dlg.GetValue())
            dlg.Destroy()
            return
        else:
            dlg.Destroy()
            return
                                
        return
    
    #------------------------------------------------------------------
    def setRunSpeciesInfo(self, evt):
    #------------------------------------------------------------------
        """
        Popup dialog to allow user to add/delete/modify initial concentration
        data for reactants in the model
        """
        treeData = self.parent.tree_ctr.GetPyData( self.selectedItem)
        model = treeData.model
        speciesInfo = model.getRunSpeciesInfo()

        # fill out speciesInfo to include all species in the model.

        for specie in model.getTop().getStoichMatrix().getSpecies():
            if (speciesInfo.has_key(specie)):
                continue
            else:
                speciesInfo.setInfo(specie, None, 0.0, isBal=1)

        dlg = RunSpecieInfoDialog(self.parent, -1, "Initial Concentrations",
                              speciesInfo)
        
        if (dlg.ShowModal() == wxID_OK):
            rsi = dlg.GetValue()
            model.setRunSpeciesInfo( rsi )


        dlg.Destroy()
        return

       
    #------------------------------------------------------------------
    def addCbItem(self, re, cbDescription):
    #------------------------------------------------------------------
        """
        Add the passed clipboard item to the Navigator.

        @type re: FaST.RecoElem
        @type cbDescription: string
        @rtype: None

        re is the RecoElem read from the clipboard that is to be
        shown in the navigator.  cbDescription is a name like
        'myClipboard:4350::' that describes the clipboard and
        is appended to the name when displayed.

        Note- clipboard items haven't a catalogEntry associated with
        them.  They did not come from a factory or, better, they are
        disowned?
        """

        # add it to the tree.  Set CatalogEntry to None...a magic value
        # sniffed out elsewhere.  Ick.
        
        m = Model( cbDescription+re.getName() )
        m.setTop( re )
        self.addRecoElemTree( self.parent.rootId, m, re, None)
        
        return

    #------------------------------------------------------------------
    def recoElemRxListCut(self, event):
    #------------------------------------------------------------------
    # this has gotta be wrong...what were we thinking?  It's ok for a
    # single selection.
    
        re = None
        for count in self.parent.list_box.GetSelections():
            (rx,offset, re, model) = self.parent.list_boxData[count]
            self.cutOrCopiedRx   = rx
            del( re.getRawReactions()[offset:offset+1] )
            re.setDirty()
            self.redrawRecoElemRxList(re, model)

        if (re == None):
            return
        else:
            rxListNum = re.nReactions()
            self.updateTreeBranchText(rxListNum, re.getName())
        
        return

    #------------------------------------------------------------------
    def recoElemRxListCopy(self, event):
    #------------------------------------------------------------------
        for count in self.parent.list_box.GetSelections():
            (rx,offset,re, model) = self.parent.list_boxData[count]
            self.cutOrCopiedRx   = rx

        return    

    #------------------------------------------------------------------
    def recoElemRxListPaste(self, event):
    #------------------------------------------------------------------
        # we're pasting into a list_box.  This list box is being
        # shown *because* a recoElem has been selected.  that means
        # _it_ is the recoElem to modify.

        #since the listbox is only allowing single select.
        #we won't count how big the selection is

        if (self.selectedItem == None): return
        re = self.parent.tree_ctr.GetPyData( self.selectedItem).re
        model = self.parent.tree_ctr.GetPyData( self.selectedItem).model
        #$$??? re.appendReactions( self.cutOrCopiedRx )
        rxNew =  copy.deepcopy(self.cutOrCopiedRx  )
        re.appendReactions( rxNew )

        rxListNum = re.nReactions()
        self.updateTreeBranchText(rxListNum, re.getName())
        self.redrawRecoElemRxList(re, model)

        return

    #------------------------------------------------------------------
    def recoElemRxListAddDyn(self, event):
    #------------------------------------------------------------------    
        """
        Popup dialog to allow user to associate dynamics with currently
        selected reaction, or to modify/delete dynamics for current
        reaction
        """
        
        if (0==len(self.parent.list_box.GetSelections())):
            self.parent.error( "Select a reaction first")
            return

        for count in self.parent.list_box.GetSelections():
            (rx,offset,re, model) = self.parent.list_boxData[count]

        m = self.parent.tree_ctr.GetPyData( self.selectedItem).model

        rxDynAssoc = m.getRxDynAssoc()
        try:
            dyn = rxDynAssoc.getDyn( rx )
            dlg = DynParamsDialog(self.parent, -1, "Input Parameters",
                                  rx, dyn)
        except KeyError:
            dlg = DynParamsDialog(self.parent, -1, "Input Parameters",
                                  rx)
            
        if (dlg.ShowModal() == wxID_OK):
            newDyn = dlg.GetValue()
            dlg.Destroy()
        else:
            dlg.Destroy()
            return

        if (not None == newDyn):
            model = self.parent.tree_ctr.GetPyData(self.selectedItem).model
            model.getRxDynAssoc().addRxDyn(rx, newDyn)
            self.redrawRecoElemRxList(re, model)


        return

    #------------------------------------------------------------------
    def startAGClipboard(self):
    #------------------------------------------------------------------
        raise NotImplementedError


        if (self.cbStarted): return


        (host, portnum) = ("porta-video.mcs.anl.gov", 303030)

        self.cbStarted  = 1
        self.clipboard  = {}
        self.nCb        = 0     #used to make unique id for items on cb

        return

    #------------------------------------------------------------------
    def stopAGClipboard(self):
    #------------------------------------------------------------------
        raise NotImplementedError


MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3