3 """@namespace IMP.pmi.tools
4 Miscellaneous utilities.
7 from __future__
import print_function
15 from math
import log,pi,sqrt,exp
21 from collections
import defaultdict
23 from collections
import OrderedDict
25 from IMP.pmi._compat_collections
import OrderedDict
27 def _get_restraint_set_key():
28 if not hasattr(_get_restraint_set_key,
'pmi_rs_key'):
29 _get_restraint_set_key.pmi_rs_key =
IMP.ModelKey(
"PMI restraints")
30 return _get_restraint_set_key.pmi_rs_key
32 def _add_restraint_set(model, mk):
34 model.add_data(mk, rs)
38 """Add a PMI restraint to the model.
39 Since Model.add_restraint() no longer exists (in modern IMP restraints
40 should be added to a ScoringFunction instead) store them instead in
41 a RestraintSet, and keep a reference to it in the Model."""
42 mk = _get_restraint_set_key()
43 if model.get_has_data(mk):
44 rs = IMP.RestraintSet.get_from(model.get_data(mk))
46 rs = _add_restraint_set(model, mk)
47 rs.add_restraint(restraint)
50 """Get a RestraintSet containing all PMI restraints added to the model"""
51 mk = _get_restraint_set_key()
52 if not model.get_has_data(mk):
53 print(
"WARNING: no restraints added to model yet")
54 _add_restraint_set(model, mk)
55 return IMP.RestraintSet.get_from(model.get_data(mk))
57 class Stopwatch(object):
59 def __init__(self, isdelta=True):
61 self.starttime = time.clock()
63 self.isdelta = isdelta
65 def set_label(self, labelstr):
71 newtime = time.clock()
75 "_delta_seconds"] = str(
78 self.starttime = newtime
80 output[
"Stopwatch_" + self.label +
81 "_elapsed_seconds"] = str(time.clock() - self.starttime)
85 class SetupNuisance(object):
87 def __init__(self, m, initialvalue, minvalue, maxvalue, isoptimized=True):
91 nuisance.set_lower(minvalue)
93 nuisance.set_upper(maxvalue)
96 nuisance.set_is_optimized(nuisance.get_nuisance_key(), isoptimized)
97 self.nuisance = nuisance
99 def get_particle(self):
103 class SetupWeight(object):
105 def __init__(self, m, isoptimized=True):
108 self.weight.set_weights_are_optimized(
True)
110 def get_particle(self):
114 class SetupSurface(object):
116 def __init__(self, m, center, normal, isoptimized=True):
119 self.surface.set_coordinates_are_optimized(isoptimized)
120 self.surface.set_normal_is_optimized(isoptimized)
122 def get_particle(self):
126 class ParticleToSampleFilter(object):
127 def __init__(self, sampled_objects):
128 self.sampled_objects=sampled_objects
131 def add_filter(self,filter_string):
132 self.filters.append(filter_string)
134 def get_particles_to_sample(self):
135 particles_to_sample={}
136 for so
in self.sampled_objects:
137 ps_dict=so.get_particles_to_sample()
139 for f
in self.filters:
141 if key
not in particles_to_sample:
142 particles_to_sample[key]=ps_dict[key]
144 particles_to_sample[key]+=ps_dict[key]
145 return particles_to_sample
147 class ParticleToSampleList(object):
149 def __init__(self, label="None"):
151 self.dictionary_particle_type = {}
152 self.dictionary_particle_transformation = {}
153 self.dictionary_particle_name = {}
160 particle_transformation,
162 if not particle_type
in [
"Rigid_Bodies",
"Floppy_Bodies",
"Nuisances",
"X_coord",
"Weights",
"Surfaces"]:
163 raise TypeError(
"not the right particle type")
165 self.dictionary_particle_type[particle] = particle_type
166 if particle_type ==
"Rigid_Bodies":
167 if type(particle_transformation) == tuple
and len(particle_transformation) == 2
and type(particle_transformation[0]) == float
and type(particle_transformation[1]) == float:
168 self.dictionary_particle_transformation[
169 particle] = particle_transformation
170 self.dictionary_particle_name[particle] = name
172 raise TypeError(
"ParticleToSampleList: not the right transformation format for Rigid_Bodies, should be a tuple of floats")
173 elif particle_type ==
"Surfaces":
174 if type(particle_transformation) == tuple
and len(particle_transformation) == 3
and all(isinstance(x, float)
for x
in particle_transformation):
175 self.dictionary_particle_transformation[
176 particle] = particle_transformation
177 self.dictionary_particle_name[particle] = name
179 raise TypeError(
"ParticleToSampleList: not the right transformation format for Surfaces, should be a tuple of floats")
181 if type(particle_transformation) == float:
182 self.dictionary_particle_transformation[
183 particle] = particle_transformation
184 self.dictionary_particle_name[particle] = name
186 raise TypeError(
"ParticleToSampleList: not the right transformation format, should be a float")
188 def get_particles_to_sample(self):
190 for particle
in self.dictionary_particle_type:
191 key = self.dictionary_particle_type[
192 particle] +
"ParticleToSampleList_" + self.dictionary_particle_name[particle] +
"_" + self.label
195 self.dictionary_particle_transformation[particle])
200 class Variance(object):
202 def __init__(self, model, tau, niter, prot, th_profile, write_data=False):
205 self.write_data = write_data
209 particles = IMP.atom.get_by_type(prot, IMP.atom.ATOM_TYPE)
210 self.particles = particles
212 self.refpos = [
IMP.core.XYZ(p).get_coordinates()
for p
in particles]
213 self.model_profile = th_profile
215 def perturb_particles(self, perturb=True):
216 for i, p
in enumerate(self.particles):
217 newpos = array(self.refpos[i])
219 newpos += random.normal(0, self.tau, 3)
223 def get_profile(self):
224 model_profile = self.model_profile
225 p = model_profile.calculate_profile(self.particles, IMP.saxs.CA_ATOMS)
226 return array([model_profile.get_intensity(i)
for i
in
227 range(model_profile.size())])
229 def init_variances(self):
231 N = self.model_profile.size()
232 a = self.profiles[0][:]
234 self.V = self.m * self.m.T
235 self.normm = linalg.norm(self.m)
236 self.normV = linalg.norm(self.V)
238 def update_variances(self):
239 a = matrix(self.profiles[-1])
240 n = float(len(self.profiles))
241 self.m = a.T / n + (n - 1) / n * self.m
242 self.V = a.T * a + self.V
243 self.oldnormm = self.normm
244 self.oldnormV = self.normV
245 self.normm = linalg.norm(self.m)
246 self.normV = linalg.norm(self.V)
247 self.diffm = (self.oldnormm - self.normm) / self.oldnormm
248 self.diffV = (self.oldnormV - self.normV) / self.oldnormV
250 def get_direct_stats(self, a):
255 for q, I
in enumerate(prof):
260 Sigma = (matrix(a - m))
261 Sigma = Sigma.T * Sigma / (nprof - 1)
262 mi = matrix(diag(1. / m))
263 Sigmarel = mi.T * Sigma * mi
264 return m, V, Sigma, Sigmarel
266 def store_data(self):
267 if not os.path.isdir(
'data'):
269 profiles = matrix(self.profiles)
270 self.directm, self.directV, self.Sigma, self.Sigmarel = \
271 self.get_direct_stats(array(profiles))
272 directV = self.directV
274 save(
'data/profiles', profiles)
276 fl = open(
'data/profiles.dat',
'w')
277 for i, l
in enumerate(array(profiles).T):
278 self.model_profile.get_q(i)
281 fl.write(
'%s ' % (k - self.directm[i]))
284 fl = open(
'data/profiles_rel.dat',
'w')
285 for i, l
in enumerate(array(profiles).T):
286 self.model_profile.get_q(i)
289 fl.write(
'%s ' % ((k - self.directm[i]) / self.directm[i]))
291 save(
'data/m', self.directm)
292 save(
'data/V', self.directV)
294 save(
'data/Sigma', Sigma)
296 fl = open(
'data/Sigma.dat',
'w')
297 model_profile = self.model_profile
298 for i
in range(model_profile.size()):
299 qi = model_profile.get_q(i)
300 for j
in range(model_profile.size()):
301 qj = model_profile.get_q(j)
302 vij = self.Sigma[i, j]
303 fl.write(
'%s %s %s\n' % (qi, qj, vij))
306 fl = open(
'data/eigenvals',
'w')
307 for i
in linalg.eigvalsh(Sigma):
309 Sigmarel = self.Sigmarel
310 save(
'data/Sigmarel', Sigmarel)
312 fl = open(
'data/Sigmarel.dat',
'w')
313 model_profile = self.model_profile
314 for i
in range(model_profile.size()):
315 qi = model_profile.get_q(i)
316 for j
in range(model_profile.size()):
317 qj = model_profile.get_q(j)
318 vij = self.Sigmarel[i, j]
319 fl.write(
'%s %s %s\n' % (qi, qj, vij))
322 fl = open(
'data/eigenvals_rel',
'w')
323 for i
in linalg.eigvalsh(Sigmarel):
326 fl = open(
'data/mean.dat',
'w')
327 for i
in range(len(self.directm)):
328 qi = self.model_profile.get_q(i)
330 fl.write(
'%s ' % self.directm[i])
331 fl.write(
'%s ' % sqrt(self.Sigma[i, i]))
334 def try_chol(self, jitter):
337 linalg.cholesky(Sigma + matrix(eye(len(Sigma))) * jitter)
338 except linalg.LinAlgError:
339 print(
"Decomposition failed with jitter =", jitter)
341 print(
"Successful decomposition with jitter =", jitter)
344 self.profiles = [self.get_profile()]
346 for n
in range(self.niter):
347 self.perturb_particles()
348 self.profiles.append(self.get_profile())
360 def get_cov(self, relative=True):
370 number_of_cross_links=10,
371 ambiguity_probability=0.1,
372 confidence_score_range=[0,100],
373 avoid_same_particles=
False):
374 '''Return a random cross-link dataset as a string.
375 Every line is a residue pair, together with UniqueIdentifier
378 residue_pairs=get_random_residue_pairs(representation, resolution, number_of_cross_links, avoid_same_particles=avoid_same_particles)
381 cmin=float(min(confidence_score_range))
382 cmax=float(max(confidence_score_range))
386 for (name1, r1, name2, r2)
in residue_pairs:
387 if random.random() > ambiguity_probability:
389 score=random.random()*(cmax-cmin)+cmin
390 dataset+=str(name1)+
" "+str(name2)+
" "+str(r1)+
" "+str(r2)+
" "+str(score)+
" "+str(unique_identifier)+
"\n"
397 def get_cross_link_data(directory, filename, dist, omega, sigma,
398 don=
None, doff=
None, prior=0, type_of_profile=
"gofr"):
400 (distmin, distmax, ndist) = dist
401 (omegamin, omegamax, nomega) = omega
402 (sigmamin, sigmamax, nsigma) = sigma
408 dictionary = eval(line)
411 xpot = dictionary[directory][filename][
"distance"]
412 pot = dictionary[directory][filename][type_of_profile]
414 dist_grid =
get_grid(distmin, distmax, ndist,
False)
415 omega_grid = get_log_grid(omegamin, omegamax, nomega)
416 sigma_grid = get_log_grid(sigmamin, sigmamax, nsigma)
418 if not don
is None and not doff
is None:
440 def get_cross_link_data_from_length(length, xxx_todo_changeme3, xxx_todo_changeme4, xxx_todo_changeme5):
441 (distmin, distmax, ndist) = xxx_todo_changeme3
442 (omegamin, omegamax, nomega) = xxx_todo_changeme4
443 (sigmamin, sigmamax, nsigma) = xxx_todo_changeme5
445 dist_grid =
get_grid(distmin, distmax, ndist,
False)
446 omega_grid = get_log_grid(omegamin, omegamax, nomega)
447 sigma_grid = get_log_grid(sigmamin, sigmamax, nsigma)
453 def get_grid(gmin, gmax, ngrid, boundaries):
455 dx = (gmax - gmin) / float(ngrid)
456 for i
in range(0, ngrid + 1):
457 if(
not boundaries
and i == 0):
459 if(
not boundaries
and i == ngrid):
461 grid.append(gmin + float(i) * dx)
467 def get_log_grid(gmin, gmax, ngrid):
469 for i
in range(0, ngrid + 1):
470 grid.append(gmin * exp(float(i) / ngrid * log(gmax / gmin)))
478 example '"{ID_Score}" > 28 AND "{Sample}" ==
479 "%10_1%" OR ":Sample}" == "%10_2%" OR ":Sample}"
480 == "%10_3%" OR ":Sample}" == "%8_1%" OR ":Sample}" == "%8_2%"'
483 import pyparsing
as pp
485 operator = pp.Regex(
">=|<=|!=|>|<|==|in").setName(
"operator")
486 value = pp.QuotedString(
488 r"[+-]?\d+(:?\.\d*)?(:?[eE][+-]?\d+)?")
489 identifier = pp.Word(pp.alphas, pp.alphanums +
"_")
490 comparison_term = identifier | value
491 condition = pp.Group(comparison_term + operator + comparison_term)
493 expr = pp.operatorPrecedence(condition, [
494 (
"OR", 2, pp.opAssoc.LEFT, ),
495 (
"AND", 2, pp.opAssoc.LEFT, ),
498 parsedstring = str(expr.parseString(inputstring)) \
504 .replace(
"{",
"float(entry['") \
505 .replace(
"}",
"'])") \
506 .replace(
":",
"str(entry['") \
507 .replace(
"}",
"'])") \
508 .replace(
"AND",
"and") \
513 def open_file_or_inline_text(filename):
515 fl = open(filename,
"r")
517 fl = filename.split(
"\n")
524 for i
in range(0, len(prot0) - 1):
525 for j
in range(i + 1, len(prot0)):
528 drmsd += (dist0 - dist1) ** 2
530 return math.sqrt(drmsd / npairs)
535 def get_ids_from_fasta_file(fastafile):
537 with open(fastafile)
as ff:
546 this function works with plain hierarchies, as read from the pdb,
547 no multi-scale hierarchies
554 atom_type=IMP.atom.AT_CA)
562 print(
"get_closest_residue_position: exiting while loop without result")
564 p = sel.get_selected_particles()
569 print(
"get_closest_residue_position: got NO residues for hierarchy %s and residue %i" % (hier, resindex))
570 raise Exception(
"get_closest_residue_position: got NO residues for hierarchy %s and residue %i" % (
573 raise ValueError(
"got multiple residues for hierarchy %s and residue %i; the list of particles is %s" % (hier, resindex, str([pp.get_name()
for pp
in p])))
578 Get the xyz position of the terminal residue at the given resolution.
579 @param hier hierarchy containing the terminal residue
580 @param terminus either 'N' or 'C'
581 @param resolution resolution to use.
589 if max(residues) >= termresidue
and not termresidue
is None:
590 termresidue = max(residues)
592 elif termresidue
is None:
593 termresidue = max(residues)
595 elif terminus ==
"N":
596 if min(residues) <= termresidue
and not termresidue
is None:
597 termresidue = min(residues)
599 elif termresidue
is None:
600 termresidue = min(residues)
603 raise ValueError(
"terminus argument should be either N or C")
609 Get the particle of the terminal residue at the GIVEN resolution
610 (NOTE: not the closest resolution!).
611 To get the terminal residue at the closest resolution use:
612 particles=IMP.pmi.tools.select_by_tuple(representation,molecule_name)
613 particles[0] and particles[-1] will be the first and last particles
614 corresponding to the two termini.
615 It is needed for instance to determine the last residue of a pdb.
616 @param hier hierarchy containing the terminal residue
617 @param terminus either 'N' or 'C'
618 @param resolution resolution to use.
624 resolution=resolution,
631 if termresidue
is None:
632 termresidue = max(residues)
634 elif max(residues) >= termresidue:
635 termresidue = max(residues)
637 elif terminus ==
"N":
638 if termresidue
is None:
639 termresidue = min(residues)
641 elif min(residues) <= termresidue:
642 termresidue = min(residues)
645 raise ValueError(
"terminus argument should be either N or C")
650 """Get XYZ coordinates of the terminal residue at the GIVEN resolution"""
656 Return the residue index gaps and contiguous segments in the hierarchy.
658 @param hierarchy hierarchy to examine
659 @param start first residue index
660 @param end last residue index
662 @return A list of lists of the form
663 [[1,100,"cont"],[101,120,"gap"],[121,200,"cont"]]
666 for n, rindex
in enumerate(range(start, end + 1)):
668 atom_type=IMP.atom.AT_CA)
670 if len(sel.get_selected_particles()) == 0:
674 rindexcont = start - 1
675 if rindexgap == rindex - 1:
681 gaps.append([rindex, rindex,
"gap"])
687 rindexgap = start - 1
689 if rindexcont == rindex - 1:
696 gaps.append([rindex, rindex,
"cont"])
707 def set_map_element(self, xvalue, yvalue):
708 self.map[xvalue] = yvalue
710 def get_map_element(self, invalue):
711 if type(invalue) == float:
715 dist = (invalue - x) * (invalue - x)
724 return self.map[minx]
725 elif type(invalue) == str:
726 return self.map[invalue]
728 raise TypeError(
"wrong type for map")
734 selection_arguments=
None,
736 name_is_ambiguous=
False,
740 representation_type=
None):
742 this function uses representation=SimplifiedModel
743 it returns the corresponding selected particles
744 representation_type="Beads", "Res:X", "Densities", "Representation", "Molecule"
747 if resolution
is None:
749 resolution_particles =
None
750 hierarchies_particles =
None
751 names_particles =
None
752 residue_range_particles =
None
753 residue_particles =
None
754 representation_type_particles =
None
756 if not resolution
is None:
757 resolution_particles = []
758 hs = representation.get_hierarchies_at_given_resolution(resolution)
762 if not hierarchies
is None:
763 hierarchies_particles = []
764 for h
in hierarchies:
769 if name_is_ambiguous:
770 for namekey
in representation.hier_dict:
773 representation.hier_dict[namekey])
774 elif name
in representation.hier_dict:
777 print(
"select: component %s is not there" % name)
779 if not first_residue
is None and not last_residue
is None:
781 residue_indexes=range(first_residue, last_residue + 1))
783 for p
in sel.get_selected_particles()]
785 if not residue
is None:
788 for p
in sel.get_selected_particles()]
790 if not representation_type
is None:
791 representation_type_particles = []
792 if representation_type ==
"Molecule":
793 for name
in representation.hier_representation:
794 for repr_type
in representation.hier_representation[name]:
795 if repr_type ==
"Beads" or "Res:" in repr_type:
796 h = representation.hier_representation[name][repr_type]
799 elif representation_type ==
"PDB":
800 for name
in representation.hier_representation:
801 for repr_type
in representation.hier_representation[name]:
802 if repr_type ==
"Res:" in repr_type:
803 h = representation.hier_representation[name][repr_type]
807 for name
in representation.hier_representation:
808 h = representation.hier_representation[
813 selections = [hierarchies_particles, names_particles,
814 residue_range_particles, residue_particles, representation_type_particles]
816 if resolution
is None:
817 selected_particles = set(allparticles)
819 selected_particles = set(resolution_particles)
823 selected_particles = (set(s) & selected_particles)
825 return list(selected_particles)
832 name_is_ambiguous=
False):
833 if isinstance(tupleselection, tuple)
and len(tupleselection) == 3:
835 name=tupleselection[2],
836 first_residue=tupleselection[0],
837 last_residue=tupleselection[1],
838 name_is_ambiguous=name_is_ambiguous)
839 elif isinstance(tupleselection, str):
842 name_is_ambiguous=name_is_ambiguous)
844 raise ValueError(
'you passed something bad to select_by_tuple()')
846 particles = IMP.pmi.tools.sort_by_residues(particles)
851 """New tuple format: molname OR (start,stop,molname,copynum,statenum)
852 Copy and state are optional. Can also use 'None' for them which will get all.
853 You can also pass -1 for stop which will go to the end.
854 Returns the particles
857 kwds[
'resolution'] = resolution
858 if type(tuple_selection)
is str:
859 kwds[
'molecule'] = tuple_selection
860 elif type(tuple_selection)
is tuple:
861 rbegin = tuple_selection[0]
862 rend = tuple_selection[1]
863 kwds[
'molecule'] = tuple_selection[2]
865 copynum = tuple_selection[3]
866 if copynum
is not None:
867 kwds[
'copy_index'] = copynum
871 statenum = tuple_selection[4]
872 if statenum
is not None:
873 kwds[
'state_index'] = statenum
880 residue_indexes=range(1,rbegin),
882 return s.get_selected_particles()
884 kwds[
'residue_indexes'] = range(rbegin,rend+1)
886 return s.get_selected_particles()
890 def get_db_from_csv(csvfilename):
893 with open(csvfilename)
as fh:
894 csvr = csv.DictReader(fh)
901 """Store the representations for a system."""
906 self.root_hierarchy_dict = {}
907 self.preroot_fragment_hierarchy_dict = {}
908 self.particle_to_name = {}
911 def add_name(self, name):
912 if name
not in self.db:
915 def add_residue_number(self, name, resn):
918 if resn
not in self.db[name]:
919 self.db[name][resn] = {}
921 def add_resolution(self, name, resn, resolution):
923 resolution = float(resolution)
925 self.add_residue_number(name, resn)
926 if resolution
not in self.db[name][resn]:
927 self.db[name][resn][resolution] = []
931 resolution = float(resolution)
933 self.add_residue_number(name, resn)
934 self.add_resolution(name, resn, resolution)
935 self.db[name][resn][resolution] += particles
937 (rh, prf) = self.get_root_hierarchy(p)
938 self.root_hierarchy_dict[p] = rh
939 self.preroot_fragment_hierarchy_dict[p] = prf
940 self.particle_to_name[p] = name
941 if self.model
is None:
942 self.model = particles[0].get_model()
948 names = list(self.db.keys())
954 resolution = float(resolution)
955 return self.db[name][resn][resolution]
957 def get_particles_at_closest_resolution(self, name, resn, resolution):
959 resolution = float(resolution)
960 closestres = min(self.get_residue_resolutions(name, resn),
961 key=
lambda x: abs(float(x) - float(resolution)))
962 return self.get_particles(name, resn, closestres)
964 def get_residue_resolutions(self, name, resn):
966 resolutions = list(self.db[name][resn].keys())
970 def get_molecule_resolutions(self, name):
972 for resn
in self.db[name]:
973 resolutions.update(list(self.db[name][resn].keys()))
977 def get_residue_numbers(self, name):
978 residue_numbers = list(self.db[name].keys())
979 residue_numbers.sort()
980 return residue_numbers
982 def get_particles_by_resolution(self, name, resolution):
983 resolution = float(resolution)
985 for resn
in self.get_residue_numbers(name):
986 result = self.get_particles_at_closest_resolution(
990 pstemp = [p
for p
in result
if p
not in particles]
994 def get_all_particles_by_resolution(self, resolution):
995 resolution = float(resolution)
997 for name
in self.get_names():
998 particles += self.get_particles_by_resolution(name, resolution)
1001 def get_root_hierarchy(self, particle):
1002 prerootfragment = particle
1012 prerootfragment = particle
1018 def get_all_root_hierarchies_by_resolution(self, resolution):
1020 resolution = float(resolution)
1021 particles = self.get_all_particles_by_resolution(resolution)
1023 rh = self.root_hierarchy_dict[p]
1024 if rh
not in hierarchies:
1028 def get_preroot_fragments_by_resolution(self, name, resolution):
1030 resolution = float(resolution)
1031 particles = self.get_particles_by_resolution(name, resolution)
1033 fr = self.preroot_fragment_hierarchy_dict[p]
1034 if fr
not in fragments:
1035 fragments.append(fr)
1038 def show(self, name):
1040 for resn
in self.get_residue_numbers(name):
1042 for resolution
in self.get_residue_resolutions(name, resn):
1043 print(
"----", resolution)
1044 for p
in self.get_particles(name, resn, resolution):
1045 print(
"--------", p.get_name())
1049 '''Return the component name provided a particle and a list of names'''
1051 protname = root.get_name()
1053 while not protname
in list_of_names:
1054 root0 = root.get_parent()
1057 protname = root0.get_name()
1062 if "Beads" in protname:
1065 return (protname, is_a_bead)
1070 Retrieve the residue indexes for the given particle.
1072 The particle must be an instance of Fragment,Residue or Atom
1073 or else returns an empty list
1088 def sort_by_residues(particles):
1091 sorted_particles_residues = sorted(
1093 key=
lambda tup: tup[1])
1094 particles = [p[0]
for p
in sorted_particles_residues]
1098 def get_residue_to_particle_map(particles):
1100 particles = sort_by_residues(particles)
1103 return dict(zip(particles_residues, particles))
1111 """Synchronize data over a parallel run"""
1112 from mpi4py
import MPI
1113 comm = MPI.COMM_WORLD
1114 rank = comm.Get_rank()
1115 number_of_processes = comm.size
1118 comm.send(data, dest=0, tag=11)
1121 for i
in range(1, number_of_processes):
1122 data_tmp = comm.recv(source=i, tag=11)
1123 if type(data) == list:
1125 elif type(data) == dict:
1126 data.update(data_tmp)
1128 raise TypeError(
"data not supported, use list or dictionaries")
1130 for i
in range(1, number_of_processes):
1131 comm.send(data, dest=i, tag=11)
1134 data = comm.recv(source=0, tag=11)
1138 """Synchronize data over a parallel run"""
1139 from mpi4py
import MPI
1140 comm = MPI.COMM_WORLD
1141 rank = comm.Get_rank()
1142 number_of_processes = comm.size
1145 comm.send(data, dest=0, tag=11)
1147 for i
in range(1, number_of_processes):
1148 data_tmp = comm.recv(source=i, tag=11)
1150 data[k]+=data_tmp[k]
1152 for i
in range(1, number_of_processes):
1153 comm.send(data, dest=i, tag=11)
1156 data = comm.recv(source=0, tag=11)
1166 Yield all sublists of length >= lmin and <= lmax
1174 for j
in range(i + 1, n):
1175 if len(l[i:j]) <= lmax
and len(l[i:j]) >= lmin:
1179 def flatten_list(l):
1180 return [item
for sublist
in l
for item
in sublist]
1184 """ Yield successive length-sized chunks from a list.
1186 for i
in range(0, len(list), length):
1187 yield list[i:i + length]
1190 def chunk_list_into_segments(seq, num):
1192 avg = len(seq) / float(num)
1196 while last < len(seq):
1197 out.append(seq[int(last):int(last + avg)])
1205 ''' This class stores integers
1206 in ordered compact lists eg:
1208 the methods help splitting and merging the internal lists
1210 s=Segments([1,2,3]) is [[1,2,3]]
1211 s.add(4) is [[1,2,3,4]] (add right)
1212 s.add(3) is [[1,2,3,4]] (item already existing)
1213 s.add(7) is [[1,2,3,4],[7]] (new list)
1214 s.add([8,9]) is [[1,2,3,4],[7,8,9]] (add item right)
1215 s.add([5,6]) is [[1,2,3,4,5,6,7,8,9]] (merge)
1216 s.remove(3) is [[1,2],[4,5,6,7,8,9]] (split)
1221 '''index can be a integer or a list of integers '''
1222 if type(index)
is int:
1224 elif type(index)
is list:
1225 self.segs=[[index[0]]]
1230 '''index can be a integer or a list of integers '''
1231 if type(index)
is int:
1234 for n,s
in enumerate(self.segs):
1242 if mergeright
is None and mergeleft
is None:
1243 self.segs.append([index])
1244 if not mergeright
is None and mergeleft
is None:
1245 self.segs[mergeright].append(index)
1246 if not mergeleft
is None and mergeright
is None:
1247 self.segs[mergeleft]=[index]+self.segs[mergeleft]
1248 if not mergeleft
is None and not mergeright
is None:
1249 self.segs[mergeright]=self.segs[mergeright]+[index]+self.segs[mergeleft]
1250 del self.segs[mergeleft]
1252 for n
in range(len(self.segs)):
1255 self.segs.sort(key=
lambda tup: tup[0])
1257 elif type(index)
is list:
1262 '''index can be a integer'''
1263 for n,s
in enumerate(self.segs):
1270 i=self.segs[n].index(index)
1272 self.segs.append(s[i+1:])
1273 for n
in range(len(self.segs)):
1275 if len(self.segs[n])==0:
1277 self.segs.sort(key=
lambda tup: tup[0])
1280 ''' Returns a flatten list '''
1281 return [item
for sublist
in self.segs
for item
in sublist]
1292 Apply a translation to a hierarchy along the input vector.
1296 if type(translation_vector) == list:
1315 def translate_hierarchies(hierarchies, translation_vector):
1316 for h
in hierarchies:
1320 def translate_hierarchies_to_reference_frame(hierarchies):
1325 for h
in hierarchies:
1335 IMP.pmi.tools.translate_hierarchies(hierarchies, (-xc, -yc, -zc))
1342 def normal_density_function(expected_value, sigma, x):
1344 1 / math.sqrt(2 * math.pi) / sigma *
1345 math.exp(-(x - expected_value) ** 2 / 2 / sigma / sigma)
1349 def log_normal_density_function(expected_value, sigma, x):
1351 1 / math.sqrt(2 * math.pi) / sigma / x *
1352 math.exp(-(math.log(x / expected_value) ** 2 / 2 / sigma / sigma))
1356 def get_random_residue_pairs(representation, resolution,
1359 avoid_same_particles=
False,
1364 names=list(representation.hier_dict.keys())
1367 prot = representation.hier_dict[name]
1368 particles +=
select(representation,name=name,resolution=resolution)
1369 random_residue_pairs = []
1370 while len(random_residue_pairs)<=number:
1371 p1 = random.choice(particles)
1372 p2 = random.choice(particles)
1373 if max_distance
is not None and \
1378 if r1==r2
and avoid_same_particles:
continue
1379 name1 = representation.get_prot_name_from_particle(p1)
1380 name2 = representation.get_prot_name_from_particle(p2)
1381 random_residue_pairs.append((name1, r1, name2, r2))
1383 return random_residue_pairs
1386 def get_random_data_point(
1392 begin_end_nbins_tuple,
1397 begin = begin_end_nbins_tuple[0]
1398 end = begin_end_nbins_tuple[1]
1399 nbins = begin_end_nbins_tuple[2]
1402 fmod_grid =
get_grid(begin, end, nbins,
True)
1404 fmod_grid = get_log_grid(begin, end, nbins)
1411 for i
in range(0, ntrials):
1412 a.append([random.random(),
True])
1415 for j
in range(1, len(fmod_grid)):
1417 fjm1 = fmod_grid[j - 1]
1421 pj = normal_density_function(expected_value, sigma, fj)
1422 pjm1 = normal_density_function(expected_value, sigma, fjm1)
1424 pj = log_normal_density_function(expected_value, sigma, fj)
1425 pjm1 = log_normal_density_function(expected_value, sigma, fjm1)
1427 norm += (pj + pjm1) / 2.0 * df
1433 for i
in range(len(cumul)):
1436 if (aa[0] <= cumul[i] / norm
and aa[1]):
1437 random_points.append(
1438 int(fmod_grid[i] / sensitivity) * sensitivity)
1442 random_points = [expected_value] * ntrials
1444 for i
in range(len(random_points)):
1445 if random.random() < outlierprob:
1446 a = random.uniform(begin, end)
1447 random_points[i] = int(a / sensitivity) * sensitivity
1448 print(random_points)
1450 for i in range(ntrials):
1451 if random.random() > OUTLIERPROB_:
1452 r=truncnorm.rvs(0.0,1.0,expected_value,BETA_)
1453 if r>1.0: print r,expected_value,BETA_
1456 random_points.append(int(r/sensitivity)*sensitivity)
1461 for r
in random_points:
1465 rmean /= float(ntrials)
1466 rmean2 /= float(ntrials)
1467 stddev = math.sqrt(max(rmean2 - rmean * rmean, 0.))
1468 return rmean, stddev
1470 def print_multicolumn(list_of_strings, ncolumns=2, truncate=40):
1476 for i
in range(len(l) % cols):
1479 split = [l[i:i + len(l) / cols]
for i
in range(0, len(l), len(l) / cols)]
1480 for row
in zip(*split):
1481 print(
"".join(str.ljust(i, truncate)
for i
in row))
1484 '''Change color code to hexadecimal to rgb'''
1486 self._NUMERALS =
'0123456789abcdefABCDEF'
1487 self._HEXDEC = dict((v, int(v, 16))
for v
in (x+y
for x
in self._NUMERALS
for y
in self._NUMERALS))
1488 self.LOWERCASE, self.UPPERCASE =
'x',
'X'
1490 def rgb(self,triplet):
1491 return float(self._HEXDEC[triplet[0:2]]), float(self._HEXDEC[triplet[2:4]]), float(self._HEXDEC[triplet[4:6]])
1493 def triplet(self,rgb, lettercase=None):
1494 if lettercase
is None: lettercase=self.LOWERCASE
1495 return format(rgb[0]<<16 | rgb[1]<<8 | rgb[2],
'06'+lettercase)
1499 class OrderedSet(collections.MutableSet):
1501 def __init__(self, iterable=None):
1503 end += [
None, end, end]
1505 if iterable
is not None:
1509 return len(self.map)
1511 def __contains__(self, key):
1512 return key
in self.map
1515 if key
not in self.map:
1518 curr[2] = end[1] = self.map[key] = [key, curr, end]
1520 def discard(self, key):
1522 key, prev, next = self.map.pop(key)
1529 while curr
is not end:
1533 def __reversed__(self):
1536 while curr
is not end:
1540 def pop(self, last=True):
1542 raise KeyError(
'set is empty')
1544 key = self.end[1][0]
1546 key = self.end[2][0]
1552 return '%s()' % (self.__class__.__name__,)
1553 return '%s(%r)' % (self.__class__.__name__, list(self))
1555 def __eq__(self, other):
1556 if isinstance(other, OrderedSet):
1557 return len(self) == len(other)
and list(self) == list(other)
1558 return set(self) == set(other)
1562 """Store objects in order they were added, but with default type.
1563 Source: http://stackoverflow.com/a/4127426/2608793
1565 def __init__(self, *args, **kwargs):
1567 self.default_factory =
None
1569 if not (args[0]
is None or callable(args[0])):
1570 raise TypeError(
'first argument must be callable or None')
1571 self.default_factory = args[0]
1573 super(OrderedDefaultDict, self).__init__(*args, **kwargs)
1575 def __missing__ (self, key):
1576 if self.default_factory
is None:
1578 self[key] = default = self.default_factory()
1581 def __reduce__(self):
1582 args = (self.default_factory,)
if self.default_factory
else ()
1583 return self.__class__, args,
None,
None, self.iteritems()
1588 """Extract frame from RMF file and fill coordinates. Must be identical topology.
1589 @param hier The (System) hierarchy to fill (e.g. after you've built it)
1590 @param rmf_fn The file to extract from
1591 @param frame_num The frame number to extract
1593 rh = RMF.open_rmf_file_read_only(rmf_fn)
1601 selection_tuple=
None,
1602 warn_about_slices=
True):
1603 """Adapt things for PMI (degrees of freedom, restraints, ...)
1604 Returns list of list of hierarchies, separated into Molecules if possible.
1605 (iterable of ^2) hierarchy -> returns input as list of list of hierarchies, only one entry.
1606 (iterable of ^2) PMI::System/State/Molecule/TempResidue ->
1607 returns residue hierarchies, grouped in molecules, at requested resolution
1608 @param stuff Can be one of the following inputs:
1609 IMP Hierarchy, PMI System/State/Molecule/TempResidue, or a list/set (of list/set) of them.
1610 Must be uniform input, however. No mixing object types.
1611 @param pmi_resolution For selecting, only does it if you pass PMI objects. Set it to "all"
1612 if you want all resolutions!
1613 @param flatten Set to True if you just want all hierarchies in one list.
1614 @param warn_about_slices Print a warning if you are requesting only part of a bead.
1615 Sometimes you just don't care!
1616 \note since this relies on IMP::atom::Selection, this will not return any objects if they weren't built!
1617 But there should be no problem if you request unbuilt residues, they should be ignored.
1621 def get_ok_iter(it):
1622 type_set = set(type(a)
for a
in it)
1623 if len(type_set)!=1:
1624 raise Exception(
'input_adaptor: can only pass one type of object at a time')
1625 xtp = type_set.pop()
1630 if hasattr(stuff,
'__iter__'):
1633 tp,thelist = get_ok_iter(stuff)
1636 if hasattr(next(iter(thelist)),
'__iter__'):
1637 flatlist = [i
for sublist
in thelist
for i
in sublist]
1638 tp,thelist = get_ok_iter(flatlist)
1654 for system
in stuff:
1655 for state
in system.get_states():
1656 mdict = state.get_molecules()
1657 for molname
in mdict:
1658 for copy
in mdict[molname]:
1659 indexes_per_mol[copy] += [r.get_index()
for r
in copy.get_residues()]
1662 mdict = state.get_molecules()
1663 for molname
in mdict:
1664 for copy
in mdict[molname]:
1665 indexes_per_mol[copy] += [r.get_index()
for r
in copy.get_residues()]
1667 for molecule
in stuff:
1668 indexes_per_mol[molecule] += [r.get_index()
for r
in molecule.get_residues()]
1670 for tempres
in stuff:
1671 indexes_per_mol[tempres.get_molecule()].append(tempres.get_index())
1672 for mol
in indexes_per_mol:
1673 if pmi_resolution==
'all':
1677 residue_indexes=indexes_per_mol[mol])
1680 resolution=pmi_resolution,
1681 residue_indexes=indexes_per_mol[mol])
1682 ps = sel.get_selected_particles()
1685 if warn_about_slices:
1686 rset = set(indexes_per_mol[mol])
1690 if not fset <= rset:
1697 resbreak = maxf
if minf==minset
else minset-1
1698 print(
'WARNING: You are trying to select only part of the bead %s:%i-%i.\n'
1699 'The residues you requested are %i-%i. You can fix this by:\n'
1700 '1) requesting the whole bead/none of it or\n'
1701 '2) break the bead up by passing bead_extra_breaks=[\'%i\'] in '
1702 'molecule.add_representation()'
1703 %(mol.get_name(),minset,maxset,minf,maxf,resbreak))
1713 raise Exception(
'input_adaptor: you passed something of type',tp)
1715 raise Exception(
'input_adaptor: you passed something of type',tp)
1717 if flatten
and pmi_input:
1718 return [h
for sublist
in hier_list
for h
in sublist]
1724 """Returns sequence-sorted segments array, each containing the first particle
1725 the last particle and the first residue index."""
1727 from operator
import itemgetter
1730 raise Exception(
"IMP.pmi.tools.get_sorted_segments: only pass stuff from one Molecule, please")
1746 SortedSegments.append((start, end, startres))
1747 SortedSegments = sorted(SortedSegments, key=itemgetter(2))
1748 return SortedSegments
1751 """Decorate the sequence-consecutive particles from a PMI2 molecule with a bond,
1752 so that they appear connected in the rmf file"""
1754 for x
in range(len(SortedSegments) - 1):
1756 last = SortedSegments[x][1]
1757 first = SortedSegments[x + 1][0]
1759 p1 = last.get_particle()
1760 p2 = first.get_particle()
1772 def get_residue_type_from_one_letter_code(code,is_nucleic=None):
1774 threetoone = {
'ALA':
'A',
'ARG':
'R', 'ASN': 'N', 'ASP': 'D',
1775 'CYS':
'C',
'GLU':
'E',
'GLN':
'Q',
'GLY':
'G',
1776 'HIS':
'H',
'ILE':
'I',
'LEU':
'L',
'LYS':
'K',
1777 'MET':
'M',
'PHE':
'F',
'PRO':
'P',
'SER':
'S',
1778 'THR':
'T',
'TRP':
'W',
'TYR':
'Y',
'VAL':
'V',
'UNK':
'X'}
1780 threetoone = {
'ADE':
'A',
'URA':
'U', 'CYT': 'C', 'GUA': 'G',
1781 'THY':
'T',
'UNK':
'X'}
1783 for k
in threetoone:
1784 one_to_three[threetoone[k]] = k
1789 """ Just get the leaves from a list of hierarchies """
1790 lvs = list(itertools.chain.from_iterable(
IMP.atom.get_leaves(item)
for item
in list_of_hs))
1797 """Perform selection using the usual keywords but return ALL resolutions (BEADS and GAUSSIANS).
1798 Returns in flat list!
1803 if hier
is not None:
1806 print(
"WARNING: You passed nothing to select_at_all_resolutions()")
1813 raise Exception(
'select_at_all_resolutions: you have to pass an IMP Hierarchy')
1815 raise Exception(
'select_at_all_resolutions: you have to pass an IMP Hierarchy')
1816 if 'resolution' in kwargs
or 'representation_type' in kwargs:
1817 raise Exception(
"don't pass resolution or representation_type to this function")
1819 representation_type=IMP.atom.BALLS,**kwargs)
1821 representation_type=IMP.atom.DENSITIES,**kwargs)
1822 ret |= OrderedSet(selB.get_selected_particles())
1823 ret |= OrderedSet(selD.get_selected_particles())
1832 """Utility to retrieve particles from a hierarchy within a
1833 zone around a set of ps.
1834 @param hier The hierarchy in which to look for neighbors
1835 @param target_ps The particles for zoning
1836 @param sel_zone The maximum distance
1837 @param entire_residues If True, will grab entire residues
1838 @param exclude_backbone If True, will only return sidechain particles
1842 backbone_types=[
'C',
'N',
'CB',
'O']
1843 if exclude_backbone:
1845 for n
in backbone_types])
1846 test_ps = test_sel.get_selected_particles()
1847 nn = IMP.algebra.NearestNeighbor3D([
IMP.core.XYZ(p).get_coordinates()
1850 for target
in target_ps:
1851 zone|=set(nn.get_in_ball(
IMP.core.XYZ(target).get_coordinates(),sel_zone))
1852 zone_ps = [test_ps[z]
for z
in zone]
1857 zone_ps = [h.get_particle()
for h
in final_ps]
1862 """Returns unique objects in original order"""
1866 if not hasattr(hiers,
'__iter__'):
1873 rbs_ordered.append(rb)
1878 rbs_ordered.append(rb)
1882 return rbs_ordered,beads
1886 """Given a list of PMI objects, return all density hierarchies within
1887 these objects. The output of this function can be inputted into
1888 things such as EM restraints.
1893 for i
in iter(stuff):
1894 densities.append(
IMP.atom.Selection(i,representation_type=IMP.atom.DENSITIES).get_selected_particles())
1895 except TypeError
as te:
1896 densities.append(
IMP.atom.Selection(stuff,representation_type=IMP.atom.DENSITIES).get_selected_particles())
1898 return [h
for sublist
in densities
for h
in sublist]
1901 max_translation=300., max_rotation=2.0 * pi,
1902 avoidcollision_rb=
True, avoidcollision_fb=
False,
1903 cutoff=10.0, niterations=100,
1905 excluded_rigid_bodies=[],
1906 hierarchies_excluded_from_collision=[],
1907 hierarchies_included_in_collision=[],
1909 """Shuffle particles. Used to restart the optimization.
1910 The configuration of the system is initialized by placing each
1911 rigid body and each bead randomly in a box with a side of
1912 max_translation angstroms, and far enough from each other to
1913 prevent any steric clashes. The rigid bodies are also randomly rotated.
1914 @param objects Can be one of the following inputs:
1915 IMP Hierarchy, PMI System/State/Molecule/TempResidue, or a list/set of them
1916 @param max_translation Max translation (rbs and flexible beads)
1917 @param max_rotation Max rotation (rbs only)
1918 @param avoidcollision_rb check if the particle/rigid body was
1919 placed close to another particle; uses the optional
1920 arguments cutoff and niterations
1921 @param avoidcollision_fb Advanced. Generally you want this False because it's hard to shuffle beads.
1922 @param cutoff Distance less than this is a collision
1923 @param niterations How many times to try avoiding collision
1924 @param bounding_box Only shuffle particles within this box. Defined by ((x1,y1,z1),(x2,y2,z2)).
1925 @param excluded_rigid_bodies Don't shuffle these rigid body objects
1926 @param hierarchies_excluded_from_collision Don't count collision with these bodies
1927 @param hierarchies_included_in_collision Hierarchies that are not shuffled, but should be included in collision calculation (for fixed regions)
1928 @param verbose Give more output
1929 \note Best to only call this function after you've set up degrees of freedom
1930 For debugging purposes, returns: <shuffled indexes>, <collision avoided indexes>
1935 pmi_resolution=
'all',
1938 if len(rigid_bodies)>0:
1939 mdl = rigid_bodies[0].get_model()
1940 elif len(flexible_beads)>0:
1941 mdl = flexible_beads[0].get_model()
1943 raise Exception(
"Could not find any particles in the hierarchy")
1944 if len(rigid_bodies) == 0:
1945 print(
"shuffle_configuration: rigid bodies were not intialized")
1949 gcpf.set_distance(cutoff)
1953 pmi_resolution=
'all',
1957 pmi_resolution=
'all',
1960 collision_excluded_idxs = set([l.get_particle().
get_index()
for h
in collision_excluded_hierarchies \
1963 collision_included_idxs = set([l.get_particle().
get_index()
for h
in collision_included_hierarchies \
1970 all_idxs.append(p.get_particle_index())
1972 collision_excluded_idxs.add(p.get_particle_index())
1974 print(len(all_idxs), len(collision_included_idxs), len(collision_excluded_idxs))
1976 if bounding_box
is not None:
1977 ((x1, y1, z1), (x2, y2, z2)) = bounding_box
1982 all_idxs = set(all_idxs) | collision_included_idxs
1983 all_idxs = all_idxs - collision_excluded_idxs
1984 print(len(all_idxs), len(collision_included_idxs), len(collision_excluded_idxs))
1986 print(
'shuffling', len(rigid_bodies),
'rigid bodies')
1987 for rb
in rigid_bodies:
1988 if rb
not in excluded_rigid_bodies:
1990 if avoidcollision_rb:
1991 rb_idxs = set(rb.get_member_particle_indexes()) - \
1992 collision_excluded_idxs
1993 other_idxs = all_idxs - rb_idxs
1994 print(
"----INOI", rb, len(other_idxs), len(rb_idxs))
2000 while niter < niterations:
2001 rbxyz = (rb.get_x(), rb.get_y(), rb.get_z())
2021 debug.append([rb, other_idxs
if avoidcollision_rb
else set()])
2026 if avoidcollision_rb:
2028 npairs = len(gcpf.get_close_pairs(mdl,
2037 print(
"shuffle_configuration: rigid body placed close to other %d particles, trying again..." % npairs)
2038 print(
"shuffle_configuration: rigid body name: " + rb.get_name())
2039 if niter == niterations:
2040 raise ValueError(
"tried the maximum number of iterations to avoid collisions, increase the distance cutoff")
2044 print(
'shuffling', len(flexible_beads),
'flexible beads')
2045 for fb
in flexible_beads:
2047 if avoidcollision_fb:
2049 other_idxs = all_idxs - fb_idxs
2055 while niter < niterations:
2068 xyz_transformed=transformation.get_transformed(xyz)
2071 fb.set_value(
IMP.FloatKey(4),xyz_transformed[0]-xyz[0])
2072 fb.set_value(
IMP.FloatKey(5),xyz_transformed[1]-xyz[1])
2073 fb.set_value(
IMP.FloatKey(6),xyz_transformed[2]-xyz[2])
2074 debug.append([xyz,other_idxs
if avoidcollision_fb
else set()])
2080 debug.append([xyz,other_idxs
if avoidcollision_fb
else set()])
2087 debug.append([d,other_idxs
if avoidcollision_fb
else set()])
2090 if avoidcollision_fb:
2092 npairs = len(gcpf.get_close_pairs(mdl,
2100 print(
"shuffle_configuration: floppy body placed close to other %d particles, trying again..." % npairs)
2101 if niter == niterations:
2102 raise ValueError(
"tried the maximum number of iterations to avoid collisions, increase the distance cutoff")
2108 """Given a chimera color name, return RGB"""
2109 d = {
'aquamarine': (0.4980392156862745, 1.0, 0.8313725490196079),
2110 'black': (0.0, 0.0, 0.0),
2111 'blue': (0.0, 0.0, 1.0),
2112 'brown': (0.6470588235294118, 0.16470588235294117, 0.16470588235294117),
2113 'chartreuse': (0.4980392156862745, 1.0, 0.0),
2114 'coral': (1.0, 0.4980392156862745, 0.3137254901960784),
2115 'cornflower blue': (0.39215686274509803, 0.5843137254901961, 0.9294117647058824),
2116 'cyan': (0.0, 1.0, 1.0),
2117 'dark cyan': (0.0, 0.5450980392156862, 0.5450980392156862),
2118 'dark gray': (0.6627450980392157, 0.6627450980392157, 0.6627450980392157),
2119 'dark green': (0.0, 0.39215686274509803, 0.0),
2120 'dark khaki': (0.7411764705882353, 0.7176470588235294, 0.4196078431372549),
2121 'dark magenta': (0.5450980392156862, 0.0, 0.5450980392156862),
2122 'dark olive green': (0.3333333333333333, 0.4196078431372549, 0.1843137254901961),
2123 'dark red': (0.5450980392156862, 0.0, 0.0),
2124 'dark slate blue': (0.2823529411764706, 0.23921568627450981, 0.5450980392156862),
2125 'dark slate gray': (0.1843137254901961, 0.30980392156862746, 0.30980392156862746),
2126 'deep pink': (1.0, 0.0784313725490196, 0.5764705882352941),
2127 'deep sky blue': (0.0, 0.7490196078431373, 1.0),
2128 'dim gray': (0.4117647058823529, 0.4117647058823529, 0.4117647058823529),
2129 'dodger blue': (0.11764705882352941, 0.5647058823529412, 1.0),
2130 'firebrick': (0.6980392156862745, 0.13333333333333333, 0.13333333333333333),
2131 'forest green': (0.13333333333333333, 0.5450980392156862, 0.13333333333333333),
2132 'gold': (1.0, 0.8431372549019608, 0.0),
2133 'goldenrod': (0.8549019607843137, 0.6470588235294118, 0.12549019607843137),
2134 'gray': (0.7450980392156863, 0.7450980392156863, 0.7450980392156863),
2135 'green': (0.0, 1.0, 0.0),
2136 'hot pink': (1.0, 0.4117647058823529, 0.7058823529411765),
2137 'khaki': (0.9411764705882353, 0.9019607843137255, 0.5490196078431373),
2138 'light blue': (0.6784313725490196, 0.8470588235294118, 0.9019607843137255),
2139 'light gray': (0.8274509803921568, 0.8274509803921568, 0.8274509803921568),
2140 'light green': (0.5647058823529412, 0.9333333333333333, 0.5647058823529412),
2141 'light sea green': (0.12549019607843137, 0.6980392156862745, 0.6666666666666666),
2142 'lime green': (0.19607843137254902, 0.803921568627451, 0.19607843137254902),
2143 'magenta': (1.0, 0.0, 1.0),
2144 'medium blue': (0.19607843137254902, 0.19607843137254902, 0.803921568627451),
2145 'medium purple': (0.5764705882352941, 0.4392156862745098, 0.8588235294117647),
2146 'navy blue': (0.0, 0.0, 0.5019607843137255),
2147 'olive drab': (0.4196078431372549, 0.5568627450980392, 0.13725490196078433),
2148 'orange red': (1.0, 0.27058823529411763, 0.0),
2149 'orange': (1.0, 0.4980392156862745, 0.0),
2150 'orchid': (0.8549019607843137, 0.4392156862745098, 0.8392156862745098),
2151 'pink': (1.0, 0.7529411764705882, 0.796078431372549),
2152 'plum': (0.8666666666666667, 0.6274509803921569, 0.8666666666666667),
2153 'purple': (0.6274509803921569, 0.12549019607843137, 0.9411764705882353),
2154 'red': (1.0, 0.0, 0.0),
2155 'rosy brown': (0.7372549019607844, 0.5607843137254902, 0.5607843137254902),
2156 'salmon': (0.9803921568627451, 0.5019607843137255, 0.4470588235294118),
2157 'sandy brown': (0.9568627450980393, 0.6431372549019608, 0.3764705882352941),
2158 'sea green': (0.1803921568627451, 0.5450980392156862, 0.3411764705882353),
2159 'sienna': (0.6274509803921569, 0.3215686274509804, 0.17647058823529413),
2160 'sky blue': (0.5294117647058824, 0.807843137254902, 0.9215686274509803),
2161 'slate gray': (0.4392156862745098, 0.5019607843137255, 0.5647058823529412),
2162 'spring green': (0.0, 1.0, 0.4980392156862745),
2163 'steel blue': (0.27450980392156865, 0.5098039215686274, 0.7058823529411765),
2164 'tan': (0.8235294117647058, 0.7058823529411765, 0.5490196078431373),
2165 'turquoise': (0.25098039215686274, 0.8784313725490196, 0.8156862745098039),
2166 'violet red': (0.8156862745098039, 0.12549019607843137, 0.5647058823529412),
2167 'white': (1.0, 1.0, 1.0),
2168 'yellow': (1.0, 1.0, 0.0)}
2174 "reds":[(
"maroon",
"#800000",(128,0,0)),(
"dark red",
"#8B0000",(139,0,0)),
2175 (
"brown",
"#A52A2A",(165,42,42)),(
"firebrick",
"#B22222",(178,34,34)),
2176 (
"crimson",
"#DC143C",(220,20,60)),(
"red",
"#FF0000",(255,0,0)),
2177 (
"tomato",
"#FF6347",(255,99,71)),(
"coral",
"#FF7F50",(255,127,80)),
2178 (
"indian red",
"#CD5C5C",(205,92,92)),(
"light coral",
"#F08080",(240,128,128)),
2179 (
"dark salmon",
"#E9967A",(233,150,122)),(
"salmon",
"#FA8072",(250,128,114)),
2180 (
"light salmon",
"#FFA07A",(255,160,122)),(
"orange red",
"#FF4500",(255,69,0)),
2181 (
"dark orange",
"#FF8C00",(255,140,0))],
2182 "yellows":[(
"orange",
"#FFA500",(255,165,0)),(
"gold",
"#FFD700",(255,215,0)),
2183 (
"dark golden rod",
"#B8860B",(184,134,11)),(
"golden rod",
"#DAA520",(218,165,32)),
2184 (
"pale golden rod",
"#EEE8AA",(238,232,170)),(
"dark khaki",
"#BDB76B",(189,183,107)),
2185 (
"khaki",
"#F0E68C",(240,230,140)),(
"olive",
"#808000",(128,128,0)),
2186 (
"yellow",
"#FFFF00",(255,255,0)),(
"antique white",
"#FAEBD7",(250,235,215)),
2187 (
"beige",
"#F5F5DC",(245,245,220)),(
"bisque",
"#FFE4C4",(255,228,196)),
2188 (
"blanched almond",
"#FFEBCD",(255,235,205)),(
"wheat",
"#F5DEB3",(245,222,179)),
2189 (
"corn silk",
"#FFF8DC",(255,248,220)),(
"lemon chiffon",
"#FFFACD",(255,250,205)),
2190 (
"light golden rod yellow",
"#FAFAD2",(250,250,210)),(
"light yellow",
"#FFFFE0",(255,255,224))],
2191 "greens":[(
"yellow green",
"#9ACD32",(154,205,50)),(
"dark olive green",
"#556B2F",(85,107,47)),
2192 (
"olive drab",
"#6B8E23",(107,142,35)),(
"lawn green",
"#7CFC00",(124,252,0)),
2193 (
"chart reuse",
"#7FFF00",(127,255,0)),(
"green yellow",
"#ADFF2F",(173,255,47)),
2194 (
"dark green",
"#006400",(0,100,0)),(
"green",
"#008000",(0,128,0)),
2195 (
"forest green",
"#228B22",(34,139,34)),(
"lime",
"#00FF00",(0,255,0)),
2196 (
"lime green",
"#32CD32",(50,205,50)),(
"light green",
"#90EE90",(144,238,144)),
2197 (
"pale green",
"#98FB98",(152,251,152)),(
"dark sea green",
"#8FBC8F",(143,188,143)),
2198 (
"medium spring green",
"#00FA9A",(0,250,154)),(
"spring green",
"#00FF7F",(0,255,127)),
2199 (
"sea green",
"#2E8B57",(46,139,87)),(
"medium aqua marine",
"#66CDAA",(102,205,170)),
2200 (
"medium sea green",
"#3CB371",(60,179,113)),(
"light sea green",
"#20B2AA",(32,178,170)),
2201 (
"dark slate gray",
"#2F4F4F",(47,79,79)),(
"teal",
"#008080",(0,128,128)),
2202 (
"dark cyan",
"#008B8B",(0,139,139))],
2203 "blues":[(
"dark turquoise",
"#00CED1",(0,206,209)),
2204 (
"turquoise",
"#40E0D0",(64,224,208)),(
"medium turquoise",
"#48D1CC",(72,209,204)),
2205 (
"pale turquoise",
"#AFEEEE",(175,238,238)),(
"aqua marine",
"#7FFFD4",(127,255,212)),
2206 (
"powder blue",
"#B0E0E6",(176,224,230)),(
"cadet blue",
"#5F9EA0",(95,158,160)),
2207 (
"steel blue",
"#4682B4",(70,130,180)),(
"corn flower blue",
"#6495ED",(100,149,237)),
2208 (
"deep sky blue",
"#00BFFF",(0,191,255)),(
"dodger blue",
"#1E90FF",(30,144,255)),
2209 (
"light blue",
"#ADD8E6",(173,216,230)),(
"sky blue",
"#87CEEB",(135,206,235)),
2210 (
"light sky blue",
"#87CEFA",(135,206,250)),(
"midnight blue",
"#191970",(25,25,112)),
2211 (
"navy",
"#000080",(0,0,128)),(
"dark blue",
"#00008B",(0,0,139)),
2212 (
"medium blue",
"#0000CD",(0,0,205)),(
"blue",
"#0000FF",(0,0,255)),(
"royal blue",
"#4169E1",(65,105,225)),
2213 (
"aqua",
"#00FFFF",(0,255,255)),(
"cyan",
"#00FFFF",(0,255,255)),(
"light cyan",
"#E0FFFF",(224,255,255))],
2214 "violets":[(
"blue violet",
"#8A2BE2",(138,43,226)),(
"indigo",
"#4B0082",(75,0,130)),
2215 (
"dark slate blue",
"#483D8B",(72,61,139)),(
"slate blue",
"#6A5ACD",(106,90,205)),
2216 (
"medium slate blue",
"#7B68EE",(123,104,238)),(
"medium purple",
"#9370DB",(147,112,219)),
2217 (
"dark magenta",
"#8B008B",(139,0,139)),(
"dark violet",
"#9400D3",(148,0,211)),
2218 (
"dark orchid",
"#9932CC",(153,50,204)),(
"medium orchid",
"#BA55D3",(186,85,211)),
2219 (
"purple",
"#800080",(128,0,128)),(
"thistle",
"#D8BFD8",(216,191,216)),
2220 (
"plum",
"#DDA0DD",(221,160,221)),(
"violet",
"#EE82EE",(238,130,238)),
2221 (
"magenta / fuchsia",
"#FF00FF",(255,0,255)),(
"orchid",
"#DA70D6",(218,112,214)),
2222 (
"medium violet red",
"#C71585",(199,21,133)),(
"pale violet red",
"#DB7093",(219,112,147)),
2223 (
"deep pink",
"#FF1493",(255,20,147)),(
"hot pink",
"#FF69B4",(255,105,180)),
2224 (
"light pink",
"#FFB6C1",(255,182,193)),(
"pink",
"#FFC0CB",(255,192,203))],
2225 "browns":[(
"saddle brown",
"#8B4513",(139,69,19)),(
"sienna",
"#A0522D",(160,82,45)),
2226 (
"chocolate",
"#D2691E",(210,105,30)),(
"peru",
"#CD853F",(205,133,63)),
2227 (
"sandy brown",
"#F4A460",(244,164,96)),(
"burly wood",
"#DEB887",(222,184,135)),
2228 (
"tan",
"#D2B48C",(210,180,140)),(
"rosy brown",
"#BC8F8F",(188,143,143)),
2229 (
"moccasin",
"#FFE4B5",(255,228,181)),(
"navajo white",
"#FFDEAD",(255,222,173)),
2230 (
"peach puff",
"#FFDAB9",(255,218,185)),(
"misty rose",
"#FFE4E1",(255,228,225)),
2231 (
"lavender blush",
"#FFF0F5",(255,240,245)),(
"linen",
"#FAF0E6",(250,240,230)),
2232 (
"old lace",
"#FDF5E6",(253,245,230)),(
"papaya whip",
"#FFEFD5",(255,239,213)),
2233 (
"sea shell",
"#FFF5EE",(255,245,238))],
2234 "greys":[(
"black",
"#000000",(0,0,0)),(
"dim gray / dim grey",
"#696969",(105,105,105)),
2235 (
"gray / grey",
"#808080",(128,128,128)),(
"dark gray / dark grey",
"#A9A9A9",(169,169,169)),
2236 (
"silver",
"#C0C0C0",(192,192,192)),(
"light gray / light grey",
"#D3D3D3",(211,211,211)),
2237 (
"gainsboro",
"#DCDCDC",(220,220,220)),(
"white smoke",
"#F5F5F5",(245,245,245)),
2238 (
"white",
"#FFFFFF",(255,255,255))]}
2240 def assign_color_group(self,color_group,representation,component_names):
2241 for n,p
in enumerate(component_names):
2243 psel=s.get_selected_particles()
2244 ctuple=self.colors[color_group][n]
2245 print(
"Assigning "+p+
" to color "+ctuple[0])
2254 def get_list_distant_colors(self):
2255 cnames = [
'#F0F8FF',
'#FAEBD7',
'#00FFFF',
'#7FFFD4',
'#F0FFFF',
'#F5F5DC',
2256 '#FFE4C4',
'#000000',
'#FFEBCD',
'#0000FF',
'#8A2BE2',
'#A52A2A',
'#DEB887',
2257 '#5F9EA0',
'#7FFF00',
'#D2691E',
'#FF7F50',
'#6495ED',
'#FFF8DC',
'#DC143C',
2258 '#00FFFF',
'#00008B',
'#008B8B',
'#B8860B',
'#A9A9A9',
'#006400',
'#BDB76B',
2259 '#8B008B',
'#556B2F',
'#FF8C00',
'#9932CC',
'#8B0000',
'#E9967A',
'#8FBC8F',
2260 '#483D8B',
'#2F4F4F',
'#00CED1',
'#9400D3',
'#FF1493',
'#00BFFF',
'#696969',
2261 '#1E90FF',
'#B22222',
'#FFFAF0',
'#228B22',
'#FF00FF',
'#DCDCDC',
'#F8F8FF',
2262 '#FFD700',
'#DAA520',
'#808080',
'#008000',
'#ADFF2F',
'#F0FFF0',
'#FF69B4',
2263 '#CD5C5C',
'#4B0082',
'#FFFFF0',
'#F0E68C',
'#E6E6FA',
'#FFF0F5',
'#7CFC00',
2264 '#FFFACD',
'#ADD8E6',
'#F08080',
'#E0FFFF',
'#FAFAD2',
'#90EE90',
'#D3D3D3',
2265 '#FFB6C1',
'#FFA07A',
'#20B2AA',
'#87CEFA',
'#778899',
'#B0C4DE',
'#FFFFE0',
2266 '#00FF00',
'#32CD32',
'#FAF0E6',
'#FF00FF',
'#800000',
'#66CDAA',
'#0000CD',
2267 '#BA55D3',
'#9370DB',
'#3CB371',
'#7B68EE',
'#00FA9A',
'#48D1CC',
'#C71585',
2268 '#191970',
'#F5FFFA',
'#FFE4E1',
'#FFE4B5',
'#FFDEAD',
'#000080',
'#FDF5E6',
2269 '#808000',
'#6B8E23',
'#FFA500',
'#FF4500',
'#DA70D6',
'#EEE8AA',
'#98FB98',
2270 '#AFEEEE',
'#DB7093',
'#FFEFD5',
'#FFDAB9',
'#CD853F',
'#FFC0CB',
'#DDA0DD',
2271 '#B0E0E6',
'#800080',
'#FF0000',
'#BC8F8F',
'#4169E1',
'#8B4513',
'#FA8072',
2272 '#FAA460',
'#2E8B57',
'#FFF5EE',
'#A0522D',
'#C0C0C0',
'#87CEEB',
'#6A5ACD',
2273 '#708090',
'#FFFAFA',
'#00FF7F',
'#4682B4',
'#D2B48C',
'#008080',
'#D8BFD8',
2274 '#FF6347',
'#40E0D0',
'#EE82EE',
'#F5DEB3',
'#FFFFFF',
'#F5F5F5',
'#FFFF00',
static bool get_is_setup(const IMP::ParticleAdaptor &p)
A decorator to associate a particle with a part of a protein/DNA/RNA.
static bool get_is_setup(const IMP::ParticleAdaptor &p)
void add_particles(RMF::FileHandle fh, const ParticlesTemp &hs)
Set of python classes to create a multi-state, multi-resolution IMP hierarchy.
static Weight setup_particle(Model *m, ParticleIndex pi)
A decorator for a particle which has bonds.
double get_drmsd(const Vector3DsOrXYZs0 &m0, const Vector3DsOrXYZs1 &m1)
Calculate distance the root mean square deviation between two sets of 3D points.
Rotation3D get_random_rotation_3d(const Rotation3D ¢er, double distance)
Pick a rotation at random near the provided one.
def deprecated_function
Python decorator to mark a function as deprecated.
IMP::Vector< Color > Colors
ParticlesTemp get_particles(Model *m, const ParticleIndexes &ps)
static Surface setup_particle(Model *m, ParticleIndex pi)
void add_particle(RMF::FileHandle fh, Particle *hs)
static bool get_is_setup(const IMP::ParticleAdaptor &p)
static bool get_is_setup(const IMP::ParticleAdaptor &p)
GenericHierarchies get_leaves(Hierarchy mhd)
Get all the leaves of the bit of hierarchy.
This class initializes the root node of the global IMP.atom.Hierarchy.
double get_distance(XYZR a, XYZR b)
Compute the sphere distance between a and b.
Vector3D get_random_vector_in(const Cylinder3D &c)
Generate a random vector in a cylinder with uniform density.
Add resolution to a particle.
Bond create_bond(Bonded a, Bonded b, Bond o)
Connect the two wrapped particles by a custom bond.
Object used to hold a set of restraints.
algebra::GridD< 3, algebra::DenseGridStorageD< 3, float >, float > get_grid(DensityMap *in_map)
Return a dense grid containing the voxels of the passed density map.
Stores a named protein chain.
static bool get_is_setup(Model *m, ParticleIndex pi)
ParticleIndexPairs get_indexes(const ParticlePairsTemp &ps)
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.
void transform(XYZ a, const algebra::Transformation3D &tr)
Apply a transformation to the particle.
static Bonded setup_particle(Model *m, ParticleIndex pi)
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.
static Scale setup_particle(Model *m, ParticleIndex pi)
static Colored setup_particle(Model *m, ParticleIndex pi, Color color)
A decorator for a particle that is part of a rigid body but not rigid.
std::ostream & show(Hierarchy h, std::ostream &out=std::cout)
Print the hierarchy using a given decorator to display each node.
Find all nearby pairs by testing all pairs.
static bool get_is_setup(const IMP::ParticleAdaptor &p)
A decorator for a residue.
General purpose algebraic and geometric methods that are expected to be used by a wide variety of IMP...
static bool get_is_setup(const IMP::ParticleAdaptor &p)
static bool get_is_setup(Model *m, ParticleIndex p)
Check if the particle has the needed attributes for a cast to succeed.
The general base class for IMP exceptions.
Rotation3D get_identity_rotation_3d()
Return a rotation that does not do anything.
void link_hierarchies(RMF::FileConstHandle fh, const atom::Hierarchies &hs)
Class to handle individual particles of a Model object.
Bond get_bond(Bonded a, Bonded b)
Get the bond between two particles.
Stores a list of Molecules all with the same State index.
std::string get_data_path(std::string file_name)
Return the full path to one of this module's data files.
Python classes to represent, score, sample and analyze models.
double get_resolution(Model *m, ParticleIndex pi)
Estimate the resolution of the hierarchy as used by Representation.
A decorator for a rigid body.
static bool get_is_setup(const IMP::ParticleAdaptor &p)
Hierarchies get_leaves(const Selection &h)
Select hierarchy particles identified by the biological name.
Support for the RMF file format for storing hierarchical molecular data and markup.
static bool get_is_setup(const IMP::ParticleAdaptor &p)
Transformation3D get_random_local_transformation(Vector3D origin, double max_translation=5., double max_angle_in_rad=0.26)
Get a local transformation.
Temporarily stores residue information, even without structure available.
Inferential scoring building on methods developed as part of the Inferential Structure Determination ...