Exemple #1
0
def async_calculation(im_and_box, numFiles, filenames):
    (ref_img, ref_box) = im_and_box
    try:
        distances = []
        for j in range(numFiles):
            cg = ftmc.CoarseGrainRNA(filenames[j])
            distance, img, _ = fph.globally_minimal_distance(
                ref_img, ref_box[1] - ref_box[0], cg)
            distances.append(distance)
        return distances
    except KeyboardInterrupt:
        print("In worker {}: Keyboard Interrupt".format(id(ref_img)))
        return
Exemple #2
0
 def test_projection_with_some_virtual_atoms(self):
     cg = ftmc.CoarseGrainRNA('test/forgi/threedee/data/1y26.cg')
     proj = fpp.Projection2D(cg, [1., 1., 1.],
                             project_virtual_atoms="selected")
     proj_all = fpp.Projection2D(cg, [1., 1., 1.],
                                 project_virtual_atoms=True)
     all_vas = sum(
         len(cg.virtual_atoms(i).keys()) for d in cg.defines.keys()
         for i in cg.define_residue_num_iterator(d))
     self.assertLess(proj._virtual_atoms.shape[0], all_vas)
     self.assertLess(proj._virtual_atoms.shape[0],
                     proj_all._virtual_atoms.shape[0])
     self.assertGreater(proj._virtual_atoms.shape[0],
                        5)  #At least some atoms
Exemple #3
0
    def test_get_load_coordinates(self):
        cg = ftmc.CoarseGrainRNA('test/forgi/threedee/data/1y26.cg')

        coords = cg.get_coordinates_array()
        new_cg = copy.deepcopy(cg)

        for key in new_cg.coords:
            new_cg.coords[key] = [0, 0, 0], [0, 0, 0]

        new_cg.load_coordinates_array(coords)
        for key in new_cg.coords:
            for i in range(len(new_cg.coords[key])):
                self.assertTrue(
                    np.allclose(new_cg.coords[key][i], cg.coords[key][i]))
Exemple #4
0
    def test_clamp_with_dist(self):
        cg = ftmc.CoarseGrainRNA("test/fess/data/1GID_A-structure1.coord")
        open_main, open_stats, stdout, stderr = self.runErnwin(
            "python ernwin_new.py test/fess/data/1GID_A-structure1.coord -i 200 "
            "--dist 65,136 --seed 1 --energy ROG,SLD,AME,CLA --clamp 65,136"
        )  #Clamping h1 and h2

        dists = np.array(self.getStatsFor(stdout, "Distance_65-136", True))
        print(dists)

        self.assertLess(np.mean(dists[100:]),
                        np.mean(dists[:100]))  #Decreasing dist
        self.assertLess(np.mean(dists[150:]),
                        25)  # Minimal clamp energy is at 15A
Exemple #5
0
    def test_multiple_chain_to_cg(self):
        cg = ftmc.from_pdb('test/forgi/threedee/data/4GV9.pdb', chain_id='all')
        log.debug("======= FIRST IS LOADED =========")
        cg_str = cg.to_cg_string()
        log.debug("\n" + cg_str)
        print(cg_str)
        cg2 = ftmc.CoarseGrainRNA()
        cg2.from_cg_string(cg_str)
        self.assertEqual(cg.defines, cg2.defines)
        self.assertAlmostEqual(ftme.cg_rmsd(cg, cg2),
                               0)  #This only looks at stems
        self.assertEqual(cg.backbone_breaks_after, cg2.backbone_breaks_after)

        cg = ftmc.from_pdb('test/forgi/threedee/data/3CQS.pdb', chain_id='all')
        cg.log(logging.WARNING)
        cg_str = cg.to_cg_string()
        cg2 = ftmc.CoarseGrainRNA()
        cg2.from_cg_string(cg_str)

        self.assertEqual(cg.defines, cg2.defines)
        self.assertAlmostEqual(ftme.cg_rmsd(cg, cg2),
                               0)  #This only looks at stems
        self.assertEqual(cg.backbone_breaks_after, cg2.backbone_breaks_after)
