示例#1
0
def load():
   try:
      r = 0
      list = glob(ent_dir)
      list.sort()
#      list = [ "pdb/vq" ]
      for dir in list:
         sys.__stdout__.write("\n"+dir)
         sys.__stdout__.flush()
         for file in glob(dir+"/pdb*"):
            name = os.path.split(file)[-1]
            name = string.split(name,'.')[0]
            cmd.disable()
            cmd.load(file,name)
            cmd.show_as("cartoon",name)
            cmd.refresh()
            cmd.dss(name)
            cmd.refresh()
            time.sleep(0.1)
            sys.__stdout__.write(".")
            sys.__stdout__.flush()
         sys.__stdout__.write("("+str(cmd.count_atoms())+")")
         sys.__stdout__.flush()         
         cmd.dss()
         cmd.delete('all')
   except:
      traceback.print_exc()
示例#2
0
 def _view(mol, viewname):
     topo = tempname(suffix=".cif")
     xtc = tempname(suffix=".xtc")
     mol.write(topo)
     mol.write(xtc)
     cmd.delete(viewname)
     cmd.load(topo, viewname)
     cmd.load_traj(xtc, viewname, state=1)
     cmd.dss()  # Guess SS
     os.remove(topo)
     os.remove(xtc)
     showing[viewname] = True
示例#3
0
def clean(pose):
    """Deletes everything and load the validated models"""
    cmd.delete('all')
    cmd.load('%s_Ca.pdb' % pose)
    cmd.load('%s_Cb.pdb' % pose)
    cmd.load('%s_CaCb.pdb' % pose)
    cmd.intra_fit('%s_Ca' % pose, 0, quiet=1)
    cmd.intra_fit('%s_Cb' % pose, 0, quiet=1)
    cmd.intra_fit('%s_CaCb' % pose, 0, quiet=1)
    cmd.dss('all')
    cmd.disable('%s_Ca' % pose)
    cmd.disable('%s_Cb' % pose)
示例#4
0
    def _gpssLoadPdb(pdbCode,reinitialize):

        pdbCode = pdbCode.lower()
        
        GPSSpdbCode = 'GPSS_' + pdbCode

        _gpssVersionCheck('0.3');

        if cmd.get_names().count(GPSSpdbCode) < 1:
                
            if reinitialize==1:
                cmd.do('reinitialize')
                
            pdbFile = urllib2.urlopen('http://gpss.mcsg.anl.gov/webservices/'+
                                      'gpssServerPymol.php?pdbId='+
                                      pdbCode + '&mode=pdbFile').read()
            
            
            if pdbFile:
                pdbFile = urllib2.urlopen('http://gpss.mcsg.anl.gov/webservices/'+
                                          'gpssServerPymol.php?pdbId='+
                                          pdbCode + '&mode=pdbFile')
                cmd.read_pdbstr(pdbFile.read(),GPSSpdbCode)
            
                # Make structure pretty
                # David Borhani, 14-JAN-2009
                # Changed to color by chain, show lines only, keep user's bg color.
                #cmd.do('set bg_rgb=[1,1,1]')
                #cmd.do('hide everything')
                cmd.hide('everything', GPSSpdbCode)
                #cmd.do('dss')
                cmd.dss(GPSSpdbCode)
                #util.cbc(selection='(GPSS-' + pdbCode + ')',first_color=7,quiet=1,legacy=1,_self=cmd)
                #sel_string = '("' + GPSSpdbCode + '")'
                #cmd.do('util.cbc(selection=' + sel_string + ',first_color=9,quiet=1,legacy=1)')
                cmd.do('util.cbc(selection=("' + GPSSpdbCode + '"),first_color=9,quiet=1,legacy=1)')
                #cmd.do('show lines, ' + GPSSpdbCode)
                cmd.show('lines', GPSSpdbCode)
                #cmd.do('show cartoon, ' + GPSSpdbCode)
                #cmd.do('color gray')
                return True
            else:
                tkMessageBox.showerror('GPSS                                    ',
                                       pdbCode + ' was not found on the GPSS server.')

            #cmd.do('zoom GPSS-'+pdbCode)
            cmd.zoom(GPSSpdbCode, animate=0)

        else:

            return True
示例#5
0
def load_crd(filename, object=''):
    """
        Load a fDynamo coordinates file (.crd)

        Parameters
        ----------
        filename : str
            file path
        object : str, optional
            name of the object (def: filename prefix)
    """

    if not object:
        object = "".join(os.path.basename(filename).rpartition('.')[:-2])

    # read file as list of strings
    with open(filename, "rt") as f:
        crd_file = f.readlines()
        # remove comment lines, trailing comments and space split
        crd_file = [
            line.split("!")[0].split() for line in crd_file
            if line.strip() and not line.startswith("!")
        ]

    # reversed dictionary of atomic numbers to elements
    atomic_number_inv = {n: elem for elem, n in atomic_number.items()}

    # create new model and append crd's atoms
    model = Indexed()
    a = Atom()
    a.hetatm = False
    for line in crd_file:
        if line[0].lower() == "subsystem":
            a.segi = str(line[2])
        elif line[0].lower() == "residue":
            a.resi_number = int(line[1])
            a.resn = str(line[2])
        elif len(line) != 6:
            continue
        else:
            a.name = str(line[1])
            a.symbol = atomic_number_inv[int(line[2])]
            a.coord = (float(line[3]), float(line[4]), float(line[5]))
            model.add_atom(deepcopy(a))
    model.update_index()
    cmd.load_model(model, object)
    cmd.rebond(object)
    cmd.dss(object)

    print(f" pyDYNAMON: \"{filename}\" loaded as \"{object}\"")
