def images_spin(images, sweep, axis):

    global imagecount
    global ray
    global filename
    global ximage
    global yimage

    print "... Images %s - %s:" % (imagecount, imagecount + images - 1)
    print "Writing %s images turning about %s axis by %s degrees per image" % \
      (images, axis, sweep/images)

    #cycle over images
    for i in range(0, images):

        #move camera
        cmd.turn(axis, sweep /
                 images)  # turn each image the fraction of the total spin

        #print image
        cmd.png("images/%s_%04d" % (filename, imagecount), ray=ray)

        #increment imagecounter
        print "cycle %s, image %s" % (i + 1, imagecount)
        imagecount = imagecount + 1
        cmd.refresh()
def vis(res,
        path_prefix,
        c=["firebrick", "forest", 'purple', 'salmon', "gold", "red"]):

    for ind, r in enumerate(res):
        for a in r.atoms:
            cmd.show("spheres", "id " + str(a.id))
            cmd.set("sphere_color", c[ind], "id " + str(a.id))
        cmd.distance("d" + str(ind), "id " + str(r.atoms[0].id),
                     "id " + str(r.atoms[1].id))
        cmd.hide("labels")
        cmd.set("grid_slot", -2, "d" + str(ind))

    cmd.ray(1200)
    time.sleep(2)
    cmd.set("grid_mode", 0)
    cmd.png(path_prefix + "_restraints.png")
    #cmd.set("grid_mode", 1)
    cmd.move("zoom", -10)

    cmd.ray(1200, )
    time.sleep(4)
    cmd.png(path_prefix + "_grid_restraints.png")
    cmd.set("grid_mode", 0)
    cmd.hide("spheres")
    cmd.delete("d*")
def images_refocus(images, target):

    global imagecount
    global ray
    global filename
    global ximage
    global yimage

    print "... Images %s - %s:" % (imagecount, imagecount + images - 1)
    print "Writing %s images zooming to selection:" % images
    print "  %s" % target

    current_view = cmd.get_view()  #get the starting view
    temporary_view = current_view  #make variabe to track interpolation
    cmd.zoom(target)  #zoom to the target selection
    end_view = cmd.get_view()  #get the ending view

    #get the difference between the start and ending views, divide per step
    views_difference = tuple(np.subtract(end_view, temporary_view))
    diff_per_image = tuple(i / images for i in views_difference)

    for i in range(0, images):  #cycle for number of images

        #update the interpolating view
        temporary_view = tuple(np.add(temporary_view, diff_per_image))

        cmd.set_view(temporary_view)

        #print image
        cmd.png("images/%s_%04d" % (filename, imagecount), ray=ray)

        #increment imagecounter
        imagecount = imagecount + 1
        cmd.refresh()
def images_spin3_slide3(images, distance, sweep):

    global imagecount
    global ray
    global filename
    global ximage
    global yimage

    print "... Images %s - %s:" % (imagecount, imagecount + images - 1)
    print "Writing %s images turning about:" % images
    print "     x axis by %s degrees, then" % (sweep[0] / images)
    print "     y axis by %s degrees, and" % (sweep[1] / images)
    print "     z axis by %s degrees per image," % (sweep[2] / images)
    print "   while moving along:"
    print "     x axis by %s Angstrom," % (distance[0] / images)
    print "     y axis by %s Angstrom, and" % (distance[1] / images)
    print "     z axis by %s Angstrom per image" % (distance[2] / images)

    for i in range(0, images):  #cycle for number of images

        # transformations
        cmd.turn("x", sweep[0] / images)
        cmd.turn("y", sweep[1] / images)
        cmd.turn("z", sweep[2] / images)
        cmd.move("x", distance[0] / images)
        cmd.move("y", distance[1] / images)
        cmd.move("z", distance[2] / images)

        #print image
        cmd.png("images/%s_%04d" % (filename, imagecount), ray=ray)

        #increment imagecounter
        imagecount = imagecount + 1
        cmd.refresh()
def images_screw(images, distance, sweep, axis):

    global imagecount
    global ray
    global filename
    global ximage
    global yimage

    print "... Images %s - %s:" % (imagecount, imagecount + images - 1)
    print "Writing %s images moving along %s axis by %s Angstrom" % \
      (images, axis, distance/images)
    print "     and rotating %s degrees per image" % (sweep / images)

    for i in range(0, images):  #cycle for number of images

        # transformations
        cmd.move(axis, distance / images)
        cmd.turn(axis, sweep / images)

        #print image
        cmd.png("images/%s_%04d" % (filename, imagecount), ray=ray)

        #increment imagecounter
        imagecount = imagecount + 1
        cmd.refresh()
Exemple #6
0
    def rotate_and_capture(self, rotation_axis, increment, res_width,
                           res_height):
        self.images_for_gif = []
        self.images_for_mp4 = []

        # cycles through all possible angles (multiple of increment)
        for current_angle in range(0, 360, increment):
            cmd.rotate(rotation_axis, angle=increment)

            # creates the file folder if it doesn't exist
            if not os.path.exists(str(self.file_path)):
                os.makedirs(str(self.file_path))

            # file_name = str(self.file_path/"{}_{}.png".format(self.protein, str(current_angle)))
            file_name = str(self.file_path /
                            f"{self.method.name}_{str(current_angle)}.png")

            cmd.zoom(complete=1)
            cmd.png(file_name,
                    width=res_width,
                    height=res_height,
                    dpi=500,
                    ray=1,
                    quiet=0)

            self.drawLegend(file_name, res_width, res_height)

            self.images_for_gif.append(imageio.imread(file_name))
            self.images_for_mp4.append(cv2.imread(file_name))
Exemple #7
0
def show_motif(interaction, domain1, domain2, residues1, residues2):
    cmd.load("PDBFiles/%s.pdb" % domain1)
    cmd.load("PDBFiles/%s.pdb" % domain2)
    cmd.bg_color("white")

    cmd.hide("all")
    cmd.show("cartoon", "all")
    cmd.select("motif1", "none")
    cmd.select("motif1",
               "motif1 or (%s and n. CA and resi %s)" % (domain1, residues1))
    cmd.select("motif2", "none")
    cmd.select("motif2",
               "motif2 or (%s and n. CA and resi %s)" % (domain2, residues2))
    cmd.select("none")
    cmd.color("gray80", domain1)
    cmd.color("gray60", domain2)
    cmd.color("cyan", "motif1")
    cmd.color("magenta", "motif2")
    try:
        cmd.pair_fit("motif1", "motif2")
        cmd.center(domain1)
        cmd.png("PNGs/%s_%s_%s_PF.png" % (interaction, domain1, domain2),
                dpi=300)
    except CmdException:
        pass

    try:
        cmd.cealign("motif1", "motif2")
        cmd.center(domain1)
        cmd.png("PNGs/%s_%s_%s_CE.png" % (interaction, domain1, domain2),
                dpi=300)
    except CmdException:
        pass
Exemple #8
0
 def png(self, filename, *args, **kwargs):
     '''
     Save image to filename, with antialias=0.
     '''
     cmd.unset('antialias')
     cmd.png(filename, *args, **kwargs)
     cmd.draw()
Exemple #9
0
def render_to_file(fname, top=True, side=True, vesicle=False,
                   zoom_obj="pbcbox",
                   zoom_distance=10):
    fname = os.path.splitext(fname)[0]

    cmd.reset()
    cmd.zoom(zoom_obj, zoom_distance)
    if vesicle:
        cmd.turn("z", -90)
        cmd.move("y", -50)
    if top:
        cmd.ray("2048")
        cmd.png("%s_top.png" % fname)

    if side:
        cmd.turn("x", -90)
        if vesicle:
            cmd.move("y", 150)
        cmd.ray("2048")
        cmd.png("%s_side.png" % fname)
    cmd.reset()
    cmd.zoom(zoom_obj, zoom_distance)
    if vesicle:
        cmd.turn("z", -90)
        cmd.move("y", -50)
