1 """@namespace IMP.pmi1.output
2 Classes for writing output files and processing them.
5 from __future__
import print_function, division
20 import cPickle
as pickle
24 class _ChainIDs(object):
25 """Map indices to multi-character chain IDs.
26 We label the first 26 chains A-Z, then we move to two-letter
27 chain IDs: AA through AZ, then BA through BZ, through to ZZ.
28 This continues with longer chain IDs."""
29 def __getitem__(self, ind):
30 chars = string.ascii_uppercase
34 ids.append(chars[ind % lc])
36 ids.append(chars[ind])
37 return "".join(reversed(ids))
41 """Base class for capturing a modeling protocol.
42 Unlike simple output of model coordinates, a complete
43 protocol includes the input data used, details on the restraints,
44 sampling, and clustering, as well as output models.
45 Use via IMP.pmi1.representation.Representation.add_protocol_output()
47 IMP.pmi1.topology.System.add_protocol_output() (for PMI 2).
49 @see IMP.pmi1.mmcif.ProtocolOutput for a concrete subclass that outputs
58 if t
is tuple
or t
is list:
59 for elt2
in _flatten(elt):
66 """Class for easy writing of PDBs, RMFs, and stat files
68 \note Model should be updated prior to writing outputs.
70 def __init__(self, ascii=True,atomistic=False):
71 self.dictionary_pdbs = {}
72 self.dictionary_rmfs = {}
73 self.dictionary_stats = {}
74 self.dictionary_stats2 = {}
75 self.best_score_list =
None
76 self.nbestscoring =
None
78 self.replica_exchange =
False
83 self.chainids =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
85 self.multi_chainids = _ChainIDs()
87 self.particle_infos_for_pdb = {}
88 self.atomistic=atomistic
90 def get_pdb_names(self):
91 return list(self.dictionary_pdbs.keys())
93 def get_rmf_names(self):
94 return list(self.dictionary_rmfs.keys())
96 def get_stat_names(self):
97 return list(self.dictionary_stats.keys())
99 def _init_dictchain(self, name, prot, multichar_chain=False):
100 self.dictchain[name] = {}
102 chainids = self.multi_chainids
if multichar_chain
else self.chainids
103 for n, i
in enumerate(self.dictionary_pdbs[name].get_children()):
104 self.dictchain[name][i.get_name()] = chainids[n]
108 @param name The PDB filename
109 @param prot The hierarchy to write to this pdb file
110 \note if the PDB name is 'System' then will use Selection to get molecules
112 flpdb = open(name,
'w')
114 self.dictionary_pdbs[name] = prot
115 self._init_dictchain(name, prot)
117 def write_psf(self,filename,name):
118 flpsf=open(filename,
'w')
119 flpsf.write(
"PSF CMAP CHEQ"+
"\n")
120 index_residue_pair_list={}
121 (particle_infos_for_pdb, geometric_center)=self.get_particle_infos_for_pdb_writing(name)
122 nparticles=len(particle_infos_for_pdb)
123 flpsf.write(str(nparticles)+
" !NATOM"+
"\n")
124 for n,p
in enumerate(particle_infos_for_pdb):
129 flpsf.write(
'{0:8d}{1:1s}{2:4s}{3:1s}{4:4s}{5:1s}{6:4s}{7:1s}{8:4s}{9:1s}{10:4s}{11:14.6f}{12:14.6f}{13:8d}{14:14.6f}{15:14.6f}'.format(atom_index,
" ",chain,
" ",str(resid),
" ",
'"'+residue_type.get_string()+
'"',
" ",
"C",
" ",
"C",1.0,0.0,0,0.0,0.0))
132 if chain
not in index_residue_pair_list:
133 index_residue_pair_list[chain]=[(atom_index,resid)]
135 index_residue_pair_list[chain].append((atom_index,resid))
140 for chain
in sorted(index_residue_pair_list.keys()):
142 ls=index_residue_pair_list[chain]
144 ls=sorted(ls, key=
lambda tup: tup[1])
146 indexes=[x[0]
for x
in ls]
149 nbonds=len(indexes_pairs)
150 flpsf.write(str(nbonds)+
" !NBOND: bonds"+
"\n")
152 sublists=[indexes_pairs[i:i+4]
for i
in range(0,len(indexes_pairs),4)]
157 flpsf.write(
'{0:8d}{1:8d}{2:8d}{3:8d}{4:8d}{5:8d}{6:8d}{7:8d}'.format(ip[0][0],ip[0][1],
158 ip[1][0],ip[1][1],ip[2][0],ip[2][1],ip[3][0],ip[3][1]))
160 flpsf.write(
'{0:8d}{1:8d}{2:8d}{3:8d}{4:8d}{5:8d}'.format(ip[0][0],ip[0][1],ip[1][0],
161 ip[1][1],ip[2][0],ip[2][1]))
163 flpsf.write(
'{0:8d}{1:8d}{2:8d}{3:8d}'.format(ip[0][0],ip[0][1],ip[1][0],ip[1][1]))
165 flpsf.write(
'{0:8d}{1:8d}'.format(ip[0][0],ip[0][1]))
168 del particle_infos_for_pdb
173 translate_to_geometric_center=
False,
174 write_all_residues_per_bead=
False):
176 flpdb = open(name,
'a')
178 flpdb = open(name,
'w')
180 (particle_infos_for_pdb,
181 geometric_center) = self.get_particle_infos_for_pdb_writing(name)
183 if not translate_to_geometric_center:
184 geometric_center = (0, 0, 0)
186 for n,tupl
in enumerate(particle_infos_for_pdb):
187 (xyz, atom_type, residue_type,
188 chain_id, residue_index, all_indexes, radius) = tupl
189 if atom_type
is None:
190 atom_type = IMP.atom.AT_CA
191 if ( (write_all_residues_per_bead)
and (all_indexes
is not None) ):
192 for residue_number
in all_indexes:
193 flpdb.write(IMP.atom.get_pdb_string((xyz[0] - geometric_center[0],
194 xyz[1] - geometric_center[1],
195 xyz[2] - geometric_center[2]),
196 n+1, atom_type, residue_type,
197 chain_id, residue_number,
' ',1.00,radius))
199 flpdb.write(IMP.atom.get_pdb_string((xyz[0] - geometric_center[0],
200 xyz[1] - geometric_center[1],
201 xyz[2] - geometric_center[2]),
202 n+1, atom_type, residue_type,
203 chain_id, residue_index,
' ',1.00,radius))
204 flpdb.write(
"ENDMDL\n")
207 del particle_infos_for_pdb
210 """Get the protein name from the particle.
211 This is done by traversing the hierarchy."""
213 p, self.dictchain[name])
215 def get_particle_infos_for_pdb_writing(self, name):
225 particle_infos_for_pdb = []
227 geometric_center = [0, 0, 0]
233 for n, p
in enumerate(ps):
236 if protname
not in resindexes_dict:
237 resindexes_dict[protname] = []
241 rt = residue.get_residue_type()
242 resind = residue.get_index()
246 geometric_center[0] += xyz[0]
247 geometric_center[1] += xyz[1]
248 geometric_center[2] += xyz[2]
250 particle_infos_for_pdb.append((xyz,
251 atomtype, rt, self.dictchain[name][protname], resind,
None, radius))
252 resindexes_dict[protname].append(resind)
257 resind = residue.get_index()
260 if resind
in resindexes_dict[protname]:
263 resindexes_dict[protname].append(resind)
264 rt = residue.get_residue_type()
267 geometric_center[0] += xyz[0]
268 geometric_center[1] += xyz[1]
269 geometric_center[2] += xyz[2]
271 particle_infos_for_pdb.append((xyz,
None,
272 rt, self.dictchain[name][protname], resind,
None, radius))
276 resind = resindexes[len(resindexes) // 2]
277 if resind
in resindexes_dict[protname]:
280 resindexes_dict[protname].append(resind)
284 geometric_center[0] += xyz[0]
285 geometric_center[1] += xyz[1]
286 geometric_center[2] += xyz[2]
288 particle_infos_for_pdb.append((xyz,
None,
289 rt, self.dictchain[name][protname], resind, resindexes, radius))
295 if len(resindexes) > 0:
296 resind = resindexes[len(resindexes) // 2]
299 geometric_center[0] += xyz[0]
300 geometric_center[1] += xyz[1]
301 geometric_center[2] += xyz[2]
303 particle_infos_for_pdb.append((xyz,
None,
304 rt, self.dictchain[name][protname], resind, resindexes, radius))
307 geometric_center = (geometric_center[0] / atom_count,
308 geometric_center[1] / atom_count,
309 geometric_center[2] / atom_count)
313 particle_infos_for_pdb = sorted(particle_infos_for_pdb,
314 key=
lambda x: (len(x[3]), x[3], x[4]))
316 return (particle_infos_for_pdb, geometric_center)
319 def write_pdbs(self, appendmode=True):
320 for pdb
in self.dictionary_pdbs.keys():
321 self.write_pdb(pdb, appendmode)
323 def init_pdb_best_scoring(self,
327 replica_exchange=
False):
331 self.suffixes.append(suffix)
332 self.replica_exchange = replica_exchange
333 if not self.replica_exchange:
337 self.best_score_list = []
341 self.best_score_file_name =
"best.scores.rex.py"
342 self.best_score_list = []
343 best_score_file = open(self.best_score_file_name,
"w")
344 best_score_file.write(
345 "self.best_score_list=" + str(self.best_score_list))
346 best_score_file.close()
348 self.nbestscoring = nbestscoring
349 for i
in range(self.nbestscoring):
350 name = suffix +
"." + str(i) +
".pdb"
351 flpdb = open(name,
'w')
353 self.dictionary_pdbs[name] = prot
354 self._init_dictchain(name, prot)
356 def write_pdb_best_scoring(self, score):
357 if self.nbestscoring
is None:
358 print(
"Output.write_pdb_best_scoring: init_pdb_best_scoring not run")
361 if self.replica_exchange:
363 exec(open(self.best_score_file_name).read())
365 if len(self.best_score_list) < self.nbestscoring:
366 self.best_score_list.append(score)
367 self.best_score_list.sort()
368 index = self.best_score_list.index(score)
369 for suffix
in self.suffixes:
370 for i
in range(len(self.best_score_list) - 2, index - 1, -1):
371 oldname = suffix +
"." + str(i) +
".pdb"
372 newname = suffix +
"." + str(i + 1) +
".pdb"
374 if os.path.exists(newname):
376 os.rename(oldname, newname)
377 filetoadd = suffix +
"." + str(index) +
".pdb"
378 self.write_pdb(filetoadd, appendmode=
False)
381 if score < self.best_score_list[-1]:
382 self.best_score_list.append(score)
383 self.best_score_list.sort()
384 self.best_score_list.pop(-1)
385 index = self.best_score_list.index(score)
386 for suffix
in self.suffixes:
387 for i
in range(len(self.best_score_list) - 1, index - 1, -1):
388 oldname = suffix +
"." + str(i) +
".pdb"
389 newname = suffix +
"." + str(i + 1) +
".pdb"
390 os.rename(oldname, newname)
391 filenametoremove = suffix + \
392 "." + str(self.nbestscoring) +
".pdb"
393 os.remove(filenametoremove)
394 filetoadd = suffix +
"." + str(index) +
".pdb"
395 self.write_pdb(filetoadd, appendmode=
False)
397 if self.replica_exchange:
399 best_score_file = open(self.best_score_file_name,
"w")
400 best_score_file.write(
401 "self.best_score_list=" + str(self.best_score_list))
402 best_score_file.close()
404 def init_rmf(self, name, hierarchies, rs=None, geometries=None, listofobjects=None):
406 This function initialize an RMF file
408 @param name the name of the RMF file
409 @param hierarchies the hierarchies to be included (it is a list)
410 @param rs optional, the restraint sets (it is a list)
411 @param geometries optional, the geometries (it is a list)
412 @param listofobjects optional, the list of objects for the stat (it is a list)
414 rh = RMF.create_rmf_file(name)
417 outputkey_rmfkey=
None
421 if geometries
is not None:
423 if listofobjects
is not None:
424 cat = rh.get_category(
"stat")
426 for l
in listofobjects:
427 if not "get_output" in dir(l):
428 raise ValueError(
"Output: object %s doesn't have get_output() method" % str(l))
429 output=l.get_output()
430 for outputkey
in output:
431 rmftag=RMF.string_tag
432 if type(output[outputkey])
is float:
434 elif type(output[outputkey])
is int:
436 elif type(output[outputkey])
is str:
437 rmftag = RMF.string_tag
439 rmftag = RMF.string_tag
440 rmfkey=rh.get_key(cat, outputkey, rmftag)
441 outputkey_rmfkey[outputkey]=rmfkey
442 outputkey_rmfkey[
"rmf_file"]=rh.get_key(cat,
"rmf_file", RMF.string_tag)
443 outputkey_rmfkey[
"rmf_frame_index"]=rh.get_key(cat,
"rmf_frame_index", RMF.int_tag)
445 self.dictionary_rmfs[name] = (rh,cat,outputkey_rmfkey,listofobjects)
447 def add_restraints_to_rmf(self, name, objectlist):
448 flatobjectlist=_flatten(objectlist)
449 for o
in flatobjectlist:
451 rs = o.get_restraint_for_rmf()
453 rs = o.get_restraint()
455 self.dictionary_rmfs[name][0],
458 def add_geometries_to_rmf(self, name, objectlist):
460 geos = o.get_geometries()
463 def add_particle_pair_from_restraints_to_rmf(self, name, objectlist):
466 pps = o.get_particle_pairs()
469 self.dictionary_rmfs[name][0],
472 def write_rmf(self, name):
474 if self.dictionary_rmfs[name][1]
is not None:
475 cat=self.dictionary_rmfs[name][1]
476 outputkey_rmfkey=self.dictionary_rmfs[name][2]
477 listofobjects=self.dictionary_rmfs[name][3]
478 for l
in listofobjects:
479 output=l.get_output()
480 for outputkey
in output:
481 rmfkey=outputkey_rmfkey[outputkey]
483 self.dictionary_rmfs[name][0].get_root_node().set_value(rmfkey,output[outputkey])
484 except NotImplementedError:
486 rmfkey = outputkey_rmfkey[
"rmf_file"]
487 self.dictionary_rmfs[name][0].get_root_node().set_value(rmfkey, name)
488 rmfkey = outputkey_rmfkey[
"rmf_frame_index"]
490 self.dictionary_rmfs[name][0].get_root_node().set_value(rmfkey, nframes-1)
491 self.dictionary_rmfs[name][0].flush()
493 def close_rmf(self, name):
494 rh = self.dictionary_rmfs[name][0]
495 del self.dictionary_rmfs[name]
498 def write_rmfs(self):
499 for rmfinfo
in self.dictionary_rmfs.keys():
500 self.write_rmf(rmfinfo[0])
502 def init_stat(self, name, listofobjects):
504 flstat = open(name,
'w')
507 flstat = open(name,
'wb')
511 for l
in listofobjects:
512 if not "get_output" in dir(l):
513 raise ValueError(
"Output: object %s doesn't have get_output() method" % str(l))
514 self.dictionary_stats[name] = listofobjects
516 def set_output_entry(self, key, value):
517 self.initoutput.update({key: value})
519 def write_stat(self, name, appendmode=True):
520 output = self.initoutput
521 for obj
in self.dictionary_stats[name]:
524 dfiltered = dict((k, v)
for k, v
in d.items()
if k[0] !=
"_")
525 output.update(dfiltered)
533 flstat = open(name, writeflag)
534 flstat.write(
"%s \n" % output)
537 flstat = open(name, writeflag +
'b')
538 cPickle.dump(output, flstat, 2)
541 def write_stats(self):
542 for stat
in self.dictionary_stats.keys():
543 self.write_stat(stat)
545 def get_stat(self, name):
547 for obj
in self.dictionary_stats[name]:
548 output.update(obj.get_output())
551 def write_test(self, name, listofobjects):
558 flstat = open(name,
'w')
559 output = self.initoutput
560 for l
in listofobjects:
561 if not "get_test_output" in dir(l)
and not "get_output" in dir(l):
562 raise ValueError(
"Output: object %s doesn't have get_output() or get_test_output() method" % str(l))
563 self.dictionary_stats[name] = listofobjects
565 for obj
in self.dictionary_stats[name]:
567 d = obj.get_test_output()
571 dfiltered = dict((k, v)
for k, v
in d.items()
if k[0] !=
"_")
572 output.update(dfiltered)
576 flstat.write(
"%s \n" % output)
579 def test(self, name, listofobjects, tolerance=1e-5):
580 output = self.initoutput
581 for l
in listofobjects:
582 if not "get_test_output" in dir(l)
and not "get_output" in dir(l):
583 raise ValueError(
"Output: object %s doesn't have get_output() or get_test_output() method" % str(l))
584 for obj
in listofobjects:
586 output.update(obj.get_test_output())
588 output.update(obj.get_output())
593 flstat = open(name,
'r')
597 test_dict = ast.literal_eval(l)
600 old_value = str(test_dict[k])
601 new_value = str(output[k])
609 fold = float(old_value)
610 fnew = float(new_value)
611 diff = abs(fold - fnew)
613 print(
"%s: test failed, old value: %s new value %s; "
614 "diff %f > %f" % (str(k), str(old_value),
615 str(new_value), diff,
616 tolerance), file=sys.stderr)
618 elif test_dict[k] != output[k]:
619 if len(old_value) < 50
and len(new_value) < 50:
620 print(
"%s: test failed, old value: %s new value %s"
621 % (str(k), old_value, new_value), file=sys.stderr)
624 print(
"%s: test failed, omitting results (too long)"
625 % str(k), file=sys.stderr)
629 print(
"%s from old objects (file %s) not in new objects"
630 % (str(k), str(name)), file=sys.stderr)
633 def get_environment_variables(self):
635 return str(os.environ)
637 def get_versions_of_relevant_modules(self):
644 except (ImportError):
648 versions[
"ISD2_VERSION"] = IMP.isd2.get_module_version()
649 except (ImportError):
653 versions[
"ISD_EMXL_VERSION"] = IMP.isd_emxl.get_module_version()
654 except (ImportError):
664 listofsummedobjects=
None):
670 if listofsummedobjects
is None:
671 listofsummedobjects = []
672 if extralabels
is None:
674 flstat = open(name,
'w')
676 stat2_keywords = {
"STAT2HEADER":
"STAT2HEADER"}
677 stat2_keywords.update(
678 {
"STAT2HEADER_ENVIRON": str(self.get_environment_variables())})
679 stat2_keywords.update(
680 {
"STAT2HEADER_IMP_VERSIONS": str(self.get_versions_of_relevant_modules())})
683 for l
in listofobjects:
684 if not "get_output" in dir(l):
685 raise ValueError(
"Output: object %s doesn't have get_output() method" % str(l))
689 dfiltered = dict((k, v)
690 for k, v
in d.items()
if k[0] !=
"_")
691 output.update(dfiltered)
694 for l
in listofsummedobjects:
696 if not "get_output" in dir(t):
697 raise ValueError(
"Output: object %s doesn't have get_output() method" % str(t))
699 if "_TotalScore" not in t.get_output():
700 raise ValueError(
"Output: object %s doesn't have _TotalScore entry to be summed" % str(t))
702 output.update({l[1]: 0.0})
704 for k
in extralabels:
705 output.update({k: 0.0})
707 for n, k
in enumerate(output):
708 stat2_keywords.update({n: k})
709 stat2_inverse.update({k: n})
711 flstat.write(
"%s \n" % stat2_keywords)
713 self.dictionary_stats2[name] = (
719 def write_stat2(self, name, appendmode=True):
721 (listofobjects, stat2_inverse, listofsummedobjects,
722 extralabels) = self.dictionary_stats2[name]
725 for obj
in listofobjects:
726 od = obj.get_output()
727 dfiltered = dict((k, v)
for k, v
in od.items()
if k[0] !=
"_")
729 output.update({stat2_inverse[k]: od[k]})
732 for l
in listofsummedobjects:
736 partial_score += float(d[
"_TotalScore"])
737 output.update({stat2_inverse[l[1]]: str(partial_score)})
740 for k
in extralabels:
741 if k
in self.initoutput:
742 output.update({stat2_inverse[k]: self.initoutput[k]})
744 output.update({stat2_inverse[k]:
"None"})
751 flstat = open(name, writeflag)
752 flstat.write(
"%s \n" % output)
755 def write_stats2(self):
756 for stat
in self.dictionary_stats2.keys():
757 self.write_stat2(stat)
761 """Collect statistics from ProcessOutput.get_fields().
762 Counters of the total number of frames read, plus the models that
763 passed the various filters used in get_fields(), are provided."""
766 self.passed_get_every = 0
767 self.passed_filterout = 0
768 self.passed_filtertuple = 0
772 """A class for reading stat files (either rmf or ascii v1 and v2)"""
773 def __init__(self, filename):
774 self.filename = filename
780 if not self.filename
is None:
781 f = open(self.filename,
"r")
783 raise ValueError(
"No file name provided. Use -h for help")
787 rh = RMF.open_rmf_file_read_only(self.filename)
789 cat=rh.get_category(
'stat')
790 rmf_klist=rh.get_keys(cat)
791 self.rmf_names_keys=dict([(rh.get_name(k),k)
for k
in rmf_klist])
797 for line
in f.readlines():
798 d = ast.literal_eval(line)
799 self.klist = list(d.keys())
801 if "STAT2HEADER" in self.klist:
804 if "STAT2HEADER" in str(k):
810 for k
in sorted(stat2_dict.items(), key=operator.itemgetter(1))]
812 for k
in sorted(stat2_dict.items(), key=operator.itemgetter(1))]
813 self.invstat2_dict = {}
815 self.invstat2_dict.update({stat2_dict[k]: k})
818 "Please convert to statfile v2.\n")
828 return sorted(self.rmf_names_keys.keys())
832 def show_keys(self, ncolumns=2, truncate=65):
833 IMP.pmi1.tools.print_multicolumn(self.get_keys(), ncolumns, truncate)
835 def get_fields(self, fields, filtertuple=None, filterout=None, get_every=1,
838 Get the desired field names, and return a dictionary.
839 Namely, "fields" are the queried keys in the stat file (eg. ["Total_Score",...])
840 The returned data structure is a dictionary, where each key is a field and the value
841 is the time series (ie, frame ordered series)
842 of that field (ie, {"Total_Score":[Score_0,Score_1,Score_2,Score_3,...],....} )
844 @param fields (list of strings) queried keys in the stat file (eg. "Total_Score"....)
845 @param filterout specify if you want to "grep" out something from
846 the file, so that it is faster
847 @param filtertuple a tuple that contains
848 ("TheKeyToBeFiltered",relationship,value)
849 where relationship = "<", "==", or ">"
850 @param get_every only read every Nth line from the file
851 @param statistics if provided, accumulate statistics in an
852 OutputStatistics object
855 if statistics
is None:
863 rh = RMF.open_rmf_file_read_only(self.filename)
864 nframes=rh.get_number_of_frames()
865 for i
in range(nframes):
866 statistics.total += 1
868 statistics.passed_get_every += 1
869 statistics.passed_filterout += 1
871 if not filtertuple
is None:
872 keytobefiltered = filtertuple[0]
873 relationship = filtertuple[1]
874 value = filtertuple[2]
875 datavalue=rh.get_root_node().get_value(self.rmf_names_keys[keytobefiltered])
876 if self.isfiltered(datavalue,relationship,value):
continue
878 statistics.passed_filtertuple += 1
880 outdict[field].append(rh.get_root_node().get_value(self.rmf_names_keys[field]))
883 f = open(self.filename,
"r")
886 for line
in f.readlines():
887 statistics.total += 1
888 if not filterout
is None:
889 if filterout
in line:
891 statistics.passed_filterout += 1
894 if line_number % get_every != 0:
895 if line_number == 1
and self.isstat2:
896 statistics.total -= 1
897 statistics.passed_filterout -= 1
899 statistics.passed_get_every += 1
903 d = ast.literal_eval(line)
905 print(
"# Warning: skipped line number " + str(line_number) +
" not a valid line")
910 if not filtertuple
is None:
911 keytobefiltered = filtertuple[0]
912 relationship = filtertuple[1]
913 value = filtertuple[2]
914 datavalue=d[keytobefiltered]
915 if self.isfiltered(datavalue, relationship, value):
continue
917 statistics.passed_filtertuple += 1
918 [outdict[field].append(d[field])
for field
in fields]
922 statistics.total -= 1
923 statistics.passed_filterout -= 1
924 statistics.passed_get_every -= 1
927 if not filtertuple
is None:
928 keytobefiltered = filtertuple[0]
929 relationship = filtertuple[1]
930 value = filtertuple[2]
931 datavalue=d[self.invstat2_dict[keytobefiltered]]
932 if self.isfiltered(datavalue, relationship, value):
continue
934 statistics.passed_filtertuple += 1
935 [outdict[field].append(d[self.invstat2_dict[field]])
for field
in fields]
941 def isfiltered(self,datavalue,relationship,refvalue):
944 fdatavalue=float(datavalue)
946 raise ValueError(
"ProcessOutput.filter: datavalue cannot be converted into a float")
948 if relationship ==
"<":
949 if float(datavalue) >= refvalue:
951 if relationship ==
">":
952 if float(datavalue) <= refvalue:
954 if relationship ==
"==":
955 if float(datavalue) != refvalue:
961 """ class to allow more advanced handling of RMF files.
962 It is both a container and a IMP.atom.Hierarchy.
963 - it is iterable (while loading the corresponding frame)
964 - Item brackets [] load the corresponding frame
965 - slice create an iterator
966 - can relink to another RMF file
970 @param model: the IMP.Model()
971 @param rmf_file_name: str, path of the rmf file
975 self.rh_ref = RMF.open_rmf_file_read_only(rmf_file_name)
977 raise TypeError(
"Wrong rmf file name or type: %s"% str(rmf_file_name))
980 self.root_hier_ref = hs[0]
981 IMP.atom.Hierarchy.__init__(self, self.root_hier_ref)
983 self.ColorHierarchy=
None
988 Link to another RMF file
990 self.rh_ref = RMF.open_rmf_file_read_only(rmf_file_name)
992 if self.ColorHierarchy:
993 self.ColorHierarchy.method()
994 RMFHierarchyHandler.set_frame(self,0)
996 def set_frame(self,index):
1000 print(
"skipping frame %s:%d\n"%(self.current_rmf, index))
1004 return self.rh_ref.get_number_of_frames()
1006 def __getitem__(self,int_slice_adaptor):
1007 if type(int_slice_adaptor)
is int:
1008 self.set_frame(int_slice_adaptor)
1009 return int_slice_adaptor
1010 elif type(int_slice_adaptor)
is slice:
1011 return self.__iter__(int_slice_adaptor)
1013 raise TypeError(
"Unknown Type")
1016 return self.get_number_of_frames()
1018 def __iter__(self,slice_key=None):
1019 if slice_key
is None:
1020 for nframe
in range(len(self)):
1023 for nframe
in list(range(len(self)))[slice_key]:
1026 class CacheHierarchyCoordinates(object):
1027 def __init__(self,StatHierarchyHandler):
1034 self.current_index=
None
1035 self.rmfh=StatHierarchyHandler
1037 self.model=self.rmfh.get_model()
1042 self.nrms.append(nrm)
1045 self.xyzs.append(fb)
1047 def do_store(self,index):
1048 self.rb_trans[index]={}
1049 self.nrm_coors[index]={}
1050 self.xyz_coors[index]={}
1052 self.rb_trans[index][rb]=rb.get_reference_frame()
1053 for nrm
in self.nrms:
1054 self.nrm_coors[index][nrm]=nrm.get_internal_coordinates()
1055 for xyz
in self.xyzs:
1056 self.xyz_coors[index][xyz]=xyz.get_coordinates()
1057 self.current_index=index
1059 def do_update(self,index):
1060 if self.current_index!=index:
1062 rb.set_reference_frame(self.rb_trans[index][rb])
1063 for nrm
in self.nrms:
1064 nrm.set_internal_coordinates(self.nrm_coors[index][nrm])
1065 for xyz
in self.xyzs:
1066 xyz.set_coordinates(self.xyz_coors[index][xyz])
1067 self.current_index=index
1071 return len(self.rb_trans.keys())
1073 def __getitem__(self,index):
1074 if type(index)
is int:
1075 if index
in self.rb_trans.keys():
1080 raise TypeError(
"Unknown Type")
1083 return self.get_number_of_frames()
1089 """ class to link stat files to several rmf files """
1090 def __init__(self,model=None,stat_file=None,number_best_scoring_models=None,score_key=None,StatHierarchyHandler=None,cache=None):
1093 @param model: IMP.Model()
1094 @param stat_file: either 1) a list or 2) a single stat file names (either rmfs or ascii, or pickled data or pickled cluster), 3) a dictionary containing an rmf/ascii
1095 stat file name as key and a list of frames as values
1096 @param number_best_scoring_models:
1097 @param StatHierarchyHandler: copy constructor input object
1098 @param cache: cache coordinates and rigid body transformations.
1101 if not StatHierarchyHandler
is None:
1104 self.model=StatHierarchyHandler.model
1105 self.data=StatHierarchyHandler.data
1106 self.number_best_scoring_models=StatHierarchyHandler.number_best_scoring_models
1108 self.current_rmf=StatHierarchyHandler.current_rmf
1109 self.current_frame=
None
1110 self.current_index=
None
1111 self.score_threshold=StatHierarchyHandler.score_threshold
1112 self.score_key=StatHierarchyHandler.score_key
1113 self.cache=StatHierarchyHandler.cache
1114 RMFHierarchyHandler.__init__(self, self.model,self.current_rmf)
1116 self.cache=CacheHierarchyCoordinates(self)
1125 self.number_best_scoring_models=number_best_scoring_models
1128 if score_key
is None:
1129 self.score_key=
"Total_Score"
1131 self.score_key=score_key
1133 self.current_rmf=
None
1134 self.current_frame=
None
1135 self.current_index=
None
1136 self.score_threshold=
None
1138 if type(stat_file)
is str:
1139 self.add_stat_file(stat_file)
1140 elif type(stat_file)
is list:
1142 self.add_stat_file(f)
1144 def add_stat_file(self,stat_file):
1146 import cPickle
as pickle
1151 '''check that it is not a pickle file with saved data from a previous calculation'''
1152 self.load_data(stat_file)
1154 if self.number_best_scoring_models:
1155 scores = self.get_scores()
1156 max_score = sorted(scores)[0:min(len(self), self.number_best_scoring_models)][-1]
1157 self.do_filter_by_score(max_score)
1159 except pickle.UnpicklingError:
1160 '''alternatively read the ascii stat files'''
1162 scores,rmf_files,rmf_frame_indexes,features = self.get_info_from_stat_file(stat_file, self.score_threshold)
1167 rh = RMF.open_rmf_file_read_only(stat_file)
1168 nframes = rh.get_number_of_frames()
1169 scores=[0.0]*nframes
1170 rmf_files=[stat_file]*nframes
1171 rmf_frame_indexes=range(nframes)
1177 if len(set(rmf_files)) > 1:
1178 raise (
"Multiple RMF files found")
1181 print(
"StatHierarchyHandler: Error: Trying to set none as rmf_file (probably empty stat file), aborting")
1184 for n,index
in enumerate(rmf_frame_indexes):
1185 featn_dict=dict([(k,features[k][n])
for k
in features])
1188 if self.number_best_scoring_models:
1189 scores=self.get_scores()
1190 max_score=sorted(scores)[0:min(len(self),self.number_best_scoring_models)][-1]
1191 self.do_filter_by_score(max_score)
1193 if not self.is_setup:
1194 RMFHierarchyHandler.__init__(self, self.model,self.get_rmf_names()[0])
1196 self.cache=CacheHierarchyCoordinates(self)
1200 self.current_rmf=self.get_rmf_names()[0]
1204 def save_data(self,filename='data.pkl'):
1206 import cPickle
as pickle
1209 fl=open(filename,
'wb')
1210 pickle.dump(self.data,fl)
1212 def load_data(self,filename='data.pkl'):
1214 import cPickle
as pickle
1217 fl=open(filename,
'rb')
1218 data_structure=pickle.load(fl)
1220 if not type(data_structure)
is list:
1221 raise TypeError(
"%filename should contain a list of IMP.pmi1.output.DataEntry or IMP.pmi1.output.Cluster" % filename)
1224 self.data=data_structure
1227 for cluster
in data_structure:
1228 nmodels+=len(cluster)
1229 self.data=[
None]*nmodels
1230 for cluster
in data_structure:
1231 for n,data
in enumerate(cluster):
1232 index=cluster.members[n]
1233 self.data[index]=data
1235 raise TypeError(
"%filename should contain a list of IMP.pmi1.output.DataEntry or IMP.pmi1.output.Cluster" % filename)
1237 def set_frame(self,index):
1238 if self.cache
is not None and self.cache[index]:
1239 self.cache.do_update(index)
1241 nm=self.data[index].rmf_name
1242 fidx=self.data[index].rmf_index
1243 if nm != self.current_rmf:
1246 self.current_frame=-1
1247 if fidx!=self.current_frame:
1248 RMFHierarchyHandler.set_frame(self, fidx)
1249 self.current_frame=fidx
1250 if self.cache
is not None:
1251 self.cache.do_store(index)
1253 self.current_index = index
1255 def __getitem__(self,int_slice_adaptor):
1256 if type(int_slice_adaptor)
is int:
1257 self.set_frame(int_slice_adaptor)
1258 return self.data[int_slice_adaptor]
1259 elif type(int_slice_adaptor)
is slice:
1260 return self.__iter__(int_slice_adaptor)
1262 raise TypeError(
"Unknown Type")
1265 return len(self.data)
1267 def __iter__(self,slice_key=None):
1268 if slice_key
is None:
1269 for i
in range(len(self)):
1272 for i
in range(len(self))[slice_key]:
1275 def do_filter_by_score(self,maximum_score):
1276 self.data=[d
for d
in self.data
if d.score<=maximum_score]
1278 def get_scores(self):
1279 return [d.score
for d
in self.data]
1281 def get_feature_series(self,feature_name):
1282 return [d.features[feature_name]
for d
in self.data]
1284 def get_feature_names(self):
1285 return self.data[0].features.keys()
1287 def get_rmf_names(self):
1288 return [d.rmf_name
for d
in self.data]
1290 def get_stat_files_names(self):
1291 return [d.stat_file
for d
in self.data]
1293 def get_rmf_indexes(self):
1294 return [d.rmf_index
for d
in self.data]
1296 def get_info_from_stat_file(self, stat_file, score_threshold=None):
1300 score_key=self.score_key,
1302 rmf_file_key=
"rmf_file",
1303 rmf_file_frame_key=
"rmf_frame_index",
1304 prefiltervalue=score_threshold,
1309 scores = [float(y)
for y
in models[2]]
1310 rmf_files = models[0]
1311 rmf_frame_indexes = models[1]
1313 return scores, rmf_files, rmf_frame_indexes,features
1318 A class to store data associated to a model
1320 def __init__(self,stat_file=None,rmf_name=None,rmf_index=None,score=None,features=None):
1321 self.rmf_name=rmf_name
1322 self.rmf_index=rmf_index
1324 self.features=features
1325 self.stat_file=stat_file
1328 s=
"IMP.pmi1.output.DataEntry\n"
1329 s+=
"---- stat file %s \n"%(self.stat_file)
1330 s+=
"---- rmf file %s \n"%(self.rmf_name)
1331 s+=
"---- rmf index %s \n"%(str(self.rmf_index))
1332 s+=
"---- score %s \n"%(str(self.score))
1333 s+=
"---- number of features %s \n"%(str(len(self.features.keys())))
1339 A container for models organized into clusters
1341 def __init__(self,cid=None):
1345 self.center_index=
None
1346 self.members_data={}
1348 def add_member(self,index,data=None):
1349 self.members.append(index)
1350 self.members_data[index]=data
1351 self.average_score=self.compute_score()
1353 def compute_score(self):
1355 score=sum([d.score
for d
in self])/len(self)
1356 except AttributeError:
1361 s=
"IMP.pmi1.output.Cluster\n"
1362 s+=
"---- cluster_id %s \n"%str(self.cluster_id)
1363 s+=
"---- precision %s \n"%str(self.precision)
1364 s+=
"---- average score %s \n"%str(self.average_score)
1365 s+=
"---- number of members %s \n"%str(len(self.members))
1366 s+=
"---- center index %s \n"%str(self.center_index)
1369 def __getitem__(self,int_slice_adaptor):
1370 if type(int_slice_adaptor)
is int:
1371 index=self.members[int_slice_adaptor]
1372 return self.members_data[index]
1373 elif type(int_slice_adaptor)
is slice:
1374 return self.__iter__(int_slice_adaptor)
1376 raise TypeError(
"Unknown Type")
1379 return len(self.members)
1381 def __iter__(self,slice_key=None):
1382 if slice_key
is None:
1383 for i
in range(len(self)):
1386 for i
in range(len(self))[slice_key]:
1389 def __add__(self, other):
1390 self.members+=other.members
1391 self.members_data.update(other.members_data)
1392 self.average_score=self.compute_score()
1394 self.center_index=
None
1398 def plot_clusters_populations(clusters):
1401 for cluster
in clusters:
1402 indexes.append(cluster.cluster_id)
1403 populations.append(len(cluster))
1405 import matplotlib.pyplot
as plt
1406 fig, ax = plt.subplots()
1407 ax.bar(indexes, populations, 0.5, color=
'r') #, yerr=men_std)
1408 ax.set_ylabel('Population')
1409 ax.set_xlabel((
'Cluster index'))
1412 def plot_clusters_precisions(clusters):
1415 for cluster
in clusters:
1416 indexes.append(cluster.cluster_id)
1418 prec=cluster.precision
1419 print(cluster.cluster_id,prec)
1422 precisions.append(prec)
1424 import matplotlib.pyplot
as plt
1425 fig, ax = plt.subplots()
1426 ax.bar(indexes, precisions, 0.5, color=
'r') #, yerr=men_std)
1427 ax.set_ylabel('Precision [A]')
1428 ax.set_xlabel((
'Cluster index'))
1431 def plot_clusters_scores(clusters):
1434 for cluster
in clusters:
1435 indexes.append(cluster.cluster_id)
1437 for data
in cluster:
1438 values[-1].append(data.score)
1441 valuename=
"Scores", positionname=
"Cluster index", xlabels=
None,scale_plot_length=1.0)
1443 class CrossLinkIdentifierDatabase(object):
1447 def check_key(self,key):
1448 if key
not in self.clidb:
1451 def set_unique_id(self,key,value):
1453 self.clidb[key][
"XLUniqueID"]=str(value)
1455 def set_protein1(self,key,value):
1457 self.clidb[key][
"Protein1"]=str(value)
1459 def set_protein2(self,key,value):
1461 self.clidb[key][
"Protein2"]=str(value)
1463 def set_residue1(self,key,value):
1465 self.clidb[key][
"Residue1"]=int(value)
1467 def set_residue2(self,key,value):
1469 self.clidb[key][
"Residue2"]=int(value)
1471 def set_idscore(self,key,value):
1473 self.clidb[key][
"IDScore"]=float(value)
1475 def set_state(self,key,value):
1477 self.clidb[key][
"State"]=int(value)
1479 def set_sigma1(self,key,value):
1481 self.clidb[key][
"Sigma1"]=str(value)
1483 def set_sigma2(self,key,value):
1485 self.clidb[key][
"Sigma2"]=str(value)
1487 def set_psi(self,key,value):
1489 self.clidb[key][
"Psi"]=str(value)
1491 def get_unique_id(self,key):
1492 return self.clidb[key][
"XLUniqueID"]
1494 def get_protein1(self,key):
1495 return self.clidb[key][
"Protein1"]
1497 def get_protein2(self,key):
1498 return self.clidb[key][
"Protein2"]
1500 def get_residue1(self,key):
1501 return self.clidb[key][
"Residue1"]
1503 def get_residue2(self,key):
1504 return self.clidb[key][
"Residue2"]
1506 def get_idscore(self,key):
1507 return self.clidb[key][
"IDScore"]
1509 def get_state(self,key):
1510 return self.clidb[key][
"State"]
1512 def get_sigma1(self,key):
1513 return self.clidb[key][
"Sigma1"]
1515 def get_sigma2(self,key):
1516 return self.clidb[key][
"Sigma2"]
1518 def get_psi(self,key):
1519 return self.clidb[key][
"Psi"]
1521 def set_float_feature(self,key,value,feature_name):
1523 self.clidb[key][feature_name]=float(value)
1525 def set_int_feature(self,key,value,feature_name):
1527 self.clidb[key][feature_name]=int(value)
1529 def set_string_feature(self,key,value,feature_name):
1531 self.clidb[key][feature_name]=str(value)
1533 def get_feature(self,key,feature_name):
1534 return self.clidb[key][feature_name]
1536 def write(self,filename):
1538 with open(filename,
'wb')
as handle:
1539 pickle.dump(self.clidb,handle)
1541 def load(self,filename):
1543 with open(filename,
'rb')
as handle:
1544 self.clidb=pickle.load(handle)
1546 def plot_fields(fields, framemin=None, framemax=None):
1547 import matplotlib
as mpl
1549 import matplotlib.pyplot
as plt
1551 plt.rc(
'lines', linewidth=4)
1552 fig, axs = plt.subplots(nrows=len(fields))
1553 fig.set_size_inches(10.5, 5.5 * len(fields))
1554 plt.rc(
'axes', color_cycle=[
'r'])
1558 if framemin
is None:
1560 if framemax
is None:
1561 framemax = len(fields[key])
1562 x = list(range(framemin, framemax))
1563 y = [float(y)
for y
in fields[key][framemin:framemax]]
1566 axs[n].set_title(key, size=
"xx-large")
1567 axs[n].tick_params(labelsize=18, pad=10)
1570 axs.set_title(key, size=
"xx-large")
1571 axs.tick_params(labelsize=18, pad=10)
1575 plt.subplots_adjust(hspace=0.3)
1580 name, values_lists, valuename=
None, bins=40, colors=
None, format=
"png",
1581 reference_xline=
None, yplotrange=
None, xplotrange=
None,normalized=
True,
1584 '''Plot a list of histograms from a value list.
1585 @param name the name of the plot
1586 @param value_lists the list of list of values eg: [[...],[...],[...]]
1587 @param valuename the y-label
1588 @param bins the number of bins
1589 @param colors If None, will use rainbow. Else will use specific list
1590 @param format output format
1591 @param reference_xline plot a reference line parallel to the y-axis
1592 @param yplotrange the range for the y-axis
1593 @param normalized whether the histogram is normalized or not
1594 @param leg_names names for the legend
1597 import matplotlib
as mpl
1599 import matplotlib.pyplot
as plt
1600 import matplotlib.cm
as cm
1601 fig = plt.figure(figsize=(18.0, 9.0))
1604 colors = cm.rainbow(np.linspace(0, 1, len(values_lists)))
1605 for nv,values
in enumerate(values_lists):
1607 if leg_names
is not None:
1612 [float(y)
for y
in values],
1615 normed=normalized,histtype=
'step',lw=4,
1619 plt.tick_params(labelsize=12, pad=10)
1620 if valuename
is None:
1621 plt.xlabel(name, size=
"xx-large")
1623 plt.xlabel(valuename, size=
"xx-large")
1624 plt.ylabel(
"Frequency", size=
"xx-large")
1626 if not yplotrange
is None:
1628 if not xplotrange
is None:
1629 plt.xlim(xplotrange)
1633 if not reference_xline
is None:
1640 plt.savefig(name +
"." + format, dpi=150, transparent=
True)
1645 valuename=
"None", positionname=
"None", xlabels=
None,scale_plot_length=1.0):
1647 Plot time series as boxplots.
1648 fields is a list of time series, positions are the x-values
1649 valuename is the y-label, positionname is the x-label
1652 import matplotlib
as mpl
1654 import matplotlib.pyplot
as plt
1655 from matplotlib.patches
import Polygon
1658 fig = plt.figure(figsize=(float(len(positions))*scale_plot_length, 5.0))
1659 fig.canvas.set_window_title(name)
1661 ax1 = fig.add_subplot(111)
1663 plt.subplots_adjust(left=0.1, right=0.990, top=0.95, bottom=0.4)
1665 bps.append(plt.boxplot(values, notch=0, sym=
'', vert=1,
1666 whis=1.5, positions=positions))
1668 plt.setp(bps[-1][
'boxes'], color=
'black', lw=1.5)
1669 plt.setp(bps[-1][
'whiskers'], color=
'black', ls=
":", lw=1.5)
1671 if frequencies
is not None:
1672 for n,v
in enumerate(values):
1673 plist=[positions[n]]*len(v)
1674 ax1.plot(plist, v,
'gx', alpha=0.7, markersize=7)
1677 if not xlabels
is None:
1678 ax1.set_xticklabels(xlabels)
1679 plt.xticks(rotation=90)
1680 plt.xlabel(positionname)
1681 plt.ylabel(valuename)
1683 plt.savefig(name+
".pdf",dpi=150)
1687 def plot_xy_data(x,y,title=None,out_fn=None,display=True,set_plot_yaxis_range=None,
1688 xlabel=
None,ylabel=
None):
1689 import matplotlib
as mpl
1691 import matplotlib.pyplot
as plt
1692 plt.rc(
'lines', linewidth=2)
1694 fig, ax = plt.subplots(nrows=1)
1695 fig.set_size_inches(8,4.5)
1696 if title
is not None:
1697 fig.canvas.set_window_title(title)
1700 ax.plot(x,y,color=
'r')
1701 if set_plot_yaxis_range
is not None:
1702 x1,x2,y1,y2=plt.axis()
1703 y1=set_plot_yaxis_range[0]
1704 y2=set_plot_yaxis_range[1]
1705 plt.axis((x1,x2,y1,y2))
1706 if title
is not None:
1708 if xlabel
is not None:
1709 ax.set_xlabel(xlabel)
1710 if ylabel
is not None:
1711 ax.set_ylabel(ylabel)
1712 if out_fn
is not None:
1713 plt.savefig(out_fn+
".pdf")
1718 def plot_scatter_xy_data(x,y,labelx="None",labely="None",
1719 xmin=
None,xmax=
None,ymin=
None,ymax=
None,
1720 savefile=
False,filename=
"None.eps",alpha=0.75):
1722 import matplotlib
as mpl
1724 import matplotlib.pyplot
as plt
1726 from matplotlib
import rc
1728 rc(
'font',**{
'family':
'sans-serif',
'sans-serif':[
'Helvetica']})
1731 fig, axs = plt.subplots(1)
1735 axs0.set_xlabel(labelx, size=
"xx-large")
1736 axs0.set_ylabel(labely, size=
"xx-large")
1737 axs0.tick_params(labelsize=18, pad=10)
1741 plot2.append(axs0.plot(x, y,
'o', color=
'k',lw=2, ms=0.1, alpha=alpha, c=
"w"))
1750 fig.set_size_inches(8.0, 8.0)
1751 fig.subplots_adjust(left=0.161, right=0.850, top=0.95, bottom=0.11)
1752 if (
not ymin
is None)
and (
not ymax
is None):
1753 axs0.set_ylim(ymin,ymax)
1754 if (
not xmin
is None)
and (
not xmax
is None):
1755 axs0.set_xlim(xmin,xmax)
1759 fig.savefig(filename, dpi=300)
1762 def get_graph_from_hierarchy(hier):
1766 (graph, depth, depth_dict) = recursive_graph(
1767 hier, graph, depth, depth_dict)
1770 node_labels_dict = {}
1772 for key
in depth_dict:
1773 node_size_dict = 10 / depth_dict[key]
1774 if depth_dict[key] < 3:
1775 node_labels_dict[key] = key
1777 node_labels_dict[key] =
""
1778 draw_graph(graph, labels_dict=node_labels_dict)
1781 def recursive_graph(hier, graph, depth, depth_dict):
1784 index = str(hier.get_particle().
get_index())
1785 name1 = nameh +
"|#" + index
1786 depth_dict[name1] = depth
1790 if len(children) == 1
or children
is None:
1792 return (graph, depth, depth_dict)
1796 (graph, depth, depth_dict) = recursive_graph(
1797 c, graph, depth, depth_dict)
1799 index = str(c.get_particle().
get_index())
1800 namec = nameh +
"|#" + index
1801 graph.append((name1, namec))
1804 return (graph, depth, depth_dict)
1807 def draw_graph(graph, labels_dict=None, graph_layout='spring',
1808 node_size=5, node_color=
None, node_alpha=0.3,
1809 node_text_size=11, fixed=
None, pos=
None,
1810 edge_color=
'blue', edge_alpha=0.3, edge_thickness=1,
1812 validation_edges=
None,
1813 text_font=
'sans-serif',
1816 import matplotlib
as mpl
1818 import networkx
as nx
1819 import matplotlib.pyplot
as plt
1820 from math
import sqrt, pi
1826 if type(edge_thickness)
is list:
1827 for edge,weight
in zip(graph,edge_thickness):
1828 G.add_edge(edge[0], edge[1], weight=weight)
1831 G.add_edge(edge[0], edge[1])
1833 if node_color==
None:
1834 node_color_rgb=(0,0,0)
1835 node_color_hex=
"000000"
1840 for node
in G.nodes():
1841 cctuple=cc.rgb(node_color[node])
1842 tmpcolor_rgb.append((cctuple[0]/255,cctuple[1]/255,cctuple[2]/255))
1843 tmpcolor_hex.append(node_color[node])
1844 node_color_rgb=tmpcolor_rgb
1845 node_color_hex=tmpcolor_hex
1848 if type(node_size)
is dict:
1850 for node
in G.nodes():
1851 size=sqrt(node_size[node])/pi*10.0
1852 tmpsize.append(size)
1855 for n,node
in enumerate(G.nodes()):
1856 color=node_color_hex[n]
1858 nx.set_node_attributes(G,
"graphics", {node : {
'type':
'ellipse',
'w': size,
'h': size,
'fill':
'#'+color,
'label': node}})
1859 nx.set_node_attributes(G,
"LabelGraphics", {node : {
'type':
'text',
'text':node,
'color':
'#000000',
'visible':
'true'}})
1861 for edge
in G.edges():
1862 nx.set_edge_attributes(G,
"graphics", {edge : {
'width': 1,
'fill':
'#000000'}})
1864 for ve
in validation_edges:
1866 if (ve[0],ve[1])
in G.edges():
1867 print(
"found forward")
1868 nx.set_edge_attributes(G,
"graphics", {ve : {
'width': 1,
'fill':
'#00FF00'}})
1869 elif (ve[1],ve[0])
in G.edges():
1870 print(
"found backward")
1871 nx.set_edge_attributes(G,
"graphics", {(ve[1],ve[0]) : {
'width': 1,
'fill':
'#00FF00'}})
1873 G.add_edge(ve[0], ve[1])
1875 nx.set_edge_attributes(G,
"graphics", {ve : {
'width': 1,
'fill':
'#FF0000'}})
1879 if graph_layout ==
'spring':
1881 graph_pos = nx.spring_layout(G,k=1.0/8.0,fixed=fixed,pos=pos)
1882 elif graph_layout ==
'spectral':
1883 graph_pos = nx.spectral_layout(G)
1884 elif graph_layout ==
'random':
1885 graph_pos = nx.random_layout(G)
1887 graph_pos = nx.shell_layout(G)
1891 nx.draw_networkx_nodes(G, graph_pos, node_size=node_size,
1892 alpha=node_alpha, node_color=node_color_rgb,
1894 nx.draw_networkx_edges(G, graph_pos, width=edge_thickness,
1895 alpha=edge_alpha, edge_color=edge_color)
1896 nx.draw_networkx_labels(
1897 G, graph_pos, labels=labels_dict, font_size=node_text_size,
1898 font_family=text_font)
1900 plt.savefig(out_filename)
1901 nx.write_gml(G,
'out.gml')
1909 from ipyD3
import d3object
1910 from IPython.display
import display
1912 d3 = d3object(width=800,
1917 title=
'Example table with d3js',
1918 desc=
'An example table created created with d3js with data generated with Python.')
2004 [72.0, 60.0, 60.0, 10.0, 120.0, 172.0, 1092.0, 675.0, 408.0, 360.0, 156.0, 100.0]]
2005 data = [list(i)
for i
in zip(*data)]
2006 sRows = [[
'January',
2018 sColumns = [[
'Prod {0}'.format(i)
for i
in range(1, 9)],
2019 [
None,
'',
None,
None,
'Group 1',
None,
None,
'Group 2']]
2020 d3.addSimpleTable(data,
2021 fontSizeCells=[12, ],
2024 sRowsMargins=[5, 50, 0],
2025 sColsMargins=[5, 20, 10],
2028 addOutsideBorders=-1,
2032 html = d3.render(mode=[
'html',
'show'])
class to link stat files to several rmf files
def get_prot_name_from_particle
Get the protein name from the particle.
static bool get_is_setup(const IMP::ParticleAdaptor &p)
atom::Hierarchies create_hierarchies(RMF::FileConstHandle fh, Model *m)
RMF::FrameID save_frame(RMF::FileHandle file, std::string name="")
Save the current state of the linked objects as a new RMF frame.
Collect statistics from ProcessOutput.get_fields().
static bool get_is_setup(const IMP::ParticleAdaptor &p)
A container for models organized into clusters.
Class for easy writing of PDBs, RMFs, and stat files.
Legacy PMI1 module to represent, score, sample and analyze models.
void handle_use_deprecated(std::string message)
Break in this method in gdb to find deprecated uses at runtime.
void write_pdb(const Selection &mhd, TextOutput out, unsigned int model=1)
Utility classes and functions for reading and storing PMI files.
def init_pdb
Init PDB Writing.
Base class for capturing a modeling protocol.
def plot_field_histogram
Plot a list of histograms from a value list.
static bool get_is_setup(Model *m, ParticleIndex pi)
std::string get_module_version()
Return the version of this module, as a string.
The standard decorator for manipulating molecular structures.
Ints get_index(const ParticlesTemp &particles, const Subset &subset, const Subsets &excluded)
int get_number_of_frames(const ::npctransport_proto::Assignment &config, double time_step)
A decorator for a particle representing an atom.
def link_to_rmf
Link to another RMF file.
class to allow more advanced handling of RMF files.
A class to store data associated to a model.
void load_frame(RMF::FileConstHandle file, RMF::FrameID frame)
Load the given RMF frame into the state of the linked objects.
A decorator for a particle with x,y,z coordinates.
void add_hierarchies(RMF::NodeHandle fh, const atom::Hierarchies &hs)
void add_geometries(RMF::NodeHandle parent, const display::GeometriesTemp &r)
Add geometries to a given parent node.
void add_restraints(RMF::NodeHandle fh, const Restraints &hs)
A decorator for a particle that is part of a rigid body but not rigid.
Display a segment connecting a pair of particles.
A decorator for a residue.
Basic functionality that is expected to be used by a wide variety of IMP users.
def get_best_models
Given a list of stat files, read them all and find the best models.
A class for reading stat files (either rmf or ascii v1 and v2)
def init_rmf
This function initialize an RMF file.
void link_hierarchies(RMF::FileConstHandle fh, const atom::Hierarchies &hs)
void add_geometry(RMF::FileHandle file, display::Geometry *r)
Add a single geometry to the file.
Functionality for loading, creating, manipulating and scoring atomic structures.
def get_fields
Get the desired field names, and return a dictionary.
Hierarchies get_leaves(const Selection &h)
def plot_fields_box_plots
Plot time series as boxplots.
static bool get_is_setup(const IMP::ParticleAdaptor &p)
std::string get_module_version()
Return the version of this module, as a string.
A decorator for a particle with x,y,z coordinates and a radius.