예제 #1
0
    def addNodeToSearchPanel(self, node, nodes, maxx, posy):
        from NetworkEditor.items import NetworkNode
        sc_canvas = self.searchCanvas
        
        font = self.editor.font['LibNodes']
        canvas = sc_canvas.component('canvas')

        n1 = NetworkNode(name=node.name)
        n1.iconMaster = sc_canvas
        n1.buildSmallIcon(sc_canvas, 10, posy, font)

        color = node.kw['library'].color
        canvas.itemconfigure(n1.id, fill=color)
        
        self.balloons.tagbind(sc_canvas, n1.iconTag,
                              node.nodeClass.__doc__)

        bb = sc_canvas.bbox(n1.id)
        w = bb[2]-bb[0]
        h = bb[3]-bb[1]
        maxx = max(maxx, w)
        posy = posy + h + 8

        nodes[n1.id] = (n1, node)
        self.searchNodes.append(n1)

        return nodes, maxx, posy
예제 #2
0
 def resetTags(self):
     """This method subclasses NetworkNode.resetTags(). Used to reset
     the attributes _modified and _original in node, ports, widgets, conn"""
     NetworkNode.resetTags(self)
     for node in self.macroNetwork.nodes:
         node.resetTags()
     self.macroNetwork.ipNode._setOriginal(False)
     self.macroNetwork.opNode._setOriginal(False)
예제 #3
0
 def afterAddingToNetwork(self):
     NetworkNode.afterAddingToNetwork(self)
     top = Tkinter.Toplevel()
     top.withdraw()
     ed = EditorWindow(root=top)
     ed.top.withdraw()
     self.top = ed.top
     self.editorDialogue = ed
     b=Tkinter.Button(master=ed.status_bar,
                      text='Apply', command=self.applyCmd)
     b.pack(side='left')
예제 #4
0
 def buildIcons(self, canvas, posx, posy):
     NetworkNode.buildIcons(self, canvas, posx, posy)
     myfont = list(self.getFont())
     if not 'bold' in myfont:
         myfont.append('bold')
     self.setFont(tuple(myfont))
     self.autoResizeX()
     try:
         self.menu.index('shrink')
     except:
         self.menu.add_command(label='shrink',command=self.macroNode.shrink)
예제 #5
0
 def buildIcons(self, canvas, posx, posy):
     NetworkNode.buildIcons(self, canvas, posx, posy)
     myfont = list(self.getFont())
     if not 'bold' in myfont:
         myfont.append('bold')
     self.setFont(tuple(myfont))
     self.autoResizeX()
     try:
         self.menu.index('expand')
     except:
         self.menu.add_separator()
         self.menu.add_command(label='expand', command=self.expand)
         self.menu.add_command(label='shrink', command=self.shrink)
         self.addSaveNodeMenuEntries()
예제 #6
0
    def getNodeDefinitionSourceCode(self, networkName, indent="",
                                    ignoreOriginal=False):

        """subclass baseclass method to add lines to load the molecule in
        Pmv if it is not loaded yet"""

        lines = []
        if self.network.filename is not None:
            lNetworkDir = os.path.dirname(os.path.abspath(self.network.filename))
            lFileName = relpath(lNetworkDir, os.path.abspath(self.mol.parser.filename))
        else:
            lFileName = self.mol.parser.filename

        # we save the name of the file in a path relatives to the network
        s00 = 'import os\n'
        s01 = 'from mglutil.util.relpath import rel2abs\n'
        s02 = "lRelFileName = '%s'\n"%lFileName
        # we prepare the readding with an absolut path
        s03 = 'lNetworkDir = os.path.dirname(os.path.abspath(%s.filename))\n'%networkName
        s04 = 'lAbsFileName = rel2abs(lRelFileName, lNetworkDir)\n'
        
        s1 = 'mol = %s.editor.vf.loadMoleculeIfNeeded(lAbsFileName)\n'%networkName
        s2 = 'assert mol\n'
        lines.append(indent+s00)
        lines.append(indent+s01)
        lines.append(indent+s02)
        lines.append(indent+s03)
        lines.append(indent+s04)
        lines.append(indent+s1)
        lines.append(indent+s2)
        lines.extend(NetworkNode.getNodeDefinitionSourceCode(
            self, networkName, indent, ignoreOriginal) )
        return lines