if show_fragments:
    files = glob(f'{path}/Mpro-x*.mol2')
    for filename in files:
        print(filename)
        match = re.search('Mpro-(?P<fragment>x\d+)_', filename)
        fragment = match.group('fragment')
        cmd.load(filename, f'fragment-{fragment}')
    cmd.select('fragments', 'fragments-*')

# remove waters
cmd.remove('resn HOH')
cmd.deselect()

# Show molecular representation
cmd.hide('all')
cmd.dss('6lu7')
cmd.bg_color('white')
util.cbaw('*-protein')

cmd.show('sticks', f'*-protein and not hydrogen')
cmd.show('surface', f'*-protein')
cmd.disable('*-protein')
cmd.enable('N3-protein')

#cmd.show('sticks', f'({molecule}-protein and not hydrogen) within 7 of N3-ligand')
cmd.set('surface_color', 'white')

molecule = 'N3'
cmd.show('sticks', f'{molecule}-ligand and not hydrogen')
#cmd.show('cartoon', f'{molecule}-protein')
if show_fragments:
示例#7
0
def bfactorRamp(mol,
                color1="blue",
                color2="red",
                color3="yellow",
                cartoon="off",
                cartoon_putty="off",
                invcolor="grey40",
                style="off",
                fancy="off"):
    '''
DESCRIPTION
    
    Version: bfactorRamp_v1.1
    Author : Erik Breslmayr; April 2020
    
    - bfactorRamp colors the molecule of choise in regard of bfactors provided in the pdb file and adds a color legend starting from the lowest to the highest bfactor. 
    - Additionally some styling features are included, for nicer visualization
    
    Usage: bfactorRamp mol, color1, color2, color3, cartoon=on or off, cartoon_putty=on or off, invcolor=color, style=on or off, fancy=on or off
    
    mol = any object selection (within one single object!)
    color1,2,3 (optional) = three colors, first for lowest, second for middle and third for highest bfactors
    cartoon (optional) = on or off -> enbales cartoon representation
    cartoon_putty (optional) = on or off -> enbales cartoon_putty representation
    invcolor (optional) = add color, which should represent not selected atoms
    style (optional) = styles the cartoon representation in regard of helix oval length and width
    fancy = changes to fancy helices representaton
    
    Defaults:
    - spectrum colors: blue, red, yellow
    - cartoon:         off
    - cartoon_putty:   off
    - invcolor:        grey40 
    - style:           off
    - fancy:           off
    
    Examples: 
    > bfactorRamp objectName -> uses all defaults
    > bfactorRamp objectName, red, green, grey -> changes the colors for the spectrum
    > bfactorRamp objectName, cartoon=on -> turns cartoon representation on
    > bfactorRamp objectName, cartoon=on -> turns cartoon_putty representation on
    > bfactorRamp objectName, invcolor=green -> changes the color of the not selected region to green
    > bfactorRamp objectName, style=on -> changes helices style and not selected region will be transparent
    > bfactorRamp objectName, fancy=on -> changes helices style to fancy and not selected region will be transparent
    '''
    obj = cmd.get_object_list(mol)[0]
    range = cmd.spectrum("b", "%s %s %s" % (color1, color2, color3), mol)
    cmd.select("invSele", "!%s" % (mol))
    cmd.color(invcolor, "invSele")
    cmd.ramp_new("ramp",
                 obj,
                 range,
                 color=["%s" % (color1),
                        "%s" % (color2),
                        "%s" % (color3)])
    #reset styles
    cmd.set("cartoon_transparency", 0, "enabled")
    cmd.set("cartoon_oval_length", 1.2, obj)
    cmd.set("cartoon_oval_width", 0.25, obj)
    cmd.set("cartoon_fancy_helices", 0, obj)
    cmd.set("cartoon_highlight_color", -1, obj)

    if cartoon == "on":
        cmd.show_as("cartoon", mol)
        cmd.dss(obj, 1)
        cmd.recolor()
    if cartoon_putty == "on":
        cmd.show_as("cartoon", mol)
        cmd.cartoon("putty", mol)
        cmd.recolor()
    if style == "on":
        cmd.set("cartoon_transparency", 0.5, "invSele")
        cmd.set("cartoon_oval_length", 0.8, obj)
        cmd.set("cartoon_oval_width", 0.2, obj)
    if fancy == "on":
        cmd.set("cartoon_transparency", 0.5, "invSele")
        cmd.set("cartoon_highlight_color", invcolor, obj)
        cmd.set("cartoon_fancy_helices", 1, obj)

    #Output for screen
    print("for help type: help bfactorRamp")
    print("")
    print("Minimum bfactor: %s | Maximum bfactor: %s" % (range[0], range[1]))
    print("")
    print("Following settings were taken:")
    print("- mol           : %s" % (obj))
    print("- color1,2,3    : %s, %s, %s" % (color1, color2, color3))
    print("- cartoon       : %s" % (cartoon))
    print("- cartoon_putty : %s" % (cartoon_putty))
    print("- invcolor      : %s" % (invcolor))
    print("- style         : %s" % (style))
    print("- fancy         : %s" % (fancy))

    return (color1, color2, color3)