Exemple #10
0
def paper_png(filename, width=100, height=0, dpi=300, ray=1):
    """
DESCRIPTION

    Saves a PNG format image file of the current display.
    Instead of pixel dimensions, physical dimensions for
    printing (in millimeters) and DPI are specified.

USAGE

    paper_png filename [, width [, height [, dpi [, ray ]]]]

ARGUMENTS

    filename = string: filename

    width = float: width in millimeters {default: 100 = 10cm}
    width = string: width including unit (like: '10cm' or '100mm')

    height = float or string, like "width" argument. If height=0, keep
    aspect ratio {default: 0}

    dpi = float: dots-per-inch {default: 300}

    ray = 0 or 1: should ray be run first {default: 1 (yes)}

SEE ALSO

    png
    """
    dpi, ray = float(dpi), int(ray)
    width = unittouu(width, dpi)
    height = unittouu(height, dpi)
    cmd.png(filename, width, height, dpi, ray)
Exemple #11
0
def surfback(width,height,color="gray",showcartoon=True,dname=""):
    #if (cmd.get("bg_image_filename")==None):
    cmd.set("bg_image_filename",None)
    cmd.hide("")
    cmd.set("fog", 0)
    cmd.set("reflect", 0)
    cmd.set("ambient",1)
    cmd.set("ray_trace_mode", 0)
    cmd.show("surface")
    cmd.set("surface_color",color)
    cmd.set("spec_reflect",0)
    cmd.ray(width,height)
    # I want below to work with tmpdir but, it fails. So this script makes unwanted tmpfile to dir named as dname
    cmd.png(dname+"surf.png")
    cmd.do("ls " + dname)
    cmd.do("ls " + dname+"surf.png")
    #cmd.load_png(dname+"surf.png")
    time.sleep(0.01)
    cmd.set("bg_image_filename",dname+"surf.png")
    cmd.set("bg_image_mode",0)
    if (showcartoon):
        cmd.hide("")
        cmd.show("cartoon")
        cmd.color("white")
        cmd.set("ray_trace_mode", 3)
        cmd.set("ambient", 1)
        cmd.set("reflect",0)
        cmd.set("valence", 0)
        cmd.set("spec_reflect",0)
        cmd.set("ray_trace_color", "gray0")
    #cmd.ray(n,n)
    #cmd.png("/
    print("Ray your image in the same aspect ratio as you specified in surfback")
def export_objects_to_png():
    objects = cmd.get_object_list('all')
    cmd.disable('all')
    for pobj in objects:
        cmd.enable(pobj)
        cmd.png('{}.png'.format(pobj), width=2340, height=1239, ray=1)
        cmd.disable(pobj)
Exemple #13
0
def abl(*files, **kwargs):
    MdsPymol.reset(options)

    if 'optionsFile' in kwargs:
        execfile(kwargs['optionsFile'], globals(), locals())

    for file in files:
        print "Processing file '%s'." % file
        fileOptions = perMapOptions.get(file, {})
        # Add a CGO prefix if we have multiple files and a prefix was not given.
        if len(files) > 1 and 'cgo prefix' not in fileOptions:
            basename, _ = os.path.splitext(os.path.basename(file))
            fileOptions['cgo prefix'] = basename + '_'
        mapOptions = defaultMapOptions.copy()
        restrictedUpdate(mapOptions, fileOptions)
        ACmap(file, mapOptions)

    # Process global options.

    cmd.clip('far', -20.0)
    #cmd.clip('near', 100.0)

    if options['axes compute']:
        Axes(options)
    if options['base grid compute']:
        BaseGrid(options)
    if options['view']:
        cmd.set_view(options['view'])
    if options['ray']:
        cmd.ray()
    if options['png file']:
        cmd.png(options['png file'])
    if options['quit']:
        cmd.quit()
Exemple #14
0
    def snapshotPymolShape(self, inputName, idList, rot, tran, extension=None):

        if extension is not None:
            # Temporarily extend shape
            lastNodeName = idList[-1]
            lastNodeName = lastNodeName[:lastNodeName.rfind('#')]
            idList,extRot,extTran,extName = \
                self.growShape(lastNodeName,
                    idList,
                    extension)

        self.transformPymolShape(idList, tran, rot, [0, 0, 0])
        for single in idList:
            cmd.show('cartoon', single)
        self.alignPymolView()
        cmd.png(elfinMovieDir + inputName + '/frame' + str(self.frameCount))
        self.frameCount += 1

        # Restore shape so next transform will be correct
        self.transformPymolShape(idList, [0, 0, 0], np.linalg.inv(rot),
                                 -1 * np.asarray(tran))
        for single in idList:
            cmd.hide('cartoon', single)

        if extension is not None:
            # Restore temporary extension
            idList = idList[:-1]
            cmd.delete(extName)
            self.transformPymolShape(idList, -1 * np.asarray(extTran),
                                     np.linalg.inv(extRot), [0, 0, 0])
Exemple #15
0
def vis_cif(cif_path, im_path):
    import pymol
    from pymol import cmd

    cmd.load(cif_path, "mov")
    cmd.zoom()
    cmd.png(im_path, 300, 200)
def stereo_ray(filename, width=0, height=0, quiet=1):
    '''
DESCRIPTION

   "stereo_ray" ray-traces the current scene twice (separated by 
   a six-degree rotation around the y axis)
   and saves a pair of images that can be combined in any image
   manipulation software to form a stereoimage.
   The first argument, the output file name, is mandatory.
   The second and third arguments, the size of the image, are not.
   If the width is given, the height will be calculated.
 
USAGE

   stereo_ray filename [, width [, height]]
 
EXAMPLE

   stereo_ray output, 1000, 600
   stereo_ray secondImage.png
   '''
    if filename.lower().endswith('.png'):
        filename = filename[:-4]

    cmd.ray(width, height, angle=-3)
    cmd.png(filename + "_r", quiet=quiet)
    cmd.ray(width, height, angle=3)
    cmd.png(filename + "_l", quiet=quiet)
Exemple #17
0
 def png(self, filename, *args, **kwargs):
     '''
     Save image to filename, with antialias=0.
     '''
     cmd.set('antialias', 0)
     cmd.png(filename, *args, **kwargs)
     cmd.draw()
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)
def images_spin_3ax(images, sweep):

    global imagecount
    global ray
    global filename
    global ximage
    global yimage

    print "... Images %s - %s:" % (imagecount, imagecount + images - 1)
    print "Writing %s images turning about:" % images
    print "     x axis by %s degrees," % (sweep[0] / images)
    print "     y axis by %s degrees, and" % (sweep[1] / images)
    print "     z axis by %s degrees per image" % (sweep[2] / images)

    #cycle over number of images
    for i in range(0, images):

        # transformations
        cmd.turn("x", sweep[0] / images)
        cmd.turn("y", sweep[1] / images)
        cmd.turn("z", sweep[2] / images)

        #print image
        cmd.png("images/%s_%04d" % (filename, imagecount), ray=ray)

        #increment imagecounter
        imagecount = imagecount + 1
        cmd.refresh()
def paper_png(filename, width=100, height=0, dpi=300, ray=1):
    '''
DESCRIPTION

    Saves a PNG format image file of the current display.
    Instead of pixel dimensions, physical dimensions for
    printing (in millimeters) and DPI are specified.

USAGE

    paper_png filename [, width [, height [, dpi [, ray ]]]]

ARGUMENTS

    filename = string: filename

    width = float: width in millimeters {default: 100 = 10cm}
    width = string: width including unit (like: '10cm' or '100mm')

    height = float or string, like "width" argument. If height=0, keep
    aspect ratio {default: 0}

    dpi = float: dots-per-inch {default: 300}

    ray = 0 or 1: should ray be run first {default: 1 (yes)}

SEE ALSO

    png
    '''
    dpi, ray = float(dpi), int(ray)
    width = unittouu(width, dpi)
    height = unittouu(height, dpi)
    cmd.png(filename, width, height, dpi, ray)
