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')
cg = ftmc.CoarseGrainRNA(dotbracket_str=dotbracket, seq=seq) return cg parser=generateParser() if __name__=="__main__": args = parser.parse_args() energy = fbe.CombinedEnergy([fbe.RoughJunctionClosureEnergy()]) for link_length in range(0,4): cutoff_distance = (link_length) * 6.22 + 14.0 print("\nLink Length {}".format(link_length)) for l in range(1, 30): #Sampling 30 times with different stem stats cg = construct_test_graph(random.randrange(3,15),l,link_length) sm=fbm.SpatialModel(cg, ftms.get_conformation_stats(data_file("stats/all_filtered.stats"))) sm.sample_stats() possible_sstats=sm.conf_stats.sample_stats(cg, "s1") for sstat in possible_sstats: if sstat.pdb_name.startswith("ideal"): break maxdist=0 sm.elem_defs["s1"] = sstat possible_stats=sm.conf_stats.sample_stats(cg, "m0") for i, stat in enumerate(possible_stats): #if i%1000 == 0: # print(i, "/", len(possible_stats), end="") sm.elem_defs["m0"] = stat sm.traverse_and_build() e=energy.eval_energy(sm)
import collections as col import sklearn.cluster def generateParser(): parser=argparse.ArgumentParser( description="Cluster angle stats.") parser.add_argument("--stats-file", type=str, help="What stats file to use", default="stats/all_filtered.stats") parser.add_argument("-p", "--plot", action="store_true", help="Plot some clusters") parser.add_argument("-t", "--threshold", type=float, help="Threshold for the Birch clustering algorithm", default=0.3) return parser parser=generateParser() if __name__=="__main__": args = parser.parse_args() #Get the stats object conf_stats = ftms.get_conformation_stats(data_file(args.stats_file)) angle_stats = conf_stats.angle_stats colors = plt.cm.Spectral(np.linspace(0, 1, 10)) colors=np.array(list(colors)*500) markers="o"*10+"v"*10+"<"*10+">"*10+"."*10+"s"*10+"^"*10+"8"*10+"*"*10+"+"*10 markers=markers*500 for key in angle_stats.keys(): point_to=[] to_clust=[] angles=[] for stat in angle_stats[key]: stem_start = np.array(ftuv.spherical_polar_to_cartesian([stat.r1, stat.u1, stat.v1])) #stem_vec = np.array(ftuv.spherical_polar_to_cartesian([1, stat.u, stat.v])) #point1 = stem_start+stem_vec stem_vec = np.array(ftuv.spherical_polar_to_cartesian([1, stat.u, stat.v])) #point2 = stem_start+stem_vec
"--plot", action="store_true", help="Plot some clusters") parser.add_argument("-t", "--threshold", type=float, help="Threshold for the Birch clustering algorithm", default=0.3) return parser parser = generateParser() if __name__ == "__main__": args = parser.parse_args() #Get the stats object conf_stats = ftms.get_conformation_stats(data_file(args.stats_file)) angle_stats = conf_stats.angle_stats colors = plt.cm.Spectral(np.linspace(0, 1, 10)) colors = np.array(list(colors) * 500) markers = "o" * 10 + "v" * 10 + "<" * 10 + ">" * 10 + "." * 10 + "s" * 10 + "^" * 10 + "8" * 10 + "*" * 10 + "+" * 10 markers = markers * 500 for key in angle_stats.keys(): point_to = [] to_clust = [] angles = [] for stat in angle_stats[key]: stem_start = np.array( ftuv.spherical_polar_to_cartesian([stat.r1, stat.u1, stat.v1])) #stem_vec = np.array(ftuv.spherical_polar_to_cartesian([1, stat.u, stat.v])) #point1 = stem_start+stem_vec stem_vec = np.array(
def compare(self, d, other_stats): if not self.rmsd: stats = self.ref_sm.elem_defs[d] return is_similar(stats, other_stats, self.tol) else: self.ref_sm.elem_defs[d]=other_stats self.ref_sm.traverse_and_build(start=d) curr_vress=self.ref_sm.bg.get_ordered_virtual_residue_poss() rmsd=ftur.rmsd(self.ref_vress, curr_vress) return rmsd<self.tol parser=generateParser() if __name__=="__main__": args = parser.parse_args() cg=ftmc.CoarseGrainRNA(args.cg) sm=fbm.SpatialModel(cg, ftms.get_conformation_stats(args.stats_file)) sm.load_sampled_elems() maxNum=0 maxLoop=0 sumStats=0 comp = Comparison(sm.bg, args.tolerance, args.rmsd) for define in cg.defines: similar_stats=0 allstats = sm.conf_stats.sample_stats(cg, define) numStats = len(allstats) if define[0] in "mi" and numStats: if args.cluster: distance=np.full((len(allstats),len(allstats)),np.NAN) for i, stat in enumerate(allstats): if args.cluster: for j, stat2 in enumerate(allstats):
from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str, super, zip) import forgi.threedee.model.coarse_grain as ftmc import fess.builder.models as fbm import time import forgi.threedee.model.stats as ftms #This takes some time, which is why it is only executed once at startup of the server. print(" * Loading default conformation stats") default_conf_stats=ftms.get_conformation_stats() class CgFileCache(): def __init__(self): self.cached={} self.time={} self.max_size=64 def loadSM(self, filename): if filename not in self.cached: if len(self.cached)>self.max_size: self.cleanup() cg=ftmc.CoarseGrainRNA("user_files/"+filename) sm=fbm.SpatialModel(cg, conf_stats=default_conf_stats) self.cached[filename]=sm self.time[filename]=time.time() return self.cached[filename] def removeSM(self, filename): """
def setup_deterministic(args): """ The part of the setup procedure that does not use any call to the random number generator. :param args: An argparse.ArgumentParser object holding the parsed arguments. """ #Load the RNA from file rnafile, = args.rna #Tuple unpacking if rnafile[-3:] == '.fa': cg = ftmc.CoarseGrainRNA() try: with open(rnafile) as fastafile: cg.from_fasta(fastafile.read()) except IOError as e: print("ERROR: Could not open file '{}' for reading:".format(rnafile),e, file=sys.stderr) sys.exit(1) else: cg = ftmc.CoarseGrainRNA(rnafile) #Output file and directory ofilename=None if not args.eval_energy: if args.output_base_dir and not os.path.exists(args.output_base_dir): os.makedirs(args.output_base_dir) print ("INFO: Directory {} created.".format(args.output_base_dir), file=sys.stderr) subdir=cg.name+args.output_dir_suffix config.Configuration.sampling_output_dir = os.path.join(args.output_base_dir, subdir) if not os.path.exists(config.Configuration.sampling_output_dir): os.makedirs(config.Configuration.sampling_output_dir) print ("INFO: Directory {} created. This folder will be used for all output " "files.".format(config.Configuration.sampling_output_dir), file=sys.stderr) if args.output_file: ofilename=os.path.join(config.Configuration.sampling_output_dir, args.output_file) #Initialize the spatial model if args.clustered_angle_stats and args.jar3d: print("ERROR: --clustered-angle-stats and --jar3d are mutually exclusive!", file=sys.stderr) sys.exit(1) if args.clustered_angle_stats: sm=fbm.SpatialModel(cg, ftms.get_conformation_stats(args.stats_file, args.clustered_angle_stats)) elif args.jar3d: jared_out = op.join(config.Configuration.sampling_output_dir, "filtered_stats") jared_tmp = op.join(config.Configuration.sampling_output_dir, "jar3d") motifs = fma.annotate_structure(cg, jared_tmp, cg.name.split('_')[0]) elems = fma.motifs_to_cg_elements(motifs, config.Configuration.sampling_output_dir, filename = jared_out) filtered_stats = ftms.FilteredConformationStats(stats_file=args.stats_file, filter_filename=jared_out) ftms.set_conformation_stats(filtered_stats) sm=fbm.SpatialModel(cg, ftms.get_conformation_stats()) else: sm=fbm.SpatialModel(cg, ftms.get_conformation_stats(args.stats_file)) #Load the reference sm (if given) if args.rmsd_to: if args.rmsd_to.endswith(".pdb"): with warnings.catch_warnings(): warnings.simplefilter("ignore") pdb = list(bp.PDBParser().get_structure('reference', args.rmsd_to).get_chains())[0] original_sm = fbm.SpatialModel(ftmc.from_pdb(pdb)) else: original_sm=fbm.SpatialModel(ftmc.CoarseGrainRNA(args.rmsd_to)) else: original_sm=fbm.SpatialModel(copy.deepcopy(sm.bg)) #Initialize the requested energies if args.energy=="D": energy=fbe.CombinedEnergy([],getDefaultEnergies(cg)) else: energy=parseCombinedEnergyString(args.energy, cg, original_sm.bg, args) #Initialize energies to track energies_to_track=[] for track_energy_string in args.track_energies.split(":"): if track_energy_string: if track_energy_string=="D": energies_to_track.append(fbe.CombinedEnergy([],getDefaultEnergies(cg))) else: energies_to_track.append(parseCombinedEnergyString(track_energy_string, cg, original_sm.bg, args)) #Initialize the Constraint energies junction_energy=None clash_energy=None if args.constraint_energy in ["D","B","J"]: sm.junction_constraint_energy=fbe.CombinedEnergy([fbe.RoughJunctionClosureEnergy()]) if args.constraint_energy in ["D","B","C"]: sm.constraint_energy=fbe.CombinedEnergy([fbe.StemVirtualResClashEnergy()]) return sm, original_sm, ofilename, energy, energies_to_track
cg = ftmc.CoarseGrainRNA(dotbracket_str=dotbracket, seq=seq) return cg parser = generateParser() if __name__ == "__main__": args = parser.parse_args() energy = fbe.CombinedEnergy([fbe.RoughJunctionClosureEnergy()]) for link_length in range(0, 4): cutoff_distance = (link_length) * 6.22 + 14.0 print("\nLink Length {}".format(link_length)) for l in range(1, 30): #Sampling 30 times with different stem stats cg = construct_test_graph(random.randrange(3, 15), l, link_length) sm = fbm.SpatialModel( cg, ftms.get_conformation_stats( data_file("stats/all_filtered.stats"))) sm.sample_stats() possible_sstats = sm.conf_stats.sample_stats(cg, "s1") for sstat in possible_sstats: if sstat.pdb_name.startswith("ideal"): break maxdist = 0 sm.elem_defs["s1"] = sstat possible_stats = sm.conf_stats.sample_stats(cg, "m0") for i, stat in enumerate(possible_stats): #if i%1000 == 0: # print(i, "/", len(possible_stats), end="") sm.elem_defs["m0"] = stat sm.traverse_and_build() e = energy.eval_energy(sm)