Exemple #6
0
 def test_NDR_energy_can_change_rog(self):
     #Originally, the ROG is small:
     origROG = ftmc.CoarseGrainRNA(
         "test/fess/data/1GID_A-structure1.coord").radius_of_gyration()
     if origROG > 30.0:
         raise WrongAssumptionAboutTestInput(
             "1GID_A-structure1.coord should have a smaller "
             "initial ROG. Found {}".format(origROG))
     # The NDR60 energy will try to generate a radius of gyration of ~42
     open_main, open_stats, stdout, stderr = self.runErnwin(
         "python ernwin_new.py test/fess/data/1GID_A-structure1.coord "
         "-i 500 --energy NDR60 --seed 1")
     rog = self.getStatsFor(stdout, "ROG", True)[-1]
     self.assertGreater(float(rog), 40.0)
Exemple #7
0
 def test_cg_from_sg_invalid_subgraph_breaking_m(self):
     cg = ftmc.CoarseGrainRNA('test/forgi/threedee/data/3D0U_A.cg')
     """
          /s3 --h1
        m1  |
       /    |
     s0     m2
       \    |
        m0  |
          \s1--i0--s2--h0
     """
     split_ml = ["s0", "m0", "s1"]
     with self.assertRaises(Exception):
         ftmc.cg_from_sg(cg, split_ml)
Exemple #8
0
    def test_sample_stats(self):
        fa_text = """>1
        AGAGGUUCUAGCUACACCCUCUAUAAAAAACUAAGG
        (((((............)))))..............
        """

        cg = ftmc.CoarseGrainRNA()
        cg.from_fasta(fa_text)

        conf_stats = ftms.get_conformation_stats()
        stats = conf_stats.sample_stats(cg, 't1')

        fud.pv('cg.to_cg_string()')
        fud.pv('stats')
Exemple #9
0
    def test_cg_from_sg_breaking_after_s(self):
        cg = ftmc.CoarseGrainRNA('test/forgi/threedee/data/3D0U_A.cg')
        """
             /s3 --h1
           m1  |
          /    |
        s0     m2
          \    |
           m0  |
             \s1--i0--s2--h0
        """
        split_ml = ["s0", "m0", "s1", "m2", "s3", "m1", "h1"]

        sg = ftmc.cg_from_sg(cg, split_ml)
        self.check_graph_integrity(sg)
Exemple #10
0
def main():
    usage = """
    python calculate_mcc.py struct1.cg struct2.cg
    """
    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')

    (options, args) = parser.parse_args()

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

    cg1 = ftmc.CoarseGrainRNA(args[0])
    cg2 = ftmc.CoarseGrainRNA(args[1])

    confusion_matrix = ftme.confusion_matrix(cg1, cg2)

    print "confusion_matrix:", confusion_matrix
    print "mcc:", ftme.mcc(confusion_matrix)
    print "rmsd:", ftme.cg_rmsd(cg1, cg2)
Exemple #11
0
    def test_radius_of_gyration_different_methods(self):
        cg = ftmc.CoarseGrainRNA('test/forgi/threedee/data/1y26.cg')

        rog_fast = cg.radius_of_gyration(method="fast")
        rog_vres = cg.radius_of_gyration(method="vres")
        print(rog_fast, rog_vres, rog_fast - rog_vres, file=sys.stderr)
        self.assertGreater(
            abs(rog_fast - rog_vres),
            0,
            msg="Different methods for ROG calculation "
            "producting the exactly same result? Something seems to be wrong.")
        self.assertLess(abs(rog_fast - rog_vres),
                        1,
                        msg="Different methods for ROG calculation "
                        "should produce roughly the same result.")
Exemple #12
0
 def getSavedFile(self, mock, filename):
     for i_rev, call in enumerate(reversed(mock.mock_calls)):
         if call[1]:
             if call[1][0] == filename:
                 break
     else:
         return None
     for i in range(-i_rev, len(mock.mock_calls)):
         call = mock.mock_calls[i]
         if call[0] == "().write":
             cg = ftmc.CoarseGrainRNA()
             cg.from_cg_string(call[1][0])
             return cg
     else:
         return None
Exemple #13
0
 def allSavedFiles(self, mock, pattern):
     cgs = []
     in_file = False
     for call in mock.mock_calls:
         if call[1]:
             try:
                 if pattern.match(call[1][0]):
                     in_file = True
             except:
                 pass
         if in_file and call[0] == "().write":
             cg = ftmc.CoarseGrainRNA()
             cg.from_cg_string(call[1][0])
             cgs.append(cg)
             in_file = False
     return cgs
