コード例 #1
0
ファイル: visualize_rna.py プロジェクト: porteusconf/forgi
def pymol_printer_from_args(args):
    pp = ftvp.PymolPrinter()
    if args.thin_cylinders:
        pp.cylinder_width = 0.5
        pp.show_twists = False
    pp.display_virtual_residues = args.virtual_residues
    pp.virtual_atoms = args.virtual_atoms

    if args.only_elements is not None:
        pp.only_elements = args.only_elements.split(',')
    pp.add_loops = not args.no_loops
    pp.add_longrange = args.longrange
    pp.stem_color = args.stem_color
    pp.multiloop_color = args.multiloop_color
    pp.print_text = args.text
    pp.encompassing_stems = args.encompassing_stems
    pp.sidechain_atoms = args.sidechain_atoms
    pp.basis = args.basis
    pp.rainbow = args.rainbow
    if args.element_colors:
        directives = args.element_colors.split(",")
        elem_colors = {}
        for directive in directives:
            elem, _, color = directive.partition(":")
            log.debug("Element %s: %s", elem, color)
            if not color:
                color = "purple"
            if color not in ftvp.NAMED_COLORS:  # A hex value
                try:
                    color = tuple(
                        int(color[i:i + 2], 16) / 255 for i in (0, 2, 4))
                except:
                    raise ValueError("Color value '{}' not understood. "
                                     "Either provide a HEX value or "
                                     "one of {}".format(
                                         color,
                                         ",".join(ftvp.NAMED_COLORS.keys())))
            if elem.lower() == "default":
                default_color = color  # Color is changed later
                elem_colors = defaultdict(lambda: default_color, elem_colors)
            else:
                elem_colors[elem] = color
            log.debug("Element %s", elem_colors)

        pp.element_specific_colors = elem_colors
    return pp