예제 #7
0
    def getNodeDefinitionSourceCode(self, networkName, indent="",
                                    ignoreOriginal=False):

        """subclass baseclass method to add lines to load the molecule in
        Pmv if it is not loaded yet"""

        if self.network.filename is not None:
            lNetworkDir = os.path.dirname(os.path.abspath(self.network.filename))
        elif hasattr(self.network, 'macroNode') \
          and self.network.macroNode.network.filename is not None:
            lNetworkDir = os.path.dirname(os.path.abspath(self.network.macroNode.network.filename))
        else:
            lNetworkDir = None
            assert False, "my guess is we don't go here"

        lines = []
        molecules = []
        for mol in self.set.top.uniq().data:
            # we save the name of the file in a path relatives to the network
            if lNetworkDir is not None:
                lFileName = relpath(lNetworkDir, os.path.abspath(mol.parser.filename))
            else:
                lFileName = mol.parser.filename
            molecules.append(lFileName)

        # we prepare the readding with an absolut path
        s0 = 'import os\n'
        s1 = 'from mglutil.util.relpath import rel2abs\n'
        s2 = 'lNetworkDir = os.path.dirname(os.path.abspath(%s.filename))\n'%networkName
        s3 = 'mols = %s\n'%molecules
        s4 = 'for m in mols:\n'
        s5 = '    lAbsFileName = rel2abs(m, lNetworkDir)\n'
        s6 = '    mol = %s.editor.vf.loadMoleculeIfNeeded(lAbsFileName)\n'%networkName
        s7 = '    assert mol\n'
        s8 = 'selString = "%s"\n'%self.selString
        s9 = '%s.editor.vf.loadModule("selectionCommands")\n'%networkName
        s10 = '%s.editor.vf.createSetIfNeeded(selString, "%s")\n'%(networkName, self.name)
        s11 = 'from Pmv.selectionCommands import sets__\n'
        lines.append(indent+s0)
        lines.append(indent+s1)
        lines.append(indent+s2)
        lines.append(indent+s3)
        lines.append(indent+s4)
        lines.append(indent+s5)
        lines.append(indent+s6)
        lines.append(indent+s7)
        lines.append(indent+s8)
        lines.append(indent+s9)
        lines.append(indent+s10)
        lines.append(indent+s11)

        lines.extend(NetworkNode.getNodeDefinitionSourceCode(
            self, networkName, indent, ignoreOriginal) )
        return lines
예제 #8
0
    def addNodeToLibPanel(self, node):
        if node in self.libNodes:
            return
        
        from NetworkEditor.items import NetworkNode
        sc_canvas = self.libCanvas
        
        font = self.editor.font['LibNodes']
        canvas = sc_canvas.component('canvas')

        n1 = NetworkNode(name=node.name)
        n1.iconMaster = sc_canvas

        posy = self.posyForLibNode
        n1.buildSmallIcon(sc_canvas, 10, posy, font)

        color = node.kw['library'].color
        canvas.itemconfigure(n1.id, fill=color)
        
        self.balloons.tagbind(sc_canvas, n1.iconTag,
                              node.nodeClass.__doc__)

        bb = sc_canvas.bbox(n1.id)
        w = bb[2]-bb[0]
        h = bb[3]-bb[1]
        self.maxxForLibNode = max(self.maxxForLibNode, w)
        posy = posy + h + 8
        self.posyForLibNode = posy

        self.libNodes.append(node)
        nodes = self.editor.idToNodes[self.libCanvas]
        nodes[n1.id] = (n1, node)
        self.editor.idToNodes[self.libCanvas] = nodes

        # update scrolled canvas
        maxx = self.maxxForLibNode
        canvas.configure(width=60, height=150,
                         scrollregion=tuple((0,0,maxx,posy)))
예제 #9
0
    def getNodeDefinitionSourceCode(self, lib, nodeId, nodeUniqId, networkName,
                                    ):
        
        txt = '#create CGI Form object:\n'
        txt = txt + 'from mglutil.web.HTMLParser import CGIForm\n'
        txt = txt + 'obj='+self.CGIFormObj.getCreationSourceCode()

        self.constrkw['CGIFormObj']='obj' # temporarily add kw to generate
                                          # correct list of arguments
        src = NetworkNode.getNodeDefinitionSourceCode(self, lib, nodeId,
                                                    nodeUniqId, networkName)

        del self.constrkw['CGIFormObj']   # now we remove it

        for line in src[0]:
            txt = txt + line
        
        return [txt], nodeId, nodeUniqId
예제 #10
0
    def getNodeDefinitionSourceCode(
        self,
        lib,
        nodeId,
        nodeUniqId,
        networkName,
    ):

        txt = '#create CGI Form object:\n'
        txt = txt + 'from mglutil.web.HTMLParser import CGIForm\n'
        txt = txt + 'obj=' + self.CGIFormObj.getCreationSourceCode()

        self.constrkw['CGIFormObj'] = 'obj'  # temporarily add kw to generate
        # correct list of arguments
        src = NetworkNode.getNodeDefinitionSourceCode(self, lib, nodeId,
                                                      nodeUniqId, networkName)

        del self.constrkw['CGIFormObj']  # now we remove it

        for line in src[0]:
            txt = txt + line

        return [txt], nodeId, nodeUniqId