Exemple #21
0
def output_PNG(this_PDB_file, OUTPUT_FOLDER_PNG, OUTPUT_FOLDER_SESSION):
  # show complex
  cmd.hide("all")
  cmd.bg_color("white")
  cmd.show("cartoon", "this_complex")
  # show protein A
  cmd.set_color("A_interface_color", [167, 244, 66]) # lightgreen
  cmd.set_color("A_C_term_color", [252, 245, 146])   # pale yellow
  cmd.color("yellow", "chain A")
  cmd.color("A_interface_color", "A_interface")
  cmd.alter("A_center_pseudoatom", "vdw=2")
  cmd.show("sphere", "A_center_pseudoatom")
  cmd.color("green", "A_center_pseudoatom")
  cmd.show("sphere", "A_N_term")
  cmd.color("yellow", "A_N_term")
  cmd.show("sphere", "A_C_term")
  cmd.color("A_C_term_color", "A_C_term")
  # show protein B
  cmd.set_color("B_interface_color", [80, 181, 244]) # medium blue
  cmd.set_color("B_C_term_color", [179, 229, 229])   # pale cyan
  cmd.color("cyan", "chain B")
  cmd.color("B_interface_color", "B_interface")
  cmd.alter("B_center_pseudoatom", "vdw=2")
  cmd.show("sphere", "B_center_pseudoatom")
  cmd.color("blue", "B_center_pseudoatom")
  cmd.show("sphere", "B_N_term")
  cmd.color("cyan", "B_N_term")
  cmd.show("sphere", "B_C_term")
  cmd.color("B_C_term_color", "B_C_term")
  # nice output
  cmd.rebuild()
  cmd.zoom("all")
  cmd.png("%s/%s.png" % (OUTPUT_FOLDER_PNG, this_PDB_file), quiet=1)
  # save session
  cmd.save("%s/%s.pse" % (OUTPUT_FOLDER_SESSION, this_PDB_file))
Exemple #22
0
def stereo_ray(filename, width=0, height=0, quiet=1):
    """
DESCRIPTION

   "stereo_ray" ray-traces the current scene twice (separated by 
   a six-degree rotation around the y axis)
   and saves a pair of images that can be combined in any image
   manipulation software to form a stereoimage.
   The first argument, the output file name, is mandatory.
   The second and third arguments, the size of the image, are not.
   If the width is given, the height will be calculated.
 
USAGE

   stereo_ray filename [, width [, height]]
 
EXAMPLE

   stereo_ray output, 1000, 600
   stereo_ray secondImage.png
   """
    if filename.lower().endswith(".png"):
        filename = filename[:-4]

    cmd.ray(width, height, angle=-3)
    cmd.png(filename + "_r", quiet=quiet)
    cmd.ray(width, height, angle=3)
    cmd.png(filename + "_l", quiet=quiet)
Exemple #23
0
def morph_movie(morph,
                view,
                color,
                base_name,
                frameno_offset=0,
                morph_reverse=False):
    number_of_states = cmd.count_states(morph)
    # after this I will have each state available as its own object, called "{morphname}_000x" (padded to length of 4)
    # x starts with 1 --> not clear - that might depend on the numbering in the input file
    cmd.split_states(morph)
    last_frame = frameno_offset
    for statenum in range(0, number_of_states + 1):
        if morph_reverse:
            statenum = max(1, cmd.count_states(morph) - statenum)
        else:
            statenum = min(statenum + 1, cmd.count_states(morph))
        state_name = morph + "_" + str(statenum).zfill(4)
        clump_representation([state_name], color, state_name),
        cmd.set_view(view)
        cmd.png(base_name + str(last_frame).zfill(3),
                width=1920,
                height=1080,
                ray=True)
        clump_cleanup([state_name], state_name)
        cmd.remove(state_name)
        last_frame += 1

    return last_frame
Exemple #24
0
    def plot(self, outfile):
        ctrl_id, case_id, snp_df_sub = self.score_on_var()
        df = pd.merge(snp_df_sub, self.snps2aa, on='id')

        #pymol.finish_launching()
        cmd.reinitialize()
        cmd.fetch(self.pdb)
        cmd.alter(self.pdb, 'b = 0.5')
        cmd.show_as('cartoon', self.pdb)
        cmd.color('white', self.pdb)

        for i, row in df.iterrows():
            resi = row['structure_position']
            chain = row['chain']
            pheno = row['es']
            selec = 'snp%s' % i
            selec_atom = 'snp_atom%s' % i
            cmd.select(selec,
                       'name ca and resi %s and chain %s' % (resi, chain))
            cmd.create(selec_atom, selec)
            cmd.set("sphere_scale", 0.8)
            cmd.show('sphere', selec_atom)
            cmd.alter(selec_atom, 'b=%s' % pheno)
            cmd.spectrum("b",
                         "blue_white_red",
                         selec_atom,
                         maximum=1.0,
                         minimum=0.0)
        cmd.bg_color("white")
        cmd.zoom()
        cmd.orient()
        cmd.save('%s.pse' % outfile)
        cmd.png('%s.png' % outfile, width=2400, height=2400, dpi=300, ray=1)
Exemple #25
0
def save_image_closeup(filename, width=ray_width_closeups(), height=ray_height_closeups()):
    cmd.bg_color("white")
#    cmd.ray(ray_width_closeups(), ray_height_closeups())
    cmd.ray(width, height)
    cmd.png("./output/" + filename + ".png", dpi=dpi())
    cmd.bg_color("black")
    return 
 def photo_pdb(pdb_file, out_file):
     pymol.finish_launching(['pymol', '-qc'])
     cmd.reinitialize()
     cmd.load(pdb_file)
     cmd.show_as('cartoon', 'all')
     cmd.util.cbc()
     cmd.png(filename=out_file, width=350, height=350, ray=0, dpi=300)
     cmd.quit()
Exemple #27
0
def take_screenshot(params, pdb_file_name, protein_number, step_number):
    print("")
    print("SCREENSHOT! protein #", protein_number, pdb_file_name, " step ", step_number, " with ", cmd.count_atoms("all"), " atoms")
    screenshot_path = "./results/{}/screenshots/{}-{}/{}-{}.png".format(params.run_time_stamp, pdb_file_name, protein_number, pdb_file_name, step_number)
    cmd.ray()
    # cmd.zoom("all")
    cmd.center("all")
    cmd.png(screenshot_path)
def colour_by_heatmap(colour_data,
                      structure_path,
                      molecule_name="protein",
                      output_path="colour_by_heatmap",
                      view=None):
    '''
DESCRIPTION

    Colours PDB structure by colour map data.
    output_filepath
    >>> colour_by_heatmap(df, structure_filepath="xxxx.pdb", mol_name="protein", out_dir='.')
    '''

    # if not (isinstance(colour_data, pd.core.series.Series) or isinstance(colour_data, dict)):
    #     print('''
    #             Passed data must be either dictionary or Pandas Series object.
    #             Key = residue number
    #             Value = PyMOL hex code
    #             ''')
    #     return None

    cmd.load(structure_path, object=molecule_name)

    # Set view
    if view == None:
        cmd.reset()
        cmd.orient()
    else:
        cmd.set_view(view)

    cmd.viewport(width=1200, height=1200)
    cmd.zoom(complete=1)

    cmd.set('cartoon_discrete_colors', 1)
    cmd.set('sphere_scale', 1)

    cmd.show_as('cartoon', molecule_name)
    cmd.color('white', molecule_name)

    # Iterate over the alpha-carbons
    # residue_numbers = []
    # cmd.iterate('{} and name CA'.format(molecule_name) , 'residue_numbers.append(resi)')

    # Colour the structure
    for residue_number in colour_data.columns:
        # print(colour_data[residue_number].item())
        cmd.color(colour_data[residue_number].item(),
                  '{0} and resi {1}'.format(molecule_name, residue_number))

    png_out_path = output_path + ".png"
    pse_out_path = output_path + ".pse"

    cmd.save(pse_out_path)

    cmd.set('ray_opaque_background', 0)
    cmd.png(png_out_path, width=1200, height=1200, ray=1, quiet=0)
