IMP logo
IMP Reference Guide  2.17.0
The Integrative Modeling Platform
exhaust.py
1 from __future__ import print_function
2 from IMP import ArgumentParser
3 import os
4 
5 __doc__ = "Perform analysis to determine sampling convergence."
6 
7 ############################################################
8 # Scripts written by Shruthi Viswanath and Ilan E. Chemmama#
9 # in Andrej Sali Lab at UCSF. #
10 # Based on Viswanath, Chemmama et al. Biophys. J. (2017) #
11 # #
12 ############################################################
13 
14 
15 def parse_args():
16  parser = ArgumentParser(
17  description="First stages of analysis for assessing sampling "
18  "convergence")
19  parser.add_argument(
20  '--sysname', '-n', dest="sysname",
21  help='name of the system', default="")
22  parser.add_argument(
23  '--path', '-p', dest="path",
24  help='path to the good-scoring models', default="./")
25  parser.add_argument(
26  '--extension', '-e', dest="extension",
27  help='extension of the file', choices=['rmf', 'pdb'], default="rmf")
28  parser.add_argument(
29  '--mode', '-m', dest="mode", help='pyRMSD calculator',
30  choices=['cuda', 'cpu_omp', 'cpu_serial'], default="cuda")
31  parser.add_argument(
32  '--cores', '-c', dest="cores", type=int,
33  help='number of cores for parallel clustering at '
34  'different thresholds and RMSD matrix calculations; '
35  'only for cpu_omp', default=1)
36  parser.add_argument(
37  '--resolution', '-r', dest="resolution", type=int,
38  help='resolution at which to select proteins in a multiscale system',
39  default=1)
40  parser.add_argument(
41  '--subunit', '-su', dest="subunit",
42  help='calculate RMSD/sampling and cluster precision/densities '
43  'etc over this subunit only', default=None)
44  parser.add_argument(
45  '--align', '-a', dest="align",
46  help='boolean flag to allow superposition of models',
47  default=False, action='store_true')
48  parser.add_argument(
49  '--ambiguity', '-amb', dest="symmetry_groups",
50  help='file containing symmetry groups', default=None)
51  parser.add_argument(
52  '--scoreA', '-sa', dest="scoreA",
53  help='name of the file having the good-scoring scores for sample A',
54  default="scoresA.txt")
55  parser.add_argument(
56  '--scoreB', '-sb', dest="scoreB",
57  help='name of the file having the good-scoring scores for sample B',
58  default="scoresB.txt")
59  parser.add_argument(
60  '--rmfA', '-ra', dest="rmf_A",
61  help='RMF file with conformations from Sample A', default=None)
62  parser.add_argument(
63  '--rmfB', '-rb', dest="rmf_B",
64  help='RMF file with conformations from Sample B', default=None)
65  parser.add_argument(
66  '--gridsize', '-g', dest="gridsize", type=float,
67  help='grid size for calculating sampling precision', default=10.0)
68  parser.add_argument(
69  '--skip', '-s', dest="skip_sampling_precision",
70  help="This option will bypass the calculation of sampling "
71  "precision. This option needs to be used with the clustering "
72  "threshold option. Otherwise by default, sampling precision "
73  "is calculated and the clustering threshold is the "
74  "calculated sampling precision.", default=False,
75  action='store_true')
76  parser.add_argument(
77  '--cluster_threshold', '-ct', dest="cluster_threshold", type=float,
78  help='final clustering threshold to visualize clusters. Assumes '
79  'that the user has previously calculated sampling precision '
80  'and wants clusters defined at a threshold higher than the '
81  'sampling precision for ease of analysis (lesser number of '
82  'clusters).', default=30.0)
83  parser.add_argument(
84  '--voxel', '-v', dest="voxel", type=float,
85  help='voxel size for the localization densities', default=5.0)
86  parser.add_argument(
87  '--density_threshold', '-dt', type=float,
88  dest="density_threshold",
89  help='threshold for localization densities', default=20.0)
90  parser.add_argument(
91  '--density', '-d', dest="density",
92  help='file containing dictionary of density custom ranges',
93  default=None)
94  parser.add_argument(
95  '--gnuplot', '-gp', dest="gnuplot",
96  help="plotting automatically with gnuplot", default=False,
97  action='store_true')
98  parser.add_argument(
99  '--selection', '-sn', dest="selection",
100  help='file containing dictionary'
101  'of selected subunits and residues'
102  'for RMSD and clustering calculation'
103  "each entry in the dictionary takes the form"
104  "'selection name': [(residue_start, residue_end, protein name)",
105  default=None)
106  return parser.parse_args()
107 
108 
109 def make_cluster_centroid(infname, frame, outfname, cluster_index,
110  cluster_size, precision, density, path):
111 
112  import RMF
113  # If we have new enough IMP/RMF, do our own RMF slicing with provenance
114  if hasattr(RMF.NodeHandle, 'replace_child'):
115  print(infname, outfname)
116  inr = RMF.open_rmf_file_read_only(infname)
117  outr = RMF.create_rmf_file(outfname)
118  cpf = RMF.ClusterProvenanceFactory(outr)
119  RMF.clone_file_info(inr, outr)
120  RMF.clone_hierarchy(inr, outr)
121  RMF.clone_static_frame(inr, outr)
122  inr.set_current_frame(RMF.FrameID(frame))
123  outr.add_frame("f0")
124  RMF.clone_loaded_frame(inr, outr)
125  rn = outr.get_root_node()
126  children = rn.get_children()
127  if len(children) == 0:
128  return
129  rn = children[0] # Should be the top-level IMP node
130  prov = [c for c in rn.get_children() if c.get_type() == RMF.PROVENANCE]
131  if not prov:
132  return
133  prov = prov[0]
134  # Add cluster-provenance info
135  newp = rn.replace_child(
136  prov, "cluster.%d" % cluster_index, RMF.PROVENANCE)
137  cp = cpf.get(newp)
138  cp.set_members(cluster_size)
139  cp.set_precision(precision)
140  cp.set_density(os.path.abspath(density))
141  else:
142  # Otherwise, fall back to RMF's command line tool
143  import subprocess
144  print(infname, frame, outfname)
145  subprocess.call(['rmf_slice', path + infname, '-f', str(frame),
146  outfname])
147 
148 
149 def main():
150  args = parse_args()
151 
152  import os
153  import shutil
154  import numpy
155 
156  import scipy as sp
157 
158  import IMP.sampcon
159  from IMP.sampcon import scores_convergence, clustering_rmsd
160  from IMP.sampcon import rmsd_calculation, precision_rmsd
161 
162  import IMP
163 
164  idfile_A = "Identities_A.txt"
165  idfile_B = "Identities_B.txt"
166 
167  # Step 0: Compute Score convergence
168  score_A = []
169  score_B = []
170 
171  with open(os.path.join(args.path, args.scoreA), 'r') as f:
172  for line in f:
173  score_A.append(float(line.strip("\n")))
174 
175  with open(os.path.join(args.path, args.scoreB), 'r') as f:
176  for line in f:
177  score_B.append(float(line.strip("\n")))
178 
179  scores = score_A + score_B
180 
181  # Get the convergence of the best score
182  scores_convergence.get_top_scorings_statistics(scores, 0, args.sysname)
183 
184  # Check if the two score distributions are similar
185  scores_convergence.get_scores_distributions_KS_Stats(
186  score_A, score_B, 100, args.sysname)
187 
188  # Step 1: Compute RMSD matrix
189  if args.extension == "pdb":
190  ps_names = [] # bead names are not stored in PDB files
191  symm_groups = None
192  conforms, masses, radii, models_name = \
193  rmsd_calculation.get_pdbs_coordinates(
194  args.path, idfile_A, idfile_B)
195  else:
196  args.extension = "rmf3"
197  if args.selection is not None:
198  rmsd_custom_ranges = \
199  precision_rmsd.parse_custom_ranges(args.selection)
200  else:
201  rmsd_custom_ranges = None
202  # If we have a single RMF file, read conformations from that
203  if args.rmf_A is not None:
204  (ps_names, masses, radii, conforms, symm_groups, models_name,
205  n_models) = rmsd_calculation.get_rmfs_coordinates_one_rmf(
206  args.path, args.rmf_A, args.rmf_B,
207  args.subunit,
208  args.symmetry_groups,
209  rmsd_custom_ranges,
210  args.resolution,
211  args.cores)
212 
213  # If not, default to the Identities.txt file
214  else:
215  symm_groups = None
216  (ps_names, masses, radii, conforms,
217  models_name) = rmsd_calculation.get_rmfs_coordinates(
218  args.path, idfile_A, idfile_B, args.subunit,
219  selection=rmsd_custom_ranges,
220  resolution=args.resolution)
221 
222  print("Size of conformation matrix", conforms.shape)
223 
224  if not args.skip_sampling_precision:
225  # get_rmsds_matrix modifies conforms, so save it to a file and restore
226  # afterwards (so that we retain the original IMP orientation)
227  numpy.save("conforms", conforms)
228  inner_data = rmsd_calculation.get_rmsds_matrix(
229  conforms, args.mode, args.align, args.cores, symm_groups)
230  print("Size of RMSD matrix (flattened):", inner_data.shape)
231  del conforms
232  conforms = numpy.load("conforms.npy")
233  os.unlink('conforms.npy')
234 
235  from pyRMSD.matrixHandler import MatrixHandler
236  mHandler = MatrixHandler()
237  mHandler.loadMatrix("Distances_Matrix.data")
238 
239  rmsd_matrix = mHandler.getMatrix()
240  distmat = rmsd_matrix.get_data()
241 
242  distmat_full = sp.spatial.distance.squareform(distmat)
243  print("Size of RMSD matrix (unpacked, N x N):", distmat_full.shape)
244 
245  # Get model lists
246  if args.rmf_A is not None:
247  sampleA_all_models = list(range(n_models[0]))
248  sampleB_all_models = list(range(n_models[0],
249  n_models[1] + n_models[0]))
250  total_num_models = n_models[1] + n_models[0]
251  else:
252  (sampleA_all_models,
253  sampleB_all_models) = clustering_rmsd.get_sample_identity(
254  idfile_A, idfile_B)
255  total_num_models = len(sampleA_all_models) + len(sampleB_all_models)
256  all_models = list(sampleA_all_models) + list(sampleB_all_models)
257  print("Size of Sample A:", len(sampleA_all_models),
258  " ; Size of Sample B: ", len(sampleB_all_models),
259  "; Total", total_num_models)
260 
261  if not args.skip_sampling_precision:
262 
263  print("Calculating sampling precision")
264 
265  # Step 2: Cluster at intervals of grid size to get the
266  # sampling precision
267  gridSize = args.gridsize
268 
269  # Get cutoffs for clustering
270  cutoffs_list = clustering_rmsd.get_cutoffs_list(distmat, gridSize)
271  print("Clustering at thresholds:", cutoffs_list)
272 
273  # Do clustering at each cutoff
274  pvals, cvs, percents = clustering_rmsd.get_clusters(
275  cutoffs_list, distmat_full, all_models, total_num_models,
276  sampleA_all_models, sampleB_all_models, args.sysname,
277  args.cores)
278 
279  # Now apply the rule for selecting the right precision based
280  # on population of contingency table, pvalue and cramersv
281  (sampling_precision, pval_converged, cramersv_converged,
282  percent_converged) = clustering_rmsd.get_sampling_precision(
283  cutoffs_list, pvals, cvs, percents)
284 
285  # Output test statistics
286  with open("%s.Sampling_Precision_Stats.txt"
287  % args.sysname, 'w+') as fpv:
288  print("The sampling precision is defined as the largest allowed "
289  "RMSD between the cluster centroid and a ", args.sysname,
290  "model within any cluster in the finest clustering for "
291  "which each sample contributes models proportionally to "
292  "its size (considering both significance and magnitude of "
293  "the difference) and for which a sufficient proportion of "
294  "all models occur in sufficiently large clusters. The "
295  "sampling precision for our ", args.sysname,
296  " modeling is %.3f" % (sampling_precision), " A.", file=fpv)
297 
298  print("Sampling precision, P-value, Cramer's V and percentage "
299  "of clustered models below:", file=fpv)
300  print("%.3f\t%.3f\t%.3f\t%.3f"
301  % (sampling_precision, pval_converged, cramersv_converged,
302  percent_converged), file=fpv)
303  print("", file=fpv)
304 
305  final_clustering_threshold = sampling_precision
306 
307  else:
308  final_clustering_threshold = args.cluster_threshold
309 
310  # Perform final clustering at the required precision
311  print("Clustering at threshold %.3f" % final_clustering_threshold)
312  (cluster_centers, cluster_members) = clustering_rmsd.precision_cluster(
313  distmat_full, total_num_models, final_clustering_threshold)
314 
315  (ctable, retained_clusters) = clustering_rmsd.get_contingency_table(
316  len(cluster_centers), cluster_members, all_models,
317  sampleA_all_models, sampleB_all_models)
318  print("Contingency table:", ctable)
319  # Output the number of models in each cluster and each sample
320  with open("%s.Cluster_Population.txt" % args.sysname, 'w+') as fcp:
321  for rows in range(len(ctable)):
322  print(rows, ctable[rows][0], ctable[rows][1], file=fcp)
323 
324  # Obtain the subunits for which we need to calculate densities
325  density_custom_ranges = precision_rmsd.parse_custom_ranges(args.density)
326 
327  # Output cluster precisions
328  fpc = open("%s.Cluster_Precision.txt" % args.sysname, 'w+')
329 
330  # For each cluster, output the models in the cluster
331  # Also output the densities for the cluster models
332  for i in range(len(retained_clusters)):
333  clus = retained_clusters[i]
334 
335  # The cluster centroid is the first conformation.
336  # We use this as to align and compute RMSD/precision
337  conform_0 = conforms[all_models[cluster_members[clus][0]]]
338 
339  # create a directory for the cluster
340  if not os.path.exists("./cluster.%s" % i):
341  os.mkdir("./cluster.%s" % i)
342  os.mkdir("./cluster.%s/Sample_A/" % i)
343  os.mkdir("./cluster.%s/Sample_B/" % i)
344  else:
345  shutil.rmtree("./cluster.%s" % i)
346  os.mkdir("./cluster.%s" % i)
347  os.mkdir("./cluster.%s/Sample_A/" % i)
348  os.mkdir("./cluster.%s/Sample_B/" % i)
349 
350  # Create densities for all subunits for both sample A and sample B
351  # as well as separately.
352  gmd1 = precision_rmsd.GetModelDensity(
353  custom_ranges=density_custom_ranges,
354  resolution=args.density_threshold, voxel=args.voxel,
355  bead_names=ps_names)
356  gmd2 = precision_rmsd.GetModelDensity(
357  custom_ranges=density_custom_ranges,
358  resolution=args.density_threshold, voxel=args.voxel,
359  bead_names=ps_names)
360  gmdt = precision_rmsd.GetModelDensity(
361  custom_ranges=density_custom_ranges,
362  resolution=args.density_threshold, voxel=args.voxel,
363  bead_names=ps_names)
364 
365  # Also output the identities of cluster members
366  both_file = open('cluster.'+str(i)+'.all.txt', 'w')
367  sampleA_file = open('cluster.'+str(i)+'.sample_A.txt', 'w')
368  sampleB_file = open('cluster.'+str(i)+'.sample_B.txt', 'w')
369 
370  # Create a model with just the cluster_member particles
371  model = IMP.Model()
372  ps = [] # particle list to be updated by each RMF frame
373  for pi in range(len(conform_0)):
374  p = IMP.Particle(model, "%s" % str(pi))
375  IMP.core.XYZ.setup_particle(p, (0, 0, 0))
376  IMP.core.XYZR.setup_particle(p, float(radii[pi]))
377  IMP.atom.Mass.setup_particle(p, float(masses[pi]))
378  ps.append(p)
379 
380  # Obtain cluster precision by obtaining average RMSD of each model
381  # to the cluster center
382  cluster_precision = 0.0
383 
384  # transformation from internal pyRMSD orientation
385  trans = None
386  # for each model in the cluster
387  for mem in cluster_members[clus]:
388 
389  model_index = all_models[mem]
390 
391  # get superposition of each model to cluster center and the
392  # RMSD between the two
393  rmsd, superposed_ps, trans = \
394  precision_rmsd.get_particles_from_superposed(
395  conforms[model_index], conform_0, args.align,
396  ps, trans, symm_groups)
397 
398  model.update() # why not?
399 
400  cluster_precision += rmsd
401 
402  # Add the superposed particles to the respective density maps
403  gmdt.add_subunits_density(superposed_ps) # total density map
404  print(model_index, file=both_file)
405 
406  if model_index in sampleA_all_models:
407  # density map for sample A
408  gmd1.add_subunits_density(superposed_ps)
409  print(model_index, file=sampleA_file)
410  else:
411  # density map for sample B
412  gmd2.add_subunits_density(superposed_ps)
413  print(model_index, file=sampleB_file)
414 
415  cluster_precision /= float(len(cluster_members[clus]) - 1.0)
416 
417  print("Cluster precision (average distance to cluster centroid) "
418  "of cluster ", str(i), " is %.3f" % cluster_precision, "A",
419  file=fpc)
420 
421  both_file.close()
422  sampleA_file.close()
423  sampleB_file.close()
424 
425  # Output density files for the cluster
426  density = gmdt.write_mrc(path="./cluster.%s" % i, file_prefix="LPD")
427  gmd1.write_mrc(path="./cluster.%s/Sample_A/" % i, file_prefix="LPD")
428  gmd2.write_mrc(path="./cluster.%s/Sample_B/" % i, file_prefix="LPD")
429 
430  # Add the cluster center model RMF to the cluster directory
431  cluster_center_index = cluster_members[clus][0]
432  if args.rmf_A is not None:
433  cluster_center_model_id = cluster_center_index
434  if cluster_center_index < n_models[0]:
435  make_cluster_centroid(
436  os.path.join(args.path, args.rmf_A),
437  cluster_center_index,
438  os.path.join("cluster.%d" % i,
439  "cluster_center_model.rmf3"),
440  i, len(cluster_members[clus]),
441  cluster_precision, density, args.path)
442  else:
443  make_cluster_centroid(
444  os.path.join(args.path, args.rmf_B),
445  cluster_center_index - n_models[0],
446  os.path.join("cluster.%d" % i,
447  "cluster_center_model.rmf3"),
448  i, len(cluster_members[clus]),
449  cluster_precision, density, args.path)
450  else:
451  # index to Identities file.
452  cluster_center_model_id = all_models[cluster_center_index]
453  outfname = os.path.join("cluster.%d" % i,
454  "cluster_center_model." + args.extension)
455  if 'rmf' in args.extension:
456  make_cluster_centroid(
457  models_name[cluster_center_model_id], 0, outfname,
458  i, len(cluster_members[clus]),
459  cluster_precision, density, args.path)
460  else:
461  shutil.copy(models_name[cluster_center_model_id], outfname)
462 
463  fpc.close()
464 
465  # generate plots for the score and structure tests
466  if args.gnuplot:
467  import subprocess
468  import glob
469 
470  gnuplotdir = IMP.sampcon.get_data_path("gnuplot_scripts")
471  for filename in sorted(glob.glob(os.path.join(gnuplotdir, "*.plt"))):
472  cmd = ['gnuplot', '-e', 'sysname="%s"' % args.sysname, filename]
473  print(" ".join(cmd))
474  subprocess.check_call(cmd)
475 
476 
477 if __name__ == '__main__':
478  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)
Definition: XYZR.h:48
static XYZ setup_particle(Model *m, ParticleIndex pi)
Definition: XYZ.h:51
Class for storing model, its restraints, constraints, and particles.
Definition: Model.h:73
static Mass setup_particle(Model *m, ParticleIndex pi, Float mass)
Definition: Mass.h:48
Class to handle individual particles of a Model object.
Definition: Particle.h:41
Sampling exhaustiveness protocol.