예제 #11
0
    def __init__(self, name='filterLigands', **kw):
        kw['name'] = name
        NetworkNode.__init__(*(self, ), **kw)

        # create filter object
        lfilter = self.lfilter = FilterLigands()
        lfilter.setFilter('default')

        ip = self.inputPortsDescr
        ip.append(datatype='LigandDB', name='ligands')
        ip.append(datatype='string', name='filterMode')

        self.widgetDescr['filterMode'] = {
            'class':
            'NEComboBox',
            'master':
            'node',
            'choices': [
                'None', 'default', 'Lipinski-like', 'Drug-like',
                'Drug-like frag', 'Custom'
            ],
            'fixedChoices':
            True,
            'initialValue':
            'default',
            'entryfield_entry_width':
            8,
            'labelGridCfg': {
                'sticky': 'w'
            },
            'widgetGridCfg': {
                'sticky': 'w'
            },
            'labelCfg': {
                'text': 'filter type:'
            }
        }

        labels = [
            'Min num. of h-bond donors:', 'Max num. of h-bond donors:',
            'Min num. of h-bond acceptors', 'Max num. of h-bond acceptors',
            'Min molecular weight', 'Max molecular weight',
            'Min num. of heavy atoms', 'Max num. of heavy atoms',
            'Min num. of rotatable bonds', 'Max num. of rotatable bonds'
        ]

        for i, param in enumerate([
                'hbd_min', 'hbd_max', 'hba_min', 'hba_max', 'mw_min', 'mw_max',
                'nat_min', 'nat_max', 'torsdof_min', 'torsdof_max'
        ]):
            ip.append(datatype='int', name=param)
            value = getattr(lfilter, self.attr[i])

            self.widgetDescr[param] = {
                'class': 'NEThumbWheel',
                'master': 'ParamPanel',
                'width': 75,
                'height': 12,
                'oneTurn': 10,
                'type': 'int',
                'wheelPad': 0,
                'initialValue': value,
                'min': 0,
                'labelCfg': {
                    'text': labels[i]
                }
            }

        op = self.outputPortsDescr
        op.append(datatype='LigandDB', name='ligands')
        op.append(datatype='int', name='num_accepted')
        op.append(datatype='int', name='num_rejected')

        code = """def doit(self, ligands, filterMode='default', hbd_min=None, hbd_max=None, hba_min=None, hba_max=None, mw_min=None, mw_max=None, nat_min=None, nat_max=None, torsdof_min=None, torsdof_max=None):

    lfilter = self.lfilter

    if filterMode != "Custom":
        lfilter.setFilter(filterMode)
    else:
        kwargs = {"HbDMin": hbd_min,
                  "HbDMax": hbd_max,
                  "HbAMin": hba_min,
                  "HbAMax": hba_max,
                  "MWMin": mw_min,
                  "MWMax": mw_max,
                  "NatMin": nat_min,
                  "NatMax": nat_max,
                  "TORSDOFMin": torsdof_min,
                  "TORSDOFMax": torsdof_max}
        lfilter.setFilterRanges('Custom', **kwargs)

    if self.inputPorts[1].hasNewValidData(): # new mode -> update widgets
        self.setParamPanelWidget(lfilter)

    print "Running Filter node with parameters:"
    print "min number of hydrogen bond donors: " + str(lfilter.HbDMin)
    print "max number of hydrogen bond donors: " + str(lfilter.HbDMax)
    print "min number of hydrogen bond acceptors: " + str(lfilter.HbAMin)
    print "max number of hydrogen bond acceptors: " + str(lfilter.HbAMax)
    print "min molecular weight: " + str(lfilter.MWMin)
    print "max molecular weight: " + str(lfilter.MWMax)
    print "min number of heavy atoms: " + str(lfilter.NatMin)
    print "max number of heavy atoms: " + str(lfilter.NatMax)
    print "min number of rotatable bonds: " + str(lfilter.TORSDOFMin)
    print "max number of rotatable bonds: " + str(lfilter.TORSDOFMax)

#    accepted, rejected = lfilter.filterTable(ligands.propertyTable)

    accepted, rejected = lfilter.filterTable(ligands.propertyTable, ligands.accepted)

    ligands.SetAcceptedLigands(accepted.filenames)

    if len(accepted.filenames) > 2500:
        print "ERROR: Sorry, we cannot send your virtual screening job to the server because the number of accepted ligands from the filter is greater than the maximum number of ligands (2500) the server can support"
        return 'stop'

    self.outputData(ligands=ligands, num_accepted = len(accepted.filenames), num_rejected=len(rejected))
"""
        self.setFunction(code)