Exemple #29
0
def save_dens(fname, isovals="-0.02 0.02", colors="cyan orange", delete=True):
    """
    Plot and save the density (same options as show_dens).
    """
    dname = show_dens(fname, isovals, colors)
    pname = dname + ".png"
    cmd.png(pname, ray=1)
    print("Image saved as %s." % pname)
    if delete:
        cmd.delete(dname + "*")
Exemple #30
0
def screenshotProteins():
    # proteinsPath = ".\pdbs"

    # set style parameters
    # cmd.set("ray_opaque_background", 0)
    # cmd.remove("solvent")
    cmd.set("ambient", 0.3)
    cmd.set("antialias", 1)
    cmd.bg_color("white")
    # cmd.set("direct", 1.0)
    # cmd.set("ribbon_radius", 0.2)
    # cmd.set("cartoon_highlight_color", "grey50")
    # cmd.set("ray_trace_mode", 1)
    # cmd.set("stick_radius", 0.2)
    # cmd.set("mesh_radius", 0.02)

    # loop thru folders
    # for dir in os.walk(proteinsPath):
    # proteinPath = dir[0]

    # loop thru pdbs
    # for file in os.listdir(proteinPath):
    # if file.endswith('.pdb'):

    csvFileName = "docked-protein-homomers.csv"

    # to loop through csv

    file = open(csvFileName, "r")
    reader = csv.reader(file, delimiter=",")
    k = 1
    for row in reader:
        for item in row:
            print(k, item)

            cmd.reinitialize()

            # load the pdb file
            cmd.fetch(item, path="./pdbs", type='pdb')
            #pdbPath= "./pdbs/" + item + ".cif"
            #cmd.load(pdbPath)
            color = pickAColor()
            cmd.color(color)
            cmd.show("cartoon")
            cmd.remove("solvent")

            # take a screenshot
            screenshotFileName = item + ".png"
            screenshotPath = os.path.join('screenshots', screenshotFileName)
            cmd.png(screenshotPath, 128, 128, ray=1)

            # clear
            cmd.delete("all")

            k = k + 1
Exemple #31
0
def ross_pic(molecule):
    '''
    for Jennifer Ross picture.
    '''
    # if pic != 0:
    cmd.png(molecule,
            width=4800,
            height=3600,
            dpi=1200, # currently creates 1.2 Mb.
            ray=0, # shadowing if 1,2
            quiet=0)
Exemple #32
0
    def testPngExists(self):
        '''
        Save a PNG image with width/height specified and
        check if the file exists.
        '''
        cmd.pseudoatom('m1')
        cmd.show('spheres')

        with testing.mktemp('.png') as filename:
            cmd.png(filename, width=100, height=100, ray=0)
            cmd.draw()
            self.assertTrue(os.path.exists(filename), 'png file not written')
Exemple #33
0
def ray_tracer(width, height, scenes="all", ray=1, directory=""):
    """
	ray_tracer will call png for scenes in a pymol session.  All these scenes will be
	produced with the same dimensions.  By default, all scenes are generated with ray
	tracing turned on in the current directory.  Files will be named the same as their
	scene names.
	
	width, height = The width and height in pixels of the resulting images.
	scenes = A scene or pythonic list of scenes to raytrace (e.g. "scene1" or ["scene1", "scene2"]).  By default, do all scenes.
	raytrace = Should we raytrace?  Passed on to ray in png command.
	directory = By default, images will be saved in the current directory.  A relative path can be given
		here for a different directory to be used.
	"""

    #Check if 'all' happens to be a scene name.  If so, print an error message and quit.
    assert (
        "all" not in cmd.get_scene_list()
    ), "You have 'all' as a scene name.  This causes a conflict with ray_tracer.  Change the scene name."

    #The directory name must end in a forward / (unless it is an empty string).  If it doesn't, add one for the user
    if (directory != "" and directory[-1:] != "/"): directory = directory + "/"

    #Figure out which scenes to png
    #if scenes == all, get all scenes and use that as our list.
    if (scenes == 'all'):
        scene_list = cmd.get_scene_list()
    #if scenes is a list object, use that as our list.
    elif (isinstance(scenes, list)):
        scene_list = scenes
    #Otherwise, assume we have a string that corresponds to a scene name
    else:
        scene_list = [scenes]

    #Make sure that the scene_animation setting is set to 0, or changing view will not work.
    cmd.set("scene_animation", 0)

    #scene_list should now have a list of all the scenes to render.
    #Loop over scene_list and cmd.png each one.
    for scene in scene_list:
        #Check that the scene actually exists, or spit out an error.
        if (scene not in cmd.get_scene_list()):
            print("The scene " + scene +
                  " is not a scene in your pymol environment.  Skipping.")
            continue

        #Change to the appropriate scene.
        cmd.scene(scene)
        cmd.sync()
        #Figure out the full name of the output file.
        imgname = directory + scene + ".png"

        #Actually make the image.
        cmd.png(filename=imgname, width=width, height=height, ray=ray)
Exemple #34
0
def rotation_series(axis, increment, width, height, filename, with_centering):
    if (increment == 0):
        max_turns = 1
    else:
        max_turns = (360/increment) + 1

    for x in range(max_turns):    
        if x > 0: cmd.rotate(axis, increment)
        if with_centering: cmd.center("(all)")
        cmd.ray(width, height)
        cmd.png(filename + "_" + str(x * increment) + ".png", dpi=dpi())
    return
Exemple #35
0
def mark_res():
    """ mark_res <pdb_file> <highlight_residue>
    select the chain and residue that ICP dipeptide locate and highlight it.
    """
    #list of pdb id, chain id, and residues informations for ICP. the lower case pdbs are from blast,
    #upercase PDBs are from SGD pdb homologous search.
    pdb_input_lists = [('1fa0', 'A', '177-178', '117-147'),
                       ('1u5t', 'A', '42-43'),
                       ('1yke', 'A', '103-104', '43-73'),
                       ('2b1e', 'A', '294-295', '234-264'),
                       ('2PFV', 'A', '294-295', '234-264'),
                       ('1MNM', 'C', '177-178', '117-147'),
                       ('2ckz', 'D', '11-12'),
                       ('2pk9', 'D', '150-151+245-246', '90-120+185-215'),
                       ('2pmi', 'D', '150-151+245-246', '90-120+185-215'),
                       ('2xfv', 'A', '7-8'),
                       ('3esl', 'A', '191-192', '131-161'),
                       ('3n7n', 'E', '20-21'),
                       ('3t5v', 'E', '288-289', '228-258'),
                       ('4bh6', 'A', '365-366', '305-335')]
    #iterate pdbs
    for pdb_info in pdb_input_lists:
        pdb_id = pdb_info[0]
        chain_id = pdb_info[1]
        res_id = pdb_info[2]
        up_region = pdb_info[3] if len(pdb_info) == 4 else '0'
        pdb_file = pdb_id + ".pdb"
        chain_selection = "chain " + chain_id
        res_selection = "res " + res_id
        up_region_selection = "res " + up_region

        #command chains to process the pdb files.
        cmd.load(pdb_file)
        cmd.remove("solvent")
        cmd.color("gray80")
        cmd.show("cartoon")
        cmd.hide("line")
        cmd.select("monomer", chain_selection)
        cmd.color("cyan", "monomer")
        cmd.select("icp_dipep", chain_selection + " and " + res_selection)
        cmd.select("up_region", chain_selection + " and " + up_region_selection)
        cmd.select("none")
        cmd.color("red", "icp_dipep")
        cmd.color("yellow", "up_region")
        cmd.zoom(chain_selection)
        # cmd.zoom("all")
        cmd.png(pdb_id + ".png")
        cmd.save(pdb_id + ".pse")

        cmd.delete("all")
