def draw_ENM(structure_filepath, script_filepath, structure_name="CAonly", output_dir='.', view=None):
    """ Draws elastic network model of a structure and saves image.
    """

    cmd.delete('all')
    cmd.load(structure_filepath, "CAonly")
    cmd.run(script_filepath)

    # Set name
    if structure_name == "CAonly":
        pass
    else:
        cmd.set_name("CAonly", structure_name)

    # Set view
    if view == None:
        cmd.orient()
    else:
        cmd.set_view(view)
    
    cmd.viewport(width=1200, height=1200)
    cmd.zoom(complete=1)

    png_filepath = os.path.join(output_dir, structure_name) + ".png"
    pse_filepath = os.path.join(output_dir, structure_name) + ".pse"

    cmd.save(pse_filepath)
    cmd.set('ray_opaque_background', 0)
    cmd.png(png_filepath, width=1200, height=1200, ray=1)

    return (pse_filepath, png_filepath)
Ejemplo n.º 2
0
def tview(pdbid: str):

    species = str(int(log.get_struct(pdbid)['taxid'].values[0]))

    l22chain = log.get_struct(pdbid).uL22.values[0]
    l4chain = log.get_struct(pdbid).uL4.values[0]

    l22_res = int(log.get_struct(pdbid).constrictionResidueL22_id.values[0])
    l4_res = int(log.get_struct(pdbid).constrictionResidueL4_id.values[0])

    # cmd.delete('all')

    pdbid = pdbid.upper()

    TUNNELS = os.getenv("TUNNELS")
    SCOOP_RADIUS = os.getenv("SCOOP_RADIUS")
    TUNNEL_SCRIPT = os.path.join(TUNNELS, species, pdbid, 'pymol',
                                 'complex.py')

    inputstructpath = os.path.join(
        TUNNELS, species, pdbid, '{}_{}Ascoop.pdb'.format(pdbid, SCOOP_RADIUS))
    csvpaths = os.path.join(
        TUNNELS,
        species,
        pdbid,
        'csv',
    )

    cmd.load(inputstructpath)
    cmd.color('gray', 'all')

    if not os.path.exists(TUNNEL_SCRIPT):

        print("TUNNEL SCRIPT NOT FOUND.")
        return

    cmd.run(TUNNEL_SCRIPT)

    cmd.hide('everything', 'Tunnels')
    cmd.show('mesh', 'Tunnels')

    # tunnels    = os.listdir(csvpaths)
    # tunnumbers = map(lambda x: re.findall(r'\d+',x)[0], tunnels)
    # [cmd.delete(f'Tunnel{tunN}') if tunN not in choices else None for tunN in tunnumbers]
    # paint_tunnel(pdbid)

    sele_ptc(9606)
    # cmd.select('PTC', 'resi 2055 or resi 2056 or resi 2451 or resi 2452 or resi 2507 or resi 2506')
    # cmd.create('PTC',"PTC")
    # cmd.color('blue', 'PTC')

    cmd.select(
        'ConstrictionSite', 'c. {} and resi {} or c. {} and resi {}'.format(
            l22chain, l22_res, l4chain, l4_res))

    cmd.create('ConstrictionSite', "ConstrictionSite")
    cmd.show('everything', 'ConstrictionSite')
    cmd.color('magenta', 'ConstrictionSite')

    cmd.reset()
Ejemplo n.º 3
0
def show_chain_in_PDB(entry):
    PDB = entry[:4]
    chain = entry[-1:]
    cmd.reinitialize('everything')
    cmd.set("bg_rgb", "white")
    cmd.run("%s/B_strands_%s.py" % (PyMOL_script_dir, PDB))
    cmd.show("cartoon", "all")
Ejemplo n.º 4
0
def remred():
    pdb_list = glob.glob("*.pdb")
    for pdb in pdb_list:
        cmd.load(pdb)
    cmd.run("/usr/local/bin/all_against_all.py")
    cmd.do(
        "align_all_to_all(selection='all',cutoff=0,cycles=0,full_matrix=1,method='align')"
    )
Ejemplo n.º 5
0
def show_chain_in_PDB(entry):
    PDB = entry[:4]
    chain = entry[-1:]
    cmd.reinitialize('everything')
    cmd.do('@~/.pymolrc')
    cmd.set("bg_rgb", "white")
    cmd.run("%s/strands_%s.py" % (PyMOL_script_dir, PDB))
    cmd.show("cartoon", "all")
    cmd.set("cartoon_transparency", .85, PDB)
    cmd.set("cartoon_transparency", 0.05, "%s_barrel" % PDB)