Exemple #14
0
    def test_init_with_rotate_for_virtual_residues(self):
        cg = ftmc.CoarseGrainRNA('test/forgi/threedee/data/1y26.cg')
        proj = fpp.Projection2D(cg, [1., 1., 1.],
                                project_virtual_residues=[1, 30])
        projRot = fpp.Projection2D(cg, [1., 1., 1.],
                                   rotation=90,
                                   project_virtual_residues=[1, 30])

        self.assertAlmostEqual(
            np.dot(
                proj.get_vres_by_position(1) - proj.get_vres_by_position(30),
                projRot.get_vres_by_position(1) -
                projRot.get_vres_by_position(30)),
            0.,
            msg="Rotating the projection by 90 degrees does not make "
            "corresponding virtual residue vectors orthogonal!")
Exemple #15
0
def main():
    usage = """
    ./virtual_atom_real_atom_distances.py temp.comp temp.pdb

    Calculate the distances between the virtual atoms and the real
    atoms.
    """
    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')

    (options, args) = parser.parse_args()

    with warnings.catch_warnings():
        warnings.simplefilter("ignore")

        c = list(bpdb.PDBParser().get_structure('test',
                                                args[1]).get_chains())[0]

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

    bg = ttmc.CoarseGrainRNA(args[0])
    vposs = []
    rposs = []
    stem_length = 0
    bg.add_all_virtual_residues()
    for s in bg.stem_iterator():
        stem_length += bg.stem_length(s)
        for i in range(bg.stem_length(s)):
            for strand in range(2):
                va = cgg.virtual_residue_atoms(bg, s, i, strand)
                r = bg.stem_side_vres_to_resn(s, strand, i)
                for a, p in va.items():
                    try:
                        vec1 = p
                        vec2 = c[r][a].get_vector().get_array()

                        vposs += [vec1]
                        rposs += [vec2]
                    except KeyError as ke:
                        continue

    print cbc.Configuration.mids_method, stem_length, cbr.rmsd(
        np.array(vposs), np.array(rposs))
Exemple #16
0
def main():
    parser = OptionParser()

    parser.add_option('-a', '--all-pairs', dest='all_pairs', default=False, action='store_true', help='Print all interactions')

    (options, args) = parser.parse_args()

    if len(args) < 1:
        print >>sys.stderr, "Usage: ./long_range_distances.py temp.comp"
        sys.exit(1)

    bg = ftmc.CoarseGrainRNA(args[0])

    if options.all_pairs:
        output_all_distances(bg)
    else: 
        output_long_range_distances(bg)
Exemple #17
0
    def test_coords_from_direction_with_pseudoknot(self):
        #This tests the case where the link is inserted from reverse direction.
        cg = ftmc.CoarseGrainRNA('test/forgi/threedee/data/3D0U_A.cg')
        cg_old = copy.deepcopy(cg)

        coords = cg.get_coordinates_array()
        directions = cg.coords_to_directions()

        cg._init_coords()
        cg.twists = cg_old.twists
        log.info("len(coords):{}, len(directions):{}, len(defines):{}".format(
            len(coords), len(directions), len(cg.defines)))

        cg.coords_from_directions(directions)
        self.assertAlmostEqual(ftme.cg_rmsd(cg, cg_old), 0)
        new_coords = cg.get_coordinates_array()
        offset = (coords - new_coords)
        assert np.allclose(offset, offset[0])
Exemple #18
0
 def test_eq_for_cgs(self):
     cg1 = ftmc.CoarseGrainRNA('test/forgi/threedee/data/1GID_A.cg')
     cg1_a = ftmc.CoarseGrainRNA('test/forgi/threedee/data/1GID_A.cg')
     cg2 = ftmc.CoarseGrainRNA('test/forgi/threedee/data/1GID_A_sampled.cg')
     cg2_a = ftmc.CoarseGrainRNA('test/forgi/threedee/data/1GID_A_sampled.cg')
     cg3 = ftmc.CoarseGrainRNA('test/forgi/threedee/data/1J1U.cg')
     cg3_a = ftmc.CoarseGrainRNA('test/forgi/threedee/data/1J1U.cg')
     self.assertEqual(cg1.coords, cg1.coords)
     self.assertEqual(cg1.coords, cg1_a.coords)
     self.assertEqual(cg2.coords, cg2_a.coords)
     self.assertEqual(cg3.coords, cg3_a.coords)
     self.assertNotEqual(cg1.coords, cg2.coords)
     self.assertNotEqual(cg1.coords, cg3.coords)