def render_false_color_image(width, height, filename=''):
    global tmpdir

    tmpFile = get_temporary_file(filename)

    # draw with antialiasing disabled
    cmd.draw(width, height, 0)
    cmd.png(tmpFile)
    while not os.path.exists(tmpFile):
        time.sleep(1)

    if DEBUG:
        print "created temporary file %s" % tmpFile

    return tmpFile
    def test(self):
        cmd.set('opaque_background')
        with testing.mktemp('tmp.pse') as session_filename:
            with testing.mktemp('bg.png') as bg_image_filename:
                cmd.bg_color('red')
                cmd.png(bg_image_filename)
                cmd.bg_color('blue')
                cmd.set('bg_image_filename', bg_image_filename)
                cmd.save(session_filename)

            cmd.load(session_filename)
        x = cmd.get('bg_image_filename')
        self.assertTrue(x.startswith('data:'))
        self.assertImageHasColor('red', delta=4,
                msg='bg_image_filename=data: not rendered')
Exemple #38
0
def save_images(title=1):
	cmd.set( 'ray_opaque_background', 0 )
	for x in cmd.get_names( 'all' ):
		rg = rgyrate( x , 1 )

		cmd.disable( 'all' )
		cmd.enable( x )
		cmd.zoom( x, buffer=0.0, state=0, complete=1 )
		if title:
			cmd.set( 'label_size', 25 )
			#cmd.set( 'label_position', (0,-25,0) )
			cmd.set( 'label_position', (0,(-10-rg),0) )
			cmd.pseudoatom( 'pa', label=x )
		cmd.zoom( 'visible', buffer=5, state=0, complete=1 )
		cmd.png( x+'.png', dpi=300, ray=1 )
		cmd.delete( 'pa' )
def save_image(spath, name_maxlength, prefix = ''):
    fname = os.path.splitext(os.path.basename(spath))[0]
    image_name = prefix + image_filename(fname, name_maxlength)
    if exists(image_name):
        print 'Skip: ' + fname
    else:
        print 'Process: ' + fname
        cmd.load(spath, fname)
        cmd.disable('all')
        cmd.enable(fname)

        cmd.color('green', fname)
        cmd.h_add('(all)')
        cmd.show('surface')

        cmd.rotate([-1, 0.5, 0.5], 60)
        cmd.zoom(fname, -7.0, 0, 1)

        cmd.png(image_name)
        time.sleep(3) # wtf?!
        cmd.delete('all')
def stereo_ray(output='', width='', height=''):

   if output == '':
      print 'no output filename defined\n'
      print 'try: \'stereo_ray filename\''
      return -1
      # abort if no output file name given
 
   if width == '':
      width,height = cmd.get_session()['main'][0:2]
      # get dimensions from viewer if not given
 
   elif height == '':
      oldWidth,oldHeight = cmd.get_session()['main'][0:2]
      height = int(width)*oldHeight/oldWidth
      # calculate height from proportions of viewer if
      # only width is given
 
   cmd.ray(width, height, angle=-3)
   cmd.png(output+"_r")
   cmd.ray(width, height, angle=3)
   cmd.png(output+"_l")
def stereo_ray(output="", width="", height=""):
    """
DESCRIPTION
   "stereo_ray" ray-traces the current scene twice (separated by 
   a six-degree rotation around the y axis)
   and saves a pair of images that can be combined in any image
   manipulation software to form a stereoimage.
   The first argument, the output file name, is mandatory.
   The second and third arguments, the size of the image, are not.
   If the width is given, the height will be calculated.
 
USAGE
   stereo_ray filename [, width [, height]]
 
EXAMPLE
   stereo_ray output, 1000, 600
   stereo_ray secondImage.png
   """

    if output == "":
        print "no output filename defined\n"
        print "try: 'stereo_ray filename'"
        return -1
        # abort if no output file name given

    if width == "":
        width, height = cmd.get_session()["main"][0:2]
        # get dimensions from viewer if not given

    elif height == "":
        oldWidth, oldHeight = cmd.get_session()["main"][0:2]
        height = int(width) * oldHeight / oldWidth
        # calculate height from proportions of viewer if
        # only width is given

    cmd.ray(width, height, angle=-3)
    cmd.png(output + "_r")
    cmd.ray(width, height, angle=3)
    cmd.png(output + "_l")
Exemple #42
0
def render_to_file(fname, top=True, side=True, vesicle=False, zoom_obj="pbcbox", zoom_distance=10):
    fname = os.path.splitext(fname)[0]

    cmd.reset()
    cmd.zoom(zoom_obj, zoom_distance)
    if vesicle:
        cmd.turn("z", -90)
        cmd.move("y", -50)
    if top:
        cmd.ray("2048")
        cmd.png("%s_top.png" % fname)

    if side:
        cmd.turn("x", -90)
        if vesicle:
            cmd.move("y", 150)
        cmd.ray("2048")
        cmd.png("%s_side.png" % fname)
    cmd.reset()
    cmd.zoom(zoom_obj, zoom_distance)
    if vesicle:
        cmd.turn("z", -90)
        cmd.move("y", -50)
Exemple #43
0
"""
A script that will execute a 360 degree spin of the structure, ray-tracing the
structure at each interval and saving the image.
"""

from pymol import cmd
import os.path

FRAMES = 360  # How many frames to spread the spin over
AXIS = 'y'  # The axis about which to spin
OUTPUT = 'turn_ray_images'  # The output directory for images
RAY_X = 1920  # The x-dimension of the image, 0 will use current window size
RAY_Y = 1080  # The y-dimension of the image, 0 will use current window size

os.mkdir(OUTPUT)

for i in xrange(FRAMES):
    cmd.turn(AXIS, 360.0 / FRAMES)
    cmd.ray(width=RAY_X, height=RAY_Y)
    frame_name = '{0}.png'.format(str(i).zfill(4))
    cmd.png(os.path.join(os.getcwd(), OUTPUT, frame_name))
 def _pngExistsAsync(self, filename, sync_in_thread):
     cmd.png(filename, width=100, height=100, ray=0)
     cmd.draw()
     if sync_in_thread:
         cmd.sync()
def produce_frame():
    name = '/tmp/frame.png'
    cmd.png(name, ray=True, width=1920, height=1080)
    with open(name, 'rb') as frame:
        os.write(produce_frame.pipe, frame.read())
    os.remove(name)
Exemple #46
0
import threading
def dump_thread():
    print
    for thr in threading.enumerate():
        print(thr)
dump_thread()
import pymol
pymol.pymol_launch=4
pymol.pymol_argv = [ 'pymol', '-qc'] #  Quiet / no GUI
from pymol import cmd
pymol.finish_launching()
dump_thread()

cmd.fetch('1TUP', async=False)
cmd.disable('all')
cmd.enable('1TUP')
cmd.bg_color('white')
cmd.hide('all')
cmd.show('cartoon')
#cmd.hide('cartoon', 'chain E+F')
#cmd.show('ribbon', 'chain E+F')
cmd.select('zinc', 'name zn')
cmd.show('sphere', 'zinc')
cmd.set('ray_trace_mode', 3)
cmd.png('1TUP.png', width=1980, height=1080, quiet=0, ray=1, prior=False)
dump_thread()