コード例 #2
0
ファイル: visualize_pdb.py プロジェクト: happyshi0402/forgi
def main():
    usage = """
    ./visualize_pdb.py pdb_file

    Display a pdb file along with its coarse grain representation in pymol.
    """
    num_args = 0
    parser = OptionParser(usage=usage)

    parser.add_option('-s',
                      '--secondary-structure',
                      dest='secondary_structure',
                      default='',
                      help="Enter a dot-bracket string for the \
                      secondary structure of this model",
                      type=str)
    parser.add_option('-x',
                      '--text',
                      dest='text',
                      default=False,
                      action='store_true',
                      help="Add labels to the figure.")
    parser.add_option('-r',
                      '--longrange',
                      dest='longrange',
                      default=False,
                      action='store_true',
                      help="Display long-range interactions")
    parser.add_option('-p',
                      '--pseudoknots',
                      dest='pseudoknots',
                      default=False,
                      action='store_true',
                      help='Allow pseudoknots in the CG structure')
    #parser.add_option('', '--batch', dest='batch', default=False, action='store_true', help='Start pymol in batch mode') #Crashes currently
    parser.add_option('',
                      '--virtual-residues',
                      dest='virtual_residues',
                      default=False,
                      action='store_true',
                      help='Display the virtual residues as spheres')
    parser.add_option(
        '',
        '--color-residues',
        dest='color_residues',
        default=False,
        action='store_true',
        help="Color the residues according to the element they're in")

    #parser.add_option('-u', '--useless', dest='uselesss', default=False, action='store_true', help='Another useless option')

    parser.add_option('-l',
                      '--loops',
                      dest='loops',
                      default=True,
                      action='store_false',
                      help="Don't display the coarse-grain hairpin loops")
    parser.add_option('-d',
                      '--distance',
                      dest='distance',
                      default=None,
                      help="Draw the lines between specified virtual residues")
    parser.add_option('-o',
                      '--output',
                      dest='output',
                      default=None,
                      help="Create a picture of the scene and exit",
                      type='str')
    parser.add_option('',
                      '--only-elements',
                      dest='only_elements',
                      default=None,
                      help='Display only these elements '
                      'element names should be '
                      'separated by commas')
    parser.add_option('-v',
                      '--virtual-atoms',
                      dest='virtual_atoms',
                      default=False,
                      action='store_true',
                      help='Display the virtual atoms')

    (options, args) = parser.parse_args()

    if len(args) < 1:
        parser.print_help()
        sys.exit(1)

    if not op.exists(args[0]):
        print >> sys.stderr, "File doesn't exist: %s" % (args[0])
        sys.exit(1)

    cg = ftmc.from_pdb(args[0],
                       options.secondary_structure.strip("\"'"),
                       remove_pseudoknots=not options.pseudoknots)
    pp = ftvp.PymolPrinter()
    pp.display_virtual_residues = options.virtual_residues
    pp.virtual_atoms = options.virtual_atoms

    if options.only_elements is not None:
        orig_only_elements = options.only_elements.split(',')
        only_elements = set(orig_only_elements[::])
        for c in orig_only_elements:
            for e in cg.edges[c]:
                only_elements.add(e)
        pp.only_elements = only_elements

    pp.add_loops = options.loops
    pp.add_longrange = options.longrange
    #sys.exit(1)
    pp.coordinates_to_pymol(cg)
    pp.print_text = options.text
    print >> sys.stderr, "virtual_residues:", options.virtual_residues
    #pp.print_text = False
    #pp.output_pymol_file()

    if options.only_elements is not None:
        pp.only_elements = options.only_elements.split(',')

    with tf.NamedTemporaryFile() as f:
        with tf.NamedTemporaryFile(suffix='.pml') as f1:
            with tf.NamedTemporaryFile(suffix='.pdb') as f2:
                # extract just the biggest chain and renumber it so
                # the nucleotides start at 1
                chain = ftup.get_biggest_chain(args[0])
                #chain = ftup.renumber_chain(chain)
                ftup.output_chain(chain, f2.name)
                f2.flush()

                # display the distances between nucleotides
                if options.distance is not None:
                    for dist_pair in options.distance.split(':'):
                        fr, to = dist_pair.split(',')

                        fr = int(fr)
                        to = int(to)

                        try:
                            vec1 = chain[fr]["C1*"].get_vector().get_array()
                            vec2 = chain[to]["C1*"].get_vector().get_array()
                        except KeyError:
                            # Rosetta produces atoms with non-standard names
                            vec1 = chain[fr]["C1*"].get_vector().get_array()
                            vec2 = chain[to]["C1*"].get_vector().get_array()

                        pp.add_dashed(vec1, vec2, width=1.2)

                f.write(pp.pymol_string())
                f.flush()

                pymol_cmd = 'hide all\n'
                pymol_cmd += 'show cartoon, all\n'
                pymol_cmd += 'set cartoon_ring_mode\n'
                pymol_cmd += 'set cartoon_tube_radius, .3\n'

                if options.only_elements is not None:
                    pymol_cmd += "hide all\n"

                    for constraint in only_elements:
                        color = pp.get_element_color(constraint)

                        for r in cg.define_residue_num_iterator(constraint,
                                                                seq_ids=True):
                            pymol_cmd += "show sticks, resi %r\n" % (r[1])
                            pymol_cmd += "color %s, resi %r\n" % (color, r[1])

                if options.color_residues:
                    for d in cg.defines:
                        color = pp.get_element_color(d)

                        for r in cg.define_residue_num_iterator(d,
                                                                seq_ids=True):
                            pymol_cmd += "color %s, resi %r\n" % (color, r[1])

                pymol_cmd += 'run %s\n' % (f.name)
                pymol_cmd += 'bg white\n'
                pymol_cmd += 'clip slab, 10000\n'
                pymol_cmd += 'orient\n'

                if options.output is not None:
                    pymol_cmd += 'ray\n'
                    pymol_cmd += 'png %s\n' % (options.output)
                    #pymol_cmd += 'quit\n' #This would lead to an error message

                f1.write(pymol_cmd)
                f1.flush()

                #if options.batch:
                #    p = sp.Popen(['pymol', '-cq', f2.name, f1.name], stdout=sp.PIPE, stderr=sp.PIPE)
                if True:  #else:
                    p = sp.Popen(['pymol', f2.name, f1.name],
                                 stdout=sp.PIPE,
                                 stderr=sp.PIPE)

                out, err = p.communicate()