Exemple #19
0
    def test_cg_from_sg(self):
        bg = ftmc.CoarseGrainRNA(
            dotbracket_str=
            '.(((((..(((.(((((((.((.((((..((((((....))))))..)))).)).))........(((((.....((((...((((....))))...))))...))))).))))).)))...)))))'
        )
        self.check_graph_integrity(bg)

        # bg = cgb.BulgeGraph(dotbracket_str='.(((((........)))))..((((((((.(((.((...........((((((..(((((.((((((((..(((..)))...((((....)))).....))))))))..)))))................((((((...........))))))..((...(((((((...((((((..)))))).....((......))....)))))))...(((((((((.........))))))))).(((....))).))..........(((((.(((((.......))))))))))..........))))..))............(((.((((((((...((.......))...))))))..))))).........((((((((((((..(((((((((......))))))..))).((((.......)))).....)))))..))..))).))....((...............))....))..)))))))))))...')

        for j in range(40):
            sg = bg.random_subgraph()
            new_cg = cg_from_sg(bg, sg)

            for i in it.chain(new_cg.iloop_iterator(),
                              new_cg.mloop_iterator()):
                c = new_cg.connections(i)

                if len(c) != 2:
                    self.assertEqual(len(c), 2)
Exemple #20
0
def main(args):
    cg = ftmc.CoarseGrainRNA(args.rna)
    for stem in cg.stem_iterator():
        stem_vec = cg.coords.get_direction(stem)
        twist_vec = cg.twists[stem][0]
        try:
            ftuv.create_orthonormal_basis(stem_vec, twist_vec)
        except AssertionError:
            cg.twists[stem] = ftuv.vector_rejection(twist_vec, stem_vec), cg.twists[stem][1]
        twist_vec = cg.twists[stem][1]
        try:
            ftuv.create_orthonormal_basis(stem_vec, twist_vec)
        except AssertionError:
            cg.twists[stem] = cg.twists[stem][0], ftuv.vector_rejection(twist_vec, stem_vec)
    try:
        cg.add_all_virtual_residues()
    except:
        assert False
    print(cg.to_cg_string())
Exemple #21
0
 def test_elements_closer_than_like_old_confusion_matrix(self):
     BP_DIST = 16
     CUTOFF_DIST = 25.
     cg2 = ftmc.CoarseGrainRNA('test/forgi/threedee/data/1GID_A_sampled.cg')
     ignore = set()
     for n1, n2 in it.combinations(cg2.defines.keys(), r=2):
         if cg2.connected(n1, n2):
             ignore.add((n1,n2))
             continue
         bp_dist = cg2.min_max_bp_distance(n1, n2)[0]
         if bp_dist < BP_DIST:
             ignore.add((n1,n2))
     old = interactions_old(cg2, CUTOFF_DIST, BP_DIST)
     new = set(cg2.coords.elements_closer_than(CUTOFF_DIST, ignore = ignore))
     print("m0-m1: {} A phys, dist, "
           "{} bp dist".format(cg2.element_physical_distance("m0", "m1"),
                               cg2.min_max_bp_distance("m0", "m1")[0]))
     print("m0: {}".format(cg2.coords["m0"]))
     print("m1: {}".format(cg2.coords["m1"]))
     self.assertEqual(old, new,
                     msg = "ONLY old: {}\n, ONLY new {},\n {} both".format(old-new, new-old, len(old&new)))