Ejemplo n.º 6
0
def images(B):
    #cmd.do("cd {}".format(B))
    pdb_list = glob.glob("*.pdb")
    for pdb in pdb_list:
        cmd.load(pdb)
    cmd.run("/usr/local/bin/all_against_all.py")
    cmd.select("all_ps", "name PS1+PS2+PS3")
    cmd.do(
        "align_all_to_all(selection='all_ps',cutoff=0,cycles=0,full_matrix=1,method='align')"
    )
    cmd.remove("het")
    cmd.remove("all_ps")
    cmd.show("sticks", "all")
    cmd.hide("sticks", "all_ps")
    cmd.hide("sphere", "all_ps")
    cmd.set("sphere_scale", 0.30, "all_ps")
    cmd.orient("all")
    cmd.multisave("{}.pdb".format(B))
    cmd.set("ray_opaque_background", 0)
    cmd.ray(2400)
    cmd.set("antialias", 1)
    cmd.png("{}.png".format(B), 1200, 1200, 300)
    cmd.quit()
Ejemplo n.º 7
0
# Update cached modules
for module, (url, hash_remote) in modules.items():
    module_path = Path(cachedir / module)
    try:
        assert module_path.exists()
        # Change this to test for changes (/w file hashes)
        with open(module_path, 'rb') as file_to_hash:
            b_file = file_to_hash.read()
            # Apparently git uses this weird way of hashing files which includes
            # "blob {length of file}\0" (\0 being NULL)
            b_blob = b'blob ' + bytearray(str(len(b_file)), 'utf-8') + b'\0'
            hash_local = sha(b_blob + b_file).hexdigest()
        print(f"Reading {module} hash")
        print(f"Remote hash {hash_remote}")
        print(f"Local hash {hash_local}")
        assert hash_local == hash_remote
        print(f"{module} is up to date")
    except AssertionError:
        print(f"Caching {module}")
        with open(module_path, 'wb') as fout:
            reponse = requests.get(url)
            fout.write(reponse.content)

# Cache first, load later..
for module in modules.keys():
    # Finally load the module and inform the user
    module_path = Path(cachedir / module)
    cmd.run(str(module_path.absolute()))
    print(f"Loaded {module}")