コード例 #3
0
ファイル: visualize_cg.py プロジェクト: happyshi0402/forgi
def main():
    usage = """
    ./visualize_cg.py cg_file

    Display the coarse-grain representation of a structure in pymol.
    """
    num_args = 1
    parser = OptionParser(usage=usage)

    # parser.add_option('-u', '--useless', dest='uselesss',
    # default=False, action='store_true', help='Another useless option')
    parser.add_option('-g',
                      '--highlight',
                      dest='highlight',
                      default=None,
                      help="Highlight some elements",
                      type='str')
    parser.add_option('-o',
                      '--output',
                      dest='output',
                      default=None,
                      help="Create a picture of the scene and exit",
                      type='str')
    parser.add_option('-r',
                      '--longrange',
                      dest='longrange',
                      default=False,
                      action='store_true',
                      help="Display long-range interactions")
    parser.add_option('-l',
                      '--loops',
                      dest='loops',
                      default=True,
                      action='store_false',
                      help="Don't display the coarse-grain hairpin loops")
    parser.add_option('-c',
                      '--cones',
                      dest='cones',
                      default=False,
                      action='store_true',
                      help="Display cones that portrude from the stems")
    parser.add_option('-x',
                      '--text',
                      dest='text',
                      default=False,
                      action='store_true',
                      help="Add labels to the figure.")
    parser.add_option('-a',
                      '--align',
                      dest='align',
                      default=False,
                      action='store_true',
                      help='Align all of the structures with the first')
    parser.add_option(
        '-e',
        '--encompassing-stems',
        dest='encompassing_stems',
        default=False,
        action='store_true',
        help='Show the big stems that encompass the colinear ones.')
    parser.add_option('-v',
                      '--virtual-atoms',
                      dest='virtual_atoms',
                      default=False,
                      action='store_true',
                      help='Display the virtual atoms')
    parser.add_option('-d',
                      '--distance',
                      dest='distance',
                      default=None,
                      help="Draw the lines between specified virtual residues")
    parser.add_option('-b',
                      '--basis',
                      dest='basis',
                      default=False,
                      action='store_true',
                      help='Display the coordinate basis of each element')
    parser.add_option('',
                      '--batch',
                      dest='batch',
                      default=False,
                      action='store_true',
                      help='Start pymol in batch mode')
    parser.add_option(
        '',
        '--sidechain-atoms',
        dest='sidechain_atoms',
        default=False,
        action='store_true',
        help=
        'Include the sidechain atoms. Automatically enables --virtual-atoms')
    parser.add_option(
        '',
        '--rainbow',
        dest='rainbow',
        default=False,
        action='store_true',
        help=
        'Color each of the nucleotide positions (i.e. average atoms) according to the colors of \
                      the rainbow and their position')
    parser.add_option('',
                      '--only-elements',
                      dest='only_elements',
                      default=None,
                      help='Display only these elements '
                      'element names should be '
                      'separated by commas')
    parser.add_option('',
                      '--color-gradual',
                      dest='color_gradual',
                      default=None,
                      help='Color the specified elements'
                      'gradually from one to the other, example (i1,i4,m1)',
                      type='str')

    (options, args) = parser.parse_args()

    print "hi"
    if len(args) < num_args:
        parser.print_help()
        sys.exit(1)
    print "hi1"

    pp = cvp.PymolPrinter()
    pp.add_loops = options.loops
    pp.draw_cones = options.cones
    # sys.exit(1)
    pp.add_longrange = options.longrange
    pp.print_text = options.text
    pp.encompassing_stems = options.encompassing_stems
    pp.virtual_atoms = options.virtual_atoms
    pp.sidechain_atoms = options.sidechain_atoms
    pp.basis = options.basis
    pp.rainbow = options.rainbow

    if options.only_elements is not None:
        pp.only_elements = options.only_elements.split(',')

    cgs = []
    for a in args:
        cgs += [cmg.CoarseGrainRNA(a)]

    if options.align:
        align_cgs(cgs)

    if options.color_gradual is not None:
        pp.element_specific_colors = dict()
        import matplotlib.pyplot as plt
        cmap = plt.get_cmap('coolwarm')

        for d in cgs[0].defines:
            pp.element_specific_colors[d] = 'black'

        to_color_nodes = options.color_gradual.split(',')
        for i, node in enumerate(to_color_nodes):
            print node, cmap(i / float(len(to_color_nodes)))
            pp.element_specific_colors[node] = cmap(i /
                                                    float(len(to_color_nodes)))

    for i, cg in enumerate(cgs):
        if i > 0:
            pp.color_modifier = .3
            #pp.override_color = 'middle gray'

        pp.coordinates_to_pymol(cg)

    # highlight things in purple
    if options.highlight is not None:
        for s in options.highlight.split(','):
            fud.pv('s')
            pp.add_twists = False
            pp.add_stem_like(cg, s, color='purple', width=3.)

    # display the distances between nucleotides
    if options.distance is not None:
        virtual_atoms = ftug.virtual_atoms(cg, sidechain=False)

        for dist_pair in options.distance.split(':'):
            fud.pv('dist_pair')
            fr, to = dist_pair.split(',')

            fr = int(fr)
            to = int(to)

            pp.add_dashed(virtual_atoms[fr]["C1'"],
                          virtual_atoms[to]["C1'"],
                          width=1.2)

    with tf.NamedTemporaryFile() as f:
        with tf.NamedTemporaryFile(suffix='.pml') as f1:
            f.write(pp.pymol_string())
            f.flush()

            pymol_cmd = 'hide all\n'
            pymol_cmd += 'run %s\n' % (f.name)
            pymol_cmd += 'show cartoon, all\n'
            pymol_cmd += 'bg white\n'
            pymol_cmd += 'clip slab, 10000\n'
            pymol_cmd += 'orient\n'

            if options.output is not None:
                pymol_cmd += 'ray\n'
                pymol_cmd += 'png %s\n' % (options.output)
                pymol_cmd += 'quit\n'

            f1.write(pymol_cmd)
            f1.flush()

            print "f1.name:", f1.name

            if options.batch:
                p = sp.Popen(['pymol', '-cq', f1.name],
                             stdout=sp.PIPE,
                             stderr=sp.PIPE)
            else:
                p = sp.Popen(['pymol', f1.name],
                             stdout=sp.PIPE,
                             stderr=sp.PIPE)

            out, err = p.communicate()
            print >> sys.stderr, "err:", err