def construct_test_graph(s1_len, s2_len, link_length):
    '''
    Construct a simple bulge graph containing two stems, one single
    stranded edge linking them, and a single stranded single connected
    node attached to the first stem.

    @param s1_len: The length of the first stem
    @param s2_stats: The length of the second stem
    @param link_length: The length of the single stranded region linking the two stems

    @return: A BulgeGraph of the described structure
    '''
    start_loop_len = 3

    dotbracket = "".join([
        '.' * start_loop_len, '(' * s1_len, '.' * 3, ')' * s1_len,
        '.' * link_length, '(' * s2_len, '.' * 3, ')' * s2_len
    ])
    seq = fus.gen_random_sequence(len(dotbracket))
    cg = ftmc.CoarseGrainRNA(dotbracket_str=dotbracket, seq=seq)
    return cg
Exemple #23
0
def main():
    usage = './cylinder_intersection_energies.py bulge_graph'
    parser = OptionParser()

    #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')

    (options, args) = parser.parse_args()

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

    for arg in args:
        bg = ftmc.CoarseGrainRNA(arg)
        cie = cbe.CylinderIntersectionEnergy()
        
        in_cyl_fractions = cie.calculate_intersection_coverages(bg)
        
        for (key,val) in in_cyl_fractions.items():
            print key, val
def main():
    usage = """
    python random_subgraph_radius_of_gyration.py file.cg
    """
    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('-i',
                      '--iterations',
                      dest='iterations',
                      default=1,
                      help="The number of iterations to perform",
                      type='int')
    #parser.add_option('-u', '--useless', dest='uselesss', default=False, action='store_true', help='Another useless option')

    (options, args) = parser.parse_args()

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

    cg = ftmc.CoarseGrainRNA(args[0])
    for i in range(options.iterations):
        sg = cg.random_subgraph()
        stems = [s for s in sg if s[0] == 's']

        if len(stems) == 0:
            continue

        coords = []
        for s in stems:
            coords += [cg.coords[s][0]]
            coords += [cg.coords[s][1]]

        rmsd = ftmd.radius_of_gyration(coords)
        total_length = sum(
            [len(list(cg.define_residue_num_iterator(d))) for d in sg])

        print total_length, rmsd
Exemple #25
0
 def test_get_incomplete_elements(self):
     db = "(((...(((...).)))))"
     cg = ftmc.CoarseGrainRNA(dotbracket_str=db)
     # Residue number 3 is missing. Probably bulged out from stem 0
     seq_ids = map(str, [
         1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
     ])
     cg.seq_ids = list(map(fgb.resid_from_str, seq_ids))
     self.assertEqual(ftug.get_incomplete_elements(cg), set(["s0"]))
     # Residue number 4 is missing between s0 and i0
     seq_ids = map(str, [
         1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
     ])
     cg.seq_ids = list(map(fgb.resid_from_str, seq_ids))
     self.assertEqual(ftug.get_incomplete_elements(cg), set(["i0"]))
     # Residue number 5 is missing inside i0
     seq_ids = map(str, [
         1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
     ])
     cg.seq_ids = list(map(fgb.resid_from_str, seq_ids))
     self.assertEqual(ftug.get_incomplete_elements(cg), set(["i0"]))
     # Residue number 17 is missing between s0 and s1, ==> i0
     seq_ids = map(str, [
         1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20
     ])
     cg.seq_ids = list(map(fgb.resid_from_str, seq_ids))
     self.assertEqual(ftug.get_incomplete_elements(cg), set(["i0"]))
     # Residue number 10 is missing  ==> h0
     seq_ids = map(str, [
         1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
     ])
     cg.seq_ids = list(map(fgb.resid_from_str, seq_ids))
     self.assertEqual(ftug.get_incomplete_elements(cg), set(["h0"]))
     # Multiple residues are missing
     seq_ids = map(str, [
         1, 2, 4, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22
     ])
     cg.seq_ids = list(map(fgb.resid_from_str, seq_ids))
     self.assertEqual(ftug.get_incomplete_elements(cg),
                      set(["h0", "s0", "i0"]))
