def main(parser): args = parser.parse_args() with fuc.hide_traceback(): cg1, cg2 = fuc.cgs_from_args(args, nargs=2, rna_type="3d", enable_logging=True) dir1 = np.array(args.directions[0].split(","), dtype=float) dir2 = np.array(args.directions[1].split(","), dtype=float) proj1 = ftmp.Projection2D(cg1, dir1) proj2 = ftmp.Projection2D(cg2, dir2) vrs1 = np.array( [x for p in sorted(proj1._coords.keys()) for x in proj1._coords[p]]) vrs2 = np.array( [x for p in sorted(proj2._coords.keys()) for x in proj2._coords[p]]) print(ftms.rmsd(vrs1, vrs2)) if args.plot: import matplotlib.pyplot as plt fig, ax = plt.subplots() proj1.plot(ax, line2dproperties={"color": "green"}) proj2.plot(ax, line2dproperties={"color": "red"}) plt.show()
def setUp(self): cg, = ftmc.CoarseGrainRNA.from_pdb( 'test/forgi/threedee/data/1y26_two_chains.pdb', dissolve_length_one_stems=False, load_chains="X") self.proj = fpp.Projection2D(cg, [1., 1., 1.]) self.proj2 = fpp.Projection2D(cg, [0., 0., 1.])
def test_projection_longest_axis(self): cg = ftmc.CoarseGrainRNA.from_dotbracket("((()))") cg.coords["s0"] = np.array([0., 0, -1]), np.array([0., 0, 1]) proj = fpp.Projection2D(cg, [0., 1., 0.]) self.assertAlmostEqual(proj.longest_axis, 2) proj = fpp.Projection2D(cg, [0., 0., 1.]) self.assertAlmostEqual(proj.longest_axis, 0)
def test_projection_with_nonexisting_virtual_residues(self): cg = ftmc.CoarseGrainRNA('test/forgi/threedee/data/1y26.cg') with self.assertRaises(LookupError): proj = fpp.Projection2D(cg, [1., 1., 1.], project_virtual_residues=[len(cg.seq) + 2]) with self.assertRaises(LookupError): proj = fpp.Projection2D(cg, [1., 1., 1.], project_virtual_residues=[0])
def test_init_with_rotate_for_coords(self): cg = ftmc.CoarseGrainRNA('test/forgi/threedee/data/1y26.cg') proj = fpp.Projection2D(cg, [1., 1., 1.]) projRot = fpp.Projection2D(cg, [1., 1., 1.], rotation=90) define = list(cg.defines.keys())[0] self.assertAlmostEqual( np.dot(proj._coords[define][1] - proj._coords[define][0], projRot._coords[define][1] - projRot._coords[define][0]), 0., msg="Rotating the projection by 90 degrees does not make " "corresponding coord-vectors orthogonal!")
def test_init_with_rotate_for_virtual_atoms(self): cg = ftmc.CoarseGrainRNA('test/forgi/threedee/data/1y26.cg') proj = fpp.Projection2D(cg, [1., 1., 1.], project_virtual_atoms=True) projRot = fpp.Projection2D(cg, [1., 1., 1.], rotation=90, project_virtual_atoms=True) self.assertAlmostEqual( np.dot(proj._virtual_atoms[100] - proj._virtual_atoms[0], projRot._virtual_atoms[100] - projRot._virtual_atoms[0]), 0., msg="Rotating the projection by 90 degrees does not make " "corresponding virtual atoms vectors orthogonal!")
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
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!")
def test_projection_with_virtual_residues(self): cg = ftmc.CoarseGrainRNA.from_bg_file( 'test/forgi/threedee/data/1y26.cg') proj = fpp.Projection2D(cg, [1., 1., 1.], project_virtual_residues=[1, len(cg.seq) // 2]) elem1 = cg.get_node_from_residue_num(1) elem2 = cg.get_node_from_residue_num(len(cg.seq) // 2) self.assertLess( ftuv.vec_distance(proj._coords[elem1][0], proj.get_vres_by_position(1)), ftuv.vec_distance(proj._coords[elem2][0], proj.get_vres_by_position(1)), msg= "Projected virtual residue is closer to projection of a cg-element " "far away than to the projection of corresponding cg element.") self.assertLess( ftuv.vec_distance(proj._coords[elem2][0], proj.get_vres_by_position(len(cg.seq) // 2)), ftuv.vec_distance(proj._coords[elem1][0], proj.get_vres_by_position(len(cg.seq) // 2)), msg= "Projected virtual residue is closer to projection of a cg-element " "far away than to the corresponding cg element.")
def test_get_vres_by_position_raises_if_this_vres_not_projected(self): cg = ftmc.CoarseGrainRNA.from_bg_file( 'test/forgi/threedee/data/1y26.cg') proj = fpp.Projection2D(cg, [1., 1., 1.], project_virtual_residues=[1, 4, 23]) with self.assertRaises(LookupError): proj.get_vres_by_position(7)
def test_proj_longest_axis_vs_img_diameter(self): cg = ftmc.from_pdb('test/forgi/threedee/data/1y26_two_chains.pdb') ref_proj = fpp.Projection2D(cg, [1., 1., 1. ], project_virtual_atoms=True) ref_box=ref_proj.get_bounding_square(margin=30) scale=ref_box[1]-ref_box[0] ref_img, _=ref_proj.rasterize(70, bounding_square=ref_box, rotate=0) self.assertAlmostEqual(ref_proj.longest_axis, fph.get_longest_img_diameter(ref_img, scale), places=-1)
def test_get_vres_by_position(self): cg = ftmc.CoarseGrainRNA('test/forgi/threedee/data/1y26.cg') proj = fpp.Projection2D(cg, [1., 1., 1.], project_virtual_residues=[1, 4, 23]) self.assertEqual(proj.get_vres_by_position(1).shape, (2, )) self.assertEqual(proj.get_vres_by_position(4).shape, (2, )) self.assertEqual(proj.get_vres_by_position(23).shape, (2, ))
def test_plot(self): cg = ftmc.from_pdb('test/forgi/threedee/data/1y26_two_chains.pdb') for dire in [(1., 0., 0.), (0., 0., 1.), (0., 1., 0.), (1., 1., 0.), (1., 0., 1.), (0., 1., 1.), (1., 1., 1.)]: self.proj = fpp.Projection2D(cg, dire) self.proj.condense_points(1) self.proj.plot(show=True, add_labels=True)
def test_vres_iterator(self): cg = ftmc.CoarseGrainRNA.from_bg_file( 'test/forgi/threedee/data/1y26.cg') proj = fpp.Projection2D(cg, [1., 1., 1.], project_virtual_residues=[3, 7, 26]) self.assertEqual(sorted(list(x[0] for x in proj.vres_iterator)), [3, 7, 26])
def test_projection_with_virtual_atoms(self): cg = ftmc.CoarseGrainRNA.from_bg_file( 'test/forgi/threedee/data/1y26.cg') proj = 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.assertEqual(all_vas, proj._virtual_atoms.shape[0]) self.assertGreater(proj._virtual_atoms.shape[0], 5)
def test_init_projection(self): cg, = ftmc.CoarseGrainRNA.from_pdb('test/forgi/threedee/data/2X1F.pdb') proj = fpp.Projection2D(cg, [1., 1., 1.]) self.assertTrue( ftuv.is_almost_parallel(proj.proj_direction, np.array([1., 1., 1.])), msg= "The projection direction was not stored correctly. Should be coliniar" " with {}, got {}".format(np.array([1., 1., 1.]), proj.proj_direction))
def test_init_projection2(self): cg = ftmc.from_pdb('test/forgi/threedee/data/2X1F.pdb') cg.project_from = [1., 1., 1.] proj = fpp.Projection2D(cg) self.assertTrue( ftuv.is_almost_colinear(proj.proj_direction, np.array([1., 1., 1.])), msg= "The projection direction was not stored correctly. Should be coliniar" " with {}, got {}".format(np.array([1., 1., 1.]), proj.proj_direction))
def updateProjection(self, _=None): direction = ftuv.spherical_polar_to_cartesian( np.array([ 1, math.radians(self.theta.get()), math.radians(self.phi.get()) ])) self.proj = fpp.Projection2D(self.cg, project_virtual_atoms=True, proj_direction=direction, project_virtual_residues=list( range(1, len(self.cg.seq) + 1))) self.update()
def test_get_longest_img_diameter_resolution_invariant(self): cg = ftmc.from_pdb('test/forgi/threedee/data/1y26_two_chains.pdb') ref_proj = fpp.Projection2D(cg, [1., 1., 1. ], project_virtual_atoms=True) ref_box=ref_proj.get_bounding_square(margin=30) scale=ref_box[1]-ref_box[0] img1, _=ref_proj.rasterize(70, bounding_square=ref_box, rotate=0) img2, _=ref_proj.rasterize(40, bounding_square=ref_box, rotate=0) img3, _=ref_proj.rasterize(60, bounding_square=ref_box, rotate=10) d1 = fph.get_longest_img_diameter(img1, scale) d2 = fph.get_longest_img_diameter(img2, scale) d3 = fph.get_longest_img_diameter(img3, scale) self.assertAlmostEqual(d1, d2, places=-1 ) self.assertAlmostEqual(d1, d3, places=-1 ) self.assertAlmostEqual(d3, d2, places=-1 )
def setUp(self): self.cg = ftmc.from_pdb('test/forgi/threedee/data/1y26_two_chains.pdb') self.ref_proj = fpp.Projection2D(self.cg, [1., 1., 1. ], project_virtual_atoms=True) self.ref_proj_na = fpp.Projection2D(self.cg, [1., 1., 1. ], project_virtual_atoms=False)
def setUp(self): cg = ftmc.from_pdb('test/forgi/threedee/data/1y26_two_chains.pdb') self.proj = fpp.Projection2D(cg, [1., 1., 1.]) self.proj.condense_points(1)
def main(args): cgs = [] projs = [] for file_ in args.files: cgs.append(ftmc.CoarseGrainRNA(file_)) try: projs.append(ftmp.Projection2D(cgs[-1])) except ValueError: projs.append(None) p_rmsds = OrderedDict() cg_rmsds = OrderedDict() p_rmsds[0] = 0. cg_rmsds[0] = 0. if "," in args.max_diff: diffs = map(int, args.max_diff.split(",")) else: diffs = range(1, int(args.max_diff) + 1) for diff in diffs: print("diff {}".format(diff)) prmsd = 0 cgrmsd = 0 count = 0 pcount = 0 for i in range(0, len(cgs) - diff): count += 1 try: vrs1 = np.array([ x for p in sorted(projs[i]._coords.keys()) for x in projs[i]._coords[p] ]) vrs2 = np.array([ x for p in sorted(projs[i + diff]._coords.keys()) for x in projs[i + diff]._coords[p] ]) prmsd += ftms.rmsd(vrs1, vrs2) pcount += 1 except: pass cgrmsd += ftms.cg_rmsd(cgs[i], cgs[i + diff]) if count: cg_rmsds[diff] = cgrmsd / count if pcount: p_rmsds[diff] = prmsd / pcount print("projection RMSDs:", p_rmsds) print("3D-RMSDs:", cg_rmsds) import matplotlib.pyplot as plt if args.target_structure and args.hausdorff_reference: fig, (ax, axT, axH) = plt.subplots(3) elif args.target_structure: fig, (ax, axT) = plt.subplots(2) elif args.hausdorff_reference: fig, (ax, axH) = plt.subplots(2) else: fig, ax = plt.subplots() if args.target_structure: target = ftmc.CoarseGrainRNA(args.target_structure) target_rmsds = [] target_proj_rmsds = [] try: target_proj = ftmp.Projection2D(target) except ValueError: pass else: target_vrs = np.array([ x for p in sorted(target_proj._coords.keys()) for x in target_proj._coords[p] ]) for proj in projs: try: vrs1 = np.array([ x for p in sorted(proj._coords.keys()) for x in proj._coords[p] ]) prmsd = ftms.rmsd(vrs1, target_vrs) target_proj_rmsds.append(prmsd) except: target_proj_rmsds.append(float("nan")) target_vrs = target.get_ordered_virtual_residue_poss() for cg in cgs: vrs1 = cg.get_ordered_virtual_residue_poss() cgrmsd = ftms.rmsd(vrs1, target_vrs) target_rmsds.append(cgrmsd) xval = np.arange(len(cgs)) * args.step_size if target_proj_rmsds: axT.plot(xval, target_proj_rmsds, label="Projection", color="green") axT.plot(xval, target_rmsds, label="3D", color="blue") axT.set_title("RMSD to target structure") axT.set_xlabel("step") axT.set_ylabel("RMSD") leg = axT.legend(framealpha=0.8, fancybox=True) leg.get_frame().set_linewidth(0.0) plt.subplots_adjust(hspace=0.4) if args.hausdorff_reference: ref_img = scipy.ndimage.imread(args.hausdorff_reference) ref_quarter = (scipy.ndimage.zoom(ref_img, 0.3) > 150) degrees = get_refimg_longest_axis(ref_img) global_optima = [] local_optima = [] for cg in cgs: score, img, params = fph.try_parameters(ref_img, args.hausdorff_scale, cg, degrees) local_optima.append(score) s, i, params = fph.globally_minimal_distance( ref_quarter, args.hausdorff_scale, cg, start_points=40, starting_rotations=degrees, virtual_atoms=False) score, img, params = fph.locally_minimal_distance( ref_img, args.hausdorff_scale, cg, params[1], params[2], params[0], maxiter=200) global_optima.append(score) axH.plot(xval, global_optima, label="Global Minimization", color="red") axH.plot(xval, local_optima, label="Local Minimization", color="lavender") axH.set_title("Hausdorff Distance to reference image") axH.set_xlabel("step") axH.set_ylabel("Hausdorff Distance") leg = axH.legend(framealpha=0.8, fancybox=True) leg.get_frame().set_linewidth(0.0) plt.subplots_adjust(hspace=0.4) p_rmsds = np.array(list(p_rmsds.items())) cg_rmsds = np.array(list(cg_rmsds.items())) ax.plot(p_rmsds[:, 0] * args.step_size, p_rmsds[:, 1], label="Projection", color="green", marker="o") ax.plot(cg_rmsds[:, 0] * args.step_size, cg_rmsds[:, 1], label="3D", color="blue", marker="o") ax.set_title("Average RMSD between structures X steps apart.") ax.set_xlabel("steps apart") ax.set_ylabel("RMSD") leg = ax.legend(framealpha=0.8, fancybox=True) leg.get_frame().set_linewidth(0.0) fig.patch.set_facecolor('white') if args.save_fig: with open(args.save_fig, "w") as f: pickle.dump(fig, f) plt.show()
def main(args): files = args.cgfiles # Uncomment the following line to display the files in a random order. # random.shuffle(files) # Prepare the pyplot figure totalFigures = len(files) figuresPerLine = int(math.ceil(math.sqrt(totalFigures))) fig, ax = plt.subplots(int(math.ceil( totalFigures / figuresPerLine)), figuresPerLine, squeeze=False, figsize=(8, 8)) # Background color of figure (not plot) if args.style == "WOB": fig.patch.set_facecolor('black') # Plot one projection per file. for i, file_ in enumerate(files): # get the subplot axes (Note: axes != axis in matplotlib) current_axes = ax[i // figuresPerLine, i % figuresPerLine] # Parse the file cg = ftmc.CoarseGrainRNA(file_) # Random projection direction, if no direction present in the file if args.proj_direction: direction = list(map(float, args.proj_direction.split(","))) elif cg.project_from is not None: direction = cg.project_from else: direction = ftuv.get_random_vector() # Generate the projection object proj = ftmp.Projection2D( cg, direction, rotation=180, project_virtual_atoms=args.virtual_atoms) # Simulate a reduced resolution of the image. if args.condense: proj.condense(args.condense) target_elems = [] if args.show_distances: try: num_elems = int(args.show_distances) except: target_elems = args.show_distances.split(",") else: if num_elems > len(proj._coords.keys()): raise ValueError("--show-distances must not be greater {} for the current projection ({}:'{}')".format( len(proj._coords.keys()), i, file_)) elems = list(proj._coords.keys()) random.shuffle(elems) while len(target_elems) < num_elems: r = random.random() if r < 0.4: hairpins = [x for x in elems if x[0] == "h" and x not in target_elems] if hairpins: target_elems.append(hairpins[0]) continue if r < 0.6: multiloops = [x for x in elems if x[0] == "m" and x not in target_elems] if multiloops: target_elems.append(multiloops[0]) continue others = [x for x in elems if x not in target_elems] target_elems.append(others[0]) comb = list(it.combinations(target_elems, 2)) #print(comb, target_elems) if args.label_elements: target_elems = list(proj._coords.keys()) line2dproperties = {} if args.style == "BOW": line2dproperties["color"] = "black" elif args.style == "WOB": line2dproperties["color"] = "white" #Plot the projection # proj.plot(current_axes, margin=15, linewidth=3, add_labels=set(target_elems), line2dproperties=line2dproperties, show_distances=comb, print_distances=args.print_distances) # Uncomment to set a substring of the filename as a title # current_axes.set_title(file[-15:]) # Hide the x- and y axis. current_axes.get_xaxis().set_visible(False) current_axes.get_yaxis().set_visible(False) # Print the projection direction and the filename in the plot. if args.show_direction or args.p: current_axes.text(0.01, 0.01, "Projection direction: ({},{},{})".format(round( direction[0], 3), round(direction[1], 3), round(direction[2], 3)), transform=current_axes.transAxes) if args.show_filename or args.p: current_axes.text(0.01, 0.99, "File: {}".format( file_), transform=current_axes.transAxes, verticalalignment='top',) # Change the backgroundcolor of the plot area. if args.style == "WOB": current_axes.set_axis_bgcolor('black') # Hide additional subplots with no projection on them. for i in range(len(files), int(math.ceil(totalFigures / figuresPerLine)) * figuresPerLine): ax[i // figuresPerLine, i % figuresPerLine].axis('off') # Reduce the space outside of the plots and between the subplots. plt.subplots_adjust(left=0.025, right=0.975, bottom=0.025, top=0.975, wspace=0.05, hspace=0.05) if args.out: for ofname in args.out: if args.out_path: ofname = os.path.join(args.out_path, ofname) ofname = os.path.expanduser(ofname) plt.savefig(ofname, format=ofname[-3:]) if not args.out or args.show: # Show the plot and clear it from the internal memory of matplotlib. plt.show()
def test_init_raises_if_no_proj_dir(self): cg, = ftmc.CoarseGrainRNA.from_pdb('test/forgi/threedee/data/2X1F.pdb') with self.assertRaises(ValueError): proj = fpp.Projection2D(cg)
ref_img=scipy.misc.imread(args.reference, flatten=True) if args.dpi: ref_img=scipy.misc.imresize(ref_img,(args.dpi+1,args.dpi+1), "nearest") if args.scale: s=args.scale/2 ref_box=-s/2, s/2, -s/2, s/2 else: parser.error("--scale is required if the reference is a png image") if args.show: fig, ax=plt.subplots() ax.imshow(ref_img, interpolation="none", cmap='gray') plt.show() else: ref_cg=ftmc.CoarseGrainRNA(args.reference) try: ref_proj=ftmp.Projection2D(ref_cg, project_virtual_atoms=True) except ValueError: parser.error('The reference *.cg file needs a "project" line.') if args.scale: ref_box=fph.get_box(ref_proj, args.scale) else: ref_box=ref_proj.get_bounding_square(margin=50) args.scale=ref_box[1]-ref_box[0] if args.dpi: ref_img, _=ref_proj.rasterize(args.dpi, bounding_square=ref_box) else: parser.error("If the reference is not a png image, --dpi is required") ref_img=(ref_img>np.zeros_like(ref_img)) #Make it a boolean array for f in args.files: cg=ftmc.CoarseGrainRNA(f) if args.global_search or cg.project_from is None:
parser = get_parser() if __name__ == "__main__": args = parser.parse_args() if args.res_nums: res_nums = list(map(int, args.res_nums.split(","))) else: res_nums = [] for filename in args.cgfiles: for n in range(args.n): cg = ftmc.CoarseGrainRNA(filename) try: proj = fpp.Projection2D(cg, project_virtual_atoms=True, project_virtual_residues=res_nums) except ValueError: a = random.random() b = random.random() c = random.random() print("Projecting from {}, {}, {}".format(a, b, c)) proj = fpp.Projection2D(cg, project_virtual_atoms=True, proj_direction=[a, b, c], project_virtual_residues=res_nums) if args.rotate == 99999999999: rot = random.randrange(0, 3600) / 10 else: rot = args.rotate proj.rotate(rot)
def test_get_vres_by_position_raises_if_no_vres_projected(self): cg = ftmc.CoarseGrainRNA.from_bg_file( 'test/forgi/threedee/data/1y26.cg') proj = fpp.Projection2D(cg, [1., 1., 1.]) with self.assertRaises(LookupError): proj.get_vres_by_position(1)