コード例 #4
0
def main():
    usage = """
    python plot_average_atom_positions.py

    Currently works for certain multiloops (hardcoded).
    """

    num_args = 0
    parser = OptionParser(usage=usage)

    #parser.add_option('-o', '--options', dest='some_option', default='yo', help="Place holder for a real option", type='str')
    #parser.add_option('-u', '--useless', dest='uselesss', default=False, action='store_true', help='Another useless option')
    parser.add_option(
        '-a',
        '--all',
        dest='all_entries_file',
        default=None,
        help=
        'Use a file containing the positions of each entry for this cg element.',
        type='str')

    (options, args) = parser.parse_args()

    if len(args) < num_args:
        parser.print_help()
        sys.exit(1)

    pp = ftvp.PymolPrinter()

    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    cmap = plt.get_cmap('gist_rainbow')
    stem_len = 3

    for aname in ftup.nonsidechain_atoms:
        conn_types = [2]
        for i in range(3):
            all_coords = []
            for conn_type in conn_types:
                elem_type = 'm'
                dimensions = '3 1000'
                identifier = "%s %s %d %d %s" % (elem_type, dimensions,
                                                 conn_type, i, aname)

                if options.all_entries_file is not None:
                    import imp
                    fn = op.expanduser(options.all_entries_file)
                    #fn1 = op.expanduser(op.splitext(options.all_entries_file)[0])
                    xftua = imp.load_source('xftua', fn)
                    coords = xftua.all_atom_poss[identifier]
                    for c in coords:
                        pp.add_sphere(c,
                                      width=0.2,
                                      color_rgb=cmap(i / float(stem_len)))

                    all_coords += coords
                    avg_coord = np.mean(coords, axis=0)
                    pp.add_sphere(avg_coord,
                                  width=0.6,
                                  color_rgb=cmap(i / float(stem_len)))
                else:
                    coords = ftua.avg_atom_poss[identifier]
                    pp.add_sphere(coords,
                                  width=0.2,
                                  color_rgb=cmap(i / float(stem_len)))

            avg_coord = np.mean(all_coords, axis=0)
            pp.add_sphere(avg_coord,
                          width=0.9,
                          color_rgb=cmap(i / float(stem_len)))

    # Add an axis
    pp.add_segment([0, 0, 0], [5, 0, 0], "purple", 0.5)

    with tf.NamedTemporaryFile() as f:
        with tf.NamedTemporaryFile(suffix='.pml') as f1:
            f.write(pp.pymol_string())
            f.flush()

            pymol_cmd = 'hide all\n'
            pymol_cmd += 'run %s\n' % (f.name)
            pymol_cmd += 'show cartoon, all\n'
            pymol_cmd += 'bg white\n'
            pymol_cmd += 'clip slab, 10000\n'

            f1.write(pymol_cmd)
            f1.flush()

            p = sp.Popen(['pymol', f1.name])
            out, err = p.communicate()