示例#8
0
#pymol.finish_launching()

# Delete everything
cmd.rewind()
cmd.reset()
cmd.delete('all')

# Retain order and IDs for imported atoms
cmd.set('retain_order', 1)
cmd.set('pdb_retain_ids', 1)

# Load PDB file
cmd.load(pdb_filename, 'complex')

# Recognize helices and sheets
cmd.dss()

# Align everything
cmd.intra_fit('all')

# Set up display
cmd.remove('resn WAT')  # remove waters
cmd.select('receptor', '(not resn MOL) and (not resn WAT) and (not hydrogen)')
cmd.select('ligand', 'resn MOL')
cmd.deselect()
cmd.hide('all')
cmd.show('cartoon', 'receptor')
cmd.show('spheres', 'ligand')
util.cbay('ligand')
cmd.color('green', 'receptor')
示例#9
0


cmd.do('set all_states,0')

cmd.set('two_sided_lighting', 'on')
cmd.set('transparency', '0.2')

cmd.load('../data/origins.pdb', 'origins')
cmd.load('../data/v_origins.pdb', 'v_origins')
cmd.show('nb_spheres', 'origins')
cmd.show('nb_spheres', 'v_origins')

load_trajectory = $load_trajectory

if load_trajectory:
	cmd.load("../data/trajectory.pdb", "structure", discrete=1)
	cmd.dss("structure")

else:
	cmd.load('../data/$pdb_representant', 'structure')

cmd.hide('lines', 'structure')
cmd.show('cartoon', 'structure')
cmd.color('gray', 'structure')

cmd.mset("1 -%d" % cmd.count_states())
for frame in range(1,cmd.count_states()+1):
	cmd.mdo(frame, "computeSpheres(" + str(frame) + ")")
