IMP logo
IMP Reference Guide  develop.7482b7c7af, 2026/12/05
The Integrative Modeling Platform
crosslinking.py
1"""@namespace IMP.pmi.restraints.crosslinking
2Restraints for handling cross-linking data.
3"""
4
5import IMP
6import IMP.core
7import IMP.algebra
8import IMP.atom
9import IMP.isd
10import IMP.container
11import IMP.pmi.tools
12import IMP.pmi.output
15from math import log
16from collections import defaultdict
17import itertools
18import operator
19import warnings
20
21
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:
26 else:
28
29
30class CrossLinkingMassSpectrometryRestraint(IMP.pmi.restraints.RestraintBase):
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
35 """
36 _include_in_rmf = True
37
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):
42 """Constructor.
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
47 sidechains)
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`
64 module.
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.
68 """ # noqa: E501
69
70 model = root_hier.get_model()
71
72 super().__init__(
73 model, weight=weight, label=label,
74 restraint_set_class=IMP.pmi.CrossLinkRestraintSet)
75
76 if database is None:
77 raise Exception("You must pass a database")
78 if not isinstance(database, IMP.pmi.io.crosslink.CrossLinkDataBase):
79 raise TypeError(
80 "CrossLinkingMassSpectrometryRestraint: database should "
81 "be an IMP.pmi.io.crosslink.CrossLinkDataBase object")
82 self.database = database
83
84 if resolution == 0 or resolution is None:
85 raise Exception("You must pass a resolution and it can't be zero")
86
87 _xlms_cls = _get_cross_link_restraint_class(exact_forward_model)
88
89 indb = open("included." + filelabel + ".xl.db", "w")
90 exdb = open("excluded." + filelabel + ".xl.db", "w") # noqa: F841
91 midb = open("missing." + filelabel + ".xl.db", "w")
92
93 self.linker = linker
94 if linker is None:
95 raise ValueError(
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")
103 # These are only dummy restraints, so their score can be skipped
104 self.rslin.set_weight(0.0)
105 # Add custom metadata (will be saved in RMF output)
106 self.rs.set_metadata(self.database.name, length, slope)
107 if linker:
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)
112 if val:
113 getattr(self.rs, "set_linker_" + attr)(val)
114
115 # dummy linear restraint used for Chimera display
116 self.linear = IMP.core.Linear(0, 0.0)
117 self.linear.set_slope(0.0)
118 dps2 = IMP.core.DistancePairScore(self.linear)
119
120 self.psi_is_sampled = True
121 self.sigma_is_sampled = True
122 self.psi_dictionary = {}
123 self.sigma_dictionary = {}
124 self.xl_list = []
125 self.outputlevel = "low"
126
127 restraints = []
128
129 xl_groups = [p.get_cross_link_group(self)
130 for p, state in IMP.pmi.tools._all_protocol_outputs(
131 root_hier)]
132
133 # first add all the molecule copies as clones to the database
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:
144 continue
145 sel = IMP.atom.Selection(
146 root_hier, state_index=0, molecule=c, residue_index=r,
147 resolution=resolution).get_selected_particles()
148 if len(sel) > 0:
149 copies_to_add[c] = len(sel)-1
150 print(copies_to_add)
151 for molname in copies_to_add:
152 if copies_to_add[molname] == 0:
153 continue
155 self.database.protein1_key, operator.eq, molname)
156 self.database.set_value(self.database.protein1_key,
157 molname + '.0', fo1)
159 self.database.protein2_key, operator.eq, molname)
160 self.database.set_value(self.database.protein2_key,
161 molname + '.0', fo2)
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')
166
167 for xlid in self.database.xlid_iterator():
168 new_contribution = True
169 for xl in self.database[xlid]:
170
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]
175
176 name1 = c1
177 name2 = c2
178 copy1 = 0
179 copy2 = 0
180 if '.' in c1:
181 name1, copy1 = c1.split('.')
182 if '.' in c2:
183 name2, copy2 = c2.split('.')
184
185 # todo: check that offset is handled correctly
186 ex_xls = [
187 (p[0].add_experimental_cross_link(r1, name1, r2, name2,
188 group), group)
189 for p, group in zip(
190 IMP.pmi.tools._all_protocol_outputs(root_hier),
191 xl_groups)]
192
193 iterlist = range(len(IMP.atom.get_by_type(
194 root_hier, IMP.atom.STATE_TYPE)))
195 for nstate, r in enumerate(iterlist):
196 # loop over every state
197 xl[self.database.state_key] = nstate
198 xl[self.database.data_set_name_key] = self.label
199
200 ps1 = IMP.atom.Selection(
201 root_hier, state_index=nstate, molecule=name1,
202 copy_index=int(copy1), residue_index=r1,
203 resolution=resolution).get_selected_particles()
204 ps2 = IMP.atom.Selection(
205 root_hier, state_index=nstate, molecule=name2,
206 copy_index=int(copy2), residue_index=r2,
207 resolution=resolution).get_selected_particles()
208
209 ps1 = [IMP.atom.Hierarchy(p) for p in ps1]
210 ps2 = [IMP.atom.Hierarchy(p) for p in ps2]
211
212 if len(ps1) > 1:
213 raise ValueError(
214 "residue %d of chain %s selects multiple "
215 "particles %s" % (r1, c1, str(ps1)))
216 elif len(ps1) == 0:
217 warnings.warn(
218 "CrossLinkingMassSpectrometryRestraint: "
219 "residue %d of chain %s is not there" % (r1, c1),
221 midb.write(str(xl) + "\n")
222 continue
223
224 if len(ps2) > 1:
225 raise ValueError(
226 "residue %d of chain %s selects multiple "
227 "particles %s" % (r2, c2, str(ps2)))
228 elif len(ps2) == 0:
229 warnings.warn(
230 "CrossLinkingMassSpectrometryRestraint: "
231 "residue %d of chain %s is not there" % (r2, c2),
233 midb.write(str(xl) + "\n")
234 continue
235
236 p1 = ps1[0]
237 p2 = ps2[0]
238
239 if p1 == p2 and r1 == r2:
240 warnings.warn(
241 "CrossLinkingMassSpectrometryRestraint: "
242 "same particle and same residue, skipping "
243 "cross-link", IMP.pmi.StructureWarning)
244 continue
245
246 if new_contribution:
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)
255
256 if self.database.sigma1_key not in xl.keys():
257 sigma1name = "SIGMA"
258 xl[self.database.sigma1_key] = sigma1name
259 else:
260 sigma1name = xl[self.database.sigma1_key]
261 sigma1 = self.create_sigma(sigma1name)
262
263 if self.database.sigma2_key not in xl.keys():
264 sigma2name = "SIGMA"
265 xl[self.database.sigma2_key] = sigma2name
266 else:
267 sigma2name = xl[self.database.sigma2_key]
268 sigma2 = self.create_sigma(sigma2name)
269
270 if self.database.psi_key not in xl.keys():
271 psiname = "PSI"
272 xl[self.database.psi_key] = psiname
273 else:
274 psiname = xl[self.database.psi_key]
275
276 psi = self.create_psi(psiname)
277
278 p1i = p1.get_particle_index()
279 xl["Particle1"] = p1
280 p2i = p2.get_particle_index()
281 xl["Particle2"] = p2
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
288
289 dr.add_contribution((p1i, p2i), (s1i, s2i), psii)
290 xl["Restraint"] = dr
291
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"
297 % (r1, c1, r2, c2))
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(
306 root_hier),
307 ex_xls):
308 p[0].add_cross_link(p[1], ex_xl[0], p1, p2, length,
309 sigma1, sigma2, psi, ex_xl[1])
310
311 # check if the two residues belong to the same rigid body
314 IMP.core.RigidMember(p1).get_rigid_body() ==
315 IMP.core.RigidMember(p2).get_rigid_body()):
316 xl["IntraRigidBody"] = True
317 else:
318 xl["IntraRigidBody"] = False
319
320 xl_label = self.database.get_short_cross_link_string(xl)
321 xl["ShortLabel"] = xl_label
322 dr.set_name(xl_label)
323
324 if p1i != p2i:
325 pr = IMP.core.PairRestraint(self.model, dps2,
326 (p1i, p2i))
327 pr.set_name(xl_label)
328 self.rslin.add_restraint(pr)
329
330 self.xl_list.append(xl)
331
332 indb.write(str(xl) + "\n")
333
334 if len(self.xl_list) == 0:
335 raise SystemError(
336 "CrossLinkingMassSpectrometryRestraint: no cross-link "
337 "was constructed")
338 self.xl_restraints = restraints
339 lw = IMP.isd.LogWrapper(restraints, 1.0)
340 self.rs.add_restraint(lw)
341 indb.close()
342 exdb.close()
343 midb.close()
344
345 def __set_dataset(self, ds):
346 self.database.dataset = ds
347 dataset = property(lambda self: self.database.dataset, __set_dataset)
348
350 """ get the hierarchy """
351 return self.prot
352
354 """ get the restraint set """
355 return self.rs
356
357 def get_restraints(self):
358 """ get the restraints in a list """
359 return self.xl_restraints
360
362 """ get the dummy restraints to be displayed in the rmf file """
363 return self.rs, self.rssig, self.rspsi
364
366 """ Get a list of tuples containing the particle pairs """
367 ppairs = []
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))
372 return ppairs
373
374 def set_output_level(self, level="low"):
375 """ Set the output level of the output """
376 self.outputlevel = level
377
378 def set_psi_is_sampled(self, is_sampled=True):
379 """ Switch on/off the sampling of psi particles """
380 self.psi_is_sampled = is_sampled
381
382 def set_sigma_is_sampled(self, is_sampled=True):
383 """ Switch on/off the sampling of sigma particles """
384 self.sigma_is_sampled = is_sampled
385
386 def create_sigma(self, name):
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]
391
392 sigmainit = 2.0
393 sigmaminnuis = 0.0000001
394 sigmamaxnuis = 1000.0
395 sigmamin = 0.01
396 sigmamax = 100.0
397 sigmatrans = 0.5
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] = (
402 sigma,
403 sigmatrans,
404 self.sigma_is_sampled)
405 self.rssig.add_restraint(
407 self.model,
408 sigma,
409 1000000000.0,
410 sigmamax,
411 sigmamin))
412 return sigma
413
414 def create_psi(self, name):
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]
419
420 psiinit = 0.25
421 psiminnuis = 0.0000001
422 psimaxnuis = 0.4999999
423 psimin = 0.01
424 psimax = 0.49
425 psitrans = 0.1
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)
430
431 self.rspsi.add_restraint(
432 IMP.isd.UniformPrior(self.model, psi, 1000000000.0,
433 psimax, psimin))
434
435 self.rspsi.add_restraint(IMP.isd.JeffreysRestraint(self.model, psi))
436 return psi
437
438 def get_output(self):
439 """Get the output of the restraint to be used by the IMP.pmi.output
440 object"""
441 # todo: return a callable here instead
442 output = super().get_output()(None)
443
444 for xl in self.xl_list:
445
446 xl_label = xl["ShortLabel"]
447 ln = xl["Restraint"]
448 p0 = xl["Particle1"]
449 p1 = xl["Particle2"]
450 output["CrossLinkingMassSpectrometryRestraint_Score_" +
451 xl_label] = str(-log(ln.unprotected_evaluate(None)))
452
453 d0 = IMP.core.XYZ(p0)
454 d1 = IMP.core.XYZ(p1)
455 output["CrossLinkingMassSpectrometryRestraint_Distance_" +
456 xl_label] = str(IMP.core.get_distance(d0, d1))
457
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())
462
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())
467
468 return output
469
470 def get_likelihood(self):
471 """Get the unweighted likelihood of the restraint"""
472 likelihood = 1
473 for restraint in self.xl_restraints:
474 likelihood *= restraint.get_probability()
475
476 return likelihood
477
478 def get_movers(self):
479 """ Get all need data to construct a mover in IMP.pmi.dof class"""
480 movers = []
481 if self.sigma_is_sampled:
482 for sigmaname in self.sigma_dictionary:
483 mover_name = \
484 "Nuisances_CrossLinkingMassSpectrometryRestraint_Sigma_" \
485 + str(sigmaname) + "_" + self.label
486 particle = self.sigma_dictionary[sigmaname][0]
487 maxstep = (self.sigma_dictionary[sigmaname][1])
489 [particle], IMP.FloatKeys([IMP.FloatKey("nuisance")]),
490 maxstep)
491 mv.set_name(mover_name)
492 movers.append(mv)
493
494 if self.psi_is_sampled:
495 for psiname in self.psi_dictionary:
496 mover_name = \
497 "Nuisances_CrossLinkingMassSpectrometryRestraint_Psi_" + \
498 str(psiname) + "_" + self.label
499 particle = self.psi_dictionary[psiname][0]
500 maxstep = (self.psi_dictionary[psiname][1])
502 [particle], IMP.FloatKeys([IMP.FloatKey("nuisance")]),
503 maxstep)
504 mv.set_name(mover_name)
505 movers.append(mv)
506
507 return movers
508
510 """ Get the particles to be sampled by the IMP.pmi.sampler object """
511 ps = {}
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])
518
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])
525
526 return ps
527
528
529class AtomicCrossLinkMSRestraint(IMP.pmi.restraints.RestraintBase):
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
535 """
536
537 _include_in_rmf = True
538
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.):
543 """Constructor.
544 Automatically creates one "sigma" per cross-linked residue and one
545 "psis" per pair.
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
554 help when far away
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,
562 creates one per XL)
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
567
568 """
569
570 # basic params
571 self.root = root_hier
572 rname = "AtomicXLRestraint"
573 super().__init__(
574 self.root.get_model(), name="AtomicXLRestraint", label=label,
575 weight=weight)
576 self.xldb = xldb
577 self.length = length
578 self.sigma_is_sampled = nuisances_are_optimized
579 self.psi_is_sampled = nuisances_are_optimized
580
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
585 if nstates is None:
586 self.nstates = len(IMP.atom.get_by_type(self.root,
587 IMP.atom.STATE_TYPE))
588 elif nstates != len(IMP.atom.get_by_type(self.root,
589 IMP.atom.STATE_TYPE)):
590 print("Warning: nstates is not the same as the number of states "
591 "in root")
592
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")
596
597 self.psi_dictionary = {}
598 self.sigma_dictionary = {}
599
600 self.particles = defaultdict(set)
601 self.one_psi = one_psi
602 self.bonded_pairs = []
603 if self.one_psi:
604 print('creating a single psi for all XLs')
605 else:
606 print('creating one psi for each XL')
607
608 # output logging file
609 if filelabel is not None:
610 indb = open("included." + filelabel + ".xl.db", "w") # noqa: F841
611 exdb = open("excluded." + filelabel + ".xl.db", "w") # noqa: F841
612 midb = open("missing." + filelabel + ".xl.db", "w")
613
614 # Setup nuisances
615 self._create_sigma('sigma', sigma_init)
616 if one_psi:
617 self._create_psi('psi', psi_init)
618 else:
619 for xlid in self.xldb.xlid_iterator():
620 self._create_psi(xlid, psi_init)
621
622 # create all the XLs
623 xlrs = []
624 for xlid in self.xldb.xlid_iterator():
625 # create restraint for this data point
626 if one_psi:
627 psip = self.psi_dictionary['psi'][0].get_particle_index()
628 else:
629 psip = self.psi_dictionary[
630 unique_id][0].get_particle_index() # noqa: F821
632 self.length,
633 psip,
634 slope,
635 True)
636 num_contributions = 0
637
638 # add a contribution for each XL ambiguity option within each state
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()
645
646 # perform selection. these may contain multiples if
647 # Copies are used
648 ps1 = IMP.atom.Selection(
649 self.root, state_index=nstate,
650 atom_type=IMP.atom.AtomType(self.atom_type),
651 molecule=c1,
652 residue_index=r1).get_selected_particles()
653 ps2 = IMP.atom.Selection(
654 self.root, state_index=nstate,
655 atom_type=IMP.atom.AtomType(self.atom_type),
656 molecule=c2,
657 residue_index=r2).get_selected_particles()
658 if len(ps1) == 0:
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")
664 continue
665
666 if len(ps2) == 0:
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")
672 continue
673
674 # figure out sig1 and sig2 based on num XLs
675 '''
676 num1=num_xls_per_res[str(xl.r1)]
677 num2=num_xls_per_res[str(xl.r2)]
678 if num1<sig_threshold:
679 sig1=self.sig_low
680 else:
681 sig1=self.sig_high
682 if num2<sig_threshold:
683 sig2=self.sig_low
684 else:
685 sig2=self.sig_high
686 '''
687 sig1 = self.sigma_dictionary['sigma'][0]
688 sig2 = self.sigma_dictionary['sigma'][0]
689
690 # add each copy contribution to restraint
691 for p1, p2 in itertools.product(ps1, ps2):
692 if p1 == p2:
693 continue
694 self.particles[nstate] |= set((p1, p2))
695 r.add_contribution(
696 [p1.get_index(), p2.get_index()],
697 [sig1.get_particle_index(),
698 sig2.get_particle_index()])
699 num_contributions += 1
700
701 if num_contributions > 0:
702 print('XL:', xlid, 'num contributions:', num_contributions)
703 xlrs.append(r)
704 if len(xlrs) == 0:
705 raise Exception("You didn't create any XL restraints")
706 print('created', len(xlrs), 'XL restraints')
707 rname = self.rs.get_name()
708 self.rs = IMP.isd.LogWrapper(xlrs, self.weight)
709 self.rs.set_name(rname)
710 self.rs.set_weight(self.weight)
711 self.restraint_sets = [self.rs] + self.restraint_sets[1:]
712
713 def get_hierarchy(self):
714 return self.prot
715
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]
721
722 sigmaminnuis = 0.0000001
723 sigmamaxnuis = 1000.0
724 sigmamin = 0.01
725 sigmamax = 100.0
726 sigmatrans = 0.5
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)
732 self.rs_sig.add_restraint(IMP.isd.UniformPrior(
733 self.model, sigma, 1000000000.0, sigmamax, sigmamin))
734 return sigma
735
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]
741
742 psiminnuis = 0.0000001
743 psimaxnuis = 0.4999999
744 psimin = 0.01
745 psimax = 0.49
746 psitrans = 0.1
747 psi = IMP.pmi.tools.SetupNuisance(self.model,
748 psiinit,
749 psiminnuis,
750 psimaxnuis,
751 self.psi_is_sampled).get_particle()
752 self.psi_dictionary[name] = (
753 psi,
754 psitrans,
755 self.psi_is_sampled)
756
757 self.rs_psi.add_restraint(
759 self.model,
760 psi,
761 1000000000.0,
762 psimax,
763 psimin))
764
765 self.rs_psi.add_restraint(IMP.isd.JeffreysRestraint(self.model, psi))
766 return psi
767
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
771 """
772 class MyGetRestraint:
773 def __init__(self, rs):
774 self.rs = rs
775
776 def get_restraint_for_rmf(self):
777 return self.rs
778
779 dummy_model = IMP.Model()
780 hps = IMP.core.HarmonicDistancePairScore(self.length, 1.0)
781 dummy_rs = []
782 for nxl in range(self.get_number_of_restraints()):
783 xl = IMP.isd.AtomicCrossLinkMSRestraint.get_from(
784 self.rs.get_restraint(nxl))
785 rs = IMP.RestraintSet(dummy_model, 'atomic_xl_'+str(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))
791 rs.add_restraint(dr)
792 dummy_rs.append(MyGetRestraint(rs))
793 return dummy_rs
794
796 """ Get the particles to be sampled by the IMP.pmi.sampler object """
797 ps = {}
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])
810 return ps
811
812 def get_bonded_pairs(self):
813 return self.bonded_pairs
814
815 def get_number_of_restraints(self):
816 return self.rs.get_number_of_restraints()
817
818 def __repr__(self):
819 return 'XL restraint with ' + \
820 str(len(self.rs.get_restraint(0).get_number_of_restraints())) \
821 + ' data points'
822
823 def load_nuisances_from_stat_file(self, in_fn, nframe):
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.
828 """
829 import subprocess
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))
839 psip = xl.get_psi()
840 IMP.isd.Scale(self.model, psip).set_scale(psi_val)
841 for contr in range(xl.get_number_of_contributions()):
842 sig1, sig2 = xl.get_contribution_sigmas(contr)
843 IMP.isd.Scale(self.model, sig1).set_scale(sig_val)
844
845 print('loaded nuisances from file')
846
847 def plot_violations(self, out_prefix, max_prob_for_violation=0.1,
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)
856
857 @param out_prefix Output xlink files prefix
858 @param max_prob_for_violation It's a violation if the probability
859 is below this
860 @param min_dist_for_violation It's a violation if the min dist
861 is above this
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
865 """
866 print('going to calculate violations and plot CMM files')
867 all_stats = self.get_best_stats()
868 all_dists = [s["low_dist"] for s in all_stats]
869
870 # prepare one output file per state
871 out_fns = []
872 out_nvs = []
873 state_info = []
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)
878 out_fns.append(outf)
879 out_nvs.append(0)
880 print('will limit to', limit_to_chains)
881 print('will exclude', exclude_chains)
882 state_info.append(self.get_best_stats(nstate,
883 limit_to_chains,
884 exclude_chains))
885
886 for nxl in range(self.rs.get_number_of_restraints()):
887 # for this XL, check which states passed
888 npass = []
889 nviol = []
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):
895 nviol.append(nstate)
896 else:
897 npass.append(nstate)
898
899 # special coloring when all pass or all fail
900 all_pass = False
901 all_viol = False
902 if len(npass) == self.nstates:
903 all_pass = True
904 elif len(nviol) == self.nstates:
905 all_viol = True
906
907 # finally, color based on above info
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):
913 if all_pass:
914 r = 0.365
915 g = 0.933
916 b = 0.365
917 continue
918 elif all_viol:
919 r = 0.980
920 g = 0.302
921 b = 0.247
922 continue
923 else:
924 if nstate in nviol:
925 continue
926 else:
927 r = 0.365
928 g = 0.933
929 b = 0.365
930 # now only showing if UNIQUELY PASSING in this state
931 pp = state_info[nstate][nxl]["low_pp"]
932 c1 = IMP.core.XYZ(self.model, pp[0]).get_coordinates()
933 c2 = IMP.core.XYZ(self.model, pp[1]).get_coordinates()
934
936 IMP.atom.Atom(self.model, pp[0])).get_index()
937 ch1 = IMP.atom.get_chain_id(IMP.atom.Atom(self.model, pp[0]))
939 IMP.atom.Atom(self.model, pp[0])).get_index()
940 ch2 = IMP.atom.get_chain_id(IMP.atom.Atom(self.model, pp[0]))
941
942 cmds[nstate].add((ch1, r1))
943 cmds[nstate].add((ch2, r2))
944
945 outf = out_fns[nstate]
946 nv = out_nvs[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))
956 out_nvs[nstate] += 2
957
958 for nstate in range(self.nstates):
959 out_fns[nstate].write('</marker_set>\n')
960 out_fns[nstate].close()
961 cmd = ''
962 for ch, r in cmds[nstate]:
963 cmd += '#%i:%i.%s ' % (nstate, r, ch)
964 print(cmd)
965
966 return all_dists
967
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]
973 if use_CA:
974 sel = IMP.atom.Selection(
975 IMP.atom.get_residue(IMP.atom.Atom(self.model, idx1)),
976 atom_type=IMP.atom.AtomType("CA"))
977 idx1 = sel.get_selected_particle_indexes()[0]
978 sel = IMP.atom.Selection(
979 IMP.atom.get_residue(IMP.atom.Atom(self.model, idx2)),
980 atom_type=IMP.atom.AtomType("CA"))
981 idx2 = sel.get_selected_particle_indexes()[0]
983 IMP.core.XYZ(self.model, idx1).get_coordinates(),
984 IMP.core.XYZ(self.model, idx2).get_coordinates())
985 return idx1, idx2, dist
986
987 def get_best_stats(self, limit_to_state=None, limit_to_chains=None,
988 exclude_chains='', use_CA=False):
989 ''' return the probability, best distance, two coords, and possibly
990 the psi for each xl
991 @param limit_to_state Only examine contributions from one state
992 @param limit_to_chains Returns the particles for certain "easy
993 to visualize" chains
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
997 '''
998 ret = []
999 for nxl in range(self.rs.get_number_of_restraints()):
1000 this_info = {}
1001 xl = IMP.isd.AtomicCrossLinkMSRestraint.get_from(
1002 self.rs.get_restraint(nxl))
1003 low_dist = 1e6
1004 low_pp = None
1005 state_contrs = []
1006 low_pp_lim = None
1007 low_dist_lim = 1e6
1008 for contr in range(xl.get_number_of_contributions()):
1009 pp = xl.get_contribution(contr)
1010 if use_CA:
1011 sel = IMP.atom.Selection(
1012 IMP.atom.get_residue(IMP.atom.Atom(self.model, pp[0])),
1013 atom_type=IMP.atom.AtomType("CA"))
1014 idx1 = sel.get_selected_particle_indexes()[0]
1015 sel = IMP.atom.Selection(
1016 IMP.atom.get_residue(IMP.atom.Atom(self.model, pp[1])),
1017 atom_type=IMP.atom.AtomType("CA"))
1018 idx2 = sel.get_selected_particle_indexes()[0]
1019 pp = [idx1, idx2]
1020 if limit_to_state is not None:
1021 nstate = IMP.atom.get_state_index(
1022 IMP.atom.Atom(self.model, pp[0]))
1023 if nstate != limit_to_state:
1024 continue
1025 state_contrs.append(contr)
1026 dist = IMP.core.get_distance(IMP.core.XYZ(self.model, pp[0]),
1027 IMP.core.XYZ(self.model, pp[1]))
1028 if limit_to_chains is not None:
1030 IMP.atom.Atom(self.model, pp[0]))
1032 IMP.atom.Atom(self.model, pp[1]))
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:
1037 low_dist_lim = dist
1038 low_pp_lim = pp
1039 if dist < low_dist:
1040 low_dist = dist
1041 low_pp = pp
1042 if limit_to_state is not None:
1043 this_info["prob"] = xl.evaluate_for_contributions(
1044 state_contrs, None)
1045 else:
1046 this_info["prob"] = xl.unprotected_evaluate(None)
1047 if limit_to_chains is not None:
1048 this_info["low_pp"] = low_pp_lim
1049 else:
1050 this_info["low_pp"] = low_pp
1051
1052 this_info["low_dist"] = low_dist
1053 if not self.one_psi:
1054 pval = IMP.isd.Scale(self.model, xl.get_psi()).get_scale()
1055 this_info["psi"] = pval
1056 ret.append(this_info)
1057 return ret
1058
1059 def print_stats(self):
1060 stats = self.get_best_stats()
1061 for nxl, s in enumerate(stats):
1062 print(s["low_dist"])
1063
1064 def get_output(self):
1065 output = super().get_output()
1066
1067 # HACK to make it easier to see the few sigmas
1068 # output["AtomicXLRestraint_sigma"] = self.sigma.get_scale()
1069 # if self.one_psi:
1070 # output["AtomicXLRestraint_psi"] = self.psi.get_scale()
1071 #
1072
1073 # count distances above length
1074 bad_count = 0
1075 stats = self.get_best_stats()
1076 for nxl, s in enumerate(stats):
1077 if s['low_dist'] > 20.0:
1078 bad_count += 1
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")] \
1084 = str(s['psi'])
1085 output["AtomicXLRestraint_NumViol"] = str(bad_count)
1086 return output
1087
1088
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),
1095 betaissampled=True,
1096 sigmaissampled=False,
1097 weightissampled=True,
1098 epsilonissampled=True):
1099 # the file must have residue1 chain1 residue2 chain2 fractionvalue
1100 # epsilonname
1101 # epsilonname is a name for the epsilon particle that must be used
1102 # for that particular residue pair, eg, "Epsilon-Intra-Solvent", or
1103 # "Epsilon-Solvent-Membrane", etc.
1104
1105 self.m = root_hier.get_model()
1106 self.rs = IMP.RestraintSet(self.m, 'Cysteine_Crosslink')
1107 self.cbeta = cbeta
1108 self.epsilonmaxtrans = 0.01
1109 self.sigmamaxtrans = 0.1
1110 self.betamaxtrans = 0.01
1111 self.weightmaxtrans = 0.1
1112 self.label = "None"
1113 self.outputlevel = "low"
1114 self.betaissampled = betaissampled
1115 self.sigmaissampled = sigmaissampled
1116 self.weightissampled = weightissampled
1117 self.epsilonissampled = epsilonissampled
1118
1119 betalower = betatuple[0]
1120 betaupper = betatuple[1]
1121 beta = 0.04
1122 sigma = 10.0
1123 betangrid = 30
1124
1125 # beta
1126 self.beta = IMP.pmi.tools.SetupNuisance(
1127 self.m,
1128 beta,
1129 betalower,
1130 betaupper,
1131 betaissampled).get_particle(
1132 )
1133 # sigma
1134 self.sigma = IMP.pmi.tools.SetupNuisance(
1135 self.m,
1136 sigma,
1137 sigmatuple[0],
1138 sigmatuple[1],
1139 sigmaissampled).get_particle()
1140 # population particle
1141 self.weight = IMP.pmi.tools.SetupWeight(
1142 self.m,
1143 isoptimized=False).get_particle(
1144 )
1145
1146 # read the file
1147 fl = IMP.pmi.tools.open_file_or_inline_text(filename)
1148 # determine the upperlimit for epsilon
1149 # and also how many epsilon are needed
1150 self.epsilons = {}
1151 data = []
1152 for line in fl:
1153 t = line.split()
1154 if t[0][0] == "#":
1155 continue
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]))
1159 else:
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()
1165 if up < low:
1166 self.epsilons[t[5]].set_upper(low)
1167
1168 data.append((int(t[0]), t[1], int(t[2]), t[3], float(t[4]), t[5]))
1169
1170 # create CrossLinkData
1171 if not self.cbeta:
1172 crossdata = IMP.pmi.tools.get_cross_link_data(
1173 "cysteine", "cysteine_CA_FES.txt.standard",
1174 disttuple, omegatuple, sigmatuple, disttuple[1],
1175 disttuple[1], 1)
1176 else:
1177 crossdata = IMP.pmi.tools.get_cross_link_data(
1178 "cysteine", "cysteine_CB_FES.txt.standard",
1179 disttuple, omegatuple, sigmatuple, disttuple[1],
1180 disttuple[1], 1)
1181
1182 # create grids needed by CysteineCrossLinkData
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)
1186
1187 for d in data:
1188 print("--------------")
1189 print("CysteineCrossLink: attempting to create a restraint "
1190 + str(d))
1191 resid1 = d[0]
1192 chain1 = d[1]
1193 resid2 = d[2]
1194 chain2 = d[3]
1195 fexp = d[4]
1196 epslabel = d[5]
1197
1198 # CysteineCrossLinkData
1199
1201 fexp,
1202 fmod_grid,
1203 omega2_grid,
1204 beta_grid)
1205
1207 self.m,
1208 self.beta,
1209 self.sigma,
1210 self.epsilons[epslabel],
1211 self.weight,
1212 crossdata,
1213 ccldata)
1214
1215 failed = False
1216 if not self.cbeta:
1217 p1 = None
1218 p2 = None
1219
1220 p1 = IMP.atom.Selection(root_hier, resolution=1,
1221 molecule=chain1, residue_index=resid1,
1222 copy_index=0)
1223 p1 = p1.get_selected_particles()
1224 if len(p1) > 0:
1225 p1 = p1[0]
1226 else:
1227 failed = True
1228
1229 p2 = IMP.atom.Selection(root_hier, resolution=1,
1230 molecule=chain2, residue_index=resid2,
1231 copy_index=0)
1232 p2 = p2.get_selected_particles()
1233 if len(p2) > 0:
1234 p2 = p2[0]
1235 else:
1236 failed = True
1237
1238 else:
1239 # use cbetas
1240 p1 = []
1241 p2 = []
1242 for t in range(-1, 2):
1243 p = IMP.atom.Selection(root_hier, resolution=1,
1244 molecule=chain1, copy_index=0,
1245 residue_index=resid1 + t)
1246 p = p.get_selected_particles()
1247 if len(p) == 1:
1248 p1 += p
1249 else:
1250 failed = True
1251 warnings.warn(
1252 "CysteineCrossLink: missing representation for "
1253 "residue %d of chain %s" % (resid1 + t, chain1),
1255
1256 p = IMP.atom.Selection(root_hier, resolution=1,
1257 molecule=chain2, copy_index=0,
1258 residue_index=resid2 + t)
1259 p = p.get_selected_particles()
1260 if len(p) == 1:
1261 p2 += p
1262 else:
1263 failed = True
1264 warnings.warn(
1265 "CysteineCrossLink: missing representation for "
1266 "residue %d of chain %s" % (resid2 + t, chain2),
1268
1269 if not self.cbeta:
1270 if (p1 is not None and p2 is not None):
1271 ccl.add_contribution(p1, p2)
1272 d1 = IMP.core.XYZ(p1)
1273 d2 = IMP.core.XYZ(p2)
1274
1275 print("Distance_" + str(resid1) + "_" + chain1 + ":" +
1276 str(resid2) + "_" + chain2,
1277 IMP.core.get_distance(d1, d2))
1278
1279 else:
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()
1287
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))
1295
1296 ccl.add_contribution(p1, p2)
1297
1298 if not failed:
1299 self.rs.add_restraint(ccl)
1300 ccl.set_name("CysteineCrossLink_" + str(resid1)
1301 + "_" + chain1 + ":" + str(resid2) + "_" + chain2)
1302
1304 self.weight.get_particle()
1305 ).set_weights_are_optimized(weightissampled)
1306
1307 def set_label(self, label):
1308 self.label = label
1309
1310 def add_to_model(self):
1311 IMP.pmi.tools.add_restraint_to_model(self.m, self.rs, add_to_rmf=True)
1312
1313 def get_particles_to_sample(self):
1314 ps = {}
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)
1329 return ps
1330
1331 def set_output_level(self, level="low"):
1332 # this might be "low" or "high"
1333 self.outputlevel = level
1334
1335 def get_restraint(self):
1336 return self.rs
1337
1338 def get_sigma(self):
1339 return self.sigma
1340
1341 def get_output(self):
1342 output = {}
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))
1356
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_" +
1361 cclr.get_name() +
1362 "_" + self.label] = cclr.get_model_frequency()
1363 output["CysteineCrossLinkRestraint_Standard_Error_" +
1364 cclr.get_name() + "_" +
1365 self.label] = cclr.get_standard_error()
1366 return output
1367
1368
1369class DisulfideCrossLinkRestraint:
1370 def __init__(self, representation_or_hier,
1371 selection_tuple1,
1372 selection_tuple2,
1373 length=6.5,
1374 resolution=1,
1375 slope=0.01,
1376 label="None",
1377 exact_forward_model=False):
1378
1379 self.m = representation_or_hier.get_model()
1380 ps1 = IMP.pmi.tools.select_by_tuple_2(representation_or_hier,
1381 selection_tuple1,
1382 resolution=resolution)
1383 ps2 = IMP.pmi.tools.select_by_tuple_2(representation_or_hier,
1384 selection_tuple2,
1385 resolution=resolution)
1386
1387 self.rs = IMP.RestraintSet(self.m, 'likelihood')
1388 self.rslin = IMP.RestraintSet(self.m, 'linear_dummy_restraints')
1389
1390 # dummy linear restraint used for Chimera display
1391 self.linear = IMP.core.Linear(0, 0.0)
1392 self.linear.set_slope(0.0)
1393 dps2 = IMP.core.DistancePairScore(self.linear)
1394
1395 self.label = label
1396 self.psi_dictionary = {}
1397 self.sigma_dictionary = {}
1398 self.psi_is_sampled = False
1399 self.sigma_is_sampled = False
1400 self.xl = {}
1401
1402 _xlms_cls = _get_cross_link_restraint_class(exact_forward_model)
1403
1404 if len(ps1) > 1 or len(ps1) == 0:
1405 raise ValueError(
1406 "DisulfideBondRestraint: ERROR> first selection pattern "
1407 "selects multiple particles or sero particles")
1408
1409 if len(ps2) > 1 or len(ps2) == 0:
1410 raise ValueError(
1411 "DisulfideBondRestraint: ERROR> second selection pattern "
1412 "selects multiple particles or sero particles")
1413
1414 p1 = ps1[0]
1415 p2 = ps2[0]
1416
1417 sigma = self.create_sigma("SIGMA_DISULFIDE_BOND")
1418 psi = self.create_psi("PSI_DISULFIDE_BOND")
1419
1420 p1i = p1.get_index()
1421 p2i = p2.get_index()
1422 si = sigma.get_particle().get_index()
1423 psii = psi.get_particle().get_index()
1424
1425 dr = _xlms_cls(self.m, length, slope)
1426
1427 dr.add_contribution((p1i, p2i), (si, si), psii)
1428
1429 if p1i != p2i:
1430 pr = IMP.core.PairRestraint(self.m, dps2, (p1i, p2i))
1431 pr.set_name("DISULFIDE_BOND_"+self.label)
1432 self.rslin.add_restraint(pr)
1433
1434 lw = IMP.isd.LogWrapper([dr], 1.0)
1435 self.rs.add_restraint(lw)
1436
1437 self.xl["Particle1"] = p1
1438 self.xl["Particle2"] = p2
1439 self.xl["Sigma"] = sigma
1440 self.xl["Psi"] = psi
1441
1442 def add_to_model(self):
1443 IMP.pmi.tools.add_restraint_to_model(self.m, self.rs, add_to_rmf=True)
1445 self.m, self.rslin, add_to_rmf=True)
1446
1447 def get_hierarchies(self):
1448 return self.prot
1449
1450 def get_restraint_sets(self):
1451 return self.rs
1452
1453 def get_restraint(self):
1454 return self.rs
1455
1456 def get_restraint_for_rmf(self):
1457 return self.rslin
1458
1459 def get_restraints(self):
1460 rlist = []
1461 for r in self.rs.get_restraints():
1462 rlist.append(IMP.core.PairRestraint.get_from(r))
1463 return rlist
1464
1465 def set_psi_is_sampled(self, is_sampled=True):
1466 self.psi_is_sampled = is_sampled
1467
1468 def set_sigma_is_sampled(self, is_sampled=True):
1469 self.sigma_is_sampled = is_sampled
1470
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]
1475
1476 sigmainit = 1.0
1477 sigmaminnuis = 0.0000001
1478 sigmamaxnuis = 1000.0
1479 sigmatrans = 0.5
1480 sigma = IMP.pmi.tools.SetupNuisance(
1481 self.m, sigmainit, sigmaminnuis, sigmamaxnuis,
1482 self.sigma_is_sampled).get_particle()
1483 self.sigma_dictionary[name] = (
1484 sigma,
1485 sigmatrans,
1486 self.sigma_is_sampled)
1487
1488 return sigma
1489
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]
1494
1495 psiinit = 0.001
1496 psiminnuis = 0.0000001
1497 psimaxnuis = 0.4999999
1498 psitrans = 0.1
1499 psi = IMP.pmi.tools.SetupNuisance(self.m, psiinit,
1500 psiminnuis, psimaxnuis,
1501 self.psi_is_sampled).get_particle()
1502 self.psi_dictionary[name] = (
1503 psi,
1504 psitrans,
1505 self.psi_is_sampled)
1506
1507 return psi
1508
1509 def get_output(self):
1510 output = {}
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)
1516 return output
1517
1518 def get_particles_to_sample(self):
1519 raise NotImplementedError(" ")
The general base class for IMP exceptions.
Definition exception.h:52
Class for storing model, its restraints, constraints, and particles.
Definition Model.h:111
Object used to hold a set of restraints.
A decorator for a particle representing an atom.
Definition Atom.h:238
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.
Definition Selection.h:76
Score a pair of particles based on the distance between their centers.
Score distance between two particle centers using a harmonic function.
Linear function
Definition Linear.h:22
Modify a set of continuous variables using a normal distribution.
Definition NormalMover.h:23
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.
Definition XYZ.h:30
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.
Definition LogWrapper.h:26
Add scale parameter to particle.
Definition Scale.h:24
Uniform distribution with harmonic boundaries.
Add weights to a particle.
Definition Weight.h:29
A RestraintSet subclass to track cross-link metadata.
Warning related to handling of structures.
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.
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.
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.
Definition Surface.h:153
Inferential scoring building on methods developed as part of the Inferential Structure Determination ...
Classes for writing output files and processing them.
Definition output.py:1
Classes to handle different kinds of restraints.
Miscellaneous utilities.
Definition pmi/tools.py:1
select_by_tuple_2(hier, tuple_selection, resolution)
New tuple format: molname OR (start,stop,molname,copynum,statenum) Copy and state are optional.
Definition pmi/tools.py:435
add_restraint_to_model(model, restraint, add_to_rmf=False)
Add a PMI restraint to the model.
Definition pmi/tools.py:89
log
Definition log.py:1