コード例 #5
0
ファイル: visualize_cg.py プロジェクト: marcelTBI/forgi
def main():
    usage = """
    ./visualize_cg.py cg_file

    Display the coarse-grain representation of a structure in pymol.
    """
    num_args= 0
    parser = OptionParser(usage=usage)

    #parser.add_option('-u', '--useless', dest='uselesss', default=False, action='store_true', help='Another useless option')
    parser.add_option('-o', '--output', dest='output', default=None, help="Create a picture of the scene and exit", type='str')
    parser.add_option('-r', '--longrange', dest='longrange', default=False, action='store_true', help="Display long-range interactions")
    parser.add_option('-l', '--loops', dest='loops', default=True, action='store_false', help="Don't display the coarse-grain hairpin loops")
    parser.add_option('-c', '--cones', dest='cones', default=False, action='store_true', help="Display cones that portrude from the stems")
    parser.add_option('-x', '--text', dest='text', default=False, action='store_true', help="Add labels to the figure.")
    parser.add_option('-a', '--align', dest='align', default=False, action='store_true', help='Align all of the structures with the first')
    parser.add_option('-e', '--encompassing-stems', dest='encompassing_stems', default=False, action='store_true', help='Show the big stems that encompass the colinear ones.')
    parser.add_option('-v', '--virtual-atoms', dest='virtual_atoms', default=False, action='store_true', help='Display the virtual atoms')
    parser.add_option('-b', '--basis', dest='basis', default=False, action='store_true', help='Display the coordinate basis of each element')
    parser.add_option('', '--stem-atoms', dest='stem_atoms', default=False, action='store_true', help='Display the stem atoms')
    parser.add_option('', '--rainbow', dest='rainbow', default=False, action='store_true', help='Color each of the nucleotide positions (i.e. average atoms) according to the colors of the rainbow and their position')

    (options, args) = parser.parse_args()

    if len(args) < 1:
        parser.print_help()
        sys.exit(1)

    pp = cvp.PymolPrinter()
    pp.add_loops = options.loops
    pp.draw_cones = options.cones
    #sys.exit(1)
    pp.add_longrange = options.longrange
    pp.print_text = options.text
    pp.encompassing_stems = options.encompassing_stems
    pp.virtual_atoms = options.virtual_atoms
    pp.basis = options.basis
    pp.rainbow = options.rainbow

    cgs = []
    for a in args:
        cgs += [cmg.from_file(a)]

    if options.align:
        align_cgs(cgs)

    for i,cg in enumerate(cgs):
        if i > 0:
            pp.color_modifier = .3
            #pp.override_color = 'middle gray'


        pp.coordinates_to_pymol(cg)

    for d in cg.defines:
        if d[0] == 'i' or d[0] == 's' or d[0] == 'm':
            if options.stem_atoms:
                side = 0
                if d[0] == 'm':
                    side = cg.get_strand(d)

                    pp.stem_atoms(cg.coords[d], cg.get_twists(d), 
                                  cg.get_node_dimensions(d)[0], side=side)
                elif d[0] == 's':
                    for side in range(2):
                        pp.stem_atoms(cg.coords[d], cg.get_twists(d), 
                                    cg.get_node_dimensions(d)[0], side=side)


    with tf.NamedTemporaryFile() as f:
        with tf.NamedTemporaryFile(suffix='.pml') as f1:
            f.write(pp.pymol_string())
            f.flush()

            pymol_cmd = 'hide all\n'
            pymol_cmd += 'run %s\n' % (f.name)
            pymol_cmd += 'show cartoon, all\n'
            pymol_cmd += 'bg white\n'
            pymol_cmd += 'clip slab, 10000\n'

            if options.output is not None:
                pymol_cmd += 'ray\n'
                pymol_cmd += 'png %s\n' % (options.output)
                pymol_cmd += 'quit\n'


            f1.write(pymol_cmd)
            f1.flush()

            p = sp.Popen(['pymol', f1.name])
            out, err = p.communicate()