cmd.set('ray_trace_mode', 1)
cmd.png('TUP.png', width=1980, height=1080, quiet=0, ray=1, prior=False)
cmd.quit()
        -0.017600985,
        0.988740742,
        0.088662416,
        -0.120536640,
        0.000000000,
        0.000000000,
        -178.078948975,
        1.716222763,
        2.769123077,
        -0.345157623,
        140.398803711,
        215.759094238,
        -20.000000000,
    ]
)

# Get number of steps
nsteps = cmd.count_states()

# Render movie
frame_prefix = "atom-creation-frames/frame"
cmd.set("ray_trace_frames", 1)
frame_number = 0
for step in range(nsteps):
    print("rendering frame %04d / %04d" % (step + 1, nsteps))
    cmd.frame(step + 1)
    cmd.png(frame_prefix + "%04d.png" % (frame_number), ray=True)
    frame_number += 1

cmd.set("ray_trace_frames", 0)
Exemple #48
0
 def testPng(self, w, h, dpi, size):
     with testing.mktemp('.png') as filename:
         cmd.png(filename, w, h, dpi, ray=1)
         self.assertEqual(size, Image.open(filename).size)
Exemple #49
0
# where tosda find the data
A = AggregatTransferFromFile(fname)

cmd.set_view ([
    -0.566527486,    0.549390495,    0.614174008,\
     0.489665151,    0.823900998,   -0.285317212,\
    -0.662771285,    0.139101312,   -0.735783637,\
     0.000076182,    0.000004612, -127.713699341,\
    13.776422501,   -7.558099747,   -3.967736244,\
  -413.703674316,  669.118835449,  -20.000000000 ])
# select only a few sample points
indices = np.array(np.linspace(0, A._tSteps, sample_points, endpoint=False), dtype=int)
t = np.linspace(0, A._tLength, A._tSteps)[indices]

# Get values ordered by time in first index
values = np.swapaxes(A.get(), 0, 1)[indices]

selections = ['bcl{}'.format(i + 1) for i in range(7)]
for i, val in enumerate(values):
   print('Rendering {}/{}'.format(i, sample_points))
   alpha = p_to_alpha(val)
   for n, bcl in enumerate(selections):
      cmd.set_bond('stick_transparency', alpha[n], bcl)

   cmd.label('timestamp', '"t = {0:.2f} ps"'.format(t[i] * 5.3088))
   cmd.show('labels', 'timestamp')
   cmd.refresh()
   cmd.ray(width, height)
   cmd.png(savename + "%05d.png" % i)
Exemple #50
0
                tresnum=int(tresnum)
                srcatom=titatoms[tres]
                clr = sourceclrs[source]
                print resnum,tresnum,clr
                labelatom=pkatoms[p]
                cmd.select('bb','resi %s and name %s' %(resnum,labelatom))
                cmd.show('spheres','bb')
                cmd.color(clr,'bb')
                atom = titatoms[tres] 
                cmd.select('tit','resi %s' %(tresnum))
                cmd.color(clr,'tit')
                cmd.show('sticks','tit')
                cmd.label('tit and name %s' %atom,'resn+resi')
            
draw(G)
if ghostsfile1 != None:
    G = pickle.load(open(ghostsfile1,'r'))
    draw(G)
    
cmd.set('ray_trace_mode',0)
cmd.png(name+'.png',800,800)
cmd.save(name+'.pse')
cmd.quit()

 
def function1(userSelection):
    return
cmd.extend( "yourFunction", function1 );


set_res = []
for e_tup in edges : 
	set_res.extend(e_tup)
set_res = set(set_res)

for ch,resi in itertools.product(chains,set_res) : 
	cmd.label('3H4E//'+ch+'/'+resi+'/CA','"%s%s"%(resn,resi)')

cmd.set('dash_radius','0.2');
cmd.set('dash_gap','0.0');
cmd.set('sphere_scale','0.3')
#cmd.set('sphere_scale','0.8','retinal');
#cmd.ray()
outfp = os.path.join(DATA_DIR,os.path.splitext(edgef)[0]+'_hex_top.png')
print('*'*5+'Image:%s'%os.path.abspath(outfp)+'*'*5)
cmd.png(os.path.abspath(outfp))
print('-----Finished drawing from top -----')

# Set the view from the bottom
cmd.set_view (\
    '-0.062551118,    0.668488383,   -0.741087615,\
     0.326947540,   -0.687838376,   -0.648059845,\
    -0.942967236,   -0.282835305,   -0.175534144,\
     0.000000000,    0.000000000, -294.413665771,\
   -13.488616943,  -48.363307953,  -22.056068420,\
   232.117980957,  356.709350586,  -20.000000000' )
#cmd.ray()
outfp = os.path.join(DATA_DIR,os.path.splitext(edgef)[0]+'_hex_bottom.png')
print('*'*5+'Image:%s'%os.path.abspath(outfp)+'*'*5)
cmd.png(os.path.abspath(outfp))
Exemple #52
0
import os.path
import argparse

parser = argparse.ArgumentParser()

parser.add_argument("xyzfilename", nargs="+")

args = parser.parse_args()

import pymol
pymol.finish_launching()
from pymol import cmd

for state, xyzfilename in enumerate(args.xyzfilename):
    stub = os.path.splitext(xyzfilename)[0]
    # make sure no nasty characters are lurking in our filename
    cleanname = stub.replace("-", "_")
    cmd.load(xyzfilename, object=cleanname, state=state, quiet=0)
    cmd.enable()
    cmd.bg_color("white")
    # pymol.preset.ball_and_stick(selection="all", mode=1)
    cmd.show("lines")
    # pymol.cmd.ray(width=1280, height=1024, renderer=0)
    # pymol.cmd.set("antialias", 2)
    cmd.set("ray_opaque_background", "off")
    cmd.png(stub + ".png", width=1280, height=1024, quiet=0)
    cmd.reinitialize()

cmd.quit()
def FocalBlur(aperture=2.0, samples=10, ray=0, width=0, height=0):
    '''
DESCRIPTION

    Creates fancy figures by introducing a focal blur to the image. The object
    at the origin will be in focus.

AUTHOR

    Jarl Underhaug
    University of Bergen
    jarl_dot_underhaug_at_gmail_dot_com

    Updates by Jason Vertrees and Thomas Holder

USAGE

    FocalBlur aperture=float, samples=int, ray=0/1, width=int, height=int

EXAMPELS

    FocalBlur aperture=1, samples=100
    FocalBlur aperture=2, samples=100, ray=1, width=600, height=400
    '''

    # Formalize the parameter types
    ray = (ray in ("True", "true", 1, "1"))
    aperture, samples = float(aperture), int(samples)
    width, height = int(width), int(height)

    # Create a temporary directory
    tmpdir = mkdtemp()

    # Get the orientation of the protein and the light
    light = cmd.get('light')[1:-1]
    light = [float(s) for s in light.split(',')]
    view = cmd.get_view()

    # Rotate the protein and the light in order to create the blur
    for frame in range(samples):
        # Angles to rotate protein and light
        # Populate angles as Fermat's spiral
        theta = frame * pi * 110.0 / 144.0
        radius = 0.5 * aperture * sqrt(frame / float(samples - 1))
        x = cos(theta) * radius
        y = sin(theta) * radius
        xr = x / 180.0 * pi
        yr = y / 180.0 * pi

        # Rotate the protein
        cmd.turn('x', x)
        cmd.turn('y', y)

        # Rotate the light
        ly = light[1] * cos(xr) - light[2] * sin(xr)
        lz = light[2] * cos(xr) + light[1] * sin(xr)
        lx = light[0] * cos(yr) + lz * sin(yr)
        lz = lz * cos(yr) - lx * sin(yr)
        cmd.set('light', [lx, ly, lz])

        curFile = "%s/frame-%04d.png" % (tmpdir, frame)
        print("Created frame %i/%i (%0.0f%%)" % (frame + 1, samples, 100 * (frame + 1) / samples))

        # Save the image to temporary directory
        if ray:
            cmd.ray(width, height)
            cmd.png(curFile)
        else:
            cmd.png(curFile, quiet=1)

        # Create the average/blured image
        try:
            avg = Image.blend(avg, Image.open(curFile), 1.0 / (frame + 1))
        except:
            avg = Image.open(curFile)

        # Return the protein and the light to the original orientation
        cmd.set('light', light)
        cmd.set_view(view)

    # Load the blured image
    avg.save('%s/avg.png' % (tmpdir))
    cmd.load('%s/avg.png' % (tmpdir))

    # Delete the temporary files
    rmtree(tmpdir)