Exemple #26
0
    def test_CLA_energy_clamps_together(self):
        #Make sure the original distances are not desired
        orig_cg = ftmc.CoarseGrainRNA("test/fess/data/1GID_A-structure2.coord")
        h0h2_orig = orig_cg.element_physical_distance("h0", "h2")
        h1h2_orig = orig_cg.element_physical_distance("h0", "h1")
        print(h0h2_orig, h1h2_orig)
        if h1h2_orig > h0h2_orig - 10:
            raise WrongAssumptionAboutTestInput(
                "In the initial cg model, h2 should be "
                "significantly closer to h0 than to h1. Found h0-h2={}, "
                "h1-h2={}".format(h0h2_orig, h1h2_orig))

        open_main, open_stats, stdout, stderr = self.runErnwin(
            "python ernwin_new.py test/fess/data/1GID_A-structure1.coord "
            "-i 500 --energy CLA --clamp h0,h2  --seed 1 --step-save 500")
        new_cg = self.getSavedFile(open_stats, "1GID_A/step000500.coord")
        h0h2 = new_cg.element_physical_distance("h0", "h2")
        h1h2 = new_cg.element_physical_distance("h0", "h1")
        print(h0h2, h1h2)
        self.assertLess(h0h2, h1h2)
        self.assertLess(h0h2, 30)
        self.assertLess(h0h2, h0h2_orig)
Exemple #27
0
def main():
    usage = """
    python cg_rmsd.py file1.cg

    Calculate the ROG of a coarse grain models.
    """
    num_args = 1
    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')

    (options, args) = parser.parse_args()

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

    cg1 = ftmc.CoarseGrainRNA(args[0])

    coords = cg1.get_ordered_stem_poss()
    print ftmd.radius_of_gyration(coords)
Exemple #28
0
def main():
    if len(sys.argv) < 2:
        print >> sys.stderr, "Usage: ./graph_to_angles.py temp.comp"
        print
        print >> sys.stderr, "Traverse a structure and output the stems that are connected by a bulge"
        run_tests()
        sys.exit(1)

    parser = OptionParser()

    parser.add_option(
        '-d',
        '--dump',
        dest='dump',
        default=False,
        help=
        "Dump a file called temp.angles in the same directory as the original file",
        action="store_true")

    (options, args) = parser.parse_args()

    bg = ttmc.CoarseGrainRNA(args[0])
    out_str = print_new_bulge_angles(bg)
    out_str += print_stem_stats(bg)
    out_str += print_loop_stats(bg)
    out_str += print_5prime_unpaired(bg)
    out_str += print_3prime_unpaired(bg)

    if options.dump:
        # dump an output file
        if args[0] == '-':
            dirname = '.'
        else:
            dirname = op.dirname(args[0])

        with open(op.join(dirname, 'temp.angles'), 'w') as f:
            f.write(out_str)
    else:
        print out_str
def main():
    usage = './stem_stem_orientations.py temp.comp'
    usage += '''
    Output the orientations of the stems as a set of'
    three coordinates.
    1. The distance between the closest points of the
    two stems.
    2. The angle between the two stems in the plane defined
    by the axis of stem1 and the vector between the closest
    points between the two stem.
    3. The angle of the second stem out the plane.
    '''

    parser = OptionParser()

    #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(
        '-l',
        '--loops',
        dest='loops',
        default=False,
        action='store_true',
        help=
        "Compute the statistics for the loop regions rather than the stems.")

    (options, args) = parser.parse_args()

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

    for arg in args:
        bg = ttmc.CoarseGrainRNA(arg)
        if options.loops:
            loop_loop_orientations(bg)
        else:
            stem_stem_orientations(bg)
Exemple #30
0
def main():
    usage = """
    python ordered_elements_to_forna_colors.py struct.cg element_list

    Output a forna coloring string such that nucleotides in the elements
    are colored according to the order that they are input.
    """
    num_args = 2
    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')

    (options, args) = parser.parse_args()

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

    cg = ftmc.CoarseGrainRNA(args[0])

    import matplotlib.pyplot as plt
    cmap = plt.get_cmap('Blues')

    out_str = " "
    to_color_nodes = args[1].split(',')
    for i, node in enumerate(to_color_nodes):
        chosen_color = cmap(1 - i / float(len(to_color_nodes)))

        for res in cg.define_residue_num_iterator(node):
            out_str += " {}:rgb({},{},{})".format(res,
                                                  int(255 * chosen_color[0]),
                                                  int(255 * chosen_color[1]),
                                                  int(255 * chosen_color[2]))

    print(template.format(cg.to_dotbracket_string(), cg.seq, out_str))