1 """@namespace IMP.pmi.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.pmi.representation.Representation.add_protocol_output()
47 IMP.pmi.topology.System.add_protocol_output() (for PMI 2).
49 @see IMP.pmi.mmcif.ProtocolOutput for a concrete subclass that outputs
56 if isinstance(elt, (tuple, list)):
57 for elt2
in _flatten(elt):
63 """Class for easy writing of PDBs, RMFs, and stat files
65 @note Model should be updated prior to writing outputs.
67 def __init__(self, ascii=True,atomistic=False):
68 self.dictionary_pdbs = {}
69 self.dictionary_rmfs = {}
70 self.dictionary_stats = {}
71 self.dictionary_stats2 = {}
72 self.best_score_list =
None
73 self.nbestscoring =
None
75 self.replica_exchange =
False
80 self.chainids =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
82 self.multi_chainids = _ChainIDs()
84 self.particle_infos_for_pdb = {}
85 self.atomistic=atomistic
89 """Get a list of all PDB files being output by this instance"""
90 return list(self.dictionary_pdbs.keys())
92 def get_rmf_names(self):
93 return list(self.dictionary_rmfs.keys())
95 def get_stat_names(self):
96 return list(self.dictionary_stats.keys())
98 def _init_dictchain(self, name, prot, multichar_chain=False):
99 self.dictchain[name] = {}
100 self.use_pmi2 =
False
105 self.atomistic =
True
106 for n,mol
in enumerate(IMP.atom.get_by_type(prot,IMP.atom.MOLECULE_TYPE)):
110 chainids = self.multi_chainids
if multichar_chain
else self.chainids
111 for n, i
in enumerate(self.dictionary_pdbs[name].get_children()):
112 self.dictchain[name][i.get_name()] = chainids[n]
116 @param name The PDB filename
117 @param prot The hierarchy to write to this pdb file
118 @note if the PDB name is 'System' then will use Selection to get molecules
120 flpdb = open(name,
'w')
122 self.dictionary_pdbs[name] = prot
123 self._init_dictchain(name, prot)
125 def write_psf(self,filename,name):
126 flpsf=open(filename,
'w')
127 flpsf.write(
"PSF CMAP CHEQ"+
"\n")
128 index_residue_pair_list={}
129 (particle_infos_for_pdb, geometric_center)=self.get_particle_infos_for_pdb_writing(name)
130 nparticles=len(particle_infos_for_pdb)
131 flpsf.write(str(nparticles)+
" !NATOM"+
"\n")
132 for n,p
in enumerate(particle_infos_for_pdb):
137 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))
140 if chain
not in index_residue_pair_list:
141 index_residue_pair_list[chain]=[(atom_index,resid)]
143 index_residue_pair_list[chain].append((atom_index,resid))
148 for chain
in sorted(index_residue_pair_list.keys()):
150 ls=index_residue_pair_list[chain]
152 ls=sorted(ls, key=
lambda tup: tup[1])
154 indexes=[x[0]
for x
in ls]
156 indexes_pairs+=list(IMP.pmi.tools.sublist_iterator(indexes,lmin=2,lmax=2))
157 nbonds=len(indexes_pairs)
158 flpsf.write(str(nbonds)+
" !NBOND: bonds"+
"\n")
161 for i
in range(0,len(indexes_pairs),4):
162 for bond
in indexes_pairs[i:i+4]:
163 flpsf.write(
'{0:8d}{1:8d}'.format(*bond))
166 del particle_infos_for_pdb
171 translate_to_geometric_center=
False,
172 write_all_residues_per_bead=
False):
174 flpdb = open(name,
'a')
176 flpdb = open(name,
'w')
178 (particle_infos_for_pdb,
179 geometric_center) = self.get_particle_infos_for_pdb_writing(name)
181 if not translate_to_geometric_center:
182 geometric_center = (0, 0, 0)
184 for n,tupl
in enumerate(particle_infos_for_pdb):
185 (xyz, atom_type, residue_type,
186 chain_id, residue_index, all_indexes, radius) = tupl
187 if atom_type
is None:
188 atom_type = IMP.atom.AT_CA
189 if ( (write_all_residues_per_bead)
and (all_indexes
is not None) ):
190 for residue_number
in all_indexes:
191 flpdb.write(IMP.atom.get_pdb_string((xyz[0] - geometric_center[0],
192 xyz[1] - geometric_center[1],
193 xyz[2] - geometric_center[2]),
194 n+1, atom_type, residue_type,
195 chain_id, residue_number,
' ',1.00,radius))
197 flpdb.write(IMP.atom.get_pdb_string((xyz[0] - geometric_center[0],
198 xyz[1] - geometric_center[1],
199 xyz[2] - geometric_center[2]),
200 n+1, atom_type, residue_type,
201 chain_id, residue_index,
' ',1.00,radius))
202 flpdb.write(
"ENDMDL\n")
205 del particle_infos_for_pdb
208 """Get the protein name from the particle.
209 This is done by traversing the hierarchy."""
214 p, self.dictchain[name])
216 def get_particle_infos_for_pdb_writing(self, name):
226 particle_infos_for_pdb = []
228 geometric_center = [0, 0, 0]
234 ps =
IMP.atom.Selection(self.dictionary_pdbs[name],resolution=0).get_selected_particles()
238 for n, p
in enumerate(ps):
241 if protname
not in resindexes_dict:
242 resindexes_dict[protname] = []
246 rt = residue.get_residue_type()
247 resind = residue.get_index()
251 geometric_center[0] += xyz[0]
252 geometric_center[1] += xyz[1]
253 geometric_center[2] += xyz[2]
255 particle_infos_for_pdb.append((xyz,
256 atomtype, rt, self.dictchain[name][protname], resind,
None, radius))
257 resindexes_dict[protname].append(resind)
262 resind = residue.get_index()
265 if resind
in resindexes_dict[protname]:
268 resindexes_dict[protname].append(resind)
269 rt = residue.get_residue_type()
272 geometric_center[0] += xyz[0]
273 geometric_center[1] += xyz[1]
274 geometric_center[2] += xyz[2]
276 particle_infos_for_pdb.append((xyz,
None,
277 rt, self.dictchain[name][protname], resind,
None, radius))
281 resind = resindexes[len(resindexes) // 2]
282 if resind
in resindexes_dict[protname]:
285 resindexes_dict[protname].append(resind)
289 geometric_center[0] += xyz[0]
290 geometric_center[1] += xyz[1]
291 geometric_center[2] += xyz[2]
293 particle_infos_for_pdb.append((xyz,
None,
294 rt, self.dictchain[name][protname], resind, resindexes, radius))
300 if len(resindexes) > 0:
301 resind = resindexes[len(resindexes) // 2]
304 geometric_center[0] += xyz[0]
305 geometric_center[1] += xyz[1]
306 geometric_center[2] += xyz[2]
308 particle_infos_for_pdb.append((xyz,
None,
309 rt, self.dictchain[name][protname], resind, resindexes, radius))
312 geometric_center = (geometric_center[0] / atom_count,
313 geometric_center[1] / atom_count,
314 geometric_center[2] / atom_count)
318 particle_infos_for_pdb = sorted(particle_infos_for_pdb,
319 key=
lambda x: (len(x[3]), x[3], x[4]))
321 return (particle_infos_for_pdb, geometric_center)
324 def write_pdbs(self, appendmode=True):
325 for pdb
in self.dictionary_pdbs.keys():
326 self.write_pdb(pdb, appendmode)
328 def init_pdb_best_scoring(self,
332 replica_exchange=
False):
336 self.suffixes.append(suffix)
337 self.replica_exchange = replica_exchange
338 if not self.replica_exchange:
342 self.best_score_list = []
346 self.best_score_file_name =
"best.scores.rex.py"
347 self.best_score_list = []
348 with open(self.best_score_file_name,
"w")
as best_score_file:
349 best_score_file.write(
350 "self.best_score_list=" + str(self.best_score_list) +
"\n")
352 self.nbestscoring = nbestscoring
353 for i
in range(self.nbestscoring):
354 name = suffix +
"." + str(i) +
".pdb"
355 flpdb = open(name,
'w')
357 self.dictionary_pdbs[name] = prot
358 self._init_dictchain(name, prot)
360 def write_pdb_best_scoring(self, score):
361 if self.nbestscoring
is None:
362 print(
"Output.write_pdb_best_scoring: init_pdb_best_scoring not run")
365 if self.replica_exchange:
367 exec(open(self.best_score_file_name).read())
369 if len(self.best_score_list) < self.nbestscoring:
370 self.best_score_list.append(score)
371 self.best_score_list.sort()
372 index = self.best_score_list.index(score)
373 for suffix
in self.suffixes:
374 for i
in range(len(self.best_score_list) - 2, index - 1, -1):
375 oldname = suffix +
"." + str(i) +
".pdb"
376 newname = suffix +
"." + str(i + 1) +
".pdb"
378 if os.path.exists(newname):
380 os.rename(oldname, newname)
381 filetoadd = suffix +
"." + str(index) +
".pdb"
382 self.write_pdb(filetoadd, appendmode=
False)
385 if score < self.best_score_list[-1]:
386 self.best_score_list.append(score)
387 self.best_score_list.sort()
388 self.best_score_list.pop(-1)
389 index = self.best_score_list.index(score)
390 for suffix
in self.suffixes:
391 for i
in range(len(self.best_score_list) - 1, index - 1, -1):
392 oldname = suffix +
"." + str(i) +
".pdb"
393 newname = suffix +
"." + str(i + 1) +
".pdb"
394 os.rename(oldname, newname)
395 filenametoremove = suffix + \
396 "." + str(self.nbestscoring) +
".pdb"
397 os.remove(filenametoremove)
398 filetoadd = suffix +
"." + str(index) +
".pdb"
399 self.write_pdb(filetoadd, appendmode=
False)
401 if self.replica_exchange:
403 with open(self.best_score_file_name,
"w")
as best_score_file:
404 best_score_file.write(
405 "self.best_score_list=" + str(self.best_score_list) +
'\n')
407 def init_rmf(self, name, hierarchies, rs=None, geometries=None, listofobjects=None):
409 This function initialize an RMF file
411 @param name the name of the RMF file
412 @param hierarchies the hiearchies to be included (it is a list)
413 @param rs optional, the restraint sets (it is a list)
414 @param geometries optional, the geometries (it is a list)
415 @param listofobjects optional, the list of objects for the stat (it is a list)
417 rh = RMF.create_rmf_file(name)
420 outputkey_rmfkey=
None
424 if geometries
is not None:
426 if listofobjects
is not None:
427 cat = rh.get_category(
"stat")
429 for l
in listofobjects:
430 if not "get_output" in dir(l):
431 raise ValueError(
"Output: object %s doesn't have get_output() method" % str(l))
432 output=l.get_output()
433 for outputkey
in output:
434 rmftag=RMF.string_tag
435 if type(output[outputkey])
is float:
437 elif type(output[outputkey])
is int:
439 elif type(output[outputkey])
is str:
440 rmftag = RMF.string_tag
442 rmftag = RMF.string_tag
443 rmfkey=rh.get_key(cat, outputkey, rmftag)
444 outputkey_rmfkey[outputkey]=rmfkey
445 outputkey_rmfkey[
"rmf_file"]=rh.get_key(cat,
"rmf_file", RMF.string_tag)
446 outputkey_rmfkey[
"rmf_frame_index"]=rh.get_key(cat,
"rmf_frame_index", RMF.int_tag)
448 self.dictionary_rmfs[name] = (rh,cat,outputkey_rmfkey,listofobjects)
450 def add_restraints_to_rmf(self, name, objectlist):
451 for o
in _flatten(objectlist):
453 rs = o.get_restraint_for_rmf()
455 rs = o.get_restraint()
457 self.dictionary_rmfs[name][0],
460 def add_geometries_to_rmf(self, name, objectlist):
462 geos = o.get_geometries()
465 def add_particle_pair_from_restraints_to_rmf(self, name, objectlist):
468 pps = o.get_particle_pairs()
471 self.dictionary_rmfs[name][0],
474 def write_rmf(self, name):
476 if self.dictionary_rmfs[name][1]
is not None:
477 cat=self.dictionary_rmfs[name][1]
478 outputkey_rmfkey=self.dictionary_rmfs[name][2]
479 listofobjects=self.dictionary_rmfs[name][3]
480 for l
in listofobjects:
481 output=l.get_output()
482 for outputkey
in output:
483 rmfkey=outputkey_rmfkey[outputkey]
485 self.dictionary_rmfs[name][0].get_root_node().set_value(rmfkey,output[outputkey])
486 except NotImplementedError:
488 rmfkey = outputkey_rmfkey[
"rmf_file"]
489 self.dictionary_rmfs[name][0].get_root_node().set_value(rmfkey, name)
490 rmfkey = outputkey_rmfkey[
"rmf_frame_index"]
492 self.dictionary_rmfs[name][0].get_root_node().set_value(rmfkey, nframes-1)
493 self.dictionary_rmfs[name][0].flush()
495 def close_rmf(self, name):
496 rh = self.dictionary_rmfs[name][0]
497 del self.dictionary_rmfs[name]
500 def write_rmfs(self):
501 for rmfinfo
in self.dictionary_rmfs.keys():
502 self.write_rmf(rmfinfo[0])
504 def init_stat(self, name, listofobjects):
506 flstat = open(name,
'w')
509 flstat = open(name,
'wb')
513 for l
in listofobjects:
514 if not "get_output" in dir(l):
515 raise ValueError(
"Output: object %s doesn't have get_output() method" % str(l))
516 self.dictionary_stats[name] = listofobjects
518 def set_output_entry(self, key, value):
519 self.initoutput.update({key: value})
521 def write_stat(self, name, appendmode=True):
522 output = self.initoutput
523 for obj
in self.dictionary_stats[name]:
526 dfiltered = dict((k, v)
for k, v
in d.items()
if k[0] !=
"_")
527 output.update(dfiltered)
535 flstat = open(name, writeflag)
536 flstat.write(
"%s \n" % output)
539 flstat = open(name, writeflag +
'b')
540 cPickle.dump(output, flstat, 2)
543 def write_stats(self):
544 for stat
in self.dictionary_stats.keys():
545 self.write_stat(stat)
547 def get_stat(self, name):
549 for obj
in self.dictionary_stats[name]:
550 output.update(obj.get_output())
553 def write_test(self, name, listofobjects):
560 flstat = open(name,
'w')
561 output = self.initoutput
562 for l
in listofobjects:
563 if not "get_test_output" in dir(l)
and not "get_output" in dir(l):
564 raise ValueError(
"Output: object %s doesn't have get_output() or get_test_output() method" % str(l))
565 self.dictionary_stats[name] = listofobjects
567 for obj
in self.dictionary_stats[name]:
569 d = obj.get_test_output()
573 dfiltered = dict((k, v)
for k, v
in d.items()
if k[0] !=
"_")
574 output.update(dfiltered)
578 flstat.write(
"%s \n" % output)
581 def test(self, name, listofobjects, tolerance=1e-5):
582 output = self.initoutput
583 for l
in listofobjects:
584 if not "get_test_output" in dir(l)
and not "get_output" in dir(l):
585 raise ValueError(
"Output: object %s doesn't have get_output() or get_test_output() method" % str(l))
586 for obj
in listofobjects:
588 output.update(obj.get_test_output())
590 output.update(obj.get_output())
595 flstat = open(name,
'r')
599 test_dict = ast.literal_eval(l)
602 old_value = str(test_dict[k])
603 new_value = str(output[k])
611 fold = float(old_value)
612 fnew = float(new_value)
613 diff = abs(fold - fnew)
615 print(
"%s: test failed, old value: %s new value %s; "
616 "diff %f > %f" % (str(k), str(old_value),
617 str(new_value), diff,
618 tolerance), file=sys.stderr)
620 elif test_dict[k] != output[k]:
621 if len(old_value) < 50
and len(new_value) < 50:
622 print(
"%s: test failed, old value: %s new value %s"
623 % (str(k), old_value, new_value), file=sys.stderr)
626 print(
"%s: test failed, omitting results (too long)"
627 % str(k), file=sys.stderr)
631 print(
"%s from old objects (file %s) not in new objects"
632 % (str(k), str(name)), file=sys.stderr)
635 def get_environment_variables(self):
637 return str(os.environ)
639 def get_versions_of_relevant_modules(self):
646 except (ImportError):
650 versions[
"ISD2_VERSION"] = IMP.isd2.get_module_version()
651 except (ImportError):
655 versions[
"ISD_EMXL_VERSION"] = IMP.isd_emxl.get_module_version()
656 except (ImportError):
666 listofsummedobjects=
None):
672 if listofsummedobjects
is None:
673 listofsummedobjects = []
674 if extralabels
is None:
676 flstat = open(name,
'w')
678 stat2_keywords = {
"STAT2HEADER":
"STAT2HEADER"}
679 stat2_keywords.update(
680 {
"STAT2HEADER_ENVIRON": str(self.get_environment_variables())})
681 stat2_keywords.update(
682 {
"STAT2HEADER_IMP_VERSIONS": str(self.get_versions_of_relevant_modules())})
685 for l
in listofobjects:
686 if not "get_output" in dir(l):
687 raise ValueError(
"Output: object %s doesn't have get_output() method" % str(l))
691 dfiltered = dict((k, v)
692 for k, v
in d.items()
if k[0] !=
"_")
693 output.update(dfiltered)
696 for l
in listofsummedobjects:
698 if not "get_output" in dir(t):
699 raise ValueError(
"Output: object %s doesn't have get_output() method" % str(t))
701 if "_TotalScore" not in t.get_output():
702 raise ValueError(
"Output: object %s doesn't have _TotalScore entry to be summed" % str(t))
704 output.update({l[1]: 0.0})
706 for k
in extralabels:
707 output.update({k: 0.0})
709 for n, k
in enumerate(output):
710 stat2_keywords.update({n: k})
711 stat2_inverse.update({k: n})
713 flstat.write(
"%s \n" % stat2_keywords)
715 self.dictionary_stats2[name] = (
721 def write_stat2(self, name, appendmode=True):
723 (listofobjects, stat2_inverse, listofsummedobjects,
724 extralabels) = self.dictionary_stats2[name]
727 for obj
in listofobjects:
728 od = obj.get_output()
729 dfiltered = dict((k, v)
for k, v
in od.items()
if k[0] !=
"_")
731 output.update({stat2_inverse[k]: od[k]})
734 for l
in listofsummedobjects:
738 partial_score += float(d[
"_TotalScore"])
739 output.update({stat2_inverse[l[1]]: str(partial_score)})
742 for k
in extralabels:
743 if k
in self.initoutput:
744 output.update({stat2_inverse[k]: self.initoutput[k]})
746 output.update({stat2_inverse[k]:
"None"})
753 flstat = open(name, writeflag)
754 flstat.write(
"%s \n" % output)
757 def write_stats2(self):
758 for stat
in self.dictionary_stats2.keys():
759 self.write_stat2(stat)
763 """Collect statistics from ProcessOutput.get_fields().
764 Counters of the total number of frames read, plus the models that
765 passed the various filters used in get_fields(), are provided."""
768 self.passed_get_every = 0
769 self.passed_filterout = 0
770 self.passed_filtertuple = 0
774 """A class for reading stat files (either rmf or ascii v1 and v2)"""
775 def __init__(self, filename):
776 self.filename = filename
781 if self.filename
is None:
782 raise ValueError(
"No file name provided. Use -h for help")
786 rh = RMF.open_rmf_file_read_only(self.filename)
788 cat=rh.get_category(
'stat')
789 rmf_klist=rh.get_keys(cat)
790 self.rmf_names_keys=dict([(rh.get_name(k),k)
for k
in rmf_klist])
794 f = open(self.filename,
"r")
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.pmi.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
1036 rbs,xyzs=IMP.pmi.tools.get_rbs_and_beads([self.rmfh])
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)
1163 except (KeyError, SyntaxError):
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 with open(filename,
'wb')
as fl:
1210 pickle.dump(self.data, fl)
1212 def load_data(self,filename='data.pkl'):
1214 import cPickle
as pickle
1217 with open(filename,
'rb')
as fl:
1218 data_structure=pickle.load(fl)
1220 if not type(data_structure)
is list:
1221 raise TypeError(
"%filename should contain a list of IMP.pmi.output.DataEntry or IMP.pmi.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.pmi.output.DataEntry or IMP.pmi.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.pmi.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.pmi.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"
1837 cc=IMP.pmi.tools.ColorChange()
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'])
static bool get_is_setup(const IMP::ParticleAdaptor &p)
A container for models organized into clusters.
A class for reading stat files (either rmf or ascii v1 and v2)
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.
static bool get_is_setup(const IMP::ParticleAdaptor &p)
def plot_field_histogram
Plot a list of histograms from a value list.
def plot_fields_box_plots
Plot time series as boxplots.
Utility classes and functions for reading and storing PMI files.
def get_best_models
Given a list of stat files, read them all and find the best models.
A class to store data associated to a model.
void handle_use_deprecated(std::string message)
std::string get_module_version()
void write_pdb(const Selection &mhd, TextOutput out, unsigned int model=1)
Collect statistics from ProcessOutput.get_fields().
def get_fields
Get the desired field names, and return a dictionary.
static bool get_is_setup(Model *m, ParticleIndex pi)
def link_to_rmf
Link to another RMF file.
std::string get_molecule_name_and_copy(atom::Hierarchy h)
Walk up a PMI2 hierarchy/representations and get the "molname.copynum".
The standard decorator for manipulating molecular structures.
Ints get_index(const ParticlesTemp &particles, const Subset &subset, const Subsets &excluded)
def init_pdb
Init PDB Writing.
int get_number_of_frames(const ::npctransport_proto::Assignment &config, double time_step)
A decorator for a particle representing an atom.
Base class for capturing a modeling protocol.
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)
Class for easy writing of PDBs, RMFs, and stat files.
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.
bool get_is_canonical(atom::Hierarchy h)
Walk up a PMI2 hierarchy/representations and check if the root is named System.
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_pdb_names
Get a list of all PDB files being output by this instance.
def get_prot_name_from_particle
Get the protein name from the particle.
class to link stat files to several rmf files
class to allow more advanced handling of RMF files.
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.
Store info for a chain of a protein.
Python classes to represent, score, sample and analyze models.
Functionality for loading, creating, manipulating and scoring atomic structures.
Hierarchies get_leaves(const Selection &h)
Select hierarchy particles identified by the biological name.
def init_rmf
This function initialize an RMF file.
static bool get_is_setup(const IMP::ParticleAdaptor &p)
std::string get_module_version()
A decorator for a particle with x,y,z coordinates and a radius.