1"""@namespace IMP.pmi.restraints.crosslinking
2Restraints for handling cross-linking data.
16from collections
import defaultdict
22def _get_cross_link_restraint_class(exact_forward_model):
23 """Get the crosslink restraint class for the given forward model"""
24 if exact_forward_model:
31 """Setup cross-link distance restraints from mass spectrometry data.
32 The noise in the data and the structural uncertainty of cross-linked
33 amino-acids is inferred using Bayes theory of probability
34 @note Wraps an IMP::isd::CrossLinkMSRestraint
36 _include_in_rmf =
True
38 def __init__(self, root_hier, database=None, length=10.0, resolution=None,
39 slope=0.02, label=None, filelabel="None",
40 attributes_for_label=None, linker=None, weight=1.,
41 exact_forward_model=False):
43 @param root_hier The canonical hierarchy containing all the states
44 @param database The IMP.pmi.io.crosslink.CrossLinkDataBase
45 object that contains the cross-link dataset
46 @param length maximal cross-linker length (including the residue
48 @param resolution what representation resolution should the cross-link
49 restraint be applied to.
50 @param slope The slope of a distance-linear scoring function that
51 funnels the score when the particles are
52 too far away. Suggested value 0.02.
53 @param label the extra text to label the restraint so that it is
54 searchable in the output
55 @param filelabel automatically generated file containing
56 missing/included/excluded
57 cross-links will be labeled using this text
58 @param attributes_for_label
59 @param weight Weight of restraint
60 @param linker description of the chemistry of the linker itself, as
61 an ihm.ChemDescriptor object
62 (see https://python-ihm.readthedocs.io/en/latest/main.html#ihm.ChemDescriptor).
63 Common cross-linkers can be found in the `ihm.cross_linkers`
65 @param exact_forward_model Whether to use the exact forward model,
66 or the approximation to it that was used in IMP 2.25 or earlier.
67 True is recommended for new applications.
70 model = root_hier.get_model()
73 model, weight=weight, label=label,
77 raise Exception(
"You must pass a database")
80 "CrossLinkingMassSpectrometryRestraint: database should "
81 "be an IMP.pmi.io.crosslink.CrossLinkDataBase object")
82 self.database = database
84 if resolution == 0
or resolution
is None:
85 raise Exception(
"You must pass a resolution and it can't be zero")
87 _xlms_cls = _get_cross_link_restraint_class(exact_forward_model)
89 indb = open(
"included." + filelabel +
".xl.db",
"w")
90 exdb = open(
"excluded." + filelabel +
".xl.db",
"w")
91 midb = open(
"missing." + filelabel +
".xl.db",
"w")
96 "No linker chemistry specified. A linker must be given, as an "
97 "ihm.ChemDescriptor object (see the "
98 "CrossLinkingMassSpectrometryRestraint documentation).")
99 self.rs.set_name(self.rs.get_name() +
"_Data")
100 self.rspsi = self._create_restraint_set(
"PriorPsi")
101 self.rssig = self._create_restraint_set(
"PriorSig")
102 self.rslin = self._create_restraint_set(
"Linear")
104 self.rslin.set_weight(0.0)
106 self.rs.set_metadata(self.database.name, length, slope)
108 self.rs.set_linker_auth_name(linker.auth_name)
109 for attr
in (
'chemical_name',
'smiles',
'smiles_canonical',
110 'inchi',
'inchi_key'):
111 val = getattr(linker, attr)
113 getattr(self.rs,
"set_linker_" + attr)(val)
117 self.linear.set_slope(0.0)
120 self.psi_is_sampled =
True
121 self.sigma_is_sampled =
True
122 self.psi_dictionary = {}
123 self.sigma_dictionary = {}
125 self.outputlevel =
"low"
129 xl_groups = [p.get_cross_link_group(self)
130 for p, state
in IMP.pmi.tools._all_protocol_outputs(
134 copies_to_add = defaultdict(int)
135 print(
'gathering copies')
136 for xlid
in self.database.xlid_iterator():
137 for xl
in self.database[xlid]:
138 r1 = xl[self.database.residue1_key]
139 c1 = xl[self.database.protein1_key]
140 r2 = xl[self.database.residue2_key]
141 c2 = xl[self.database.protein2_key]
142 for c, r
in ((c1, r1), (c2, r2)):
143 if c
in copies_to_add:
146 root_hier, state_index=0, molecule=c, residue_index=r,
147 resolution=resolution).get_selected_particles()
149 copies_to_add[c] = len(sel)-1
151 for molname
in copies_to_add:
152 if copies_to_add[molname] == 0:
155 self.database.protein1_key, operator.eq, molname)
156 self.database.set_value(self.database.protein1_key,
159 self.database.protein2_key, operator.eq, molname)
160 self.database.set_value(self.database.protein2_key,
162 for ncopy
in range(copies_to_add[molname]):
163 self.database.clone_protein(
'%s.0' % molname,
164 '%s.%i' % (molname, ncopy + 1))
165 print(
'done pmi2 prelims')
167 for xlid
in self.database.xlid_iterator():
168 new_contribution =
True
169 for xl
in self.database[xlid]:
171 r1 = xl[self.database.residue1_key]
172 c1 = xl[self.database.protein1_key]
173 r2 = xl[self.database.residue2_key]
174 c2 = xl[self.database.protein2_key]
181 name1, copy1 = c1.split(
'.')
183 name2, copy2 = c2.split(
'.')
187 (p[0].add_experimental_cross_link(r1, name1, r2, name2,
190 IMP.pmi.tools._all_protocol_outputs(root_hier),
194 root_hier, IMP.atom.STATE_TYPE)))
195 for nstate, r
in enumerate(iterlist):
197 xl[self.database.state_key] = nstate
198 xl[self.database.data_set_name_key] = self.label
201 root_hier, state_index=nstate, molecule=name1,
202 copy_index=int(copy1), residue_index=r1,
203 resolution=resolution).get_selected_particles()
205 root_hier, state_index=nstate, molecule=name2,
206 copy_index=int(copy2), residue_index=r2,
207 resolution=resolution).get_selected_particles()
214 "residue %d of chain %s selects multiple "
215 "particles %s" % (r1, c1, str(ps1)))
218 "CrossLinkingMassSpectrometryRestraint: "
219 "residue %d of chain %s is not there" % (r1, c1),
221 midb.write(str(xl) +
"\n")
226 "residue %d of chain %s selects multiple "
227 "particles %s" % (r2, c2, str(ps2)))
230 "CrossLinkingMassSpectrometryRestraint: "
231 "residue %d of chain %s is not there" % (r2, c2),
233 midb.write(str(xl) +
"\n")
239 if p1 == p2
and r1 == r2:
241 "CrossLinkingMassSpectrometryRestraint: "
242 "same particle and same residue, skipping "
247 print(
"generating a new cross-link restraint")
248 new_contribution =
False
249 dr = _xlms_cls(self.model, length, slope)
250 dr.set_source_protein1(c1)
251 dr.set_source_protein2(c2)
252 dr.set_source_residue1(r1)
253 dr.set_source_residue2(r2)
254 restraints.append(dr)
256 if self.database.sigma1_key
not in xl.keys():
258 xl[self.database.sigma1_key] = sigma1name
260 sigma1name = xl[self.database.sigma1_key]
263 if self.database.sigma2_key
not in xl.keys():
265 xl[self.database.sigma2_key] = sigma2name
267 sigma2name = xl[self.database.sigma2_key]
270 if self.database.psi_key
not in xl.keys():
272 xl[self.database.psi_key] = psiname
274 psiname = xl[self.database.psi_key]
278 p1i = p1.get_particle_index()
280 p2i = p2.get_particle_index()
282 s1i = sigma1.get_particle().get_index()
283 xl[
"Particle_sigma1"] = sigma1
284 s2i = sigma2.get_particle().get_index()
285 xl[
"Particle_sigma2"] = sigma2
286 psii = psi.get_particle().get_index()
287 xl[
"Particle_psi"] = psi
289 dr.add_contribution((p1i, p2i), (s1i, s2i), psii)
292 print(
"--------------")
293 print(
"CrossLinkingMassSpectrometryRestraint: generating "
294 "cross-link restraint between")
295 print(
"CrossLinkingMassSpectrometryRestraint: residue %d "
296 "of chain %s and residue %d of chain %s"
298 print(
"CrossLinkingMassSpectrometryRestraint: with sigma1 "
299 "%s sigma2 %s psi %s"
300 % (sigma1name, sigma2name, psiname))
301 print(
"CrossLinkingMassSpectrometryRestraint: between "
302 "particles %s and %s"
303 % (p1.get_name(), p2.get_name()))
304 print(
"==========================================\n")
305 for p, ex_xl
in zip(IMP.pmi.tools._all_protocol_outputs(
308 p[0].add_cross_link(p[1], ex_xl[0], p1, p2, length,
309 sigma1, sigma2, psi, ex_xl[1])
316 xl[
"IntraRigidBody"] =
True
318 xl[
"IntraRigidBody"] =
False
320 xl_label = self.database.get_short_cross_link_string(xl)
321 xl[
"ShortLabel"] = xl_label
322 dr.set_name(xl_label)
327 pr.set_name(xl_label)
328 self.rslin.add_restraint(pr)
330 self.xl_list.append(xl)
332 indb.write(str(xl) +
"\n")
334 if len(self.xl_list) == 0:
336 "CrossLinkingMassSpectrometryRestraint: no cross-link "
338 self.xl_restraints = restraints
340 self.rs.add_restraint(lw)
345 def __set_dataset(self, ds):
346 self.database.dataset = ds
347 dataset = property(
lambda self: self.database.dataset, __set_dataset)
350 """ get the hierarchy """
354 """ get the restraint set """
358 """ get the restraints in a list """
359 return self.xl_restraints
362 """ get the dummy restraints to be displayed in the rmf file """
363 return self.rs, self.rssig, self.rspsi
366 """ Get a list of tuples containing the particle pairs """
368 for i
in range(len(self.pairs)):
369 p0 = self.pairs[i][0]
370 p1 = self.pairs[i][1]
371 ppairs.append((p0, p1))
375 """ Set the output level of the output """
376 self.outputlevel = level
379 """ Switch on/off the sampling of psi particles """
380 self.psi_is_sampled = is_sampled
383 """ Switch on/off the sampling of sigma particles """
384 self.sigma_is_sampled = is_sampled
387 """ This is called internally. Creates a nuisance
388 on the structural uncertainty """
389 if name
in self.sigma_dictionary:
390 return self.sigma_dictionary[name][0]
393 sigmaminnuis = 0.0000001
394 sigmamaxnuis = 1000.0
398 sigma = IMP.pmi.tools.SetupNuisance(
399 self.model, sigmainit, sigmaminnuis, sigmamaxnuis,
400 self.sigma_is_sampled, name=name).get_particle()
401 self.sigma_dictionary[name] = (
404 self.sigma_is_sampled)
405 self.rssig.add_restraint(
415 """ This is called internally. Creates a nuisance
416 on the data uncertainty """
417 if name
in self.psi_dictionary:
418 return self.psi_dictionary[name][0]
421 psiminnuis = 0.0000001
422 psimaxnuis = 0.4999999
426 psi = IMP.pmi.tools.SetupNuisance(
427 self.model, psiinit, psiminnuis, psimaxnuis,
428 self.psi_is_sampled, name=name).get_particle()
429 self.psi_dictionary[name] = (psi, psitrans, self.psi_is_sampled)
431 self.rspsi.add_restraint(
439 """Get the output of the restraint to be used by the IMP.pmi.output
444 for xl
in self.xl_list:
446 xl_label = xl[
"ShortLabel"]
450 output[
"CrossLinkingMassSpectrometryRestraint_Score_" +
451 xl_label] = str(-log(ln.unprotected_evaluate(
None)))
455 output[
"CrossLinkingMassSpectrometryRestraint_Distance_" +
458 for psiname
in self.psi_dictionary:
459 output[
"CrossLinkingMassSpectrometryRestraint_Psi_" +
460 str(psiname) + self._label_suffix] = str(
461 self.psi_dictionary[psiname][0].get_scale())
463 for sigmaname
in self.sigma_dictionary:
464 output[
"CrossLinkingMassSpectrometryRestraint_Sigma_" +
465 str(sigmaname) + self._label_suffix] = str(
466 self.sigma_dictionary[sigmaname][0].get_scale())
471 """Get the unweighted likelihood of the restraint"""
473 for restraint
in self.xl_restraints:
474 likelihood *= restraint.get_probability()
479 """ Get all need data to construct a mover in IMP.pmi.dof class"""
481 if self.sigma_is_sampled:
482 for sigmaname
in self.sigma_dictionary:
484 "Nuisances_CrossLinkingMassSpectrometryRestraint_Sigma_" \
485 + str(sigmaname) +
"_" + self.label
486 particle = self.sigma_dictionary[sigmaname][0]
487 maxstep = (self.sigma_dictionary[sigmaname][1])
491 mv.set_name(mover_name)
494 if self.psi_is_sampled:
495 for psiname
in self.psi_dictionary:
497 "Nuisances_CrossLinkingMassSpectrometryRestraint_Psi_" + \
498 str(psiname) +
"_" + self.label
499 particle = self.psi_dictionary[psiname][0]
500 maxstep = (self.psi_dictionary[psiname][1])
504 mv.set_name(mover_name)
510 """ Get the particles to be sampled by the IMP.pmi.sampler object """
512 if self.sigma_is_sampled:
513 for sigmaname
in self.sigma_dictionary:
514 ps[
"Nuisances_CrossLinkingMassSpectrometryRestraint_Sigma_" +
515 str(sigmaname) + self._label_suffix] =\
516 ([self.sigma_dictionary[sigmaname][0]],
517 self.sigma_dictionary[sigmaname][1])
519 if self.psi_is_sampled:
520 for psiname
in self.psi_dictionary:
521 ps[
"Nuisances_CrossLinkingMassSpectrometryRestraint_Psi_" +
522 str(psiname) + self._label_suffix] = \
523 ([self.psi_dictionary[psiname][0]],
524 self.psi_dictionary[psiname][1])
530 """Setup cross-link distance restraints at atomic level
531 The "atomic" aspect is that it models the particle uncertainty with
532 a Gaussian. The noise in the data and the structural uncertainty of
533 cross-linked amino-acids is inferred using Bayes' theory of probability
534 @note Wraps an IMP::isd::AtomicCrossLinkMSRestraint
537 _include_in_rmf =
True
539 def __init__(self, root_hier, xldb, atom_type="NZ", length=10.0,
540 slope=0.01, nstates=None, label=None,
541 nuisances_are_optimized=True, sigma_init=5.0,
542 psi_init=0.01, one_psi=True, filelabel=None, weight=1.):
544 Automatically creates one "sigma" per cross-linked residue and one
546 Other nuisance options are available.
547 @note Will return an error if the data+extra_sel don't specify
548 two particles per XL pair.
549 @param root_hier The root hierarchy on which you'll do selection
550 @param xldb CrossLinkDataBase object
551 @param atom_type Can either be "NZ" or "CA"
552 @param length The XL linker length
553 @param slope Linear term to add to the restraint function to
555 @param nstates The number of states to model. Defaults to the
556 number of states in root.
557 @param label The output label for the restraint
558 @param nuisances_are_optimized Whether to optimize nuisances
559 @param sigma_init The initial value for all the sigmas
560 @param psi_init The initial value for all the psis
561 @param one_psi Use a single psi for all restraints (if False,
563 @param filelabel automatically generated file containing
564 missing/included/excluded
565 cross-links will be labeled using this text
566 @param weight Weight of restraint
571 self.root = root_hier
572 rname =
"AtomicXLRestraint"
574 self.root.get_model(), name=
"AtomicXLRestraint", label=label,
578 self.sigma_is_sampled = nuisances_are_optimized
579 self.psi_is_sampled = nuisances_are_optimized
581 if atom_type
not in (
"NZ",
"CA"):
582 raise Exception(
"AtomicXLRestraint: atom_type must be NZ or CA")
583 self.atom_type = atom_type
584 self.nstates = nstates
587 IMP.atom.STATE_TYPE))
589 IMP.atom.STATE_TYPE)):
590 print(
"Warning: nstates is not the same as the number of states "
593 self.rs_psi = self._create_restraint_set(
"psi")
594 self.rs_sig = self._create_restraint_set(
"sigma")
595 self.rs_lin = self._create_restraint_set(
"linear")
597 self.psi_dictionary = {}
598 self.sigma_dictionary = {}
600 self.particles = defaultdict(set)
601 self.one_psi = one_psi
602 self.bonded_pairs = []
604 print(
'creating a single psi for all XLs')
606 print(
'creating one psi for each XL')
609 if filelabel
is not None:
610 indb = open(
"included." + filelabel +
".xl.db",
"w")
611 exdb = open(
"excluded." + filelabel +
".xl.db",
"w")
612 midb = open(
"missing." + filelabel +
".xl.db",
"w")
615 self._create_sigma(
'sigma', sigma_init)
617 self._create_psi(
'psi', psi_init)
619 for xlid
in self.xldb.xlid_iterator():
620 self._create_psi(xlid, psi_init)
624 for xlid
in self.xldb.xlid_iterator():
627 psip = self.psi_dictionary[
'psi'][0].get_particle_index()
629 psip = self.psi_dictionary[
630 unique_id][0].get_particle_index()
636 num_contributions = 0
639 for nstate
in self.nstates:
640 for xl
in self.xldb[xlid]:
641 r1 = xl[self.xldb.residue1_key]
642 c1 = xl[self.xldb.protein1_key].strip()
643 r2 = xl[self.xldb.residue2_key]
644 c2 = xl[self.xldb.protein2_key].strip()
649 self.root, state_index=nstate,
652 residue_index=r1).get_selected_particles()
654 self.root, state_index=nstate,
657 residue_index=r2).get_selected_particles()
659 warnings.warn(
"AtomicXLRestraint: residue %d of "
660 "chain %s is not there" % (r1, c1),
662 if filelabel
is not None:
663 midb.write(str(xl) +
"\n")
667 warnings.warn(
"AtomicXLRestraint: residue %d of "
668 "chain %s is not there" % (r2, c2),
670 if filelabel
is not None:
671 midb.write(str(xl) +
"\n")
676 num1=num_xls_per_res[str(xl.r1)]
677 num2=num_xls_per_res[str(xl.r2)]
678 if num1<sig_threshold:
682 if num2<sig_threshold:
687 sig1 = self.sigma_dictionary[
'sigma'][0]
688 sig2 = self.sigma_dictionary[
'sigma'][0]
691 for p1, p2
in itertools.product(ps1, ps2):
694 self.particles[nstate] |= set((p1, p2))
696 [p1.get_index(), p2.get_index()],
697 [sig1.get_particle_index(),
698 sig2.get_particle_index()])
699 num_contributions += 1
701 if num_contributions > 0:
702 print(
'XL:', xlid,
'num contributions:', num_contributions)
705 raise Exception(
"You didn't create any XL restraints")
706 print(
'created', len(xlrs),
'XL restraints')
707 rname = self.rs.get_name()
709 self.rs.set_name(rname)
710 self.rs.set_weight(self.weight)
711 self.restraint_sets = [self.rs] + self.restraint_sets[1:]
713 def get_hierarchy(self):
716 def _create_sigma(self, name, sigmainit):
717 """ This is called internally. Creates a nuisance
718 on the structural uncertainty """
719 if name
in self.sigma_dictionary:
720 return self.sigma_dictionary[name][0]
722 sigmaminnuis = 0.0000001
723 sigmamaxnuis = 1000.0
727 sigma = IMP.pmi.tools.SetupNuisance(
728 self.model, sigmainit, sigmaminnuis, sigmamaxnuis,
729 self.sigma_is_sampled).get_particle()
730 self.sigma_dictionary[name] = (
731 sigma, sigmatrans, self.sigma_is_sampled)
733 self.model, sigma, 1000000000.0, sigmamax, sigmamin))
736 def _create_psi(self, name, psiinit):
737 """ This is called internally. Creates a nuisance
738 on the data uncertainty """
739 if name
in self.psi_dictionary:
740 return self.psi_dictionary[name][0]
742 psiminnuis = 0.0000001
743 psimaxnuis = 0.4999999
747 psi = IMP.pmi.tools.SetupNuisance(self.model,
751 self.psi_is_sampled).get_particle()
752 self.psi_dictionary[name] = (
757 self.rs_psi.add_restraint(
769 """ create dummy harmonic restraints for each XL but don't add to model
770 Makes it easy to see each contribution to each XL in RMF
772 class MyGetRestraint:
776 def get_restraint_for_rmf(self):
782 for nxl
in range(self.get_number_of_restraints()):
783 xl = IMP.isd.AtomicCrossLinkMSRestraint.get_from(
784 self.rs.get_restraint(nxl))
786 for ncontr
in range(xl.get_number_of_contributions()):
787 ps = xl.get_contribution(ncontr)
789 hps, [self.model.get_particle(p)
for p
in ps],
790 'xl%i_contr%i' % (nxl, ncontr))
792 dummy_rs.append(MyGetRestraint(rs))
796 """ Get the particles to be sampled by the IMP.pmi.sampler object """
798 if self.sigma_is_sampled:
799 for sigmaname
in self.sigma_dictionary:
800 ps[
"Nuisances_AtomicCrossLinkingMSRestraint_Sigma_" +
801 str(sigmaname) + self._label_suffix] = \
802 ([self.sigma_dictionary[sigmaname][0]],
803 self.sigma_dictionary[sigmaname][1])
804 if self.psi_is_sampled:
805 for psiname
in self.psi_dictionary:
806 ps[
"Nuisances_CrossLinkingMassSpectrometryRestraint_Psi_" +
807 str(psiname) + self._label_suffix] = \
808 ([self.psi_dictionary[psiname][0]],
809 self.psi_dictionary[psiname][1])
812 def get_bonded_pairs(self):
813 return self.bonded_pairs
815 def get_number_of_restraints(self):
816 return self.rs.get_number_of_restraints()
819 return 'XL restraint with ' + \
820 str(len(self.rs.get_restraint(0).get_number_of_restraints())) \
824 """Read a stat file and load all the sigmas.
825 This is potentially quite stupid.
826 It's also a hack since the sigmas should be stored in the RMF file.
827 Also, requires one sigma and one psi for ALL XLs.
830 sig_val = float(subprocess.check_output(
831 [
"process_output.py",
"-f", in_fn,
"-s",
832 "AtomicXLRestraint_sigma"]).split(
'\n>')[1+nframe])
833 psi_val = float(subprocess.check_output(
834 [
"process_output.py",
"-f", in_fn,
"-s",
835 "AtomicXLRestraint_psi"]).split(
'\n>')[1+nframe])
836 for nxl
in range(self.rs.get_number_of_restraints()):
837 xl = IMP.isd.AtomicCrossLinkMSRestraint.get_from(
838 self.rs.get_restraint(nxl))
841 for contr
in range(xl.get_number_of_contributions()):
842 sig1, sig2 = xl.get_contribution_sigmas(contr)
845 print(
'loaded nuisances from file')
848 min_dist_for_violation=1e9, coarsen=False,
849 limit_to_chains=None, exclude_chains=''):
850 """Create CMM files, one for each state, of all cross-links.
851 will draw in GREEN if non-violated in all states (or if only one state)
852 will draw in PURPLE if non-violated only in a subset of states
853 (draws nothing elsewhere)
854 will draw in RED in ALL states if all violated
855 (if only one state, you'll only see green and red)
857 @param out_prefix Output xlink files prefix
858 @param max_prob_for_violation It's a violation if the probability
860 @param min_dist_for_violation It's a violation if the min dist
862 @param coarsen Use CA positions
863 @param limit_to_chains Try to visualize just these chains
864 @param exclude_chains Try to NOT visualize these chains
866 print(
'going to calculate violations and plot CMM files')
868 all_dists = [s[
"low_dist"]
for s
in all_stats]
874 cmds = defaultdict(set)
875 for nstate
in range(self.nstates):
876 outf = open(out_prefix+str(nstate)+
'.cmm',
'w')
877 outf.write(
'<marker_set name="xlinks_state%i"> \n' % nstate)
880 print(
'will limit to', limit_to_chains)
881 print(
'will exclude', exclude_chains)
886 for nxl
in range(self.rs.get_number_of_restraints()):
890 for nstate
in range(self.nstates):
891 prob = state_info[nstate][nxl][
"prob"]
892 low_dist = state_info[nstate][nxl][
"low_dist"]
893 if (prob < max_prob_for_violation
or
894 low_dist > min_dist_for_violation):
902 if len(npass) == self.nstates:
904 elif len(nviol) == self.nstates:
908 print(nxl,
'state dists:',
909 [state_info[nstate][nxl][
"low_dist"]
910 for nstate
in range(self.nstates)],
911 'viol states:', nviol,
'all viol?', all_viol)
912 for nstate
in range(self.nstates):
931 pp = state_info[nstate][nxl][
"low_pp"]
942 cmds[nstate].add((ch1, r1))
943 cmds[nstate].add((ch2, r2))
945 outf = out_fns[nstate]
947 outf.write(
'<marker id= "%d" x="%.3f" y="%.3f" z="%.3f" '
948 'radius="0.8" r="%.2f" g="%.2f" b="%.2f"/> \n'
949 % (nv, c1[0], c1[1], c1[2], r, g, b))
950 outf.write(
'<marker id= "%d" x="%.3f" y="%.3f" z="%.3f" '
951 'radius="0.8" r="%.2f" g="%.2f" b="%.2f"/> \n'
952 % (nv+1, c2[0], c2[1], c2[2], r, g, b))
953 outf.write(
'<link id1= "%d" id2="%d" radius="0.8" '
954 'r="%.2f" g="%.2f" b="%.2f"/> \n'
955 % (nv, nv+1, r, g, b))
958 for nstate
in range(self.nstates):
959 out_fns[nstate].write(
'</marker_set>\n')
960 out_fns[nstate].close()
962 for ch, r
in cmds[nstate]:
963 cmd +=
'#%i:%i.%s ' % (nstate, r, ch)
968 def _get_contribution_info(self, xl, ncontr, use_CA=False):
969 """Return the particles at that contribution. If requested will
970 return CA's instead"""
971 idx1 = xl.get_contribution(ncontr)[0]
972 idx2 = xl.get_contribution(ncontr)[1]
977 idx1 = sel.get_selected_particle_indexes()[0]
981 idx2 = sel.get_selected_particle_indexes()[0]
985 return idx1, idx2, dist
988 exclude_chains='', use_CA=False):
989 ''' return the probability, best distance, two coords, and possibly
991 @param limit_to_state Only examine contributions from one state
992 @param limit_to_chains Returns the particles for certain "easy
994 @param exclude_chains Even if you limit, don't let one end be in
995 this list. Only works if you also limit chains
996 @param use_CA Limit to CA particles
999 for nxl
in range(self.rs.get_number_of_restraints()):
1001 xl = IMP.isd.AtomicCrossLinkMSRestraint.get_from(
1002 self.rs.get_restraint(nxl))
1008 for contr
in range(xl.get_number_of_contributions()):
1009 pp = xl.get_contribution(contr)
1014 idx1 = sel.get_selected_particle_indexes()[0]
1018 idx2 = sel.get_selected_particle_indexes()[0]
1020 if limit_to_state
is not None:
1023 if nstate != limit_to_state:
1025 state_contrs.append(contr)
1028 if limit_to_chains
is not None:
1033 if (c1
in limit_to_chains
or c2
in limit_to_chains)
and (
1034 c1
not in exclude_chains
1035 and c2
not in exclude_chains):
1036 if dist < low_dist_lim:
1042 if limit_to_state
is not None:
1043 this_info[
"prob"] = xl.evaluate_for_contributions(
1046 this_info[
"prob"] = xl.unprotected_evaluate(
None)
1047 if limit_to_chains
is not None:
1048 this_info[
"low_pp"] = low_pp_lim
1050 this_info[
"low_pp"] = low_pp
1052 this_info[
"low_dist"] = low_dist
1053 if not self.one_psi:
1055 this_info[
"psi"] = pval
1056 ret.append(this_info)
1059 def print_stats(self):
1061 for nxl, s
in enumerate(stats):
1062 print(s[
"low_dist"])
1064 def get_output(self):
1065 output = super().get_output()
1076 for nxl, s
in enumerate(stats):
1077 if s[
'low_dist'] > 20.0:
1079 output[
"AtomicXLRestraint_%i_%s" % (nxl,
"Prob")] = str(s[
'prob'])
1080 output[
"AtomicXLRestraint_%i_%s"
1081 % (nxl,
"BestDist")] = str(s[
'low_dist'])
1082 if not self.one_psi:
1083 output[
"AtomicXLRestraint_%i_%s" % (nxl,
"psi")] \
1085 output[
"AtomicXLRestraint_NumViol"] = str(bad_count)
1089class CysteineCrossLinkRestraint:
1090 def __init__(self, root_hier, filename, cbeta=False,
1091 betatuple=(0.03, 0.1),
1092 disttuple=(0.0, 25.0, 1000),
1093 omegatuple=(1.0, 1000.0, 50),
1094 sigmatuple=(0.3, 0.3, 1),
1096 sigmaissampled=
False,
1097 weightissampled=
True,
1098 epsilonissampled=
True):
1105 self.m = root_hier.get_model()
1108 self.epsilonmaxtrans = 0.01
1109 self.sigmamaxtrans = 0.1
1110 self.betamaxtrans = 0.01
1111 self.weightmaxtrans = 0.1
1113 self.outputlevel =
"low"
1114 self.betaissampled = betaissampled
1115 self.sigmaissampled = sigmaissampled
1116 self.weightissampled = weightissampled
1117 self.epsilonissampled = epsilonissampled
1119 betalower = betatuple[0]
1120 betaupper = betatuple[1]
1126 self.beta = IMP.pmi.tools.SetupNuisance(
1131 betaissampled).get_particle(
1134 self.sigma = IMP.pmi.tools.SetupNuisance(
1139 sigmaissampled).get_particle()
1141 self.weight = IMP.pmi.tools.SetupWeight(
1143 isoptimized=
False).get_particle(
1147 fl = IMP.pmi.tools.open_file_or_inline_text(filename)
1156 if t[5]
in self.epsilons:
1157 if 1.0 - float(t[4]) <= self.epsilons[t[5]].get_upper():
1158 self.epsilons[t[5]].set_upper(1.0 - float(t[4]))
1160 self.epsilons[t[5]] = IMP.pmi.tools.SetupNuisance(
1161 self.m, 0.01, 0.01, 1.0 - float(t[4]),
1162 epsilonissampled).get_particle()
1163 up = self.epsilons[t[5]].get_upper()
1164 low = self.epsilons[t[5]].get_lower()
1166 self.epsilons[t[5]].set_upper(low)
1168 data.append((int(t[0]), t[1], int(t[2]), t[3], float(t[4]), t[5]))
1172 crossdata = IMP.pmi.tools.get_cross_link_data(
1173 "cysteine",
"cysteine_CA_FES.txt.standard",
1174 disttuple, omegatuple, sigmatuple, disttuple[1],
1177 crossdata = IMP.pmi.tools.get_cross_link_data(
1178 "cysteine",
"cysteine_CB_FES.txt.standard",
1179 disttuple, omegatuple, sigmatuple, disttuple[1],
1183 fmod_grid = IMP.pmi.tools.get_grid(0.0, 1.0, 300,
True)
1184 omega2_grid = IMP.pmi.tools.get_log_grid(0.001, 10000.0, 100)
1185 beta_grid = IMP.pmi.tools.get_log_grid(betalower, betaupper, betangrid)
1188 print(
"--------------")
1189 print(
"CysteineCrossLink: attempting to create a restraint "
1210 self.epsilons[epslabel],
1221 molecule=chain1, residue_index=resid1,
1223 p1 = p1.get_selected_particles()
1230 molecule=chain2, residue_index=resid2,
1232 p2 = p2.get_selected_particles()
1242 for t
in range(-1, 2):
1244 molecule=chain1, copy_index=0,
1245 residue_index=resid1 + t)
1246 p = p.get_selected_particles()
1252 "CysteineCrossLink: missing representation for "
1253 "residue %d of chain %s" % (resid1 + t, chain1),
1257 molecule=chain2, copy_index=0,
1258 residue_index=resid2 + t)
1259 p = p.get_selected_particles()
1265 "CysteineCrossLink: missing representation for "
1266 "residue %d of chain %s" % (resid2 + t, chain2),
1270 if (p1
is not None and p2
is not None):
1271 ccl.add_contribution(p1, p2)
1275 print(
"Distance_" + str(resid1) +
"_" + chain1 +
":" +
1276 str(resid2) +
"_" + chain2,
1280 if (len(p1) == 3
and len(p2) == 3):
1281 p11n = p1[0].get_name()
1282 p12n = p1[1].get_name()
1283 p13n = p1[2].get_name()
1284 p21n = p2[0].get_name()
1285 p22n = p2[1].get_name()
1286 p23n = p2[2].get_name()
1288 print(
"CysteineCrossLink: generating CB cysteine "
1289 "cross-link restraint between")
1290 print(
"CysteineCrossLink: residue %d of chain %s and "
1291 "residue %d of chain %s"
1292 % (resid1, chain1, resid2, chain2))
1293 print(
"CysteineCrossLink: between particles %s %s %s and "
1294 "%s %s %s" % (p11n, p12n, p13n, p21n, p22n, p23n))
1296 ccl.add_contribution(p1, p2)
1299 self.rs.add_restraint(ccl)
1300 ccl.set_name(
"CysteineCrossLink_" + str(resid1)
1301 +
"_" + chain1 +
":" + str(resid2) +
"_" + chain2)
1304 self.weight.get_particle()
1305 ).set_weights_are_optimized(weightissampled)
1307 def set_label(self, label):
1310 def add_to_model(self):
1315 if self.epsilonissampled:
1316 for eps
in self.epsilons.keys():
1317 ps[
"Nuisances_CysteineCrossLinkRestraint_epsilon_" + eps +
1318 "_" + self.label] = ([self.epsilons[eps]],
1319 self.epsilonmaxtrans)
1320 if self.betaissampled:
1321 ps[
"Nuisances_CysteineCrossLinkRestraint_beta_" +
1322 self.label] = ([self.beta], self.betamaxtrans)
1323 if self.weightissampled:
1324 ps[
"Weights_CysteineCrossLinkRestraint_" +
1325 self.label] = ([self.weight], self.weightmaxtrans)
1326 if self.sigmaissampled:
1327 ps[
"Nuisances_CysteineCrossLinkRestraint_" +
1328 self.label] = ([self.sigma], self.sigmamaxtrans)
1331 def set_output_level(self, level="low"):
1333 self.outputlevel = level
1335 def get_restraint(self):
1338 def get_sigma(self):
1341 def get_output(self):
1343 score = self.rs.unprotected_evaluate(
None)
1344 output[
"_TotalScore"] = str(score)
1345 output[
"CysteineCrossLinkRestraint_Score_" + self.label] = str(score)
1346 output[
"CysteineCrossLinkRestraint_sigma_" +
1347 self.label] = str(self.sigma.get_scale())
1348 for eps
in self.epsilons.keys():
1349 output[
"CysteineCrossLinkRestraint_epsilon_" + eps +
"_" +
1350 self.label] = str(self.epsilons[eps].get_scale())
1351 output[
"CysteineCrossLinkRestraint_beta_" +
1352 self.label] = str(self.beta.get_scale())
1353 for n
in range(self.weight.get_number_of_weights()):
1354 output[
"CysteineCrossLinkRestraint_weights_" +
1355 str(n) +
"_" + self.label] = str(self.weight.get_weight(n))
1357 if self.outputlevel ==
"high":
1358 for rst
in self.rs.get_restraints():
1359 cclr = IMP.isd.CysteineCrossLinkRestraint.get_from(rst)
1360 output[
"CysteineCrossLinkRestraint_Total_Frequency_" +
1362 "_" + self.label] = cclr.get_model_frequency()
1363 output[
"CysteineCrossLinkRestraint_Standard_Error_" +
1364 cclr.get_name() +
"_" +
1365 self.label] = cclr.get_standard_error()
1369class DisulfideCrossLinkRestraint:
1370 def __init__(self, representation_or_hier,
1377 exact_forward_model=False):
1379 self.m = representation_or_hier.get_model()
1382 resolution=resolution)
1385 resolution=resolution)
1392 self.linear.set_slope(0.0)
1396 self.psi_dictionary = {}
1397 self.sigma_dictionary = {}
1398 self.psi_is_sampled =
False
1399 self.sigma_is_sampled =
False
1402 _xlms_cls = _get_cross_link_restraint_class(exact_forward_model)
1404 if len(ps1) > 1
or len(ps1) == 0:
1406 "DisulfideBondRestraint: ERROR> first selection pattern "
1407 "selects multiple particles or sero particles")
1409 if len(ps2) > 1
or len(ps2) == 0:
1411 "DisulfideBondRestraint: ERROR> second selection pattern "
1412 "selects multiple particles or sero particles")
1417 sigma = self.create_sigma(
"SIGMA_DISULFIDE_BOND")
1418 psi = self.create_psi(
"PSI_DISULFIDE_BOND")
1420 p1i = p1.get_index()
1421 p2i = p2.get_index()
1422 si = sigma.get_particle().get_index()
1423 psii = psi.get_particle().get_index()
1425 dr = _xlms_cls(self.m, length, slope)
1427 dr.add_contribution((p1i, p2i), (si, si), psii)
1431 pr.set_name(
"DISULFIDE_BOND_"+self.label)
1432 self.rslin.add_restraint(pr)
1435 self.rs.add_restraint(lw)
1437 self.xl[
"Particle1"] = p1
1438 self.xl[
"Particle2"] = p2
1439 self.xl[
"Sigma"] = sigma
1440 self.xl[
"Psi"] = psi
1442 def add_to_model(self):
1445 self.m, self.rslin, add_to_rmf=
True)
1447 def get_hierarchies(self):
1450 def get_restraint_sets(self):
1453 def get_restraint(self):
1456 def get_restraint_for_rmf(self):
1459 def get_restraints(self):
1461 for r
in self.rs.get_restraints():
1462 rlist.append(IMP.core.PairRestraint.get_from(r))
1465 def set_psi_is_sampled(self, is_sampled=True):
1466 self.psi_is_sampled = is_sampled
1468 def set_sigma_is_sampled(self, is_sampled=True):
1469 self.sigma_is_sampled = is_sampled
1471 def create_sigma(self, name):
1472 ''' a nuisance on the structural uncertainty '''
1473 if name
in self.sigma_dictionary:
1474 return self.sigma_dictionary[name][0]
1477 sigmaminnuis = 0.0000001
1478 sigmamaxnuis = 1000.0
1480 sigma = IMP.pmi.tools.SetupNuisance(
1481 self.m, sigmainit, sigmaminnuis, sigmamaxnuis,
1482 self.sigma_is_sampled).get_particle()
1483 self.sigma_dictionary[name] = (
1486 self.sigma_is_sampled)
1490 def create_psi(self, name):
1491 ''' a nuisance on the inconsistency '''
1492 if name
in self.psi_dictionary:
1493 return self.psi_dictionary[name][0]
1496 psiminnuis = 0.0000001
1497 psimaxnuis = 0.4999999
1499 psi = IMP.pmi.tools.SetupNuisance(self.m, psiinit,
1500 psiminnuis, psimaxnuis,
1501 self.psi_is_sampled).get_particle()
1502 self.psi_dictionary[name] = (
1505 self.psi_is_sampled)
1509 def get_output(self):
1511 score = self.rs.unprotected_evaluate(
None)
1512 output[
"_TotalScore"] = str(score)
1513 output[
"DisulfideBondRestraint_Data_Score_" + self.label] = str(score)
1514 output[
"DisulfideBondRestraint_Linear_Score_" +
1515 self.label] = self.rslin.unprotected_evaluate(
None)
1519 raise NotImplementedError(
" ")
The general base class for IMP exceptions.
Class for storing model, its restraints, constraints, and particles.
Object used to hold a set of restraints.
A decorator for a particle representing an atom.
The standard decorator for manipulating molecular structures.
Hierarchies get_by_type(Hierarchy mhd, GetByType t)
Gather all the molecular particles of a certain level in the hierarchy.
Select hierarchy particles identified by the biological name.
Score a pair of particles based on the distance between their centers.
Score distance between two particle centers using a harmonic function.
Modify a set of continuous variables using a normal distribution.
Applies a PairScore to a Pair.
static bool get_is_setup(const IMP::ParticleAdaptor &p)
A decorator for a particle with x,y,z coordinates.
Restrain atom pairs based on a set of crosslinks.
A restraint for ambiguous cross-linking MS data and multiple state approach.
A restraint for cysteine cross-linking data.
A restraint for ambiguous cross-linking MS data and multiple state approach.
Calculate the -Log of a list of restraints.
Add scale parameter to particle.
Add weights to a particle.
A RestraintSet subclass to track cross-link metadata.
Warning related to handling of structures.
this class handles a cross-link dataset and do filtering operations, adding cross-links,...
This class allows to create filter functions that can be passed to the CrossLinkDataBase in this way:
Setup cross-link distance restraints at atomic level The "atomic" aspect is that it models the partic...
__init__(self, root_hier, xldb, atom_type='NZ', length=10.0, slope=0.01, nstates=None, label=None, nuisances_are_optimized=True, sigma_init=5.0, psi_init=0.01, one_psi=True, filelabel=None, weight=1.0)
Constructor.
get_particles_to_sample(self)
Get the particles to be sampled by the IMP.pmi.sampler object.
create_restraints_for_rmf(self)
create dummy harmonic restraints for each XL but don't add to model Makes it easy to see each contrib...
get_best_stats(self, limit_to_state=None, limit_to_chains=None, exclude_chains='', use_CA=False)
return the probability, best distance, two coords, and possibly the psi for each xl
plot_violations(self, out_prefix, max_prob_for_violation=0.1, min_dist_for_violation=1000000000.0, coarsen=False, limit_to_chains=None, exclude_chains='')
Create CMM files, one for each state, of all cross-links.
load_nuisances_from_stat_file(self, in_fn, nframe)
Read a stat file and load all the sigmas.
Setup cross-link distance restraints from mass spectrometry data.
get_movers(self)
Get all need data to construct a mover in IMP.pmi.dof class.
get_likelihood(self)
Get the unweighted likelihood of the restraint.
get_particle_pairs(self)
Get a list of tuples containing the particle pairs.
get_restraints(self)
get the restraints in a list
set_psi_is_sampled(self, is_sampled=True)
Switch on/off the sampling of psi particles.
get_restraint_for_rmf(self)
get the dummy restraints to be displayed in the rmf file
__init__(self, root_hier, database=None, length=10.0, resolution=None, slope=0.02, label=None, filelabel='None', attributes_for_label=None, linker=None, weight=1.0, exact_forward_model=False)
Constructor.
get_output(self)
Get the output of the restraint to be used by the IMP.pmi.output object.
set_sigma_is_sampled(self, is_sampled=True)
Switch on/off the sampling of sigma particles.
set_output_level(self, level='low')
Set the output level of the output.
get_particles_to_sample(self)
Get the particles to be sampled by the IMP.pmi.sampler object.
create_psi(self, name)
This is called internally.
get_restraint_sets(self)
get the restraint set
create_sigma(self, name)
This is called internally.
get_hierarchies(self)
get the hierarchy
General purpose algebraic and geometric methods that are expected to be used by a wide variety of IMP...
double get_distance(const Line3D &s, const Vector3D &p)
Get closest distance between a line and a point.
Functionality for loading, creating, manipulating and scoring atomic structures.
Residue get_residue(Atom d, bool nothrow=false)
Return the Residue containing this atom.
int get_state_index(Hierarchy h)
Walk up the hierarchy to find the current state.
std::string get_chain_id(Hierarchy h)
Walk up the hierarchy to determine the chain id.
Various classes to hold sets of particles.
Basic functionality that is expected to be used by a wide variety of IMP users.
double get_distance(const Surface &s, const XYZR &d)
Get distance from sphere to surface.
Inferential scoring building on methods developed as part of the Inferential Structure Determination ...
Handles cross-link data sets.
Classes for writing output files and processing them.
Classes to handle different kinds of restraints.