예제 #12
0
    def __init__(self, constrkw={}, name='GetStructuresFromDir', **kw):
        kw['constrkw'] = constrkw
        kw['name'] = name
        NetworkNode.__init__(*(self, ), **kw)

        ip = self.inputPortsDescr
        ip.append({'name': 'directory', 'datatype': 'string'})

        self.widgetDescr['directory'] = {
            'class': 'NEEntryWithDirectoryBrowser',
            'master': 'node',
            'width': 20,
            'initialValue': '',
            'labelCfg': {
                'text': 'Structure Directory: '
            }
        }

        op = self.outputPortsDescr
        op.append({'name': 'structure_list_obj', 'datatype': 'list'})

        #        op = self.outputPortsDescr
        #        op.append({'name': 'structure_list', 'datatype': 'list'})

        code = """def doit(self, directory):
        import glob, os
        from AutoDockTools.VisionInterface.Adt.receptor import receptor

        directory = os.path.abspath(directory)

        if directory == None:
            return 'stop'

        if directory is not None:
            cwd = os.getcwd()
            os.chdir(directory)
        try:
            filenames_pdbqt = glob.glob('*.pdbqt')
            filenames_pqr = glob.glob('*.pqr')
            filenames_pdb = glob.glob('*.pdb')

            structure_list = filenames_pdbqt

            for f in filenames_pqr:
                sid = f.rstrip('.pqr')
                s = sid + '.pdbqt'
                found = False
 
                for i in structure_list:
                    if i == s:
                        found = True        
                        break

                if found == False:
                    structure_list.append(f)

            for f in filenames_pdb:
                sid = f.rstrip('.pdb')
                found = False
 
                for i in structure_list:
                    if i == sid + '.pdb' or i == sid + '.pdbqt':
                        found = True        
                        break

                if found == False:
                    structure_list.append(f)

            structure_list = [os.path.join(directory, x) for x in filenames_pdbqt]
            structure_list_obj = [receptor(x) for x in structure_list]
        finally:
            if directory is not None:
                os.chdir(cwd)

        print "--------------------------------------------------------------"
        print "The following structures are found in the structure directory:"

        count = 0

        for i in structure_list:
            count = count + 1
            print str(count) + '. ' + i
           
        print "--------------------------------------------------------------"
        
        pass
#        self.outputData(structure_list_obj=structure_list_obj, structure_list=structure_list)
        self.outputData(structure_list_obj=structure_list_obj)
"""
        self.configure(function=code)
예제 #13
0
 def schedule_cb(self, event=None):
     #print "MacroNode.schedule_cb"
     self.macroNetwork.forceExecution = 1
     NetworkNode.schedule_cb(self)
예제 #14
0
 def beforeAddingToNetwork(self, net):
     NetworkNode.beforeAddingToNetwork(self, net)
     # loading library vizlib
     importVolLib(net)
예제 #15
0
 def afterAddingToNetwork(self):
     NetworkNode.afterAddingToNetwork(self)
     # run this node so the value is output
     self.run(force=1)
    def __init__(self, constrkw={}, name='ReadDockingParameterFile', **kw):
        kw['constrkw'] = constrkw
        kw['name'] = name
        NetworkNode.__init__(*(self, ), **kw)
        fileTypes = [('dpf', '*')]

        self.widgetDescr['filename'] = {
            'class': 'NEEntryWithFileBrowser',
            'master': 'node',
            'filetypes': fileTypes,
            'title': 'read file',
            'width': 16,
            'labelCfg': {
                'text': 'file:'
            },
        }

        code = """def doit(self, template_dpf_filename):
    if template_dpf_filename:
            from AutoDockTools.DockingParameters import DockingParameters
            gpo = DockingParameters()
            gpo.read(template_dpf_filename)
            self.outputData(gpo=gpo)
"""
        self.configure(function=code)

        self.inputPortsDescr.append({
            'name': 'template_dpf_filename',
            'cast': True,
            'datatype': 'string',
            'balloon': 'template grid parameter filename',
            'required': False,
            'height': 8,
            'width': 12,
            'shape': 'oval',
            'color': 'white'
        })
        self.outputPortsDescr.append({
            'name': 'gpo',
            'datatype': 'None',
            'balloon':
            'gpo,  grid parameter object,  instance of AutoDockTools.DockingParameters',
            'height': 8,
            'width': 12,
            'shape': 'diamond',
            'color': 'white'
        })
        self.widgetDescr['template_dpf_filename'] = {
            'initialValue': '',
            'labelGridCfg': {
                'column': 0,
                'row': 0
            },
            'master': 'node',
            'widgetGridCfg': {
                'labelSide': 'left',
                'column': 1,
                'row': 0
            },
            'labelCfg': {
                'text': ''
            },
            'class': 'NEEntryWithFileBrowser'
        }
    def __init__(self, name='PublicServerLigandDB', **kw):
        import urllib.request, urllib.parse, urllib.error

        kw['name'] = name
        NetworkNode.__init__(*(self, ), **kw)

        kw['name'] = name
        NetworkNode.__init__(*(self, ), **kw)
        ip = self.inputPortsDescr
        ip.append(
            datatype='string',
            name='server_lib',
            required=True,
        )

        fqdn = "kryptonite.nbcr.net"
        url = "http://" + fqdn + "/pub_ligand_libs.txt"

        publibdir = os.path.join(getResourceFolderWithVersion(), 'ws')

        if not (os.path.exists(publibdir)):
            os.mkdir(publibdir)

        publiblocal = os.path.join(publibdir, 'publibs.txt')

        lock = publiblocal + '.lock'

        if os.path.exists(lock) and time.time() - os.path.getmtime(lock) > 15:
            os.remove(lock)

        try:
            if not (os.path.exists(lock)):
                open(lock, 'w').close()
                publibweb = urllib.request.urlopen(url)
                outfile = open(publiblocal, 'w')
                outfile.write(publibweb.read())
                outfile.close()
                os.remove(lock)
        except:
            print("[INFO]: Getting list of public server libs from cache")
            pass

        try:
            f = open(publiblocal, 'r')
            self.choices = f.read().split()
            f.close()
        except:
            self.choices = []
            print(
                "[ERROR]: Unable to public server libs from the web and from cache"
            )

        self.widgetDescr['server_lib'] = {
            'class': 'NEComboBox',
            'master': 'node',
            'choices': self.choices,
            'fixedChoices': True,
            'entryfield_entry_width': 18,
            'labelGridCfg': {
                'sticky': 'w'
            },
            'widgetGridCfg': {
                'sticky': 'w'
            },
            'labelCfg': {
                'text': 'Server Libraries:'
            }
        }

        op = self.outputPortsDescr
        op.append(datatype='LigandDB', name='ligDB')

        code = """def doit(self, server_lib):
    ligDB = LigandDB(server_lib=server_lib)

    self.outputData(ligDB=ligDB)
"""
        self.setFunction(code)