Ejemplo n.º 8
0
Archivo: stir.py Proyecto: brisvag/stir
def main():
    """
    parses arguments user input and initializes stir based on user input
    provides help for usage
    """
    parser = HelpfulParser(
        prog='stir',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        add_help=False,
        description=
        'A python wrapper for pymol and several helpful tools and scripts\n'
        'mainly focused on martini coarse-grained trajectories.\n\n'
        'The accepted file formats are:\n'
        '- structure: gro, pdb\n'
        '- scene: pse\n'
        '- topology: top, itp, tpr\n'
        '- trajectory: xtc',
        epilog='Examples:\n'
        '\tstir system.gro topol.top md.xtc\n'
        '\tstir system.gro --keep-water -r supercell 3,3,1\n'
        '\tstir system.gro topol.tpr --pymol -qi myscript.pml',
    )

    files_group = parser.add_argument_group('file arguments')
    files_group.add_argument(
        dest='files',
        action=FilesAction,
        nargs='+',
        help=
        'a structure or scene file is required. Topology files allow for topology '
        'reconstruction. Trajectory files are also accepted. Order does not matter'
    )

    opt_group = parser.add_argument_group('optional stir arguments')
    opt_group.add_argument(
        '--keep-water',
        dest='keepwater',
        action='store_true',
        help='do not delete waters from the system. Decreases performance')
    opt_group.add_argument('-g',
                           '--gmx',
                           dest='gmx',
                           type=str,
                           default=None,
                           help='path to the gromacs executable')
    opt_group.add_argument(
        '-r',
        '--run-tool',
        dest='runtool',
        metavar='token',
        type=str,
        default=[],
        nargs='*',
        action='append',
        help='a command to be run after loading. (e.g.: supercell 3,3,1). '
        'Can be specified multiple times')

    gar_group = parser.add_argument_group('optional garnish arguments')
    gar_group.add_argument(
        '--no-fix',
        dest='nofix',
        action='store_false',  # store false!
        help='disable the atom-id-based fix for the elastic network in garnish '
        '(use if your system has messy, non-sequential numbering.')
    gar_group.add_argument(
        '--no-prot',
        dest='noprot',
        action='store_false',  # store false!
        help=
        'do not guess protein backbone beads (use if normal guessing makes mistakes'
    )
    gar_group.add_argument(
        '--no-garnish',
        dest='nogarnish',
        action='store_true',
        help='do not run garnish on the system (use with atomistic systems)')

    traj_group = parser.add_argument_group('optional trajectory arguments')
    traj_group.add_argument(
        '-s',
        '--skip',
        dest='skip',
        metavar='n',
        type=int,
        default=1,
        help=
        'load trajectory frames skipping this interval. Useful to reduce memory load'
    )
    traj_group.add_argument(
        '-b',
        '--begin',
        dest='begin',
        metavar='frame',
        type=int,
        default=1,
        help=
        'first frame to load from trajectory. Only acts on first trajectory file'
    )
    traj_group.add_argument(
        '-e',
        '--end',
        dest='end',
        metavar='frame',
        type=int,
        default=-1,
        help=
        'last frame to load from trajectory. Only acts on last trajectory file'
    )
    traj_group.add_argument('-m',
                            '--max',
                            dest='max',
                            metavar='n',
                            type=int,
                            default=0,
                            help='maximum number of frames to load')

    more_group = parser.add_argument_group('pymol arguments')
    more_group.add_argument(
        '-p',
        '--pymol',
        dest='pymol',
        default=[],
        nargs=argparse.REMAINDER,
        help='all following arguments will be passed directly to pymol. '
        'Accepts options and .pml scripts')

    help_group = parser.add_argument_group('info')
    help_group.add_argument('-h',
                            '--help',
                            action='help',
                            help='show this help message and exit')
    help_group.add_argument('-V',
                            '--version',
                            action='version',
                            version=f'%(prog)s {__version__}')

    args = parser.parse_args()

    struct = args.files['struct']
    scene = args.files['scene']
    topol = args.files['topol']
    traj = args.files['traj']

    # make sure we only have 1 structure OR scene file and at most one topol
    if not bool(struct) ^ bool(scene):  # not xor
        parser.error('you must provide either a structure or scene file')
    elif len(struct) > 1 or len(scene) > 1 or len(topol) > 1:
        parser.error(
            'only one system can be opened at once... for now!')  # TODO?

    # sanitize trajectory args
    if args.skip < 1:
        args.skip = 1
    if args.begin < 1:
        args.begin = 1
    if args.end < 1 and args.end != -1:
        args.end = 1
    if args.max < 0:
        args.max = 0

    pymol_args = []
    scripts = []
    for arg in args.pymol:
        p = clean_path(arg)
        if p.suffix in ('.pml', '.py'):
            if not p.is_file():
                raise FileNotFoundError(f'{p} does not exist')
            scripts.append(str(p))
        else:
            pymol_args.append(str(p))

    # initialize pymol
    __main__.pymol_argv = ['pymol'] + pymol_args
    pymol.finish_launching()

    # run pymolrc and load all the stir tools
    config.pymolrc()
    view.load()
    supercell.load()
    render.load()
    edit.load()

    # load garnish
    garnish.extend_garnish()
    cmd.sync()

    # open the structure
    if scene:
        cmd.load(scene[0])
    elif struct:
        cmd.load(struct[0])
    cmd.sync()
    # get the loaded object's name, so we can load the traj into it as new states
    sys_obj = cmd.get_object_list()[0]

    # load trajectories, leaving out waters if not asked for
    if traj:
        skip = args.skip
        max_states = args.max
        selection = 'all'
        if not args.keepwater:
            selection = 'not resname W+WN'
        config.trajectory()
        for i, t in enumerate(traj):
            cmd.sync()
            start = 1
            if i == 0:
                start = args.begin
            stop = -1
            if i == len(traj) - 1:
                stop = args.end
            if args.max != 0:
                max_states = args.max - cmd.count_states()
                if max_states < 1:
                    break
            cmd.load_traj(t,
                          sys_obj,
                          interval=skip,
                          start=start,
                          stop=stop,
                          max=max_states,
                          selection=selection)
        cmd.sync()

    # also, delete waters from first frame
    if not args.keepwater:
        cmd.remove('resname W+WN')
        cmd.sync()

    if not args.nogarnish:
        # sanitize topol
        if not topol:
            topol = [None]
        garnish.garnish(file=topol[0],
                        gmx=args.gmx,
                        fix_elastics=args.nofix,
                        guess_prot=args.noprot,
                        show=False)
        cmd.sync()

        # load garnish data into pymol
        view.nicesele()
        cmd.sync()
        view.set_vdw()
        cmd.sync()
        view.set_chains()
        cmd.sync()

        # run nice with the default settings, or with balls if no topol was given
        view.nice()
        cmd.sync()

    # finally run user-requested tools
    for tool in args.runtool:
        command = ' '.join(tool)
        cmd.do(command)
        cmd.sync()
    # and user-provided scripts
    for scr in scripts:
        cmd.run(scr)
        cmd.sync()

    # add command for simple help function
    cmd.extend('stir', stir_help)

    # print some help after everything is loaded
    stir_help()
    cmd.sync()
Ejemplo n.º 9
0
 def run(what):
     return cmd.run(what)
Ejemplo n.º 10
0
from pymol import cmd

cmd.reinitialize()
cmd.run('/Users/joy/src/elfin/src/PyMolUtils/LineUtils.py')
cmd.load('/Users/joy/src/elfin/src/Python/Greedy.py')