cmd.frame(1)
示例#10
0
def read_moestr(contents,
                object,
                state=0,
                finish=1,
                discrete=1,
                quiet=1,
                zoom=-1,
                _self=cmd):
    moestr = contents
    name = object

    import sys
    if sys.version_info[0] > 2 and isinstance(moestr, bytes):
        moestr = moestr.decode()

    cmd = _self
    mr = MOEReader()
    mr.appendFromStr(moestr)
    split_chains = cmd.get_setting_int("moe_separate_chains")
    cmd.group(name)
    if hasattr(mr, 'system'):
        have_valences = 0
        chain_count = 0
        cmd.set_color("_aseg0", [1.0, 1.0, 1.0])
        aseg_color = cmd.get_color_index("_aseg0")
        aseg_flag = 0
        aseg_rep = {}
        model = Indexed()
        molecule = mr.system['molecule']
        if 'atoms' in molecule:
            n_atom = molecule['atoms']
            model.atom = [Atom() for x in range(n_atom)]
        residues = {}
        chains = {}
        for columns, data in molecule['attr']:
            for row in data:
                cur_atom = None
                for key, value in zip(columns, row):
                    key = key[0]
                    if key == 'ID':
                        ID = value
                    else:
                        aProp = _atom_prop_map.get(key, None)
                        if aProp != None:
                            setattr(model.atom[ID - 1], aProp, value)
                        else:
                            xyz = _atom_coord_map.get(key, None)
                            if xyz != None:
                                coord = list(model.atom[ID - 1].coord)
                                coord[xyz] = value
                                model.atom[ID - 1].coord = coord
                            elif key in _atom_vis_map:
                                atom = model.atom[ID - 1]
                                if hasattr(atom, 'visible'):
                                    visible = atom.visible
                                else:
                                    visible = _default_visible
                                if key == 'aBondLook':
                                    if value == 'cylinder':
                                        atom.visible = 0x00000001 | visible
                                    elif value == 'line':
                                        atom.visible = 0x00000080 | visible
                                    elif value == 'none':
                                        atom.visible = -129 & Visible  # 0xFFFFFF7F
                                elif key == 'aNucleusLook':
                                    if value == 'sphere':
                                        atom.visible = 0x00000002 | visible
                                    elif value == 'small-sphere':  # need to set sphere_scale=0.2 for these atoms
                                        atom.visible = 0x00000002 | visible
                                        atom.sphere_scale = 0.2
                                    elif value == 'point':  # nonbonded
                                        atom.visible = 0x00000800 | visible
                                    elif value == 'none':
                                        atom.visible = -2067 & visible  # 0xFFFFF7ED
                                elif key == 'aHidden':
                                    atom.visible = 0
                                    atom.hidden = 1
                                if hasattr(
                                        atom, 'hidden'
                                ):  # be sure that hidden atoms aren't shown
                                    atom.visible = 0
                            elif key in _atom_color_map:
                                if key == 'aRGB':
                                    model.atom[ID - 1].trgb = value
                                elif key == 'aColorBy':
                                    model.atom[ID - 1].aColorBy = value
                            elif key in _atom_label_map:
                                atom = model.atom[ID - 1]
                                if hasattr(atom, 'label_dict'):
                                    atom.label_dict[key] = None
                                else:
                                    atom.label_dict = {key: None}
                            elif key in _residue_prop_map:
                                resi_dict = residues.get(ID, {})
                                resi_dict[key] = value
                                residues[ID] = resi_dict
                            elif key in _chain_prop_map:
                                chain_dict = chains.get(ID, {})
                                if ID not in chains:
                                    chain_count = chain_count + 1
                                    chain_dict['count'] = chain_count
                                chain_dict[key] = value
                                chains[ID] = chain_dict
        chn_keys = list(chains.keys())
        chn_keys.sort()
        res_keys = list(residues.keys())
        res_keys.sort()
        # map chain properties onto residues
        chn_resi = 0
        ch_colors = copy.deepcopy(_ch_colors)
        unique_chain_names = {}
        for chn_idx in chn_keys:
            chain_dict = chains[chn_idx]
            cName = make_valid_name(chain_dict.get('cName', ''))
            segi = cName[0:4]
            chain = cName[-1:]
            if not len(cName):
                if 'count' in chain_dict:
                    cName = "chain_" + str(chain_dict['count'])
                else:
                    cName = str(chn_idx)
            if cName not in unique_chain_names:
                unique_chain_names[cName] = cName
            else:
                cnt = 2
                while (cName + "_" + str(cnt)) in unique_chain_names:
                    cnt = cnt + 1
                newCName = cName + "_" + str(cnt)
                unique_chain_names[newCName] = cName
                cName = newCName
            chain_dict['chain_color'] = ch_colors[0]
            ch_colors = ch_colors[1:] + [ch_colors[0]]
            cResCount = chain_dict.get('cResidueCount', 0)
            for res_idx in range(chn_resi, chn_resi + cResCount):
                resi_dict = residues[res_keys[res_idx]]
                resi_dict['chain'] = chain
                resi_dict['segi'] = segi
                resi_dict['cName'] = cName
                resi_dict['chain_dict'] = chain_dict
            chn_resi = chn_resi + cResCount
        # map residue properties onto atoms
        res_atom = 0
        for res_idx in res_keys:
            resi_dict = residues[res_idx]
            rRibbonMode = resi_dict.get('rRibbonMode', 'none')
            rAtomCount = resi_dict['rAtomCount']
            rType = resi_dict.get('rType', '')
            if rAtomCount > 0:
                for at_idx in range(res_atom, res_atom + rAtomCount):
                    atom = model.atom[at_idx]
                    setattr(
                        atom, 'resi',
                        string.strip(
                            str(resi_dict.get('rUID', '')) +
                            resi_dict.get('rINS', '')))
                    setattr(atom, 'resn', resi_dict.get('rName', ''))
                    setattr(atom, 'chain', resi_dict.get('chain', ''))
                    setattr(atom, 'segi', resi_dict.get('segi', ''))
                    setattr(atom, 'custom', resi_dict.get('cName', ''))
                    # add labels
                    if hasattr(atom, 'label_dict'):
                        label = ''
                        label_dict = atom.label_dict
                        if 'aLabelElement' in label_dict:
                            label = atom.symbol
                        if 'aLabelRes' in label_dict:
                            if len(label):
                                label = label + ","
                            label = label + atom.resn + "_" + atom.resi
                        if 'aLabelName' in label_dict:
                            if len(label):
                                label = label + "."
                            label = label + atom.name
                        atom.label = label
                    if rType not in ['none', 'heme']:
                        atom.hetatm = 0  # all normal atoms
                    else:
                        atom.flags = 0x02000000  # hetatom or ligand -- ignore when surfacing

                    if rRibbonMode != 'none':
                        if hasattr(atom, 'visible'):
                            visible = atom.visible
                        else:
                            visible = _default_visible

                        rRibbonColorBy = resi_dict['rRibbonColorBy']
                        repeat = 1
                        while repeat:
                            repeat = 0
                            if rRibbonColorBy in ['rgb', 'r:rgb'
                                                  ]:  # handled automatically
                                pass
                            elif rRibbonColorBy == 'chain':
                                chain_dict = resi_dict['chain_dict']
                                cColorBy = chain_dict['cColorBy']
                                if cColorBy == 'rgb':
                                    cColorBy = 'c:rgb'
                                rRibbonColorBy = cColorBy
                                repeat = 1

                        rRibbon_color = 0
                        rRibbon_trgb = 0xFFFFFF  # default -- white

                        # now color ribbon
                        if rRibbonColorBy == 'r:rgb':
                            rRibbon_trgb = resi_dict.get('rRGB', 0xFFFFFF)
                        elif rRibbonColorBy == 'rgb':
                            rRibbon_trgb = resi_dict.get(
                                'rRibbonRGB', 0xFFFFFF)
                        elif rRibbonColorBy == 'c:rgb':
                            chain_dict = resi_dict['chain_dict']
                            rRibbon_trgb = chain_dict.get('cRGB', 0xFFFFFF)
                        elif rRibbonColorBy == 'r:aseg':
                            rRibbon_trgb = None
                            rRibbon_color = aseg_color
                            aseg_flag = 1
                        elif rRibbonColorBy == 'tempfactor':
                            pass  # TO DO
                        elif rRibbonColorBy == 'c:number':  # per chain colors
                            rRibbon_trgb = chain_dict['chain_color']
                        if rRibbonMode in ['line', 'trace']:
                            atom.visible = 0x00000040 | visible  # PyMOL ribbon
                            if rRibbon_trgb != None:
                                atom.ribbon_trgb = rRibbon_trgb
                            else:
                                atom.ribbon_color = rRibbon_color
                            aseg_rep['ribbon'] = 1
                        else:
                            atom.visible = 0x00000020 | visible  # PyMOL cartoon
                            if rRibbon_trgb != None:
                                atom.cartoon_trgb = rRibbon_trgb
                            else:
                                atom.cartoon_color = rRibbon_color
                            aseg_rep['cartoon'] = 1

                    if hasattr(atom, 'label'):
                        if hasattr(atom, 'visible'):
                            visible = atom.visible
                        else:
                            visible = _default_visible
                        atom.visible = 0x00000028 | visible  # labels
                    if not hasattr(atom, 'aColorBy'):
                        atom.aColorBy = 'element'
                    if hasattr(atom, 'aColorBy'):
                        aColorBy = atom.aColorBy
                        repeat = 1
                        while repeat:
                            repeat = 0
                            if aColorBy == 'ribbon':
                                aColorBy = resi_dict.get('rRibbonColorBy')
                                if aColorBy == 'rgb':
                                    aColorBy = 'rib:rgb'
                                else:
                                    repeat = 1
                                # TO DO still need to handle "cartoon_color", "ribbon_color"
                            elif aColorBy == 'element':
                                if hasattr(atom, 'trgb'):
                                    del atom.trgb
                            elif aColorBy in ['rgb', 'a:rgb'
                                              ]:  # handled automatically
                                pass
                            elif aColorBy == 'residue':
                                rColorBy = resi_dict.get('rColorBy')
                                if rColorBy == 'rgb':
                                    rColorBy = 'r:rgb'
                                aColorBy = rColorBy
                                repeat = 1
                            elif aColorBy == 'chain':
                                chain_dict = resi_dict['chain_dict']
                                cColorBy = chain_dict['cColorBy']
                                if cColorBy == 'rgb':
                                    cColorBy = 'c:rgb'
                                aColorBy = cColorBy
                                repeat = 1

                        # now color atom...
                        if aColorBy == 'r:rgb':
                            atom.trgb = resi_dict.get('rRGB', 0xFFFFFF)
                        elif aColorBy == 'rib:rgb':
                            atom.trgb = resi_dict.get('rRibbonRGB', 0xFFFFFF)
                        elif aColorBy == 'c:rgb':
                            chain_dict = resi_dict['chain_dict']
                            atom.trgb = chain_dict.get('cRGB', 0xFFFFFF)
                        elif aColorBy == 'r:aseg':
                            pass  # TO DO
                        elif aColorBy == 'tempfactor':
                            pass  # TO DO
                        elif aColorBy == 'c:number':  # per chain colors
                            atom.trgb = chain_dict['chain_color']

                res_atom = res_atom + rAtomCount
        bond_list = molecule.get('bond', [])
        for bond in bond_list:
            new_bond = Bond()
            new_bond.index = [bond[0] - 1, bond[1] - 1]
            if len(bond) > 2:
                new_bond.order = bond[2]
                if bond[2] == 2:  # work around .MOE bug with triple bonds
                    if model.atom[new_bond.index[0]].hybridization == 'sp':
                        if model.atom[new_bond.index[1]].hybridization == 'sp':
                            new_bond.order = 3
                have_valences = 1
            model.bond.append(new_bond)
        if 'ViewOrientationY' in mr.system:
            vy = mr.system['ViewOrientationY']
            vz = mr.system['ViewOrientationZ']
            pos = mr.system['ViewLookAt']
            scale = mr.system['ViewScale']
            vx = cpv.cross_product(vy, vz)
            m = [cpv.normalize(vx), cpv.normalize(vy), cpv.normalize(vz)]
            m = cpv.transpose(m)
            asp_rat = 0.8  # MOE default (versus 0.75 for PyMOL)
            cmd.set("field_of_view", 25.0)
            fov = float(cmd.get("field_of_view"))
            window_height = scale * asp_rat
            dist = (0.5 * window_height) / math.atan(3.1415 *
                                                     (0.5 * fov) / 180.0)
            new_view = tuple(m[0] + m[1] + m[2] + [0.0, 0.0, -dist] + pos +
                             [dist * 0.5, dist * 1.5, 0.0])
            cmd.set_view(new_view)
            zoom = 0
        cmd.set("auto_color", 0)
        cmd.set_color("carbon", [0.5, 0.5, 0.5])  # default MOE grey

        obj_name = name + ".system"
        if split_chains < 0:  # by default, don't split chains if over 50 objects would be created
            if len(unique_chain_names) > 50:
                split_chains = 0
        if not split_chains:
            cmd.load_model(model,
                           obj_name,
                           state=state,
                           finish=finish,
                           discrete=discrete,
                           quiet=quiet,
                           zoom=zoom)
            obj_name_list = [obj_name]
        else:
            cmd.load_model(model,
                           obj_name,
                           state=state,
                           finish=finish,
                           discrete=discrete,
                           quiet=1,
                           zoom=zoom)
            obj_name_list = []
            system_name = obj_name
            for chain in unique_chain_names.keys():
                obj_name = name + "." + chain
                obj_name_list.append(obj_name)
                cmd.select("_moe_ext_tmp",
                           "custom %s" % chain,
                           domain=system_name)
                cmd.extract(obj_name, "_moe_ext_tmp", quiet=quiet, zoom=0)
                # cmd.extract(obj_name,system_name+" and text_type %s"%chain,quiet=quiet)
                cmd.delete("_moe_ext_tmp")
            if not cmd.count_atoms(system_name):
                cmd.delete(system_name)
            else:
                obj_name_list.append(system_name)
            cmd.order(name + ".*", sort=1)
        for obj_name in obj_name_list:
            cmd.set("stick_radius", 0.1, obj_name)
            cmd.set("line_width", 2.0, obj_name)
            cmd.set("label_color", "white", obj_name)
            cmd.set("nonbonded_size", 0.05,
                    obj_name)  # temporary workaround...
            if have_valences:  # if this MOE file has valences, then show em!
                cmd.set("valence", 1, obj_name)
                cmd.set("stick_valence_scale", 1.25, obj_name)
            if aseg_flag:
                cmd.dss(obj_name)
                if 'cartoon' in aseg_rep:
                    cmd.set("cartoon_color", "red",
                            obj_name + " and cartoon_color _aseg0 and ss h")
                    cmd.set("cartoon_color", "yellow",
                            obj_name + " and cartoon_color _aseg0 and ss s")
                    cmd.set(
                        "cartoon_color", "cyan",
                        obj_name + " and cartoon_color _aseg0 and not ss h+s")
                if 'ribbon' in aseg_rep:
                    cmd.set("ribbon_color", "red",
                            obj_name + " and ribbon_color _aseg0 and ss h"
                            )  # need selection op ribbon_color
                    cmd.set("ribbon_color", "yellow",
                            obj_name + " and ribbon_color _aseg0 and ss s")
                    cmd.set(
                        "ribbon_color", "cyan",
                        obj_name + " and ribbon_color _aseg0 and not ss h+s")
        if 'ViewZFront' in mr.system:
            moe_front = mr.system['ViewZFront']
            moe_width = mr.system['ViewZWidth']
            extent = cmd.get_extent(
                name)  # will this work with groups? TO DO: check!
            dx = (extent[0][0] - extent[1][0])
            dy = (extent[0][1] - extent[1][1])
            dz = (extent[0][2] - extent[1][2])
            half_width = 0.5 * math.sqrt(dx * dx + dy * dy + dz * dz)
            cmd.clip("atoms", 0.0, name)
            cur_view = cmd.get_view()
            center = (cur_view[-3] +
                      cur_view[-2]) * 0.5  # center of clipping slab
            front = center - half_width
            back = center + half_width
            width = half_width * 2
            new_view = tuple(
                list(cur_view[0:15]) + [
                    front + width * moe_front, front + width *
                    (moe_front + moe_width), 0.0
                ])
            cmd.set_view(new_view)
        if 'graphics' in mr.system:
            cgo_cnt = 1
            lab_cnt = 1
            unique_cgo_names = {}
            for graphics in mr.system['graphics']:
                cgo = []
                for gvertex in graphics.get('gvertex', []):
                    vrt = gvertex[0]
                    seg_list = gvertex[1]['seg']
                    idx = gvertex[1]['idx']
                    len_idx = len(idx)
                    if not cmd.is_list(seg_list):
                        seg_list = [seg_list] * (len_idx / seg_list)
                    last_seg = None
                    ix_start = 0
                    for seg in seg_list:
                        if seg != last_seg:
                            if last_seg != None:
                                cgo.append(END)
                            if seg == 3:
                                cgo.extend([BEGIN, TRIANGLES])
                            elif seg == 2:
                                cgo.extend([BEGIN, LINES])
                            elif seg == 1:
                                cgo.extend([BEGIN, POINTS])
                        ix_stop = seg + ix_start
                        if seg == 3:
                            for s in idx[ix_start:ix_stop]:
                                v = vrt[s - 1]
                                cgo.extend([
                                    COLOR, (0xFF & (v[0] >> 16)) / 255.0,
                                    (0xFF & (v[0] >> 8)) / 255.0,
                                    (0xFF & (v[0])) / 255.0
                                ])
                                if len(v) > 4:
                                    cgo.extend([NORMAL, v[4], v[5], v[6]])
                                cgo.extend([VERTEX, v[1], v[2], v[3]])
                        elif seg == 2:
                            for s in idx[ix_start:ix_stop]:
                                v = vrt[s - 1]
                                cgo.extend([
                                    COLOR, (0xFF & (v[0] >> 16)) / 255.0,
                                    (0xFF & (v[0] >> 8)) / 255.0,
                                    (0xFF & (v[0])) / 255.0
                                ])
                                if len(v) > 4:
                                    cgo.extend([NORMAL, v[4], v[5], v[6]])
                                cgo.extend([VERTEX, v[1], v[2], v[3]])
                        elif seg == 1:
                            for s in idx[ix_start:ix_stop]:
                                v = vrt[s - 1]
                                cgo.extend([
                                    COLOR, (0xFF & (v[0] >> 16)) / 255.0,
                                    (0xFF & (v[0] >> 8)) / 255.0,
                                    (0xFF & (v[0])) / 255.0
                                ])
                                if len(v) > 4:
                                    cgo.extend([NORMAL, v[4], v[5], v[6]])
                                cgo.extend([VERTEX, v[1], v[2], v[3]])
                        ix_start = ix_stop
                        last_seg = seg
                    if last_seg != None:
                        cgo.append(END)
                for gtext in graphics.get('gtext', []):
                    lab_name = name + ".label_%02d" % lab_cnt
                    exists = 0
                    for entry in gtext:
                        exists = 1
                        cmd.pseudoatom(lab_name,
                                       pos=[
                                           float(entry[1]),
                                           float(entry[2]),
                                           float(entry[3])
                                       ],
                                       color="0x%06x" % entry[0],
                                       label=entry[4])
                    if exists:
                        cmd.set('label_color', -1, lab_name)
                        lab_cnt = lab_cnt + 1
                    # TO DO -- via CGO's?

                if len(cgo):
                    cgo_name = name + "." + make_valid_name(
                        graphics.get('GTitle', 'graphics'))
                    if cgo_name not in unique_cgo_names:
                        unique_cgo_names[cgo_name] = cgo_name
                    else:
                        cnt = 2
                        while cgo_name + "_" + str(cnt) in unique_cgo_names:
                            cnt = cnt + 1
                        new_name = cgo_name + "_" + str(cnt)
                        unique_cgo_names[new_name] = new_name
                        cgo_name = new_name
                    cmd.load_cgo(cgo,
                                 cgo_name,
                                 state=state,
                                 quiet=quiet,
                                 zoom=0)
                    cgo_cnt = cgo_cnt + 1
                    cmd.set("two_sided_lighting", 1)  # global setting...
                    cmd.set("cgo_line_width", 2, cgo_name)
                    if 'GTransparency' in graphics:
                        g_trans = graphics['GTransparency']
                        if len(g_trans) >= 2:
                            if g_trans[0] != 0:
                                cmd.set('cgo_transparency',
                                        '%1.6f' % (g_trans[0] / 255.0),
                                        cgo_name)
                                cmd.set('transparency_global_sort')
        if 'meter' in mr.system:
            meter_name = name + ".meter"
            exists = 0
            for meter_block in mr.system['meter']:
                if meter_block[0][0:2] == ['type', 'atoms']:
                    for meter in meter_block[1]:
                        (type, atoms) = meter[0:2]
                        arg = tuple([meter_name] + list(
                            map(lambda x, o=name: o + " and id " + str(x - 1),
                                atoms)))
                        getattr(cmd, type)(*arg)
                        exists = 1
            if exists:
                cmd.color("green", meter_name)
