def rmsd_to(self, other): import forgi.threedee.model.similarity as ftms #This import is here to avoid circular imports. if self._elem_names == other._elem_names: return ftms.rmsd(self._coordinates, other._coordinates, self.is_centered & other.is_centered) else: common_keys = set(self._elem_names.keys()) & set( other._elem_names.keys()) if len(common_keys) == len(self._elem_names): rev_lookup = list(x for x in sorted( self._elem_names.keys(), key=self._elem_names.__getitem__)) other_array = np.array([ coord_line for d in rev_lookup for coord_line in [other[d][0], other[d][1]] ]) return ftms.rmsd(self._coordinates, other_array, self.is_centered & other.is_centered) else: common_keys = list(common_keys) this_array = np.array([ coord_line for d in common_keys for coord_line in [self[d][0], self[d][1]] ]) other_array = np.array([ coord_line for d in common_keys for coord_line in [other[d][0], other[d][1]] ]) return ftms.rmsd(this_array, other_array, False)
def rmsd_to(self, other): # This import is here to avoid circular imports. import forgi.threedee.model.similarity as ftms if self._elem_names == other._elem_names: return ftms.rmsd(self._coordinates, other._coordinates, self.is_centered & other.is_centered) else: common_keys = set(self._elem_names.keys()) & set( other._elem_names.keys()) if len(common_keys) == len(self._elem_names): rev_lookup = list(x for x in sorted( self._elem_names.keys(), key=self._elem_names.__getitem__)) other_array = np.array( [coord_line for d in rev_lookup for coord_line in [other[d][0], other[d][1]]]) return ftms.rmsd(self._coordinates, other_array, self.is_centered & other.is_centered) else: common_keys = list(common_keys) this_array = np.array( [coord_line for d in common_keys for coord_line in [self[d][0], self[d][1]]]) other_array = np.array( [coord_line for d in common_keys for coord_line in [other[d][0], other[d][1]]]) return ftms.rmsd(this_array, other_array, False)
def test_rmsd_to_same(self): a1 = np.array([[1., 1., 1.], [0., 0., 0.], [-1., -1., -1.]]) a2 = np.array([[1., 2., 1.], [0., -1., 0.], [-1., -1., -1.]]) self.assertAlmostEqual(ftme.drmsd(a1, a1), 0) self.assertAlmostEqual(ftme.drmsd(a2, a2), 0) self.assertAlmostEqual(ftme.rmsd(a1, a1), 0) self.assertAlmostEqual(ftme.rmsd(a2, a2), 0)
def realatom_vatom_rmsd(cg): """ The RMSD between the real atoms and the virtual atoms of the stems. """ vposs = [] rposs = [] for stem in cg.stem_iterator(): stemv = [] stemr = [] resseqs = cg.get_resseqs(stem) resseqs = resseqs[0] + resseqs[1] for posCg, idPdb in zip(cg.define_residue_num_iterator(stem), resseqs): chainPdb, posPdb = idPdb vas = cg.virtual_atoms(posCg) for a, coords in vas.items(): try: rp = cg.chains[chainPdb][posPdb][a].get_vector( ).get_array() except KeyError: pass else: rposs.append(rp) vposs.append(coords) assert len(vposs) == len(rposs) return ftme.rmsd(np.array(vposs), np.array(rposs))
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 realatom_vatom_rmsd(cg): """ The RMSD between the real atoms and the virtual atoms of the stems. """ vposs = [] rposs = [] for stem in cg.stem_iterator(): stemv = [] stemr = [] resseqs = cg.get_resseqs(stem) resseqs = resseqs[0] + resseqs[1] for posCg, idPdb in zip(cg.define_residue_num_iterator(stem), resseqs): chainPdb, posPdb = idPdb vas = cg.virtual_atoms(posCg) for a, coords in vas.items(): try: rp = cg.chains[chainPdb][posPdb][a].get_vector().get_array( ) except KeyError: pass else: rposs.append(rp) vposs.append(coords) assert len(vposs) == len(rposs) return ftme.rmsd(np.array(vposs), np.array(rposs))
def update(self, sm, step): if not self.silent: curr_vress=sm.bg.get_ordered_virtual_residue_poss() if self.mode=="RMSD": rmsd=ftme.rmsd(self._reference, curr_vress) elif self.mode=="dRMSD": rmsd=ftme.drmsd(self._reference, curr_vress) if self.best_cgs.can_insert_right((None, rmsd)): self.best_cgs.insert_right((sm.bg.to_cg_string(),rmsd)) if step % 10 == 0: for i, bg in enumerate(self.best_cgs): with open(os.path.join(conf.Configuration.sampling_output_dir, 'best_rmsd{:d}.coord'.format(i)), 'w') as f: f.write(bg[0]) if self._showMinMax: if rmsd>self._maxRMSD: self._maxRMSD=rmsd if self._showMinMax==True: if rmsd<self._minRMSD: self._minRMSD=rmsd self.history[1].append( self._minRMSD ) self.history[0].append( rmsd ) self.history[-1].append( self._maxRMSD ) if self._showMinMax=="max": return "{:6.3f} A\t{:6.3f} A".format(rmsd, self._maxRMSD) else: return "{:6.3f} A\t{:6.3f} A\t{:6.3f} A".format(rmsd, self._minRMSD, self._maxRMSD) else: self.history[0].append( rmsd ) return "{:6.3f} A".format(rmsd) else: return
def main(parser): args = parser.parse_args() with fuc.hide_traceback(): cg1, cg2 = fuc.cgs_from_args( args, 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 test_cg_rmsd(self): cg1 = ftmc.CoarseGrainRNA('test/forgi/threedee/data/1GID_A.cg') cg2 = ftmc.CoarseGrainRNA('test/forgi/threedee/data/1GID_A_sampled.cg') residues1 = ftug.bg_virtual_residues(cg1) residues2 = ftug.bg_virtual_residues(cg2) self.assertAlmostEqual(ftme.rmsd(residues1, residues2), ftme.cg_rmsd(cg1, cg2))
def realatom_vatom_rmsd(cg): """ The RMSD between the real atoms and the virtual atoms of the stems. """ vposs = [] rposs = [] #print(cg.seq) #print("".join(r.get_segid() for r in chain.get_residues())) #print(cg.seq[1], chain[2]) for stem in cg.stem_iterator(): stemv = [] stemr = [] resseqs = cg.get_resseqs(stem) resseqs = resseqs[0] + resseqs[1] for posCg, posPdb in zip(cg.define_residue_num_iterator(stem), resseqs): #try: # print( posCg, posPdb, cg.seq[posCg-1], cg.chain[posPdb] ) #except KeyError as e: print(e) vas = cg.virtual_atoms(posCg) for a, coords in vas.items(): try: rposs.append(cg.chain[posPdb][a].get_vector().get_array()) stemr.append(cg.chain[posPdb][a].get_vector().get_array()) except KeyError: pass else: vposs.append(coords) stemv.append(coords) assert len(vposs) == len(rposs) #print (np.array(vposs).shape, file=sys.stderr) return ftme.rmsd(np.array(vposs), np.array(rposs))
def test_cg_rmsd(self): cg1 = ftmc.CoarseGrainRNA.from_bg_file( 'test/forgi/threedee/data/1GID_A.cg') cg2 = ftmc.CoarseGrainRNA.from_bg_file( 'test/forgi/threedee/data/1GID_A_sampled.cg') cg1.add_all_virtual_residues() cg2.add_all_virtual_residues() residues1 = cg1.get_ordered_virtual_residue_poss() residues2 = cg2.get_ordered_virtual_residue_poss() self.assertAlmostEqual( ftme.rmsd(residues1, residues2), ftme.cg_rmsd(cg1, cg2))
def main(parser): args = parser.parse_args() cg1 = ftmc.CoarseGrainRNA(args.files[0]) cg2 = ftmc.CoarseGrainRNA(args.files[1]) 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 test_rmsd_in_2D(self): a1 = np.array([[1., 1.], [0., 0.], [-1., -1.]]) a2 = np.array([[2., 2.], [0., 0.], [-2., -2.]]) a3 = np.array([[2., 4.], [0., 6.], [-1., 0.]]) self.assertAlmostEqual(ftme.rmsd(a1, a1), 0) self.assertAlmostEqual(ftme.rmsd(a2, a2), 0) self.assertAlmostEqual(ftme.rmsd(a3, a3), 0) self.assertAlmostEqual(ftme.rmsd(a1, a2), math.sqrt(4. / 3.)) self.assertGreater(ftme.rmsd(a1, a3), ftme.rmsd(a1, a2))
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.0 cg_rmsds[0] = 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 = ftug.bg_virtual_residues(target) for cg in cgs: vrs1 = ftug.bg_virtual_residues(cg) 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(p_rmsds.items()) cg_rmsds = np.array(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 update(self, sm, step): if not self.silent: if self.res_ids: curr_vress = [] for res in self.res_ids: curr_vress.append( sm.bg.get_virtual_residue(res, allow_single_stranded=True)) curr_vress = np.array(curr_vress) else: curr_vress = sm.bg.get_ordered_virtual_residue_poss() if self.mode == "RMSD": try: rmsd = ftme.rmsd(self._reference, curr_vress) except Exception as e: self.res_ids = set(self.reference_cg.seq._seqids) & set( sm.bg.seq._seqids) self._reference = [] curr_vress = [] for res in self.res_ids: curr_vress.append( sm.bg.get_virtual_residue( res, allow_single_stranded=True)) self._reference.append( self.reference_cg.get_virtual_residue( res, allow_single_stranded=True)) curr_vress = np.array(curr_vress) self._reference = np.array(self._reference) log.error("Calculating rmsd between %s and %s", self._reference, curr_vress) rmsd = ftme.rmsd(self._reference, curr_vress) elif self.mode == "dRMSD": rmsd = ftme.drmsd(self._reference, curr_vress) if self.best_cgs.can_insert_right((None, rmsd)): self.best_cgs.insert_right((sm.bg.to_cg_string(), rmsd)) if step % 10 == 0: for i, bg in enumerate(self.best_cgs): with open( os.path.join( conf.Configuration.sampling_output_dir, 'best_rmsd{:d}.coord'.format(i)), 'w') as f: f.write(bg[0]) if self._showMinMax: if rmsd > self._maxRMSD: self._maxRMSD = rmsd if self._showMinMax == True: if rmsd < self._minRMSD: self._minRMSD = rmsd self.history[1].append(self._minRMSD) self.history[0].append(rmsd) self.history[-1].append(self._maxRMSD) if self._showMinMax == "max": return "{:6.3f} A\t{:6.3f} A".format(rmsd, self._maxRMSD) else: return "{:6.3f} A\t{:6.3f} A\t{:6.3f} A".format( rmsd, self._minRMSD, self._maxRMSD) else: self.history[0].append(rmsd) return "{:6.3f} A".format(rmsd) else: return
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 test_rmsd(self): a1 = np.array([[1., 1., 1.], [0., 0., 0.], [-1., -1., -1.]]) a3 = np.array([[2., 2., 2.], [0., 0., 0.], [-2., -2., -2.]]) self.assertAlmostEqual(ftme.rmsd(a1, a3), math.sqrt(2))