コード例 #6
0
def main():
    usage = """
    ./visualize_pdb.py pdb_file

    Display a pdb file along with its coarse grain representation in pymol.
    """
    num_args = 0
    parser = OptionParser(usage=usage)

    parser.add_option('-s',
                      '--secondary-structure',
                      dest='secondary_structure',
                      default='',
                      help="Enter a dot-bracket string for the \
                      secondary structure of this model",
                      type=str)
    parser.add_option('-x',
                      '--text',
                      dest='text',
                      default=False,
                      action='store_true',
                      help="Add labels to the figure.")
    parser.add_option('-r',
                      '--longrange',
                      dest='longrange',
                      default=False,
                      action='store_true',
                      help="Display long-range interactions")
    parser.add_option('-c',
                      '--constraints',
                      dest='constraints',
                      default=None,
                      help="Only visualize the elements passed as parameters",
                      type='str')

    #parser.add_option('-u', '--useless', dest='uselesss', default=False, action='store_true', help='Another useless option')

    parser.add_option('-l',
                      '--loops',
                      dest='loops',
                      default=True,
                      action='store_false',
                      help="Don't display the coarse-grain hairpin loops")

    (options, args) = parser.parse_args()

    if len(args) < 1:
        parser.print_help()
        sys.exit(1)

    if not op.exists(args[0]):
        print >> sys.stderr, "File doesn't exist: %s" % (args[0])
        sys.exit(1)

    cg = ftmc.from_pdb(args[0], options.secondary_structure.strip("\"'"))
    pp = ftvp.PymolPrinter()

    if options.constraints is not None:
        orig_constraints = options.constraints.split(',')
        constraints = set(orig_constraints[::])
        for c in orig_constraints:
            for e in cg.edges[c]:
                constraints.add(e)
        pp.constraints = constraints

    pp.add_loops = options.loops
    pp.add_longrange = options.longrange
    #sys.exit(1)
    pp.coordinates_to_pymol(cg)
    pp.print_text = options.text
    #pp.print_text = False
    #pp.output_pymol_file()

    with tf.NamedTemporaryFile() as f:
        with tf.NamedTemporaryFile(suffix='.pml') as f1:
            with tf.NamedTemporaryFile(suffix='.pdb') as f2:
                # extract just the biggest chain and renumber it so
                # the nucleotides start at 1
                chain = ftup.get_biggest_chain(args[0])
                #chain = ftup.renumber_chain(chain)
                ftup.output_chain(chain, f2.name)
                f2.flush()

                f.write(pp.pymol_string())
                f.flush()

                pymol_cmd = 'hide all\n'
                pymol_cmd += 'show cartoon, all\n'
                pymol_cmd += 'set cartoon_ring_mode\n'
                pymol_cmd += 'set cartoon_tube_radius, .3\n'

                if options.constraints is not None:
                    pymol_cmd += "hide all\n"

                    for constraint in constraints:
                        color = pp.get_element_color(constraint)

                        for r in cg.define_residue_num_iterator(constraint):
                            pymol_cmd += "show sticks, resi %r\n" % (r)
                            pymol_cmd += "color %s, resi %r\n" % (color, r)

                pymol_cmd += 'run %s\n' % (f.name)

                f1.write(pymol_cmd)
                f1.flush()

                p = sp.Popen(['pymol', f2.name, f1.name])
                out, err = p.communicate()