#            print mr.system['meter']
    elif hasattr(mr, 'feature'):
        model = Indexed()
        cols = mr.feature[0]
        rows = mr.feature[1]
        col = {}
        cnt = 0
        for a in cols:
            col[a] = cnt
            cnt = cnt + 1
        for row in rows:
            atom = Atom()
            atom.coord = [row[col['x']], row[col['y']], row[col['z']]]
            atom.vdw = row[col['r']]
            atom.custom = row[col['expr']]
            model.atom.append(atom)
        obj_name = name + ".feature"
        cmd.load_model(model,
                       obj_name,
                       state=state,
                       finish=finish,
                       discrete=discrete,
                       quiet=quiet,
                       zoom=zoom)
        rank = 1
        for row in rows:
            cmd.color("0x%06x" % row[col['color']],
                      obj_name + " & id %d" % (rank - 1))
            rank = rank + 1
        cmd.show("mesh", obj_name)
        cmd.set("min_mesh_spacing", 0.55, obj_name)
        cmd.label(obj_name, "' '+custom")
        cmd.set("label_color", "yellow", obj_name)
    else:
        print(dir(mr))
示例#11
0
 def test_dss(self):
     ss_list = []
     cmd.fab('A' * 6, ss=1)
     cmd.dss()
     cmd.iterate('2-5/CA', 'ss_list.append(ss)', space=locals())
     self.assertEqual(ss_list, ['H', 'H', 'H', 'H'])