Exemple #54
0
A = AggregatTransferFromFile(fname)

cmd.set_view ([
    -0.480811268,    0.603387773,    0.636203885,
     0.675508440,    0.717507422,   -0.169974893,
    -0.559037924,    0.348030269,   -0.752567112,
    -0.000127681,    0.000030167, -122.974456787,
    13.921709061,   -7.469791889,   -4.264435768,
  -1086.176879883, 1332.132446289,  -20.000000000])
# select only a few sample points
indices = [0, 250, 500, 1000, 1999]
t = np.linspace(0, A._tLength, A._tSteps)[indices]

# Get values ordered by time in first index
values = np.swapaxes(A.get(), 0, 1)[indices]

selections = ['lab{}'.format(i + 1) for i in range(8)]
for lab in selections:
   cmd.label(lab, '')

selections = ['bcl{}'.format(i + 1) for i in range(7)]
for i, val in enumerate(values):
   alpha = p_to_alpha(val)
   for n, bcl in enumerate(selections):
      cmd.set_bond('stick_transparency', alpha[n], bcl)

   cmd.refresh()
   cmd.ray(width, height)
   print('Belongs to time {}'.format(t[i] * 5.20883746))
   cmd.png('../fmo_transfer_{}.png'.format(i), dpi=DPI, ray=1)
values = inFile.readlines()
print values

# create the global, stored array
stored = []
 
# read the new B factors from file
for line in values: stored.append( float(line) )
print stored
max_b = max(stored)
min_b = min(stored)

cmd.bg_color("white")
print min_b
print max_b

# close the input file
inFile.close()
 
# clear out the old B Factors
cmd.alter("%s and n. CA"%pdb, "b=0.0")
 
# update the B Factors with new properties
cmd.alter("%s and n. CA"%pdb, "b=stored.pop(0)")
 
# color the protein based on the new B Factors of the alpha carbons
cmd.spectrum("b", "rainbow", "%s and n. CA"%pdb, minimum=min_b, maximum=max_b)
cmd.ray("775", "2400")
cmd.png("unscaled%s.png"%infilename.split("_")[0])
#cmd.show('surface', 'tcr')


# Create one-to-one mapping between states and frames.
cmd.mset("1 -%d" % cmd.count_states())

# Zoom viewport
#cmd.zoom('complex')
#cmd.orient('complex')
cmd.zoom('ligand')
cmd.orient('ligand')
cmd.turn('x', -90)

# Render movie
frame_prefix = 'frames/frame'
cmd.set('ray_trace_frames', 1)
cmd.set('ray_trace_frames', 0) # DEBUG
for iteration in range(niterations):
    print "rendering frame %04d / %04d" % (iteration+1, niterations)
    cmd.frame(iteration+1)
    cmd.set('stick_transparency', float(ncfile.variables['states'][iteration, replica]) / float(nstates-1))
    cmd.png(frame_prefix + '%04d.png' % (iteration), ray=True)
    #cmd.mpng(frame_prefix, iteration+1, iteration+1)
    #cmd.load_model(model, 'complex')

cmd.set('ray_trace_frames', 0)

# Close file
ncfile.close()

Exemple #57
0
def mapColor(infile, mode, color="wolfgang.v1", reverse="OFF", position="position", target="value", adjust=0, select="OFF", IDs="OFF", maxCut="OFF", minCut="OFF", maxValue="OFF", minValue="OFF", colorDict=colorDict, altColor="OFF", dpi=300, ray=1, N=256, save="OFF", NA="OFF"):
	
	"""
	infile	:	Path to value input file.
	mode	:	How should input values be treated? Options are "raw", "normalize" and "log2".
	color	:	Color ramp to be used for value mapping.
	reverse	:	Reverse color ramp for value mapping.
	position:	Position column in input file.
	target	:	Target value column to map to each position.
	adjust	:	Integer describing how many residues into the chain to begin coloring.
	IDs		:	Should residue identities (chemicals) be read for each position? If so, specify identity column.
	maxCut	:	Maximum value (cutoff) allowed for redefined value range.
	minCut	:	Minimum value (cutoff) allowed for redefined value range.
	maxValue:	Maximum value for high-range normalization.
	minValue:	Minimum value for high-range normalization.
	dpi		:	PyMol resolution; dots per inch.
	ray		:	PyMol rendering mode.
	N		:	Color ramp size.
	"""
	
	# Load color map. Note that colors come inverted:
	colorMix = list(colorDict[color])
	if reverse == "OFF":
		colorMix.reverse()
	colorMap = mpl.colors.LinearSegmentedColormap.from_list(colorMix, colors=colorMix, N=N)
	color256 = colorMap(numpy.arange(N))
	
	#for index in range(0, 255):
	#	r, g, b, f = color256[index]
	#	print index, ":", "	".join(map(str, [round(r, 2), round(g, 2), round(b, 2)]))
	#print

	print
	print "ColorMap:", color
	print "Colors:", len(color256)
	print
	
	# load input file and intensity values:
	rawDict = quickBuilder(infile, i=position, x=target, mode="float")
	positions = sorted(rawDict.keys())
	
	# load reference identities if necessary:
	if IDs != "OFF":
		idDict = quickBuilder(infile, i=position, x=IDs, mode="string")
	
	# threshold the raw (input) values, if necessary:
	rawValues, rawPositions, rawIDs = list(), list(), list()
	for position in positions:
		rawValue = float(rawDict[position])
		if maxCut != "OFF":
			rawValue = min(rawValue, maxCut)
		if minCut != "OFF":
			rawValue = max(rawValue, minCut)
		rawValues.append(rawValue)
		rawPositions.append(position)
		
		# load IDs if specified:
		if IDs != "OFF":
			rawIDs.append(idDict[position])
	
	# normalize and transform values, if necessary:
	colorValues = list()
	if mode == "raw":
		if minValue == "OFF" and maxValue == "OFF":
			colorValues = rawValues
		else:
			for value in rawValues:
				if minValue != "OFF" and value < float(minValue):
					colorValues.append(minValue)
				elif maxValue != "OFF" and value > float(maxValue):
					colorValues.append(maxValue)
				else:
					colorValues.append(value)
			
	elif mode == "normalize":
		for value in rawValues:
			if value < 0 and minValue == "OFF":
				colorValues.append(-1*value/min(rawValues))
			elif value < 0 and minValue != "OFF":
				colorValues.append(-1*value/float(minValue))
			elif value > 0 and maxValue == "OFF":
				colorValues.append(value/max(rawValues))
			elif value > 0 and maxValue != "OFF":
				colorValues.append(value/float(maxValue))
			elif value == 0:
				colorValues.append(0)
	
	elif mode == "log2":
		log2Values = [ math.log(value, 2) for value in rawValues ]
		for value in log2Values:
			if value < 0:
				colorValues.append(-1*value/min(log2Values))
			elif value > 0:
				colorValues.append(value/max(log2Values))
			elif value == 0:
				colorValues.append(0) 
	
	elif mode == "log10":
		
		logXValues = [ numpy.log10(value) for value in rawValues ]
		
		for value in logXValues:
			if value < 0 and not value == -float('Inf'):
				colorValues.append(-1*value/min(logXValues))
			elif value > 0 and not value == float('Inf'):
				colorValues.append(value/max(logXValues))
			elif value == 0:
				colorValues.append(0)
			elif value in [float('Inf'), -float('Inf'), float('NaN')]:
				colorValues.append(NA)
				print value, NA
	
	else:
		sys.exit("Error: choose a valid mode")
	
	# generate complete range of values:
	minColor, maxColor = min(colorValues), max(colorValues)
	if minValue != "OFF":
		minColor = float(minValue)
	if maxValue != "OFF":
		maxColor = float(maxValue)
	colorRanges = floatRange(minColor, maxColor, steps=N)
	
	#[x for x in colorRanges if x != 'nan']
	
	print
	print "Input values (min, max):", min(colorValues), "-", max(colorValues)
	print "Range values (min, max):", min(colorRanges), "-", max(colorRanges)
	print
	
	# color residues:
	fraction = 0.1
	for index in range(0, len(colorValues)):
	
		# define residue names:
		if select == "OFF":
			colorName = "res" + str(int(index) + adjust)
		else:
			colorName = "%s and chain %s" % tuple(select.split(",")) + " and resi " + str(int(index) + adjust)
		fraction = findValues(colorRanges, float(colorValues[index]), mode="less.equal", report="fraction")
		
		# define residue color:
		if altColor == "OFF":
			r, g, b, f = color256[int(fraction*(N-1))]
			cmd.set_color(str(colorName), str([r, g, b]))
			cmd.color(colorName, colorName)
			output = [int(index) + adjust, rawPositions[index], rawValues[index], fraction, colorName]
			
		# resets residue color:
		if altColor != "OFF" and rawValues[index] in altColor:
			r, g, b, f = altColor[rawValues[index]]
			cmd.set_color(str(colorName), str([r, g, b]))
			cmd.color(colorName, colorName)
			output = [int(index) + adjust, rawPositions[index], rawValues[index], fraction, colorName]
			
		# record IDs, if requested:
		if IDs != "OFF":
			output.append(rawIDs[index])
		#print "  ".join(map(str, output))
	#print len(color256)
	
	# save image:
	if save != "OFF":
		print save
		cmd.png((save), dpi=dpi, ray=ray)