コード例 #7
0
def main():
    usage = './bounding_box_coords.py temp.pdb [temp2.pdb ...]'
    usage += "Print out the positions of the atoms in coordinates "
    usage += "respective to the virtual residue coordinate system."
    parser = OptionParser()

    #parser.add_option('-o', '--options', dest='some_option', default='yo', help="Place holder for a real option", type='str')
    parser.add_option('-e',
                      '--edge',
                      dest='edge',
                      default=False,
                      action='store_true',
                      help='Include the edge nucleotides in the statistics.')
    parser.add_option('-p',
                      '--pymol',
                      dest='pymol',
                      default=False,
                      action='store_true',
                      help='Output in pymol cgo format.')
    parser.add_option('-a',
                      '--averages',
                      dest='averages',
                      default=False,
                      action='store_true',
                      help='Output the average coordinates')
    parser.add_option(
        '-r',
        '--residue',
        dest='residue',
        default='AUGC',
        help="The type of residue to calculate the averages for.",
        type='str')

    (options, args) = parser.parse_args()

    if len(args) < 1:
        parser.print_help()
        sys.exit(1)

    all_coords = [co.defaultdict(list), co.defaultdict(list)]

    pp = cvp.PymolPrinter()
    pp.draw_axes = True

    for pdbfile in args:
        try:
            bg = ttmc.from_pdb(pdbfile)
        except Exception as e:
            log.exception(e)
            continue
        chain = bg.chain

        for s in bg.stem_iterator():
            for i in range(bg.stem_length(s)):
                if i == 0 or i == bg.stem_length(s) - 1:
                    if not options.edge:
                        continue

                (origin, basis,
                 coords) = cgg.stem_vres_reference_atoms(bg, chain, s, i)

                # subtract one because the sequence is 0-based
                (p1, p2) = (bg.defines[s][0] + i - 1, bg.defines[s][3] - i - 1)
                (r1, r2) = (bg.seq[p1], bg.seq[p2])

                all_coords[0][r1].append(coords[0])
                all_coords[1][r2].append(coords[1])
                '''
                if options.pymol:
                    if not options.averages:
                        add_pymol_coords(coords)
                else:
                    print_atom_positions(coords)
                '''

    if options.averages:
        if options.pymol:
            print_average_atom_positions(all_coords, list(options.residue), pp)
            pp.output_pymol_file()
        else:
            print_average_atom_positions(all_coords, list(options.residue),
                                         None)
    else:
        for i, c in enumerate(all_coords):
            for k in c.keys():
                for coords in c[k]:
                    for atom in coords.keys():
                        print i, k, atom, " ".join(map(str, coords[atom]))