1 from __future__
import print_function
2 from IMP
import ArgumentParser
5 __doc__ =
"Perform analysis to determine sampling convergence."
16 parser = ArgumentParser(
17 description=
"First stages of analysis for assessing sampling "
20 '--sysname',
'-n', dest=
"sysname",
21 help=
'name of the system', default=
"")
23 '--path',
'-p', dest=
"path",
24 help=
'path to the good-scoring models', default=
"./")
26 '--extension',
'-e', dest=
"extension",
27 help=
'extension of the file', choices=[
'rmf',
'pdb'], default=
"rmf")
29 '--mode',
'-m', dest=
"mode", help=
'pyRMSD calculator',
30 choices=[
'cuda',
'cpu_omp',
'cpu_serial'], default=
"cuda")
32 '--matrix-cores',
'-c', dest=
"cores", type=int,
33 help=
'number of cores for parallel RMSD matrix calculations; '
34 'only for cpu_omp', default=1)
36 '--cluster-cores',
'-cc', dest=
"cores2", type=int,
37 help=
'number of cores for clustering at different thresholds'
38 ' and parallel IO; only for cpu_omp', default=1)
40 '--resolution',
'-r', dest=
"resolution", type=int,
41 help=
'resolution at which to select proteins in a multiscale system',
44 '--subunit',
'-su', dest=
"subunit",
45 help=
'calculate RMSD/sampling and cluster precision/densities '
46 'etc over this subunit only', default=
None)
48 '--align',
'-a', dest=
"align",
49 help=
'boolean flag to allow superposition of models',
50 default=
False, action=
'store_true')
52 '--ambiguity',
'-amb', dest=
"symmetry_groups",
53 help=
'file containing symmetry groups', default=
None)
55 '--scoreA',
'-sa', dest=
"scoreA",
56 help=
'name of the file having the good-scoring scores for sample A',
57 default=
"scoresA.txt")
59 '--scoreB',
'-sb', dest=
"scoreB",
60 help=
'name of the file having the good-scoring scores for sample B',
61 default=
"scoresB.txt")
63 '--rmfA',
'-ra', dest=
"rmf_A",
64 help=
'RMF file with conformations from Sample A', default=
None)
66 '--rmfB',
'-rb', dest=
"rmf_B",
67 help=
'RMF file with conformations from Sample B', default=
None)
69 '--gridsize',
'-g', dest=
"gridsize", type=float,
70 help=
'grid size for calculating sampling precision', default=10.0)
72 '--skip',
'-s', dest=
"skip_sampling_precision",
73 help=
"This option will bypass the calculation of sampling "
74 "precision. This option needs to be used with the clustering "
75 "threshold option. Otherwise by default, sampling precision "
76 "is calculated and the clustering threshold is the "
77 "calculated sampling precision.", default=
False,
80 '--cluster_threshold',
'-ct', dest=
"cluster_threshold", type=float,
81 help=
'final clustering threshold to visualize clusters. Assumes '
82 'that the user has previously calculated sampling precision '
83 'and wants clusters defined at a threshold higher than the '
84 'sampling precision for ease of analysis (lesser number of '
85 'clusters).', default=30.0)
87 '--voxel',
'-v', dest=
"voxel", type=float,
88 help=
'voxel size for the localization densities', default=5.0)
90 '--density_threshold',
'-dt', type=float,
91 dest=
"density_threshold",
92 help=
'threshold for localization densities', default=20.0)
94 '--density',
'-d', dest=
"density",
95 help=
'file containing dictionary of density custom ranges',
98 '--gnuplot',
'-gp', dest=
"gnuplot",
99 help=
"plotting automatically with gnuplot", default=
False,
102 '--selection',
'-sn', dest=
"selection",
103 help=
'file containing dictionary'
104 'of selected subunits and residues'
105 'for RMSD and clustering calculation'
106 "each entry in the dictionary takes the form"
107 "'selection name': [(residue_start, residue_end, protein name)",
110 '--prism',
'-pr', dest=
"prism",
111 help=
"Save input files for PrISM", default=
False,
113 return parser.parse_args()
116 def make_cluster_centroid(infname, frame, outfname, cluster_index,
117 cluster_size, precision, density, path):
121 if hasattr(RMF.NodeHandle,
'replace_child'):
122 print(infname, outfname)
123 inr = RMF.open_rmf_file_read_only(infname)
124 outr = RMF.create_rmf_file(outfname)
125 cpf = RMF.ClusterProvenanceFactory(outr)
126 RMF.clone_file_info(inr, outr)
127 RMF.clone_hierarchy(inr, outr)
128 RMF.clone_static_frame(inr, outr)
129 inr.set_current_frame(RMF.FrameID(frame))
131 RMF.clone_loaded_frame(inr, outr)
132 rn = outr.get_root_node()
133 children = rn.get_children()
134 if len(children) == 0:
137 prov = [c
for c
in rn.get_children()
if c.get_type() == RMF.PROVENANCE]
142 newp = rn.replace_child(
143 prov,
"cluster.%d" % cluster_index, RMF.PROVENANCE)
145 cp.set_members(cluster_size)
146 cp.set_precision(precision)
147 cp.set_density(os.path.abspath(density))
151 print(infname, frame, outfname)
152 subprocess.call([
'rmf_slice', path + infname,
'-f', str(frame),
166 from IMP.sampcon import scores_convergence, clustering_rmsd
167 from IMP.sampcon import rmsd_calculation, precision_rmsd
171 idfile_A =
"Identities_A.txt"
172 idfile_B =
"Identities_B.txt"
178 with open(os.path.join(args.path, args.scoreA),
'r') as f:
180 score_A.append(float(line.strip(
"\n")))
182 with open(os.path.join(args.path, args.scoreB),
'r') as f:
184 score_B.append(float(line.strip(
"\n")))
186 scores = score_A + score_B
189 scores_convergence.get_top_scorings_statistics(scores, 0, args.sysname)
192 scores_convergence.get_scores_distributions_KS_Stats(
193 score_A, score_B, 100, args.sysname)
196 if args.extension ==
"pdb":
199 conforms, masses, radii, models_name = \
200 rmsd_calculation.get_pdbs_coordinates(
201 args.path, idfile_A, idfile_B)
203 args.extension =
"rmf3"
204 if args.selection
is not None:
205 rmsd_custom_ranges = \
206 precision_rmsd.parse_custom_ranges(args.selection)
208 rmsd_custom_ranges =
None
210 if args.rmf_A
is not None:
211 (ps_names, masses, radii, conforms, symm_groups, models_name,
212 n_models) = rmsd_calculation.get_rmfs_coordinates_one_rmf(
213 args.path, args.rmf_A, args.rmf_B,
215 args.symmetry_groups,
223 (ps_names, masses, radii, conforms,
224 models_name) = rmsd_calculation.get_rmfs_coordinates(
225 args.path, idfile_A, idfile_B, args.subunit,
226 selection=rmsd_custom_ranges,
227 resolution=args.resolution)
229 print(
"Size of conformation matrix", conforms.shape)
231 if not args.skip_sampling_precision:
234 numpy.save(
"conforms", conforms)
235 inner_data = rmsd_calculation.get_rmsds_matrix(
236 conforms, args.mode, args.align, args.cores, symm_groups)
237 print(
"Size of RMSD matrix (flattened):", inner_data.shape)
239 conforms = numpy.load(
"conforms.npy")
240 os.unlink(
'conforms.npy')
242 from pyRMSD.matrixHandler
import MatrixHandler
243 mHandler = MatrixHandler()
244 mHandler.loadMatrix(
"Distances_Matrix.data")
246 rmsd_matrix = mHandler.getMatrix()
247 distmat = rmsd_matrix.get_data()
249 distmat_full = sp.spatial.distance.squareform(distmat)
250 print(
"Size of RMSD matrix (unpacked, N x N):", distmat_full.shape)
253 if args.rmf_A
is not None:
254 sampleA_all_models = list(range(n_models[0]))
255 sampleB_all_models = list(range(n_models[0],
256 n_models[1] + n_models[0]))
257 total_num_models = n_models[1] + n_models[0]
260 sampleB_all_models) = clustering_rmsd.get_sample_identity(
262 total_num_models = len(sampleA_all_models) + len(sampleB_all_models)
263 all_models = list(sampleA_all_models) + list(sampleB_all_models)
264 print(
"Size of Sample A:", len(sampleA_all_models),
265 " ; Size of Sample B: ", len(sampleB_all_models),
266 "; Total", total_num_models)
268 if not args.skip_sampling_precision:
270 print(
"Calculating sampling precision")
274 gridSize = args.gridsize
277 cutoffs_list = clustering_rmsd.get_cutoffs_list(distmat, gridSize)
278 print(
"Clustering at thresholds:", cutoffs_list)
281 pvals, cvs, percents = clustering_rmsd.get_clusters(
282 cutoffs_list, distmat_full, all_models, total_num_models,
283 sampleA_all_models, sampleB_all_models, args.sysname,
288 (sampling_precision, pval_converged, cramersv_converged,
289 percent_converged) = clustering_rmsd.get_sampling_precision(
290 cutoffs_list, pvals, cvs, percents)
293 with open(
"%s.Sampling_Precision_Stats.txt"
294 % args.sysname,
'w+')
as fpv:
295 print(
"The sampling precision is defined as the largest allowed "
296 "RMSD between the cluster centroid and a ", args.sysname,
297 "model within any cluster in the finest clustering for "
298 "which each sample contributes models proportionally to "
299 "its size (considering both significance and magnitude of "
300 "the difference) and for which a sufficient proportion of "
301 "all models occur in sufficiently large clusters. The "
302 "sampling precision for our ", args.sysname,
303 " modeling is %.3f" % (sampling_precision),
" A.", file=fpv)
305 print(
"Sampling precision, P-value, Cramer's V and percentage "
306 "of clustered models below:", file=fpv)
307 print(
"%.3f\t%.3f\t%.3f\t%.3f"
308 % (sampling_precision, pval_converged, cramersv_converged,
309 percent_converged), file=fpv)
312 final_clustering_threshold = sampling_precision
315 final_clustering_threshold = args.cluster_threshold
318 print(
"Clustering at threshold %.3f" % final_clustering_threshold)
319 (cluster_centers, cluster_members) = clustering_rmsd.precision_cluster(
320 distmat_full, total_num_models, final_clustering_threshold)
322 (ctable, retained_clusters) = clustering_rmsd.get_contingency_table(
323 len(cluster_centers), cluster_members, all_models,
324 sampleA_all_models, sampleB_all_models)
325 print(
"Contingency table:", ctable)
327 with open(
"%s.Cluster_Population.txt" % args.sysname,
'w+')
as fcp:
328 for rows
in range(len(ctable)):
329 print(rows, ctable[rows][0], ctable[rows][1], file=fcp)
332 density_custom_ranges = precision_rmsd.parse_custom_ranges(args.density)
335 fpc = open(
"%s.Cluster_Precision.txt" % args.sysname,
'w+')
339 for i
in range(len(retained_clusters)):
340 clus = retained_clusters[i]
344 conform_0 = conforms[all_models[cluster_members[clus][0]]]
347 if not os.path.exists(
"./cluster.%s" % i):
348 os.mkdir(
"./cluster.%s" % i)
349 os.mkdir(
"./cluster.%s/Sample_A/" % i)
350 os.mkdir(
"./cluster.%s/Sample_B/" % i)
352 shutil.rmtree(
"./cluster.%s" % i)
353 os.mkdir(
"./cluster.%s" % i)
354 os.mkdir(
"./cluster.%s/Sample_A/" % i)
355 os.mkdir(
"./cluster.%s/Sample_B/" % i)
358 prism_file =
'cluster.'+str(i)+
'.prism.npz'
359 superposed_coords_cluster = []
362 gmd1 = precision_rmsd.GetModelDensity(
363 custom_ranges=density_custom_ranges,
364 resolution=args.density_threshold, voxel=args.voxel,
366 gmd2 = precision_rmsd.GetModelDensity(
367 custom_ranges=density_custom_ranges,
368 resolution=args.density_threshold, voxel=args.voxel,
370 gmdt = precision_rmsd.GetModelDensity(
371 custom_ranges=density_custom_ranges,
372 resolution=args.density_threshold, voxel=args.voxel,
376 both_file = open(
'cluster.'+str(i)+
'.all.txt',
'w')
377 sampleA_file = open(
'cluster.'+str(i)+
'.sample_A.txt',
'w')
378 sampleB_file = open(
'cluster.'+str(i)+
'.sample_B.txt',
'w')
383 for pi
in range(len(conform_0)):
392 cluster_precision = 0.0
397 for mem
in cluster_members[clus]:
399 model_index = all_models[mem]
403 rmsd, superposed_ps, trans = \
404 precision_rmsd.get_particles_from_superposed(
405 conforms[model_index], conform_0, args.align,
406 ps, trans, symm_groups)
410 cluster_precision += rmsd
413 gmdt.add_subunits_density(superposed_ps)
414 print(model_index, file=both_file)
416 if model_index
in sampleA_all_models:
418 gmd1.add_subunits_density(superposed_ps)
419 print(model_index, file=sampleA_file)
422 gmd2.add_subunits_density(superposed_ps)
423 print(model_index, file=sampleB_file)
425 superposed_coords = \
427 for s_ps
in superposed_ps]
428 superposed_coords_cluster.append(
429 numpy.array(superposed_coords))
437 numpy.array(superposed_coords_cluster),
440 numpy.array(ps_names))
441 cluster_precision /= float(len(cluster_members[clus]) - 1.0)
442 print(
"Cluster precision (average distance to cluster centroid) "
443 "of cluster ", str(i),
" is %.3f" % cluster_precision,
"A",
451 density = gmdt.write_mrc(path=
"./cluster.%s" % i, file_prefix=
"LPD")
452 gmd1.write_mrc(path=
"./cluster.%s/Sample_A/" % i, file_prefix=
"LPD")
453 gmd2.write_mrc(path=
"./cluster.%s/Sample_B/" % i, file_prefix=
"LPD")
456 cluster_center_index = cluster_members[clus][0]
457 if args.rmf_A
is not None:
458 cluster_center_model_id = cluster_center_index
459 if cluster_center_index < n_models[0]:
460 make_cluster_centroid(
461 os.path.join(args.path, args.rmf_A),
462 cluster_center_index,
463 os.path.join(
"cluster.%d" % i,
464 "cluster_center_model.rmf3"),
465 i, len(cluster_members[clus]),
466 cluster_precision, density, args.path)
468 make_cluster_centroid(
469 os.path.join(args.path, args.rmf_B),
470 cluster_center_index - n_models[0],
471 os.path.join(
"cluster.%d" % i,
472 "cluster_center_model.rmf3"),
473 i, len(cluster_members[clus]),
474 cluster_precision, density, args.path)
477 cluster_center_model_id = all_models[cluster_center_index]
478 outfname = os.path.join(
"cluster.%d" % i,
479 "cluster_center_model." + args.extension)
480 if 'rmf' in args.extension:
481 make_cluster_centroid(
482 models_name[cluster_center_model_id], 0, outfname,
483 i, len(cluster_members[clus]),
484 cluster_precision, density, args.path)
486 shutil.copy(models_name[cluster_center_model_id], outfname)
496 for filename
in sorted(glob.glob(os.path.join(gnuplotdir,
"*.plt"))):
497 cmd = [
'gnuplot',
'-e',
'sysname="%s"' % args.sysname, filename]
499 subprocess.check_call(cmd)
502 if __name__ ==
'__main__':
def get_data_path
Return the full path to one of this module's data files.
static XYZR setup_particle(Model *m, ParticleIndex pi)
double get_mass(ResidueType c)
Get the mass from the residue type.
static XYZ setup_particle(Model *m, ParticleIndex pi)
Class for storing model, its restraints, constraints, and particles.
static Mass setup_particle(Model *m, ParticleIndex pi, Float mass)
A decorator for a particle with x,y,z coordinates.
Class to handle individual particles of a Model object.
Sampling exhaustiveness protocol.
A decorator for a particle with x,y,z coordinates and a radius.