예제 #18
0
    def getNodeDefinitionSourceCode(self, networkName, indent="",
                                    ignoreOriginal=False):
        """This method builds the text-string to describe a macro node
in a saved file."""
        
        lines = []
        nodeName = self.getUniqueNodeName()

        ###############################################################
        # add lines to import node from macros.py, add macro to network
        ###############################################################

        if self.library:
            txt = NetworkNode.getNodeDefinitionSourceCode(
                self, networkName, indent)
            lines.extend(txt)
            
        else:
            if not self._original:
                txt1 = 'from NetworkEditor.macros import MacroNode\n'
                txt2 = "%s = MacroNode(name='%s')\n"%(nodeName, self.name)
                txt3 = "%s.addNode(%s, %d, %d)\n"%(
                    networkName, nodeName, self.posx, self.posy)

                lines.append(indent+txt1)
                lines.append(indent+txt2)
                lines.append(indent+txt3)
            
        ###############################################################
        # add lines to add all macro nodes first, recursively
        ###############################################################
        
        # We have to add all macro nodes first, and then start in the leaf
        # macros, add the nodes there, and work our way back up
        # (because of connections)
        for node in self.macroNetwork.nodes:
            if isinstance(node, MacroNode):
                txt1 = node.getNodeDefinitionSourceCode(
                    nodeName+".macroNetwork", indent)
                lines.extend(txt1)
        
        ###############################################################
        # check if an original node was deleted
        ###############################################################
        deletedNodes = 0 # count how many nodes have already been deleted
        # NOTE: because we add a line for each node we want to delete,
        # we have to decrement the orignumber by how many nodes we already
        # deleted
        for orignode, orignumber in self.macroNetwork._originalNodes:
            if orignode not in self.macroNetwork.nodes:
                # add handle to macro node
                lines = self.checkIfNodeForSavingIsDefined(
                    lines, networkName, indent)
                # add line to delete node
                txt = "%s.deleteNodes([%s])\n"%(
                    nodeName+".macroNetwork",
                    nodeName+".macroNetwork.nodes["+str(orignumber-deletedNodes)+"]")
                deletedNodes += 1
                lines.append(indent+txt)
 
        ###############################################################
        # check if an original connection was deleted
        ###############################################################
        for origconn, p1, n1, p2, n2 in self.macroNetwork._originalConnections:
            if origconn not in self.macroNetwork.connections:
                # only generate code if the nodes still exist (if not this
                # means, the node has been deleted which will delete the
                # connections so we do not have to add code,
                # and also if ports are not None. If ports were None means
                # that the user deleted the port which we catch below and
                # this also deletes the connection so we need not add code here
            
                invalid = False # this indicates a connection to a deleted
                                # node or port

                # port1 or port2 deleted?
                if type(p1) == types.NoneType or type(p2) == types.NoneType:
                    invalid = True

                # node1 deleted?
                if n1 not in self.macroNetwork.nodes:
                    invalid = True
                # node2 deleted?
                if n2 not in self.macroNetwork.nodes:
                    invalid = True
                    
                # only if both ports still exist do the following
                if not invalid:
                    lines = self.checkIfNodeForSavingIsDefined(
                        lines, networkName, indent)

                    node1 = nodeName+".macroNetwork.nodes[%d]"%(
                        self.macroNetwork.nodeIdToNumber(n1._id),)
                    node2 = nodeName+".macroNetwork.nodes[%d]"%(
                        self.macroNetwork.nodeIdToNumber(n2._id),)
                    txt = "%s.deleteConnection(%s, '%s', %s, '%s')\n"%(
                    nodeName+".macroNetwork", node1, p1.name, node2, p2.name)
                    lines.extend(indent+txt)
            
        ###############################################################
        # add lines to add/modify nodes in a macro network
        ###############################################################
        for node in self.macroNetwork.nodes:
            if not isinstance(node, MacroNode):
                txt2 = node.getNodeDefinitionSourceCode(
                    nodeName+".macroNetwork", indent)
                lines.extend(txt2)

        ###############################################################
        # add lines to create connections in macro networks
        ###############################################################
        macroNetworkName = "%s.macroNetwork"%nodeName
        if len(self.macroNetwork.connections):
            lines.append(
                '\n'+indent+"## saving connections for network "+\
                "%s ##\n"%self.name)
            lines.append(indent+'%s.freeze()\n'%macroNetworkName)
            for conn in self.macroNetwork.connections: 
                lines.extend(conn.getSourceCode(
                    macroNetworkName, False, indent))
            lines.append(indent+'%s.unfreeze()\n'%macroNetworkName)

        ###############################################################
        # add lines to configure dynamically created MacroOutputPorts
        # Note: right now we catch the port name 
        ###############################################################
        txt = self.macroNetwork.ipNode.getDynamicPortsModificationSourceCode(
            macroNetworkName, indent, ignoreOriginal)
        lines.extend(txt)

        ###############################################################
        # add lines to configure dynamically created MacroOutputPorts
        # Note: right now we catch the name and "singleConnection"
        # which might be modified by the user
        ###############################################################
        txt = self.macroNetwork.opNode.getDynamicPortsModificationSourceCode(
            macroNetworkName, indent, ignoreOriginal)
        lines.extend(txt)

        ###############################################################
        # Also, catch singleConnection events on the MacroNode input ports
        # if they were changed compared to the node that is connected to
        # the MacroInput node. We can do this only after we have formed
        # the connections inside the macro network
        ###############################################################
        # find node connected
        txt = []
        for ip in self.inputPorts:
            # add line to allow the renaming of the macronode's input ports
            txt.append(indent+\
                       "%s.inputPorts[%d].configure(name='%s')\n"%(
                       nodeName, ip.number, ip.name) )
            txt.append(indent+\
                       "%s.inputPorts[%d].configure(datatype='%s')\n"%(
                       nodeName, ip.number, ip.datatypeObject['name']) )
        txt.append(indent+"## configure MacroNode input ports\n")
        lines.extend(txt)

        # add line to allow the renaming of the macronode's output ports
        txt = []
        for op in self.outputPorts:
            txt.append(indent+\
                       "%s.outputPorts[%d].configure(name='%s')\n"%(
                       nodeName, op.number, op.name) )
            txt.append(indent+\
                       "%s.outputPorts[%d].configure(datatype='%s')\n"%(
                       nodeName, op.number, op.datatypeObject['name']) )
        txt.append(indent+"## configure MacroNode output ports\n")
        lines.extend(txt)
        
        ###############################################################
        # Shrink the macro node
        ###############################################################
        lines.append(indent+nodeName+".shrink()\n")

        ###############################################################
        # configure macro node: Freeze, etc
        ###############################################################
        ind, txt = self.getNodeSourceCodeForNode(networkName, indent,
                                                 ignoreOriginal)
        lines.extend(txt)

        return lines
