1 """@namespace IMP.pmi.output
2 Classes for writing output files and processing them.
5 from __future__
import print_function, division
17 import cPickle
as pickle
22 """Class for easy writing of PDBs, RMFs, and stat files"""
23 def __init__(self, ascii=True,atomistic=False):
24 self.dictionary_pdbs = {}
25 self.dictionary_rmfs = {}
26 self.dictionary_stats = {}
27 self.dictionary_stats2 = {}
28 self.best_score_list =
None
29 self.nbestscoring =
None
31 self.replica_exchange =
False
35 self.chainids =
"ABCDEFGHIJKLMNOPQRSTUVXYWZabcdefghijklmnopqrstuvxywz"
37 self.particle_infos_for_pdb = {}
38 self.atomistic=atomistic
40 def get_pdb_names(self):
41 return list(self.dictionary_pdbs.keys())
43 def get_rmf_names(self):
44 return list(self.dictionary_rmfs.keys())
46 def get_stat_names(self):
47 return list(self.dictionary_stats.keys())
49 def init_pdb(self, name, prot):
50 flpdb = open(name,
'w')
52 self.dictionary_pdbs[name] = prot
53 self.dictchain[name] = {}
55 for n, i
in enumerate(self.dictionary_pdbs[name].get_children()):
56 self.dictchain[name][i.get_name()] = self.chainids[n]
58 def write_psf(self,filename,name):
59 flpsf=open(filename,
'w')
60 flpsf.write(
"PSF CMAP CHEQ"+
"\n")
61 index_residue_pair_list={}
62 (particle_infos_for_pdb, geometric_center)=self.get_particle_infos_for_pdb_writing(name)
63 nparticles=len(particle_infos_for_pdb)
64 flpsf.write(str(nparticles)+
" !NATOM"+
"\n")
65 for n,p
in enumerate(particle_infos_for_pdb):
71 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))
74 if chain
not in index_residue_pair_list:
75 index_residue_pair_list[chain]=[(atom_index,resid)]
77 index_residue_pair_list[chain].append((atom_index,resid))
82 for chain
in sorted(index_residue_pair_list.keys()):
84 ls=index_residue_pair_list[chain]
86 ls=sorted(ls, key=
lambda tup: tup[1])
88 indexes=[x[0]
for x
in ls]
91 nbonds=len(indexes_pairs)
92 flpsf.write(str(nbonds)+
" !NBOND: bonds"+
"\n")
94 sublists=[indexes_pairs[i:i+4]
for i
in range(0,len(indexes_pairs),4)]
99 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],
100 ip[1][0],ip[1][1],ip[2][0],ip[2][1],ip[3][0],ip[3][1]))
102 flpsf.write(
'{0:8d}{1:8d}{2:8d}{3:8d}{4:8d}{5:8d}'.format(ip[0][0],ip[0][1],ip[1][0],
103 ip[1][1],ip[2][0],ip[2][1]))
105 flpsf.write(
'{0:8d}{1:8d}{2:8d}{3:8d}'.format(ip[0][0],ip[0][1],ip[1][0],ip[1][1]))
107 flpsf.write(
'{0:8d}{1:8d}'.format(ip[0][0],ip[0][1]))
110 del particle_infos_for_pdb
114 translate_to_geometric_center=
False):
116 flpdb = open(name,
'a')
118 flpdb = open(name,
'w')
120 (particle_infos_for_pdb,
121 geometric_center) = self.get_particle_infos_for_pdb_writing(name)
123 if not translate_to_geometric_center:
124 geometric_center = (0, 0, 0)
126 for n,tupl
in enumerate(particle_infos_for_pdb):
128 (xyz, atom_type, residue_type,
129 chain_id, residue_index,radius) = tupl
131 flpdb.write(IMP.atom.get_pdb_string((xyz[0] - geometric_center[0],
132 xyz[1] - geometric_center[1],
133 xyz[2] - geometric_center[2]),
134 n+1, atom_type, residue_type,
135 chain_id, residue_index,
' ',1.00,radius))
137 flpdb.write(
"ENDMDL\n")
140 del particle_infos_for_pdb
142 def get_particle_infos_for_pdb_writing(self, name):
152 particle_infos_for_pdb = []
154 geometric_center = [0, 0, 0]
164 p, self.dictchain[name])
166 if protname
not in resindexes_dict:
167 resindexes_dict[protname] = []
171 rt = residue.get_residue_type()
172 resind = residue.get_index()
176 geometric_center[0] += xyz[0]
177 geometric_center[1] += xyz[1]
178 geometric_center[2] += xyz[2]
180 particle_infos_for_pdb.append((xyz,
181 atomtype, rt, self.dictchain[name][protname], resind,radius))
182 resindexes_dict[protname].append(resind)
187 resind = residue.get_index()
190 if resind
in resindexes_dict[protname]:
193 resindexes_dict[protname].append(resind)
194 rt = residue.get_residue_type()
197 geometric_center[0] += xyz[0]
198 geometric_center[1] += xyz[1]
199 geometric_center[2] += xyz[2]
201 particle_infos_for_pdb.append((xyz,
202 IMP.atom.AT_CA, rt, self.dictchain[name][protname], resind,radius))
206 resind = resindexes[len(resindexes) // 2]
207 if resind
in resindexes_dict[protname]:
210 resindexes_dict[protname].append(resind)
214 geometric_center[0] += xyz[0]
215 geometric_center[1] += xyz[1]
216 geometric_center[2] += xyz[2]
218 particle_infos_for_pdb.append((xyz,
219 IMP.atom.AT_CA, rt, self.dictchain[name][protname], resind,radius))
225 resind = resindexes[len(resindexes) // 2]
228 geometric_center[0] += xyz[0]
229 geometric_center[1] += xyz[1]
230 geometric_center[2] += xyz[2]
232 particle_infos_for_pdb.append((xyz,
233 IMP.atom.AT_CA, rt, self.dictchain[name][protname], resind,radius))
236 geometric_center = (geometric_center[0] / atom_count,
237 geometric_center[1] / atom_count,
238 geometric_center[2] / atom_count)
240 particle_infos_for_pdb = sorted(particle_infos_for_pdb, key=operator.itemgetter(3, 4))
242 return (particle_infos_for_pdb, geometric_center)
245 def write_pdbs(self, appendmode=True):
246 for pdb
in self.dictionary_pdbs.keys():
247 self.write_pdb(pdb, appendmode)
249 def init_pdb_best_scoring(
254 replica_exchange=
False):
258 self.suffixes.append(suffix)
259 self.replica_exchange = replica_exchange
260 if not self.replica_exchange:
264 self.best_score_list = []
268 self.best_score_file_name =
"best.scores.rex.py"
269 self.best_score_list = []
270 best_score_file = open(self.best_score_file_name,
"w")
271 best_score_file.write(
272 "self.best_score_list=" + str(self.best_score_list))
273 best_score_file.close()
275 self.nbestscoring = nbestscoring
276 for i
in range(self.nbestscoring):
277 name = suffix +
"." + str(i) +
".pdb"
278 flpdb = open(name,
'w')
280 self.dictionary_pdbs[name] = prot
281 self.dictchain[name] = {}
282 for n, i
in enumerate(self.dictionary_pdbs[name].get_children()):
283 self.dictchain[name][i.get_name()] = self.chainids[n]
285 def write_pdb_best_scoring(self, score):
286 if self.nbestscoring
is None:
287 print(
"Output.write_pdb_best_scoring: init_pdb_best_scoring not run")
290 if self.replica_exchange:
292 exec(open(self.best_score_file_name).read())
294 if len(self.best_score_list) < self.nbestscoring:
295 self.best_score_list.append(score)
296 self.best_score_list.sort()
297 index = self.best_score_list.index(score)
298 for suffix
in self.suffixes:
299 for i
in range(len(self.best_score_list) - 2, index - 1, -1):
300 oldname = suffix +
"." + str(i) +
".pdb"
301 newname = suffix +
"." + str(i + 1) +
".pdb"
303 if os.path.exists(newname):
305 os.rename(oldname, newname)
306 filetoadd = suffix +
"." + str(index) +
".pdb"
307 self.write_pdb(filetoadd, appendmode=
False)
310 if score < self.best_score_list[-1]:
311 self.best_score_list.append(score)
312 self.best_score_list.sort()
313 self.best_score_list.pop(-1)
314 index = self.best_score_list.index(score)
315 for suffix
in self.suffixes:
316 for i
in range(len(self.best_score_list) - 1, index - 1, -1):
317 oldname = suffix +
"." + str(i) +
".pdb"
318 newname = suffix +
"." + str(i + 1) +
".pdb"
319 os.rename(oldname, newname)
320 filenametoremove = suffix + \
321 "." + str(self.nbestscoring) +
".pdb"
322 os.remove(filenametoremove)
323 filetoadd = suffix +
"." + str(index) +
".pdb"
324 self.write_pdb(filetoadd, appendmode=
False)
326 if self.replica_exchange:
328 best_score_file = open(self.best_score_file_name,
"w")
329 best_score_file.write(
330 "self.best_score_list=" + str(self.best_score_list))
331 best_score_file.close()
333 def init_rmf(self, name, hierarchies,rs=None):
334 rh = RMF.create_rmf_file(name)
338 self.dictionary_rmfs[name] = rh
340 def add_restraints_to_rmf(self, name, objectlist):
343 rs = o.get_restraint_for_rmf()
345 rs = o.get_restraint()
347 self.dictionary_rmfs[name],
350 def add_geometries_to_rmf(self, name, objectlist):
352 geos = o.get_geometries()
355 def add_particle_pair_from_restraints_to_rmf(self, name, objectlist):
358 pps = o.get_particle_pairs()
360 IMP.rmf.add_geometry(
361 self.dictionary_rmfs[name],
364 def write_rmf(self, name):
366 self.dictionary_rmfs[name].flush()
368 def close_rmf(self, name):
369 del self.dictionary_rmfs[name]
371 def write_rmfs(self):
372 for rmf
in self.dictionary_rmfs.keys():
375 def init_stat(self, name, listofobjects):
377 flstat = open(name,
'w')
380 flstat = open(name,
'wb')
384 for l
in listofobjects:
385 if not "get_output" in dir(l):
386 raise ValueError(
"Output: object %s doesn't have get_output() method" % str(l))
387 self.dictionary_stats[name] = listofobjects
389 def set_output_entry(self, key, value):
390 self.initoutput.update({key: value})
392 def write_stat(self, name, appendmode=True):
393 output = self.initoutput
394 for obj
in self.dictionary_stats[name]:
397 dfiltered = dict((k, v)
for k, v
in d.items()
if k[0] !=
"_")
398 output.update(dfiltered)
406 flstat = open(name, writeflag)
407 flstat.write(
"%s \n" % output)
410 flstat = open(name, writeflag +
'b')
411 cPickle.dump(output, flstat, 2)
414 def write_stats(self):
415 for stat
in self.dictionary_stats.keys():
416 self.write_stat(stat)
418 def get_stat(self, name):
420 for obj
in self.dictionary_stats[name]:
421 output.update(obj.get_output())
424 def write_test(self, name, listofobjects):
431 flstat = open(name,
'w')
432 output = self.initoutput
433 for l
in listofobjects:
434 if not "get_test_output" in dir(l)
and not "get_output" in dir(l):
435 raise ValueError(
"Output: object %s doesn't have get_output() or get_test_output() method" % str(l))
436 self.dictionary_stats[name] = listofobjects
438 for obj
in self.dictionary_stats[name]:
440 d = obj.get_test_output()
444 dfiltered = dict((k, v)
for k, v
in d.items()
if k[0] !=
"_")
445 output.update(dfiltered)
449 flstat.write(
"%s \n" % output)
452 def test(self, name, listofobjects, tolerance=1e-5):
453 output = self.initoutput
454 for l
in listofobjects:
455 if not "get_test_output" in dir(l)
and not "get_output" in dir(l):
456 raise ValueError(
"Output: object %s doesn't have get_output() or get_test_output() method" % str(l))
457 for obj
in listofobjects:
459 output.update(obj.get_test_output())
461 output.update(obj.get_output())
466 flstat = open(name,
'r')
473 old_value = str(test_dict[k])
474 new_value = str(output[k])
482 fold = float(old_value)
483 fnew = float(new_value)
484 diff = abs(fold - fnew)
486 print(
"%s: test failed, old value: %s new value %s; "
487 "diff %f > %f" % (str(k), str(old_value),
488 str(new_value), diff,
489 tolerance), file=sys.stderr)
491 elif test_dict[k] != output[k]:
492 if len(old_value) < 50
and len(new_value) < 50:
493 print(
"%s: test failed, old value: %s new value %s"
494 % (str(k), old_value, new_value), file=sys.stderr)
497 print(
"%s: test failed, omitting results (too long)"
498 % str(k), file=sys.stderr)
502 print(
"%s from old objects (file %s) not in new objects"
503 % (str(k), str(name)), file=sys.stderr)
506 def get_environment_variables(self):
508 return str(os.environ)
510 def get_versions_of_relevant_modules(self):
517 except (ImportError):
521 versions[
"ISD2_VERSION"] = IMP.isd2.get_module_version()
522 except (ImportError):
526 versions[
"ISD_EMXL_VERSION"] = IMP.isd_emxl.get_module_version()
527 except (ImportError):
537 listofsummedobjects=
None):
543 if listofsummedobjects
is None:
544 listofsummedobjects = []
545 if extralabels
is None:
547 flstat = open(name,
'w')
549 stat2_keywords = {
"STAT2HEADER":
"STAT2HEADER"}
550 stat2_keywords.update(
551 {
"STAT2HEADER_ENVIRON": str(self.get_environment_variables())})
552 stat2_keywords.update(
553 {
"STAT2HEADER_IMP_VERSIONS": str(self.get_versions_of_relevant_modules())})
556 for l
in listofobjects:
557 if not "get_output" in dir(l):
558 raise ValueError(
"Output: object %s doesn't have get_output() method" % str(l))
562 dfiltered = dict((k, v)
563 for k, v
in d.items()
if k[0] !=
"_")
564 output.update(dfiltered)
567 for l
in listofsummedobjects:
569 if not "get_output" in dir(t):
570 raise ValueError(
"Output: object %s doesn't have get_output() method" % str(t))
572 if "_TotalScore" not in t.get_output():
573 raise ValueError(
"Output: object %s doesn't have _TotalScore entry to be summed" % str(t))
575 output.update({l[1]: 0.0})
577 for k
in extralabels:
578 output.update({k: 0.0})
580 for n, k
in enumerate(output):
581 stat2_keywords.update({n: k})
582 stat2_inverse.update({k: n})
584 flstat.write(
"%s \n" % stat2_keywords)
586 self.dictionary_stats2[name] = (
592 def write_stat2(self, name, appendmode=True):
594 (listofobjects, stat2_inverse, listofsummedobjects,
595 extralabels) = self.dictionary_stats2[name]
598 for obj
in listofobjects:
599 od = obj.get_output()
600 dfiltered = dict((k, v)
for k, v
in od.items()
if k[0] !=
"_")
602 output.update({stat2_inverse[k]: od[k]})
605 for l
in listofsummedobjects:
609 partial_score += float(d[
"_TotalScore"])
610 output.update({stat2_inverse[l[1]]: str(partial_score)})
613 for k
in extralabels:
614 if k
in self.initoutput:
615 output.update({stat2_inverse[k]: self.initoutput[k]})
617 output.update({stat2_inverse[k]:
"None"})
624 flstat = open(name, writeflag)
625 flstat.write(
"%s \n" % output)
628 def write_stats2(self):
629 for stat
in self.dictionary_stats2.keys():
630 self.write_stat2(stat)
634 """A class for reading stat files"""
635 def __init__(self, filename):
636 self.filename = filename
641 if not self.filename
is None:
642 f = open(self.filename,
"r")
644 raise ValueError(
"No file name provided. Use -h for help")
647 for line
in f.readlines():
649 self.klist = list(d.keys())
651 if "STAT2HEADER" in self.klist:
654 if "STAT2HEADER" in str(k):
660 for k
in sorted(stat2_dict.items(), key=operator.itemgetter(1))]
662 for k
in sorted(stat2_dict.items(), key=operator.itemgetter(1))]
663 self.invstat2_dict = {}
665 self.invstat2_dict.update({stat2_dict[k]: k})
676 def show_keys(self, ncolumns=2, truncate=65):
677 IMP.pmi.tools.print_multicolumn(self.get_keys(), ncolumns, truncate)
679 def get_fields(self, fields, filtertuple=None, filterout=None, get_every=1):
681 Get the desired field names, and return a dictionary.
683 @param fields desired field names
684 @param filterout specify if you want to "grep" out something from
685 the file, so that it is faster
686 @param filtertuple a tuple that contains
687 ("TheKeyToBeFiltered",relationship,value)
688 where relationship = "<", "==", or ">"
689 @param get_every only read every Nth line from the file
697 f = open(self.filename,
"r")
700 for line
in f.readlines():
701 if not filterout
is None:
702 if filterout
in line:
706 if line_number % get_every != 0:
713 print(
"# Warning: skipped line number " + str(line_number) +
" not a valid line")
718 if not filtertuple
is None:
719 keytobefiltered = filtertuple[0]
720 relationship = filtertuple[1]
721 value = filtertuple[2]
722 if relationship ==
"<":
723 if float(d[keytobefiltered]) >= value:
725 if relationship ==
">":
726 if float(d[keytobefiltered]) <= value:
728 if relationship ==
"==":
729 if float(d[keytobefiltered]) != value:
731 [outdict[field].append(d[field])
for field
in fields]
737 if not filtertuple
is None:
738 keytobefiltered = filtertuple[0]
739 relationship = filtertuple[1]
740 value = filtertuple[2]
741 if relationship ==
"<":
742 if float(d[self.invstat2_dict[keytobefiltered]]) >= value:
744 if relationship ==
">":
745 if float(d[self.invstat2_dict[keytobefiltered]]) <= value:
747 if relationship ==
"==":
748 if float(d[self.invstat2_dict[keytobefiltered]]) != value:
751 [outdict[field].append(d[self.invstat2_dict[field]])
758 class CrossLinkIdentifierDatabase(object):
762 def check_key(self,key):
763 if key
not in self.clidb:
766 def set_unique_id(self,key,value):
768 self.clidb[key][
"XLUniqueID"]=str(value)
770 def set_protein1(self,key,value):
772 self.clidb[key][
"Protein1"]=str(value)
774 def set_protein2(self,key,value):
776 self.clidb[key][
"Protein2"]=str(value)
778 def set_residue1(self,key,value):
780 self.clidb[key][
"Residue1"]=int(value)
782 def set_residue2(self,key,value):
784 self.clidb[key][
"Residue2"]=int(value)
786 def set_idscore(self,key,value):
788 self.clidb[key][
"IDScore"]=float(value)
790 def set_state(self,key,value):
792 self.clidb[key][
"State"]=int(value)
794 def set_sigma1(self,key,value):
796 self.clidb[key][
"Sigma1"]=str(value)
798 def set_sigma2(self,key,value):
800 self.clidb[key][
"Sigma2"]=str(value)
802 def set_psi(self,key,value):
804 self.clidb[key][
"Psi"]=str(value)
806 def get_unique_id(self,key):
807 return self.clidb[key][
"XLUniqueID"]
809 def get_protein1(self,key):
810 return self.clidb[key][
"Protein1"]
812 def get_protein2(self,key):
813 return self.clidb[key][
"Protein2"]
815 def get_residue1(self,key):
816 return self.clidb[key][
"Residue1"]
818 def get_residue2(self,key):
819 return self.clidb[key][
"Residue2"]
821 def get_idscore(self,key):
822 return self.clidb[key][
"IDScore"]
824 def get_state(self,key):
825 return self.clidb[key][
"State"]
827 def get_sigma1(self,key):
828 return self.clidb[key][
"Sigma1"]
830 def get_sigma2(self,key):
831 return self.clidb[key][
"Sigma2"]
833 def get_psi(self,key):
834 return self.clidb[key][
"Psi"]
836 def set_float_feature(self,key,value,feature_name):
838 self.clidb[key][feature_name]=float(value)
840 def set_int_feature(self,key,value,feature_name):
842 self.clidb[key][feature_name]=int(value)
844 def set_string_feature(self,key,value,feature_name):
846 self.clidb[key][feature_name]=str(value)
848 def get_feature(self,key,feature_name):
849 return self.clidb[key][feature_name]
851 def write(self,filename):
853 with open(filename,
'wb')
as handle:
854 pickle.dump(self.clidb,handle)
856 def load(self,filename):
858 with open(filename,
'rb')
as handle:
859 self.clidb=pickle.load(handle)
861 def plot_fields(fields, framemin=None, framemax=None):
862 import matplotlib
as mpl
864 import matplotlib.pyplot
as plt
866 plt.rc(
'lines', linewidth=4)
867 fig, axs = plt.subplots(nrows=len(fields))
868 fig.set_size_inches(10.5, 5.5 * len(fields))
869 plt.rc(
'axes', color_cycle=[
'r'])
876 framemax = len(fields[key])
877 x = list(range(framemin, framemax))
878 y = [float(y)
for y
in fields[key][framemin:framemax]]
881 axs[n].set_title(key, size=
"xx-large")
882 axs[n].tick_params(labelsize=18, pad=10)
885 axs.set_title(key, size=
"xx-large")
886 axs.tick_params(labelsize=18, pad=10)
890 plt.subplots_adjust(hspace=0.3)
895 name, values_lists, valuename=
None, bins=40, colors=
None, format=
"png",
896 reference_xline=
None, yplotrange=
None, xplotrange=
None,normalized=
True,
899 '''Plot a list of histograms from a value list.
900 @param name the name of the plot
901 @param value_lists the list of list of values eg: [[...],[...],[...]]
902 @param valuename the y-label
903 @param bins the number of bins
904 @param colors If None, will use rainbow. Else will use specific list
905 @param format output format
906 @param reference_xline plot a reference line parallel to the y-axis
907 @param yplotrange the range for the y-axis
908 @param normalized whether the histogram is normalized or not
909 @param leg_names names for the legend
912 import matplotlib
as mpl
914 import matplotlib.pyplot
as plt
915 import matplotlib.cm
as cm
916 fig = plt.figure(figsize=(18.0, 9.0))
919 colors = cm.rainbow(np.linspace(0, 1, len(values_lists)))
920 for nv,values
in enumerate(values_lists):
922 if leg_names
is not None:
927 [float(y)
for y
in values],
930 normed=normalized,histtype=
'step',lw=4,
934 plt.tick_params(labelsize=12, pad=10)
935 if valuename
is None:
936 plt.xlabel(name, size=
"xx-large")
938 plt.xlabel(valuename, size=
"xx-large")
939 plt.ylabel(
"Frequency", size=
"xx-large")
941 if not yplotrange
is None:
943 if not xplotrange
is None:
948 if not reference_xline
is None:
955 plt.savefig(name +
"." + format, dpi=150, transparent=
True)
960 valuename=
"None", positionname=
"None", xlabels=
None,scale_plot_length=1.0):
962 Plot time series as boxplots.
963 fields is a list of time series, positions are the x-values
964 valuename is the y-label, positionname is the x-label
967 import matplotlib
as mpl
969 import matplotlib.pyplot
as plt
970 from matplotlib.patches
import Polygon
973 fig = plt.figure(figsize=(float(len(positions))*scale_plot_length, 5.0))
974 fig.canvas.set_window_title(name)
976 ax1 = fig.add_subplot(111)
978 plt.subplots_adjust(left=0.1, right=0.990, top=0.95, bottom=0.4)
980 bps.append(plt.boxplot(values, notch=0, sym=
'', vert=1,
981 whis=1.5, positions=positions))
983 plt.setp(bps[-1][
'boxes'], color=
'black', lw=1.5)
984 plt.setp(bps[-1][
'whiskers'], color=
'black', ls=
":", lw=1.5)
986 if frequencies
is not None:
987 for n,v
in enumerate(values):
988 plist=[positions[n]]*len(v)
989 ax1.plot(plist, v,
'gx', alpha=0.7, markersize=7)
992 if not xlabels
is None:
993 ax1.set_xticklabels(xlabels)
994 plt.xticks(rotation=90)
995 plt.xlabel(positionname)
996 plt.ylabel(valuename)
998 plt.savefig(name+
".pdf",dpi=150)
1002 def plot_xy_data(x,y,title=None,out_fn=None,display=True,set_plot_yaxis_range=None,
1003 xlabel=
None,ylabel=
None):
1004 import matplotlib
as mpl
1006 import matplotlib.pyplot
as plt
1007 plt.rc(
'lines', linewidth=2)
1009 fig, ax = plt.subplots(nrows=1)
1010 fig.set_size_inches(8,4.5)
1011 if title
is not None:
1012 fig.canvas.set_window_title(title)
1015 ax.plot(x,y,color=
'r')
1016 if set_plot_yaxis_range
is not None:
1017 x1,x2,y1,y2=plt.axis()
1018 y1=set_plot_yaxis_range[0]
1019 y2=set_plot_yaxis_range[1]
1020 plt.axis((x1,x2,y1,y2))
1021 if title
is not None:
1023 if xlabel
is not None:
1024 ax.set_xlabel(xlabel)
1025 if ylabel
is not None:
1026 ax.set_ylabel(ylabel)
1027 if out_fn
is not None:
1028 plt.savefig(out_fn+
".pdf")
1033 def plot_scatter_xy_data(x,y,labelx="None",labely="None",
1034 xmin=
None,xmax=
None,ymin=
None,ymax=
None,
1035 savefile=
False,filename=
"None.eps",alpha=0.75):
1037 import matplotlib
as mpl
1039 import matplotlib.pyplot
as plt
1041 from matplotlib
import rc
1043 rc(
'font',**{
'family':
'sans-serif',
'sans-serif':[
'Helvetica']})
1046 fig, axs = plt.subplots(1)
1050 axs0.set_xlabel(labelx, size=
"xx-large")
1051 axs0.set_ylabel(labely, size=
"xx-large")
1052 axs0.tick_params(labelsize=18, pad=10)
1056 plot2.append(axs0.plot(x, y,
'o', color=
'k',lw=2, ms=0.1, alpha=alpha, c=
"w"))
1065 fig.set_size_inches(8.0, 8.0)
1066 fig.subplots_adjust(left=0.161, right=0.850, top=0.95, bottom=0.11)
1067 if (
not ymin
is None)
and (
not ymax
is None):
1068 axs0.set_ylim(ymin,ymax)
1069 if (
not xmin
is None)
and (
not xmax
is None):
1070 axs0.set_xlim(xmin,xmax)
1074 fig.savefig(filename, dpi=300)
1077 def get_graph_from_hierarchy(hier):
1081 (graph, depth, depth_dict) = recursive_graph(
1082 hier, graph, depth, depth_dict)
1085 node_labels_dict = {}
1087 for key
in depth_dict:
1088 node_size_dict = 10 / depth_dict[key]
1089 if depth_dict[key] < 3:
1090 node_labels_dict[key] = key
1092 node_labels_dict[key] =
""
1093 draw_graph(graph, labels_dict=node_labels_dict)
1096 def recursive_graph(hier, graph, depth, depth_dict):
1099 index = str(hier.get_particle().
get_index())
1100 name1 = nameh +
"|#" + index
1101 depth_dict[name1] = depth
1105 if len(children) == 1
or children
is None:
1107 return (graph, depth, depth_dict)
1111 (graph, depth, depth_dict) = recursive_graph(
1112 c, graph, depth, depth_dict)
1114 index = str(c.get_particle().
get_index())
1115 namec = nameh +
"|#" + index
1116 graph.append((name1, namec))
1119 return (graph, depth, depth_dict)
1122 def draw_graph(graph, labels_dict=None, graph_layout='spring',
1123 node_size=5, node_color=
None, node_alpha=0.3,
1124 node_text_size=11, fixed=
None, pos=
None,
1125 edge_color=
'blue', edge_alpha=0.3, edge_thickness=1,
1127 validation_edges=
None,
1128 text_font=
'sans-serif',
1131 import matplotlib
as mpl
1133 import networkx
as nx
1134 import matplotlib.pyplot
as plt
1135 from math
import sqrt, pi
1141 if type(edge_thickness)
is list:
1142 for edge,weight
in zip(graph,edge_thickness):
1143 G.add_edge(edge[0], edge[1], weight=weight)
1146 G.add_edge(edge[0], edge[1])
1148 if node_color==
None:
1149 node_color_rgb=(0,0,0)
1150 node_color_hex=
"000000"
1155 for node
in G.nodes():
1156 cctuple=cc.rgb(node_color[node])
1157 tmpcolor_rgb.append((cctuple[0]/255,cctuple[1]/255,cctuple[2]/255))
1158 tmpcolor_hex.append(node_color[node])
1159 node_color_rgb=tmpcolor_rgb
1160 node_color_hex=tmpcolor_hex
1163 if type(node_size)
is dict:
1165 for node
in G.nodes():
1166 size=sqrt(node_size[node])/pi*10.0
1167 tmpsize.append(size)
1170 for n,node
in enumerate(G.nodes()):
1171 color=node_color_hex[n]
1173 nx.set_node_attributes(G,
"graphics", {node : {
'type':
'ellipse',
'w': size,
'h': size,
'fill':
'#'+color,
'label': node}})
1174 nx.set_node_attributes(G,
"LabelGraphics", {node : {
'type':
'text',
'text':node,
'color':
'#000000',
'visible':
'true'}})
1176 for edge
in G.edges():
1177 nx.set_edge_attributes(G,
"graphics", {edge : {
'width': 1,
'fill':
'#000000'}})
1179 for ve
in validation_edges:
1181 if (ve[0],ve[1])
in G.edges():
1182 print(
"found forward")
1183 nx.set_edge_attributes(G,
"graphics", {ve : {
'width': 1,
'fill':
'#00FF00'}})
1184 elif (ve[1],ve[0])
in G.edges():
1185 print(
"found backward")
1186 nx.set_edge_attributes(G,
"graphics", {(ve[1],ve[0]) : {
'width': 1,
'fill':
'#00FF00'}})
1188 G.add_edge(ve[0], ve[1])
1190 nx.set_edge_attributes(G,
"graphics", {ve : {
'width': 1,
'fill':
'#FF0000'}})
1194 if graph_layout ==
'spring':
1196 graph_pos = nx.spring_layout(G,k=1.0/8.0,fixed=fixed,pos=pos)
1197 elif graph_layout ==
'spectral':
1198 graph_pos = nx.spectral_layout(G)
1199 elif graph_layout ==
'random':
1200 graph_pos = nx.random_layout(G)
1202 graph_pos = nx.shell_layout(G)
1206 nx.draw_networkx_nodes(G, graph_pos, node_size=node_size,
1207 alpha=node_alpha, node_color=node_color_rgb,
1209 nx.draw_networkx_edges(G, graph_pos, width=edge_thickness,
1210 alpha=edge_alpha, edge_color=edge_color)
1211 nx.draw_networkx_labels(
1212 G, graph_pos, labels=labels_dict, font_size=node_text_size,
1213 font_family=text_font)
1215 plt.savefig(out_filename)
1216 nx.write_gml(G,
'out.gml')
1224 from ipyD3
import d3object
1225 from IPython.display
import display
1227 d3 = d3object(width=800,
1232 title=
'Example table with d3js',
1233 desc=
'An example table created created with d3js with data generated with Python.')
1319 [72.0, 60.0, 60.0, 10.0, 120.0, 172.0, 1092.0, 675.0, 408.0, 360.0, 156.0, 100.0]]
1320 data = [list(i)
for i
in zip(*data)]
1321 sRows = [[
'January',
1333 sColumns = [[
'Prod {0}'.format(i)
for i
in range(1, 9)],
1334 [
None,
'',
None,
None,
'Group 1',
None,
None,
'Group 2']]
1335 d3.addSimpleTable(data,
1336 fontSizeCells=[12, ],
1339 sRowsMargins=[5, 50, 0],
1340 sColsMargins=[5, 20, 10],
1343 addOutsideBorders=-1,
1347 html = d3.render(mode=[
'html',
'show'])
static bool get_is_setup(const IMP::ParticleAdaptor &p)
A class for reading stat files.
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.
std::string get_module_version()
void write_pdb(const Selection &mhd, TextOutput out, unsigned int model=1)
def get_fields
Get the desired field names, and return a dictionary.
static bool get_is_setup(Model *m, ParticleIndex pi)
The standard decorator for manipulating molecular structures.
Ints get_index(const ParticlesTemp &particles, const Subset &subset, const Subsets &excluded)
A decorator for a particle representing an atom.
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)
void add_restraints(RMF::NodeHandle fh, const Restraints &hs)
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.
Python classes to represent, score, sample and analyze models.
Functionality for loading, creating, manipulating and scoring atomic structures.
Hierarchies get_leaves(const Selection &h)
std::string get_module_version()
A decorator for a particle with x,y,z coordinates and a radius.