Exemple #58
0
def mke(source, reference, maximum=None, export_filename=None):
    align_and_color(source, reference, maximum=maximum)
    make_export_ready()
    if export_filename:
        cmd.png(export_filename, height=1000, ray=1)
Exemple #59
0
def make_figure(output='', mode='',size=900,opaque='transparent'):

	"""

AUTHOR

	Martin Christen


DESCRIPTION

	"make_figure" creates publication-quality figures of the current scene.
	It understands several predefined "modes" and sizes.


USAGE

	make_figure filename [, mode] [, size (default=900 pixels)] [,opaque]


ARGUMENTS

	mode = string: type of desired figure (single, fb, sides, stereo or -nothing-)
	size = integer: size of the figure in pixels OR # panels (if <= 12)
	opaque = specify an opaque background.
	         By default, the script makes the background transparent.
EXAMPLES

	make_figure output
	make_figure output, single, 975, opaque
	make_figure output, fb, 2
	make_figure output, sides,4
	make_figure output, stereo


NOTES

	"single" mode makes a single 300 dpi figure
	
	"fb" mode makes TWO 300 dpi figure
	("front" and "back", rotating by 180 degrees about y)
	
	"sides" mode makes FOUR 300 dpi figures
	("front" "left" "right" and back, rotating by 90 degrees clockwise about y)
	
	"stereo" generates two 300 dpi, 750 px figures
	("L" and "R", to be combined as a stereo image)
	If you specify the stereo mode, the size argument is IGNORED.
		
	If no mode argument is given, the script generates quick figures
	for general	use: TWO figures (front and back) at 300 x 300 px, 72 dpi.
	
	Size is interpreted as pixels, except if the number is ridiculously small
	(<=12),	in which case the script as "number of panels" to make.

	Edit the script manually to define corresponding values.
	
	"""

	#define sizes here (in pixels)
	panel1 = 1800
	panel2 = 1350
	panel3 = 900
	panel4 = 900
	panel5 = 750
	panel6 = 750
	panel7 = 675
	panel8 = 675
	panel9 = 600
	panel10 = 585
	panel11 = 585
	panel12 = 585
	
	#verify size is an integer number and convert to pixels
	size = int(size)
	if size > 12:
		pixels = size
	
	elif size == 1:
		pixels = panel1
	
	elif size == 2:
		pixels = panel2
	
	elif size == 3:
		pixels = panel3
	
	elif size == 4:
		pixels = panel4
	
	elif size == 5:
		pixels = panel5
	
	elif size == 6:
		pixels = panel6
	
	elif size == 7:
		pixels = panel7
	
	elif size == 8:
		pixels = panel8
	
	elif size == 9:
		pixels = panel9
	
	elif size == 10:
		pixels = panel10
	
	elif size == 11:
		pixels = panel11
	
	elif size == 3:
		pixels = panel12

	#change background
	cmd.unset('opaque_background')
	if opaque == 'opaque':
		cmd.set('opaque_background')
	
	#apply mode
	if output == '':
		print 'no output filename defined\n'
		print 'try: \'make_figure filename\''
		return -1
		# abort if no output file name given

	if mode =='':
		cmd.set('surface_quality',1)
		cmd.set('opaque_background')
		cmd.png(output+"_back_quick",300,300,dpi=72)
		cmd.turn('y',180)
		cmd.png(output+"_front_quick",300,300,dpi=72)
		cmd.turn('y',180)
		cmd.set('surface_quality',0)
		# make front and back figures for quick mode

	elif mode == 'single':
		cmd.set('surface_quality',1)
		cmd.set('ray_shadow',0)
		cmd.ray(pixels, pixels)
		cmd.png(output, dpi=300)
		cmd.set('surface_quality',0)
		# make a figure for single mode
		
	elif mode == 'fb':
		cmd.set('surface_quality',1)
		cmd.set('ray_shadow',0)
		cmd.ray(pixels, pixels)
		cmd.png(output+"_front", dpi=300)
		cmd.turn('y',180)
		cmd.ray(pixels, pixels)
		cmd.png(output+"_back", dpi=300)
		cmd.turn('y',180)
		cmd.set('surface_quality',0)
		# make front and back figures for single mode

	elif mode == 'sides':
		cmd.set('surface_quality',1)
		cmd.set('ray_shadow',0)
		cmd.ray(pixels, pixels)
		cmd.png(output+"_1", dpi=300)
		cmd.turn('y',90)
		cmd.ray(pixels, pixels)
		cmd.png(output+"_2", dpi=300)
		cmd.turn('y',90)
		cmd.ray(pixels, pixels)
		cmd.png(output+"_3", dpi=300)
		cmd.turn('y',90)
		cmd.ray(pixels, pixels)
		cmd.png(output+"_4", dpi=300)
		cmd.turn('y',90)
		cmd.set('surface_quality',0)
		# make front and back figures for single mode
		
	elif mode == 'stereo':
		cmd.set('surface_quality',1)
		cmd.set('ray_shadow',0)
		cmd.ray(750, 750, angle=-3)
		cmd.png(output+"_R", dpi=300)
		cmd.ray(750, 750, angle=3)
		cmd.png(output+"_L", dpi=300)