예제 #19
0
 def beforeAddingToNetwork(self, net):
     NetworkNode.beforeAddingToNetwork(self, net)
     # loading library vizlib
     importVolLib(net)
 def afterAddingToNetwork(self):
     NetworkNode.afterAddingToNetwork(self)
     # run this node so the value is output
     self.run()
     self.inputPorts[0].widget.configure = self.configure_NEContourSpectrum
     self.inputPorts[0].widget.widget.setType = self.setType_NEContourSpectrum
예제 #21
0
 def afterRemovingFromNetwork(self):
     NetworkNode.afterRemovingFromNetwork(self)
     if self.top:
         self.top.destroy()
예제 #22
0
    def getNodeDefinitionSourceCode(self,
                                    networkName,
                                    indent="",
                                    ignoreOriginal=False):
        """This method builds the text-string to describe a macro node
in a saved file."""

        lines = []
        nodeName = self.getUniqueNodeName()

        ###############################################################
        # add lines to import node from macros.py, add macro to network
        ###############################################################

        if self.library:
            txt = NetworkNode.getNodeDefinitionSourceCode(
                self, networkName, indent)
            lines.extend(txt)

        else:
            if not self._original:
                txt1 = 'from NetworkEditor.macros import MacroNode\n'
                txt2 = "%s = MacroNode(name='%s')\n" % (nodeName, self.name)
                txt3 = "%s.addNode(%s, %d, %d)\n" % (networkName, nodeName,
                                                     self.posx, self.posy)

                lines.append(indent + txt1)
                lines.append(indent + txt2)
                lines.append(indent + txt3)

        ###############################################################
        # add lines to add all macro nodes first, recursively
        ###############################################################

        # We have to add all macro nodes first, and then start in the leaf
        # macros, add the nodes there, and work our way back up
        # (because of connections)
        for node in self.macroNetwork.nodes:
            if isinstance(node, MacroNode):
                txt1 = node.getNodeDefinitionSourceCode(
                    nodeName + ".macroNetwork", indent)
                lines.extend(txt1)

        ###############################################################
        # check if an original node was deleted
        ###############################################################
        deletedNodes = 0  # count how many nodes have already been deleted
        # NOTE: because we add a line for each node we want to delete,
        # we have to decrement the orignumber by how many nodes we already
        # deleted
        for orignode, orignumber in self.macroNetwork._originalNodes:
            if orignode not in self.macroNetwork.nodes:
                # add handle to macro node
                lines = self.checkIfNodeForSavingIsDefined(
                    lines, networkName, indent)
                # add line to delete node
                txt = "%s.deleteNodes([%s])\n" % (
                    nodeName + ".macroNetwork",
                    nodeName + ".macroNetwork.nodes[" +
                    str(orignumber - deletedNodes) + "]")
                deletedNodes += 1
                lines.append(indent + txt)

        ###############################################################
        # check if an original connection was deleted
        ###############################################################
        for origconn, p1, n1, p2, n2 in self.macroNetwork._originalConnections:
            if origconn not in self.macroNetwork.connections:
                # only generate code if the nodes still exist (if not this
                # means, the node has been deleted which will delete the
                # connections so we do not have to add code,
                # and also if ports are not None. If ports were None means
                # that the user deleted the port which we catch below and
                # this also deletes the connection so we need not add code here

                invalid = False  # this indicates a connection to a deleted
                # node or port

                # port1 or port2 deleted?
                if type(p1) == types.NoneType or type(p2) == types.NoneType:
                    invalid = True

                # node1 deleted?
                if n1 not in self.macroNetwork.nodes:
                    invalid = True
                # node2 deleted?
                if n2 not in self.macroNetwork.nodes:
                    invalid = True

                # only if both ports still exist do the following
                if not invalid:
                    lines = self.checkIfNodeForSavingIsDefined(
                        lines, networkName, indent)

                    node1 = nodeName + ".macroNetwork.nodes[%d]" % (
                        self.macroNetwork.nodeIdToNumber(n1._id), )
                    node2 = nodeName + ".macroNetwork.nodes[%d]" % (
                        self.macroNetwork.nodeIdToNumber(n2._id), )
                    txt = "%s.deleteConnection(%s, '%s', %s, '%s')\n" % (
                        nodeName + ".macroNetwork", node1, p1.name, node2,
                        p2.name)
                    lines.extend(indent + txt)

        ###############################################################
        # add lines to add/modify nodes in a macro network
        ###############################################################
        for node in self.macroNetwork.nodes:
            if not isinstance(node, MacroNode):
                txt2 = node.getNodeDefinitionSourceCode(
                    nodeName + ".macroNetwork", indent)
                lines.extend(txt2)

        ###############################################################
        # add lines to create connections in macro networks
        ###############################################################
        macroNetworkName = "%s.macroNetwork" % nodeName
        if len(self.macroNetwork.connections):
            lines.append(
                '\n'+indent+"## saving connections for network "+\
                "%s ##\n"%self.name)
            lines.append(indent + '%s.freeze()\n' % macroNetworkName)
            for conn in self.macroNetwork.connections:
                lines.extend(
                    conn.getSourceCode(macroNetworkName, False, indent))
            lines.append(indent + '%s.unfreeze()\n' % macroNetworkName)

        ###############################################################
        # add lines to configure dynamically created MacroOutputPorts
        # Note: right now we catch the port name
        ###############################################################
        txt = self.macroNetwork.ipNode.getDynamicPortsModificationSourceCode(
            macroNetworkName, indent, ignoreOriginal)
        lines.extend(txt)

        ###############################################################
        # add lines to configure dynamically created MacroOutputPorts
        # Note: right now we catch the name and "singleConnection"
        # which might be modified by the user
        ###############################################################
        txt = self.macroNetwork.opNode.getDynamicPortsModificationSourceCode(
            macroNetworkName, indent, ignoreOriginal)
        lines.extend(txt)

        ###############################################################
        # Also, catch singleConnection events on the MacroNode input ports
        # if they were changed compared to the node that is connected to
        # the MacroInput node. We can do this only after we have formed
        # the connections inside the macro network
        ###############################################################
        # find node connected
        txt = []
        for ip in self.inputPorts:
            # add line to allow the renaming of the macronode's input ports
            txt.append(indent+\
                       "%s.inputPorts[%d].configure(name='%s')\n"%(
                       nodeName, ip.number, ip.name) )
            txt.append(indent+\
                       "%s.inputPorts[%d].configure(datatype='%s')\n"%(
                       nodeName, ip.number, ip.datatypeObject['name']) )
        txt.append(indent + "## configure MacroNode input ports\n")
        lines.extend(txt)

        # add line to allow the renaming of the macronode's output ports
        txt = []
        for op in self.outputPorts:
            txt.append(indent+\
                       "%s.outputPorts[%d].configure(name='%s')\n"%(
                       nodeName, op.number, op.name) )
            txt.append(indent+\
                       "%s.outputPorts[%d].configure(datatype='%s')\n"%(
                       nodeName, op.number, op.datatypeObject['name']) )
        txt.append(indent + "## configure MacroNode output ports\n")
        lines.extend(txt)

        ###############################################################
        # Shrink the macro node
        ###############################################################
        lines.append(indent + nodeName + ".shrink()\n")

        ###############################################################
        # configure macro node: Freeze, etc
        ###############################################################
        ind, txt = self.getNodeSourceCodeForNode(networkName, indent,
                                                 ignoreOriginal)
        lines.extend(txt)

        return lines