# pymol.finish_launching()

# Delete everything
cmd.rewind()
cmd.reset()
cmd.delete("all")

# Retain order and IDs for imported atoms
cmd.set("retain_order", 1)
cmd.set("pdb_retain_ids", 1)

# Load PDB file
cmd.load(pdb_filename, "complex")

# Recognize helices and sheets
cmd.dss()

# Align everything
cmd.intra_fit("all")

# Set up display
cmd.remove("resn WAT")  # remove waters
cmd.select("receptor", "(not resn MOL) and (not resn WAT) and (not hydrogen)")
cmd.select("ligand", "resn MOL")
cmd.deselect()
cmd.hide("all")
cmd.show("cartoon", "receptor")
cmd.show("spheres", "ligand")
util.cbay("ligand")
cmd.color("green", "receptor")
示例#13
0
 def test_dss(self):
     ss_list = []
     cmd.fab('A' * 6, ss=1)
     cmd.dss()
     cmd.iterate('2-5/CA', 'ss_list.append(ss)', space=locals())
     self.assertEqual(ss_list, ['H', 'H', 'H', 'H'])
示例#14
0
    def load_cnstr(self):
        """
        Load constraint file
        """
        self._cnstrfile.load()

        names = []
        eval_method = self.settings.config.get('eval_method', 'contact')
        contact_type = self.settings.config.get('contact_type')
        groupname = self.settings.args.get('group')

        if self.settings.args.get('writefiles', False):
            outfile = open(
                "%s.out" % os.path.join(self.settings.args.get('output'),
                                        self.settings.args.get('prefix')), 'w')
            extra = "\t".join(("lower", "target", "upper")) if \
                eval_method == "bound" else ""
            outfile.write("\t".join(("resid1", "resid2", "atm1", "atm2",
                                     "dist_ref" if self._reflag else "dist",
                                     eval_method, extra, "spec")))
        else:
            outfile = None

        target, upper, lower, spec = None, None, None, None
        dist = []
        for idline in self._cnstrfile.lines:
            # For each restraint
            # print(idline + 1 == len(self._cnstrfile.lines))
            # If outfile and assignflag OR last line, save oldresults
            line = self._cnstrfile.lines[idline]

            # If assignflag, initialize all cnstr vars
            # Else if ambiflag, add vars to cnstr
            # Else return error
            resids = (line.get('resid1', ''), line.get('resid2', ''))
            atms = (line.get('atm1', ''), line.get('atm2', ''))
            ambiflag = line.get('ambiflag', False)
            assignflag = line.get('assignflag', False)
            if assignflag:
                dist = []
                spec = line.get('spec', 'noname')
                target = line.get('target', None)
                upper = line.get('upper', None)
                lower = line.get('lower', None)
                if target:
                    upper = float(target) + float(upper) if upper else None
                    lower = float(target) - float(lower) if lower else None

            if groupname and line.get(groupname) in ("False", "True"):
                group = groupname if line.get(groupname) == "True" \
                    else "un" + groupname
            else:
                group = line.get('group', None)

            extra = "\t".join((str(lower), str(target), str(upper))) if \
                eval_method == "bound" else ""
            # TODO: add a violation tolerance ?

            if '' in atms:
                LOG.warning('No atms related to cnsrt at line %s' %
                            (idline + 1))
            if '' in resids:
                LOG.error('No cnstr at line %s' % (idline + 1))
                continue

            # TODO: condition below can be simplified ...
            # Setting pymol selections
            if (contact_type == "all") or \
                    (contact_type == "min" and atms == ("CA", "CA")):
                sel1 = '%s and resi %s and name %s' % (
                    self._pdbname, resids[0], atms[0]) if atms[0] \
                    else '%s and resi %d' % (self._pdbname, resids[0])
                sel2 = '%s and resi %s and name %s' % (
                    self._pdbname, resids[1], atms[1]) if atms[1] \
                    else '%s and resi %d' % (self._pdbname, resids[1])
                sel3 = '{ref} and resi {resid1} and name {atm1}'.format(
                    resid1=resids[0], atm1=atms[0], ref=self._refname)
                sel4 = '{ref} and resi {resid2} and name {atm2}'.format(
                    resid2=resids[1], atm2=atms[1], ref=self._refname)
                LOG.info("Selecting restraint at line %s" % (idline + 1))
            else:
                LOG.debug("Ignoring line %s", idline + 1)
                LOG.debug("%s", line)
                continue
            # If ambig flag, append new dist to dist list
            # Otherwise initialize dist list with new dist
            if self._reflag:
                # If structure given, we look at reference distance
                dist = cmd.get_distance(sel3, sel4)
            else:
                dist = cmd.get_distance(sel1, sel2)

            # TODO: condition below can be simplified
            # Group can be decided by a contact treshold in the structure or in
            # the reference (if given). It can also be if distances in the
            # structure (or ref if given) lie inside bounds defined in the
            # cnstr file
            if not group:
                group = self._contact_label(eval_method, dist, lower, upper,
                                            idline)

            # PYMOL cmd.distance calls
            name = "_".join(('mobile', spec, group))
            nameref = "_".join(('ref', spec, group)) if self._reflag \
                else None
            if name not in names:
                names.append(name)
                if self._reflag:
                    names.append(nameref)
            try:
                LOG.debug("Distance cmd on %s and %s with groupname %s", sel1,
                          sel2, name)
                cmd.distance(name, sel1, sel2)
                if self._reflag:
                    LOG.debug("Distance cmd on %s and %s with groupname %s",
                              sel3, sel4, nameref)
                    cmd.distance(nameref, sel3, sel4)
            except CmdException:
                LOG.error("Wrong selection")

            # OUTPUT line
            if outfile:
                outfile.write("\n%s" % "\t".join(
                    (resids[0], resids[1], atms[0], atms[1], str(dist), group,
                     extra, spec)))

        for name in names:
            if name.endswith("_FP") or name.endswith("_viol"):
                color = self.settings.config.get("fp_color", 'red')
                cmd.color(color, name)
                if 'mobile' in name and self._reflag:
                    # If reference structure given, we look first at reference
                    # contacts
                    cmd.disable(name)
            else:
                color = self.settings.config.get("tp_color", 'green')
                cmd.color(color, name)
                if 'mobile' in name and self._reflag:
                    cmd.disable(name)

        cmd.show_as(self.settings.config.get('view', 'cartoon'))
        cmd.dss()
        cmd.show('dashes')
        if contact_type == "all":
            cmd.show('sticks')
            cmd.set('stick_radius',
                    self.settings.config.get('stick_radius', 0.05))
            cmd.set('dash_width', self.settings.config.get('dash_width', 0.5))
            cmd.set('dash_gap', self.settings.config.get('dash_gap', 0.5))
            cmd.set('stick_transparency',
                    self.settings.config.get('stick_alpha', 0.8))
            # cmd.hide('labels')
        cmd.color(self.settings.config.get('color', 'gray'), self._pdbname)
        if self._reflag:
            cmd.spectrum(selection=self._refname)

        if outfile:
            outfile.close()