print '\n\n\n\n\n\n\n'
print 'Loaded'

# For quick testing
# main(['/Users/joy/src/elfin/bm/l10/6vjex8d.json'])
# main(['/Users/joy/src/elfin/bm/l10/kmb0yfh.json'])
# main(['/Users/joy/src/elfin/bm/fun/M.csv'])
main(['/Users/joy/src/elfin/bm/fun/S.csv', 's=2.50'])
Ejemplo n.º 11
0
def reload():
    """Reload PyMOL4RNA.py"""
    cmd.run(RNA_TOOLS_PATH + "/rna_tools/tools/PyMOL4RNA/PyMOL4RNA.py")
Ejemplo n.º 12
0
def reload():
    """Reload PyMOL4RNA.py"""
    cmd.run(RNA_PDB_TOOLS + "/rna_tools/utils/PyMOL4RNA/PyMOL4RNA.py")
def main():
    from argparse import ArgumentParser
    from sys import argv
    parser = ArgumentParser(
        description="Open and display a WORDOM PSN and cross correlation " +
        "analysis as an correlated interaction Allosteric " +
        "Communication Graph (ciACG) in PyMOL.")
    parser.add_argument(
        "-c",
        nargs='*',
        default=[0.0],
        metavar="float",
        help="Cutoff to use for showing connections in graph, provide" +
        " white space separated list for a series of cutoffs."
        ", default=0.0")
    parser.add_argument("-pdb",
                        nargs=1,
                        metavar="PDBfile",
                        help="PDB file to draw")
    parser.add_argument("-plot",
                        action="store_true",
                        default=False,
                        help="Plot ciACG value distribution")
    parser.add_argument("-acg",
                        nargs=1,
                        metavar="ACGfile",
                        help="ACG file to read (.frm)")
    parser.add_argument("-rmp",
                        nargs=1,
                        metavar="RMPfile",
                        help="ResidueMap file to read (.rmp)")
    parser.add_argument(
        "-pml",
        nargs='*',
        metavar="PMLfile",
        default=None,
        help="PyMOL scripts to run with cmd.run(), before coloring of bonds.")
    parser.add_argument("-cnt",
                        nargs=1,
                        metavar="COUNTfile",
                        default=[None],
                        help="Counts output file to write (.frm)")
    parser.add_argument("-frq",
                        nargs=1,
                        metavar="FREQfile",
                        default=[None],
                        help="Normed frequency output file to write (.frm)")
    parser.add_argument(
        "-prc",
        nargs=1,
        metavar="PROCESSfile",
        default=[None],
        help=
        "Processed frames and endpoints output file to write (.pyo), a tuple of Counter()s - (frames, endpoints)."
    )
    parser.add_argument("-frames",
                        nargs='*',
                        metavar="FRAMEfile",
                        help="WORDOM .frame files to process")
    arguments = parser.parse_args(argv[1:])

    # Finish pymol launch
    pymol.finish_launching(['pymol'])

    # Set variables here
    pdb = arguments.pdb[0]
    cutoffs = [float(c) for c in arguments.c]
    acg = arguments.acg[0]
    rmp = arguments.rmp[0]
    pml = arguments.pml
    cnt = arguments.cnt[0]
    frq = arguments.frq[0]
    prc = arguments.prc[0]
    frames = arguments.frames

    with open(acg, 'rb') as infile:
        cigraph_table = pickle.load(infile)

    with open(rmp, 'rb') as infile:
        residuemap = pickle.load(infile)

    counts, files_processed, frames_processed, pathways_processed = process_framefiles(
        frames, residuemap)

    print("{} pathways found in {} frames from {} files".format(
        len(pathways_processed), len(frames_processed), len(files_processed)))

    # Save counts
    dump_pyobject(counts, cnt, suffix="frm")

    # Save processing Counter()s
    dump_pyobject((frames_processed, pathways_processed), prc, suffix="pyo")

    # Normalize
    frequencies = normalize_pathway_counts_wrt_no_frames_and_endpoints(
        counts, frames_processed, pathways_processed)

    # Save frequencies
    dump_pyobject(frequencies, frq, suffix="frm")

    # Align tables
    frequencies_aligned, cigraph_table_aligned = align_dataframes(
        frequencies, cigraph_table, fill_value=0.0)

    pathways = matrix_from_pandas_dataframe(frequencies_aligned)

    # Draw the loaded ciACG
    cigraph = matrix_from_pandas_dataframe(cigraph_table_aligned)
    levels = draw_ciacg(cigraph, residuemap, pdb, cutoffs)

    # Run scripts prior to coloring of bonds
    if pml is not None:
        for script in pml:
            cmd.run(script)

    # Highlight the pathways
    rgb_matrix, colored, colors = highlight_pathways(pathways, residuemap)