예제 #23
0
 def schedule_cb(self, event=None):
     #print "MacroNode.schedule_cb"
     self.macroNetwork.forceExecution = 1
     NetworkNode.schedule_cb(self)
    def __init__(self, name='MakeDPFCopies', **kw):
        kw['name'] = name
        NetworkNode.__init__(*(self, ), **kw)

        kw['name'] = name
        NetworkNode.__init__(*(self, ), **kw)
        ip = self.inputPortsDescr
        ip.append(datatype='gpf_template', name='gpf_file', required=False)
        ip.append(datatype='dpf_template', name='dpf_file', required=False)
        ip.append(datatype='string', name='struct_dir', required=True)

        op = self.outputPortsDescr
        op.append(datatype='list', name='gpf_list')
        op.append(datatype='list', name='dpf_list')
        op.append(datatype='string', name='struct_dir')

        code = """def doit(self, gpf_file, dpf_file, struct_dir):
    import os
    import shutil
    from AutoDockTools.VisionInterface.Adt.dpf_template import dpf_template
    from AutoDockTools.VisionInterface.Adt.gpf_template import gpf_template

    if dpf_file == None and gpf_file == None:
        print "ERROR: DPF and GPF input missing"
        return 'stop'


    if dpf_file != None:
        dpf_file_path = dpf_file.fullpath

        if not(os.path.exists(dpf_file_path)):
            print "ERROR: DPF template file " + dpf_file_path + " does not exist!"
            return 'stop'

    if gpf_file != None:
        gpf_file_path = gpf_file.fullpath

        if not(os.path.exists(gpf_file_path)):
            print "ERROR: GPF template file " + gpf_file_path + " does not exist!"
            return 'stop'

    name_list = set()
    d = os.path.abspath(struct_dir)

    for i in os.listdir(struct_dir):
        if i.endswith(".pdbqt") or i.endswith(".pdb") or i.endswith(".pqr"):
            name_list.add(i.split('.')[0])

    dpf_list = []
    gpf_list = []

    if dpf_file != None:
        for i in name_list:
            d_dst = os.path.join(d, i + '.dpf')
            dpf_list.append(d_dst)       

            if not(os.path.exists(d_dst)):
                shutil.copyfile(dpf_file_path, d_dst)

    if gpf_file != None:
        for i in name_list:
            g_dst = os.path.join(d, i + '.gpf')
            gpf_list.append(g_dst)       

            if not(os.path.exists(g_dst)):
                shutil.copyfile(gpf_file_path, g_dst)
  

    self.outputData(dpf_list=dpf_list, gpf_list=gpf_list, struct_dir=struct_dir)
"""
        self.setFunction(code)
예제 #25
0
 def afterAddingToNetwork(self):
     NetworkNode.afterAddingToNetwork(self)
     # run this node so the value is output
     self.run(force=1)