1 """@namespace IMP.pmi.restraints.crosslinking
2 Restraints for handling cross-linking data.
16 from collections
import defaultdict
23 """Setup cross-link distance restraints from mass spectrometry data.
24 The noise in the data and the structural uncertainty of cross-linked
25 amino-acids is inferred using Bayes theory of probability
26 @note Wraps an IMP::isd::CrossLinkMSRestraint
28 _include_in_rmf =
True
30 def __init__(self, root_hier, database=None, length=10.0, resolution=None,
31 slope=0.02, label=
None, filelabel=
"None",
32 attributes_for_label=
None, linker=
None, weight=1.):
34 @param root_hier The canonical hierarchy containing all the states
35 @param database The IMP.pmi.io.crosslink.CrossLinkDataBase
36 object that contains the cross-link dataset
37 @param length maximal cross-linker length (including the residue
39 @param resolution what representation resolution should the cross-link
40 restraint be applied to.
41 @param slope The slope of a distance-linear scoring function that
42 funnels the score when the particles are
43 too far away. Suggested value 0.02.
44 @param label the extra text to label the restraint so that it is
45 searchable in the output
46 @param filelabel automatically generated file containing
47 missing/included/excluded
48 cross-links will be labeled using this text
49 @param attributes_for_label
50 @param weight Weight of restraint
51 @param linker description of the chemistry of the linker itself, as
52 an ihm.ChemDescriptor object
53 (see https://python-ihm.readthedocs.io/en/latest/main.html#ihm.ChemDescriptor).
54 Common cross-linkers can be found in the `ihm.cross_linkers`
58 model = root_hier.get_model()
61 model, weight=weight, label=label,
65 raise Exception(
"You must pass a database")
68 "CrossLinkingMassSpectrometryRestraint: database should "
69 "be an IMP.pmi.io.crosslink.CrossLinkDataBase object")
70 self.database = database
72 if resolution == 0
or resolution
is None:
73 raise Exception(
"You must pass a resolution and it can't be zero")
75 indb = open(
"included." + filelabel +
".xl.db",
"w")
76 exdb = open(
"excluded." + filelabel +
".xl.db",
"w")
77 midb = open(
"missing." + filelabel +
".xl.db",
"w")
82 "No linker chemistry specified. A linker must be given, as an "
83 "ihm.ChemDescriptor object (see the "
84 "CrossLinkingMassSpectrometryRestraint documentation).")
85 self.rs.set_name(self.rs.get_name() +
"_Data")
86 self.rspsi = self._create_restraint_set(
"PriorPsi")
87 self.rssig = self._create_restraint_set(
"PriorSig")
88 self.rslin = self._create_restraint_set(
"Linear")
90 self.rslin.set_weight(0.0)
92 self.rs.set_metadata(self.database.name, length, slope)
94 self.rs.set_linker_auth_name(linker.auth_name)
95 for attr
in (
'chemical_name',
'smiles',
'smiles_canonical',
96 'inchi',
'inchi_key'):
97 val = getattr(linker, attr)
99 getattr(self.rs,
"set_linker_" + attr)(val)
103 self.linear.set_slope(0.0)
106 self.psi_is_sampled =
True
107 self.sigma_is_sampled =
True
108 self.psi_dictionary = {}
109 self.sigma_dictionary = {}
111 self.outputlevel =
"low"
115 xl_groups = [p.get_cross_link_group(self)
116 for p, state
in IMP.pmi.tools._all_protocol_outputs(
120 copies_to_add = defaultdict(int)
121 print(
'gathering copies')
122 for xlid
in self.database.xlid_iterator():
123 for xl
in self.database[xlid]:
124 r1 = xl[self.database.residue1_key]
125 c1 = xl[self.database.protein1_key]
126 r2 = xl[self.database.residue2_key]
127 c2 = xl[self.database.protein2_key]
128 for c, r
in ((c1, r1), (c2, r2)):
129 if c
in copies_to_add:
132 root_hier, state_index=0, molecule=c, residue_index=r,
133 resolution=resolution).get_selected_particles()
135 copies_to_add[c] = len(sel)-1
137 for molname
in copies_to_add:
138 if copies_to_add[molname] == 0:
141 self.database.protein1_key, operator.eq, molname)
142 self.database.set_value(self.database.protein1_key,
145 self.database.protein2_key, operator.eq, molname)
146 self.database.set_value(self.database.protein2_key,
148 for ncopy
in range(copies_to_add[molname]):
149 self.database.clone_protein(
'%s.0' % molname,
150 '%s.%i' % (molname, ncopy + 1))
151 print(
'done pmi2 prelims')
153 for xlid
in self.database.xlid_iterator():
154 new_contribution =
True
155 for xl
in self.database[xlid]:
157 r1 = xl[self.database.residue1_key]
158 c1 = xl[self.database.protein1_key]
159 r2 = xl[self.database.residue2_key]
160 c2 = xl[self.database.protein2_key]
167 name1, copy1 = c1.split(
'.')
169 name2, copy2 = c2.split(
'.')
173 (p[0].add_experimental_cross_link(r1, name1, r2, name2,
176 IMP.pmi.tools._all_protocol_outputs(root_hier),
179 iterlist = range(len(IMP.atom.get_by_type(
180 root_hier, IMP.atom.STATE_TYPE)))
181 for nstate, r
in enumerate(iterlist):
183 xl[self.database.state_key] = nstate
184 xl[self.database.data_set_name_key] = self.label
187 root_hier, state_index=nstate, molecule=name1,
188 copy_index=int(copy1), residue_index=r1,
189 resolution=resolution).get_selected_particles()
191 root_hier, state_index=nstate, molecule=name2,
192 copy_index=int(copy2), residue_index=r2,
193 resolution=resolution).get_selected_particles()
200 "residue %d of chain %s selects multiple "
201 "particles %s" % (r1, c1, str(ps1)))
204 "CrossLinkingMassSpectrometryRestraint: "
205 "residue %d of chain %s is not there" % (r1, c1),
207 midb.write(str(xl) +
"\n")
212 "residue %d of chain %s selects multiple "
213 "particles %s" % (r2, c2, str(ps2)))
216 "CrossLinkingMassSpectrometryRestraint: "
217 "residue %d of chain %s is not there" % (r2, c2),
219 midb.write(str(xl) +
"\n")
225 if p1 == p2
and r1 == r2:
227 "CrossLinkingMassSpectrometryRestraint: "
228 "same particle and same residue, skipping "
233 print(
"generating a new cross-link restraint")
234 new_contribution =
False
239 dr.set_source_protein1(c1)
240 dr.set_source_protein2(c2)
241 dr.set_source_residue1(r1)
242 dr.set_source_residue2(r2)
243 restraints.append(dr)
245 if self.database.sigma1_key
not in xl.keys():
247 xl[self.database.sigma1_key] = sigma1name
249 sigma1name = xl[self.database.sigma1_key]
252 if self.database.sigma2_key
not in xl.keys():
254 xl[self.database.sigma2_key] = sigma2name
256 sigma2name = xl[self.database.sigma2_key]
259 if self.database.psi_key
not in xl.keys():
261 xl[self.database.psi_key] = psiname
263 psiname = xl[self.database.psi_key]
267 p1i = p1.get_particle_index()
269 p2i = p2.get_particle_index()
272 xl[
"Particle_sigma1"] = sigma1
274 xl[
"Particle_sigma2"] = sigma2
276 xl[
"Particle_psi"] = psi
278 dr.add_contribution((p1i, p2i), (s1i, s2i), psii)
281 print(
"--------------")
282 print(
"CrossLinkingMassSpectrometryRestraint: generating "
283 "cross-link restraint between")
284 print(
"CrossLinkingMassSpectrometryRestraint: residue %d "
285 "of chain %s and residue %d of chain %s"
287 print(
"CrossLinkingMassSpectrometryRestraint: with sigma1 "
288 "%s sigma2 %s psi %s"
289 % (sigma1name, sigma2name, psiname))
290 print(
"CrossLinkingMassSpectrometryRestraint: between "
291 "particles %s and %s"
292 % (p1.get_name(), p2.get_name()))
293 print(
"==========================================\n")
294 for p, ex_xl
in zip(IMP.pmi.tools._all_protocol_outputs(
297 p[0].add_cross_link(p[1], ex_xl[0], p1, p2, length,
298 sigma1, sigma2, psi, ex_xl[1])
305 xl[
"IntraRigidBody"] =
True
307 xl[
"IntraRigidBody"] =
False
309 xl_label = self.database.get_short_cross_link_string(xl)
310 xl[
"ShortLabel"] = xl_label
311 dr.set_name(xl_label)
316 pr.set_name(xl_label)
317 self.rslin.add_restraint(pr)
319 self.xl_list.append(xl)
321 indb.write(str(xl) +
"\n")
323 if len(self.xl_list) == 0:
325 "CrossLinkingMassSpectrometryRestraint: no cross-link "
327 self.xl_restraints = restraints
329 self.rs.add_restraint(lw)
334 def __set_dataset(self, ds):
335 self.database.dataset = ds
336 dataset = property(
lambda self: self.database.dataset, __set_dataset)
339 """ get the hierarchy """
343 """ get the restraint set """
347 """ get the restraints in a list """
348 return self.xl_restraints
351 """ get the dummy restraints to be displayed in the rmf file """
352 return self.rs, self.rssig, self.rspsi
355 """ Get a list of tuples containing the particle pairs """
357 for i
in range(len(self.pairs)):
358 p0 = self.pairs[i][0]
359 p1 = self.pairs[i][1]
360 ppairs.append((p0, p1))
364 """ Set the output level of the output """
365 self.outputlevel = level
368 """ Switch on/off the sampling of psi particles """
369 self.psi_is_sampled = is_sampled
372 """ Switch on/off the sampling of sigma particles """
373 self.sigma_is_sampled = is_sampled
376 """ This is called internally. Creates a nuisance
377 on the structural uncertainty """
378 if name
in self.sigma_dictionary:
379 return self.sigma_dictionary[name][0]
382 sigmaminnuis = 0.0000001
383 sigmamaxnuis = 1000.0
387 sigma = IMP.pmi.tools.SetupNuisance(
388 self.model, sigmainit, sigmaminnuis, sigmamaxnuis,
389 self.sigma_is_sampled, name=name).get_particle()
390 self.sigma_dictionary[name] = (
393 self.sigma_is_sampled)
394 self.rssig.add_restraint(
404 """ This is called internally. Creates a nuisance
405 on the data uncertainty """
406 if name
in self.psi_dictionary:
407 return self.psi_dictionary[name][0]
410 psiminnuis = 0.0000001
411 psimaxnuis = 0.4999999
415 psi = IMP.pmi.tools.SetupNuisance(
416 self.model, psiinit, psiminnuis, psimaxnuis,
417 self.psi_is_sampled, name=name).get_particle()
418 self.psi_dictionary[name] = (psi, psitrans, self.psi_is_sampled)
420 self.rspsi.add_restraint(
428 """Get the output of the restraint to be used by the IMP.pmi.output
433 for xl
in self.xl_list:
435 xl_label = xl[
"ShortLabel"]
439 output[
"CrossLinkingMassSpectrometryRestraint_Score_" +
440 xl_label] = str(-log(ln.unprotected_evaluate(
None)))
444 output[
"CrossLinkingMassSpectrometryRestraint_Distance_" +
447 for psiname
in self.psi_dictionary:
448 output[
"CrossLinkingMassSpectrometryRestraint_Psi_" +
449 str(psiname) + self._label_suffix] = str(
450 self.psi_dictionary[psiname][0].get_scale())
452 for sigmaname
in self.sigma_dictionary:
453 output[
"CrossLinkingMassSpectrometryRestraint_Sigma_" +
454 str(sigmaname) + self._label_suffix] = str(
455 self.sigma_dictionary[sigmaname][0].get_scale())
460 """Get the unweighted likelihood of the restraint"""
462 for restraint
in self.xl_restraints:
463 likelihood *= restraint.get_probability()
468 """ Get all need data to construct a mover in IMP.pmi.dof class"""
470 if self.sigma_is_sampled:
471 for sigmaname
in self.sigma_dictionary:
473 "Nuisances_CrossLinkingMassSpectrometryRestraint_Sigma_" \
474 + str(sigmaname) +
"_" + self.label
475 particle = self.sigma_dictionary[sigmaname][0]
476 maxstep = (self.sigma_dictionary[sigmaname][1])
480 mv.set_name(mover_name)
483 if self.psi_is_sampled:
484 for psiname
in self.psi_dictionary:
486 "Nuisances_CrossLinkingMassSpectrometryRestraint_Psi_" + \
487 str(psiname) +
"_" + self.label
488 particle = self.psi_dictionary[psiname][0]
489 maxstep = (self.psi_dictionary[psiname][1])
493 mv.set_name(mover_name)
499 """ Get the particles to be sampled by the IMP.pmi.sampler object """
501 if self.sigma_is_sampled:
502 for sigmaname
in self.sigma_dictionary:
503 ps[
"Nuisances_CrossLinkingMassSpectrometryRestraint_Sigma_" +
504 str(sigmaname) + self._label_suffix] =\
505 ([self.sigma_dictionary[sigmaname][0]],
506 self.sigma_dictionary[sigmaname][1])
508 if self.psi_is_sampled:
509 for psiname
in self.psi_dictionary:
510 ps[
"Nuisances_CrossLinkingMassSpectrometryRestraint_Psi_" +
511 str(psiname) + self._label_suffix] = \
512 ([self.psi_dictionary[psiname][0]],
513 self.psi_dictionary[psiname][1])
519 """Setup cross-link distance restraints at atomic level
520 The "atomic" aspect is that it models the particle uncertainty with
521 a Gaussian. The noise in the data and the structural uncertainty of
522 cross-linked amino-acids is inferred using Bayes' theory of probability
523 @note Wraps an IMP::isd::AtomicCrossLinkMSRestraint
526 _include_in_rmf =
True
528 def __init__(self, root_hier, xldb, atom_type="NZ", length=10.0,
529 slope=0.01, nstates=
None, label=
None,
530 nuisances_are_optimized=
True, sigma_init=5.0,
531 psi_init=0.01, one_psi=
True, filelabel=
None, weight=1.):
533 Automatically creates one "sigma" per cross-linked residue and one
535 Other nuisance options are available.
536 @note Will return an error if the data+extra_sel don't specify
537 two particles per XL pair.
538 @param root_hier The root hierarchy on which you'll do selection
539 @param xldb CrossLinkDataBase object
540 @param atom_type Can either be "NZ" or "CA"
541 @param length The XL linker length
542 @param slope Linear term to add to the restraint function to
544 @param nstates The number of states to model. Defaults to the
545 number of states in root.
546 @param label The output label for the restraint
547 @param nuisances_are_optimized Whether to optimize nuisances
548 @param sigma_init The initial value for all the sigmas
549 @param psi_init The initial value for all the psis
550 @param one_psi Use a single psi for all restraints (if False,
552 @param filelabel automatically generated file containing
553 missing/included/excluded
554 cross-links will be labeled using this text
555 @param weight Weight of restraint
560 self.root = root_hier
561 rname =
"AtomicXLRestraint"
563 self.root.get_model(), name=
"AtomicXLRestraint", label=label,
567 self.sigma_is_sampled = nuisances_are_optimized
568 self.psi_is_sampled = nuisances_are_optimized
570 if atom_type
not in (
"NZ",
"CA"):
571 raise Exception(
"AtomicXLRestraint: atom_type must be NZ or CA")
572 self.atom_type = atom_type
573 self.nstates = nstates
575 self.nstates = len(IMP.atom.get_by_type(self.root,
576 IMP.atom.STATE_TYPE))
577 elif nstates != len(IMP.atom.get_by_type(self.root,
578 IMP.atom.STATE_TYPE)):
579 print(
"Warning: nstates is not the same as the number of states "
582 self.rs_psi = self._create_restraint_set(
"psi")
583 self.rs_sig = self._create_restraint_set(
"sigma")
584 self.rs_lin = self._create_restraint_set(
"linear")
586 self.psi_dictionary = {}
587 self.sigma_dictionary = {}
589 self.particles = defaultdict(set)
590 self.one_psi = one_psi
591 self.bonded_pairs = []
593 print(
'creating a single psi for all XLs')
595 print(
'creating one psi for each XL')
598 if filelabel
is not None:
599 indb = open(
"included." + filelabel +
".xl.db",
"w")
600 exdb = open(
"excluded." + filelabel +
".xl.db",
"w")
601 midb = open(
"missing." + filelabel +
".xl.db",
"w")
604 self._create_sigma(
'sigma', sigma_init)
606 self._create_psi(
'psi', psi_init)
608 for xlid
in self.xldb.xlid_iterator():
609 self._create_psi(xlid, psi_init)
613 for xlid
in self.xldb.xlid_iterator():
616 psip = self.psi_dictionary[
'psi'][0].get_particle_index()
618 psip = self.psi_dictionary[
619 unique_id][0].get_particle_index()
625 num_contributions = 0
628 for nstate
in self.nstates:
629 for xl
in self.xldb[xlid]:
630 r1 = xl[self.xldb.residue1_key]
631 c1 = xl[self.xldb.protein1_key].strip()
632 r2 = xl[self.xldb.residue2_key]
633 c2 = xl[self.xldb.protein2_key].strip()
638 self.root, state_index=nstate,
641 residue_index=r1).get_selected_particles()
643 self.root, state_index=nstate,
646 residue_index=r2).get_selected_particles()
648 warnings.warn(
"AtomicXLRestraint: residue %d of "
649 "chain %s is not there" % (r1, c1),
651 if filelabel
is not None:
652 midb.write(str(xl) +
"\n")
656 warnings.warn(
"AtomicXLRestraint: residue %d of "
657 "chain %s is not there" % (r2, c2),
659 if filelabel
is not None:
660 midb.write(str(xl) +
"\n")
665 num1=num_xls_per_res[str(xl.r1)]
666 num2=num_xls_per_res[str(xl.r2)]
667 if num1<sig_threshold:
671 if num2<sig_threshold:
676 sig1 = self.sigma_dictionary[
'sigma'][0]
677 sig2 = self.sigma_dictionary[
'sigma'][0]
680 for p1, p2
in itertools.product(ps1, ps2):
683 self.particles[nstate] |= set((p1, p2))
685 [p1.get_index(), p2.get_index()],
686 [sig1.get_particle_index(),
687 sig2.get_particle_index()])
688 num_contributions += 1
690 if num_contributions > 0:
691 print(
'XL:', xlid,
'num contributions:', num_contributions)
694 raise Exception(
"You didn't create any XL restraints")
695 print(
'created', len(xlrs),
'XL restraints')
696 rname = self.rs.get_name()
698 self.rs.set_name(rname)
699 self.rs.set_weight(self.weight)
700 self.restraint_sets = [self.rs] + self.restraint_sets[1:]
702 def get_hierarchy(self):
705 def _create_sigma(self, name, sigmainit):
706 """ This is called internally. Creates a nuisance
707 on the structural uncertainty """
708 if name
in self.sigma_dictionary:
709 return self.sigma_dictionary[name][0]
711 sigmaminnuis = 0.0000001
712 sigmamaxnuis = 1000.0
716 sigma = IMP.pmi.tools.SetupNuisance(
717 self.model, sigmainit, sigmaminnuis, sigmamaxnuis,
718 self.sigma_is_sampled).get_particle()
719 self.sigma_dictionary[name] = (
720 sigma, sigmatrans, self.sigma_is_sampled)
722 self.model, sigma, 1000000000.0, sigmamax, sigmamin))
725 def _create_psi(self, name, psiinit):
726 """ This is called internally. Creates a nuisance
727 on the data uncertainty """
728 if name
in self.psi_dictionary:
729 return self.psi_dictionary[name][0]
731 psiminnuis = 0.0000001
732 psimaxnuis = 0.4999999
736 psi = IMP.pmi.tools.SetupNuisance(self.model,
740 self.psi_is_sampled).get_particle()
741 self.psi_dictionary[name] = (
746 self.rs_psi.add_restraint(
758 """ create dummy harmonic restraints for each XL but don't add to model
759 Makes it easy to see each contribution to each XL in RMF
761 class MyGetRestraint:
765 def get_restraint_for_rmf(self):
771 for nxl
in range(self.get_number_of_restraints()):
772 xl = IMP.isd.AtomicCrossLinkMSRestraint.get_from(
773 self.rs.get_restraint(nxl))
775 for ncontr
in range(xl.get_number_of_contributions()):
776 ps = xl.get_contribution(ncontr)
778 hps, [self.model.get_particle(p)
for p
in ps],
779 'xl%i_contr%i' % (nxl, ncontr))
781 dummy_rs.append(MyGetRestraint(rs))
785 """ Get the particles to be sampled by the IMP.pmi.sampler object """
787 if self.sigma_is_sampled:
788 for sigmaname
in self.sigma_dictionary:
789 ps[
"Nuisances_AtomicCrossLinkingMSRestraint_Sigma_" +
790 str(sigmaname) + self._label_suffix] = \
791 ([self.sigma_dictionary[sigmaname][0]],
792 self.sigma_dictionary[sigmaname][1])
793 if self.psi_is_sampled:
794 for psiname
in self.psi_dictionary:
795 ps[
"Nuisances_CrossLinkingMassSpectrometryRestraint_Psi_" +
796 str(psiname) + self._label_suffix] = \
797 ([self.psi_dictionary[psiname][0]],
798 self.psi_dictionary[psiname][1])
801 def get_bonded_pairs(self):
802 return self.bonded_pairs
804 def get_number_of_restraints(self):
805 return self.rs.get_number_of_restraints()
808 return 'XL restraint with ' + \
809 str(len(self.rs.get_restraint(0).get_number_of_restraints())) \
813 """Read a stat file and load all the sigmas.
814 This is potentially quite stupid.
815 It's also a hack since the sigmas should be stored in the RMF file.
816 Also, requires one sigma and one psi for ALL XLs.
819 sig_val = float(subprocess.check_output(
820 [
"process_output.py",
"-f", in_fn,
"-s",
821 "AtomicXLRestraint_sigma"]).split(
'\n>')[1+nframe])
822 psi_val = float(subprocess.check_output(
823 [
"process_output.py",
"-f", in_fn,
"-s",
824 "AtomicXLRestraint_psi"]).split(
'\n>')[1+nframe])
825 for nxl
in range(self.rs.get_number_of_restraints()):
826 xl = IMP.isd.AtomicCrossLinkMSRestraint.get_from(
827 self.rs.get_restraint(nxl))
830 for contr
in range(xl.get_number_of_contributions()):
831 sig1, sig2 = xl.get_contribution_sigmas(contr)
834 print(
'loaded nuisances from file')
837 min_dist_for_violation=1e9, coarsen=
False,
838 limit_to_chains=
None, exclude_chains=
''):
839 """Create CMM files, one for each state, of all cross-links.
840 will draw in GREEN if non-violated in all states (or if only one state)
841 will draw in PURPLE if non-violated only in a subset of states
842 (draws nothing elsewhere)
843 will draw in RED in ALL states if all violated
844 (if only one state, you'll only see green and red)
846 @param out_prefix Output xlink files prefix
847 @param max_prob_for_violation It's a violation if the probability
849 @param min_dist_for_violation It's a violation if the min dist
851 @param coarsen Use CA positions
852 @param limit_to_chains Try to visualize just these chains
853 @param exclude_chains Try to NOT visualize these chains
855 print(
'going to calculate violations and plot CMM files')
857 all_dists = [s[
"low_dist"]
for s
in all_stats]
863 cmds = defaultdict(set)
864 for nstate
in range(self.nstates):
865 outf = open(out_prefix+str(nstate)+
'.cmm',
'w')
866 outf.write(
'<marker_set name="xlinks_state%i"> \n' % nstate)
869 print(
'will limit to', limit_to_chains)
870 print(
'will exclude', exclude_chains)
875 for nxl
in range(self.rs.get_number_of_restraints()):
879 for nstate
in range(self.nstates):
880 prob = state_info[nstate][nxl][
"prob"]
881 low_dist = state_info[nstate][nxl][
"low_dist"]
882 if (prob < max_prob_for_violation
or
883 low_dist > min_dist_for_violation):
891 if len(npass) == self.nstates:
893 elif len(nviol) == self.nstates:
897 print(nxl,
'state dists:',
898 [state_info[nstate][nxl][
"low_dist"]
899 for nstate
in range(self.nstates)],
900 'viol states:', nviol,
'all viol?', all_viol)
901 for nstate
in range(self.nstates):
920 pp = state_info[nstate][nxl][
"low_pp"]
931 cmds[nstate].add((ch1, r1))
932 cmds[nstate].add((ch2, r2))
934 outf = out_fns[nstate]
936 outf.write(
'<marker id= "%d" x="%.3f" y="%.3f" z="%.3f" '
937 'radius="0.8" r="%.2f" g="%.2f" b="%.2f"/> \n'
938 % (nv, c1[0], c1[1], c1[2], r, g, b))
939 outf.write(
'<marker id= "%d" x="%.3f" y="%.3f" z="%.3f" '
940 'radius="0.8" r="%.2f" g="%.2f" b="%.2f"/> \n'
941 % (nv+1, c2[0], c2[1], c2[2], r, g, b))
942 outf.write(
'<link id1= "%d" id2="%d" radius="0.8" '
943 'r="%.2f" g="%.2f" b="%.2f"/> \n'
944 % (nv, nv+1, r, g, b))
947 for nstate
in range(self.nstates):
948 out_fns[nstate].write(
'</marker_set>\n')
949 out_fns[nstate].close()
951 for ch, r
in cmds[nstate]:
952 cmd +=
'#%i:%i.%s ' % (nstate, r, ch)
957 def _get_contribution_info(self, xl, ncontr, use_CA=False):
958 """Return the particles at that contribution. If requested will
959 return CA's instead"""
960 idx1 = xl.get_contribution(ncontr)[0]
961 idx2 = xl.get_contribution(ncontr)[1]
966 idx1 = sel.get_selected_particle_indexes()[0]
970 idx2 = sel.get_selected_particle_indexes()[0]
974 return idx1, idx2, dist
977 exclude_chains=
'', use_CA=
False):
978 ''' return the probability, best distance, two coords, and possibly
980 @param limit_to_state Only examine contributions from one state
981 @param limit_to_chains Returns the particles for certain "easy
983 @param exclude_chains Even if you limit, don't let one end be in
984 this list. Only works if you also limit chains
985 @param use_CA Limit to CA particles
988 for nxl
in range(self.rs.get_number_of_restraints()):
990 xl = IMP.isd.AtomicCrossLinkMSRestraint.get_from(
991 self.rs.get_restraint(nxl))
997 for contr
in range(xl.get_number_of_contributions()):
998 pp = xl.get_contribution(contr)
1003 idx1 = sel.get_selected_particle_indexes()[0]
1007 idx2 = sel.get_selected_particle_indexes()[0]
1009 if limit_to_state
is not None:
1012 if nstate != limit_to_state:
1014 state_contrs.append(contr)
1017 if limit_to_chains
is not None:
1022 if (c1
in limit_to_chains
or c2
in limit_to_chains)
and (
1023 c1
not in exclude_chains
1024 and c2
not in exclude_chains):
1025 if dist < low_dist_lim:
1031 if limit_to_state
is not None:
1032 this_info[
"prob"] = xl.evaluate_for_contributions(
1035 this_info[
"prob"] = xl.unprotected_evaluate(
None)
1036 if limit_to_chains
is not None:
1037 this_info[
"low_pp"] = low_pp_lim
1039 this_info[
"low_pp"] = low_pp
1041 this_info[
"low_dist"] = low_dist
1042 if not self.one_psi:
1044 this_info[
"psi"] = pval
1045 ret.append(this_info)
1048 def print_stats(self):
1050 for nxl, s
in enumerate(stats):
1051 print(s[
"low_dist"])
1053 def get_output(self):
1054 output = super().get_output()
1065 for nxl, s
in enumerate(stats):
1066 if s[
'low_dist'] > 20.0:
1068 output[
"AtomicXLRestraint_%i_%s" % (nxl,
"Prob")] = str(s[
'prob'])
1069 output[
"AtomicXLRestraint_%i_%s"
1070 % (nxl,
"BestDist")] = str(s[
'low_dist'])
1071 if not self.one_psi:
1072 output[
"AtomicXLRestraint_%i_%s" % (nxl,
"psi")] \
1074 output[
"AtomicXLRestraint_NumViol"] = str(bad_count)
1078 class CysteineCrossLinkRestraint:
1079 def __init__(self, root_hier, filename, cbeta=False,
1080 betatuple=(0.03, 0.1),
1081 disttuple=(0.0, 25.0, 1000),
1082 omegatuple=(1.0, 1000.0, 50),
1083 sigmatuple=(0.3, 0.3, 1),
1085 sigmaissampled=
False,
1086 weightissampled=
True,
1087 epsilonissampled=
True):
1094 self.m = root_hier.get_model()
1097 self.epsilonmaxtrans = 0.01
1098 self.sigmamaxtrans = 0.1
1099 self.betamaxtrans = 0.01
1100 self.weightmaxtrans = 0.1
1102 self.outputlevel =
"low"
1103 self.betaissampled = betaissampled
1104 self.sigmaissampled = sigmaissampled
1105 self.weightissampled = weightissampled
1106 self.epsilonissampled = epsilonissampled
1108 betalower = betatuple[0]
1109 betaupper = betatuple[1]
1115 self.beta = IMP.pmi.tools.SetupNuisance(
1120 betaissampled).get_particle(
1123 self.sigma = IMP.pmi.tools.SetupNuisance(
1128 sigmaissampled).get_particle()
1130 self.weight = IMP.pmi.tools.SetupWeight(
1132 isoptimized=
False).get_particle(
1136 fl = IMP.pmi.tools.open_file_or_inline_text(filename)
1145 if t[5]
in self.epsilons:
1146 if 1.0 - float(t[4]) <= self.epsilons[t[5]].get_upper():
1147 self.epsilons[t[5]].set_upper(1.0 - float(t[4]))
1149 self.epsilons[t[5]] = IMP.pmi.tools.SetupNuisance(
1150 self.m, 0.01, 0.01, 1.0 - float(t[4]),
1151 epsilonissampled).get_particle()
1152 up = self.epsilons[t[5]].get_upper()
1153 low = self.epsilons[t[5]].get_lower()
1155 self.epsilons[t[5]].set_upper(low)
1157 data.append((int(t[0]), t[1], int(t[2]), t[3], float(t[4]), t[5]))
1161 crossdata = IMP.pmi.tools.get_cross_link_data(
1162 "cysteine",
"cysteine_CA_FES.txt.standard",
1163 disttuple, omegatuple, sigmatuple, disttuple[1],
1166 crossdata = IMP.pmi.tools.get_cross_link_data(
1167 "cysteine",
"cysteine_CB_FES.txt.standard",
1168 disttuple, omegatuple, sigmatuple, disttuple[1],
1172 fmod_grid = IMP.pmi.tools.get_grid(0.0, 1.0, 300,
True)
1173 omega2_grid = IMP.pmi.tools.get_log_grid(0.001, 10000.0, 100)
1174 beta_grid = IMP.pmi.tools.get_log_grid(betalower, betaupper, betangrid)
1177 print(
"--------------")
1178 print(
"CysteineCrossLink: attempting to create a restraint "
1199 self.epsilons[epslabel],
1210 molecule=chain1, residue_index=resid1,
1212 p1 = p1.get_selected_particles()
1219 molecule=chain2, residue_index=resid2,
1221 p2 = p2.get_selected_particles()
1231 for t
in range(-1, 2):
1233 molecule=chain1, copy_index=0,
1234 residue_index=resid1 + t)
1235 p = p.get_selected_particles()
1241 "CysteineCrossLink: missing representation for "
1242 "residue %d of chain %s" % (resid1 + t, chain1),
1246 molecule=chain2, copy_index=0,
1247 residue_index=resid2 + t)
1248 p = p.get_selected_particles()
1254 "CysteineCrossLink: missing representation for "
1255 "residue %d of chain %s" % (resid2 + t, chain2),
1259 if (p1
is not None and p2
is not None):
1260 ccl.add_contribution(p1, p2)
1264 print(
"Distance_" + str(resid1) +
"_" + chain1 +
":" +
1265 str(resid2) +
"_" + chain2,
1269 if (len(p1) == 3
and len(p2) == 3):
1270 p11n = p1[0].get_name()
1271 p12n = p1[1].get_name()
1272 p13n = p1[2].get_name()
1273 p21n = p2[0].get_name()
1274 p22n = p2[1].get_name()
1275 p23n = p2[2].get_name()
1277 print(
"CysteineCrossLink: generating CB cysteine "
1278 "cross-link restraint between")
1279 print(
"CysteineCrossLink: residue %d of chain %s and "
1280 "residue %d of chain %s"
1281 % (resid1, chain1, resid2, chain2))
1282 print(
"CysteineCrossLink: between particles %s %s %s and "
1283 "%s %s %s" % (p11n, p12n, p13n, p21n, p22n, p23n))
1285 ccl.add_contribution(p1, p2)
1288 self.rs.add_restraint(ccl)
1289 ccl.set_name(
"CysteineCrossLink_" + str(resid1)
1290 +
"_" + chain1 +
":" + str(resid2) +
"_" + chain2)
1293 self.weight.get_particle()
1294 ).set_weights_are_optimized(weightissampled)
1296 def set_label(self, label):
1299 def add_to_model(self):
1304 if self.epsilonissampled:
1305 for eps
in self.epsilons.keys():
1306 ps[
"Nuisances_CysteineCrossLinkRestraint_epsilon_" + eps +
1307 "_" + self.label] = ([self.epsilons[eps]],
1308 self.epsilonmaxtrans)
1309 if self.betaissampled:
1310 ps[
"Nuisances_CysteineCrossLinkRestraint_beta_" +
1311 self.label] = ([self.beta], self.betamaxtrans)
1312 if self.weightissampled:
1313 ps[
"Weights_CysteineCrossLinkRestraint_" +
1314 self.label] = ([self.weight], self.weightmaxtrans)
1315 if self.sigmaissampled:
1316 ps[
"Nuisances_CysteineCrossLinkRestraint_" +
1317 self.label] = ([self.sigma], self.sigmamaxtrans)
1320 def set_output_level(self, level="low"):
1322 self.outputlevel = level
1324 def get_restraint(self):
1327 def get_sigma(self):
1330 def get_output(self):
1332 score = self.rs.unprotected_evaluate(
None)
1333 output[
"_TotalScore"] = str(score)
1334 output[
"CysteineCrossLinkRestraint_Score_" + self.label] = str(score)
1335 output[
"CysteineCrossLinkRestraint_sigma_" +
1336 self.label] = str(self.sigma.get_scale())
1337 for eps
in self.epsilons.keys():
1338 output[
"CysteineCrossLinkRestraint_epsilon_" + eps +
"_" +
1339 self.label] = str(self.epsilons[eps].get_scale())
1340 output[
"CysteineCrossLinkRestraint_beta_" +
1341 self.label] = str(self.beta.get_scale())
1342 for n
in range(self.weight.get_number_of_weights()):
1343 output[
"CysteineCrossLinkRestraint_weights_" +
1344 str(n) +
"_" + self.label] = str(self.weight.get_weight(n))
1346 if self.outputlevel ==
"high":
1347 for rst
in self.rs.get_restraints():
1348 cclr = IMP.isd.CysteineCrossLinkRestraint.get_from(rst)
1349 output[
"CysteineCrossLinkRestraint_Total_Frequency_" +
1351 "_" + self.label] = cclr.get_model_frequency()
1352 output[
"CysteineCrossLinkRestraint_Standard_Error_" +
1353 cclr.get_name() +
"_" +
1354 self.label] = cclr.get_standard_error()
1358 class DisulfideCrossLinkRestraint:
1359 def __init__(self, representation_or_hier,
1367 self.m = representation_or_hier.get_model()
1370 resolution=resolution)
1373 resolution=resolution)
1380 self.linear.set_slope(0.0)
1384 self.psi_dictionary = {}
1385 self.sigma_dictionary = {}
1386 self.psi_is_sampled =
False
1387 self.sigma_is_sampled =
False
1390 if len(ps1) > 1
or len(ps1) == 0:
1392 "DisulfideBondRestraint: ERROR> first selection pattern "
1393 "selects multiple particles or sero particles")
1395 if len(ps2) > 1
or len(ps2) == 0:
1397 "DisulfideBondRestraint: ERROR> second selection pattern "
1398 "selects multiple particles or sero particles")
1403 sigma = self.create_sigma(
"SIGMA_DISULFIDE_BOND")
1404 psi = self.create_psi(
"PSI_DISULFIDE_BOND")
1406 p1i = p1.get_index()
1407 p2i = p2.get_index()
1413 dr.add_contribution((p1i, p2i), (si, si), psii)
1417 pr.set_name(
"DISULFIDE_BOND_"+self.label)
1418 self.rslin.add_restraint(pr)
1421 self.rs.add_restraint(lw)
1423 self.xl[
"Particle1"] = p1
1424 self.xl[
"Particle2"] = p2
1425 self.xl[
"Sigma"] = sigma
1426 self.xl[
"Psi"] = psi
1428 def add_to_model(self):
1431 self.m, self.rslin, add_to_rmf=
True)
1433 def get_hierarchies(self):
1436 def get_restraint_sets(self):
1439 def get_restraint(self):
1442 def get_restraint_for_rmf(self):
1445 def get_restraints(self):
1447 for r
in self.rs.get_restraints():
1448 rlist.append(IMP.core.PairRestraint.get_from(r))
1451 def set_psi_is_sampled(self, is_sampled=True):
1452 self.psi_is_sampled = is_sampled
1454 def set_sigma_is_sampled(self, is_sampled=True):
1455 self.sigma_is_sampled = is_sampled
1457 def create_sigma(self, name):
1458 ''' a nuisance on the structural uncertainty '''
1459 if name
in self.sigma_dictionary:
1460 return self.sigma_dictionary[name][0]
1463 sigmaminnuis = 0.0000001
1464 sigmamaxnuis = 1000.0
1466 sigma = IMP.pmi.tools.SetupNuisance(
1467 self.m, sigmainit, sigmaminnuis, sigmamaxnuis,
1468 self.sigma_is_sampled).get_particle()
1469 self.sigma_dictionary[name] = (
1472 self.sigma_is_sampled)
1476 def create_psi(self, name):
1477 ''' a nuisance on the inconsistency '''
1478 if name
in self.psi_dictionary:
1479 return self.psi_dictionary[name][0]
1482 psiminnuis = 0.0000001
1483 psimaxnuis = 0.4999999
1485 psi = IMP.pmi.tools.SetupNuisance(self.m, psiinit,
1486 psiminnuis, psimaxnuis,
1487 self.psi_is_sampled).get_particle()
1488 self.psi_dictionary[name] = (
1491 self.psi_is_sampled)
1495 def get_output(self):
1497 score = self.rs.unprotected_evaluate(
None)
1498 output[
"_TotalScore"] = str(score)
1499 output[
"DisulfideBondRestraint_Data_Score_" + self.label] = str(score)
1500 output[
"DisulfideBondRestraint_Linear_Score_" +
1501 self.label] = self.rslin.unprotected_evaluate(
None)
1505 raise NotImplementedError(
" ")
def set_sigma_is_sampled
Switch on/off the sampling of sigma particles.
Setup cross-link distance restraints from mass spectrometry data.
Add weights to a particle.
A restraint for ambiguous cross-linking MS data and multiple state approach.
def get_best_stats
return the probability, best distance, two coords, and possibly the psi for each xl ...
def get_hierarchies
get the hierarchy
Various classes to hold sets of particles.
def get_particles_to_sample
Get the particles to be sampled by the IMP.pmi.sampler object.
Restrain atom pairs based on a set of crosslinks.
Handles cross-link data sets.
def get_likelihood
Get the unweighted likelihood of the restraint.
Add scale parameter to particle.
static bool get_is_setup(const IMP::ParticleAdaptor &p)
Score distance between two particle centers using a harmonic function.
double get_distance(XYZR a, XYZR b)
Compute the sphere distance between a and b.
def get_particles_to_sample
Get the particles to be sampled by the IMP.pmi.sampler object.
Object used to hold a set of restraints.
Class for storing model, its restraints, constraints, and particles.
Classes to handle different kinds of restraints.
A RestraintSet subclass to track cross-link metadata.
Warning related to handling of structures.
def set_output_level
Set the output level of the output.
The standard decorator for manipulating molecular structures.
Ints get_index(const ParticlesTemp &particles, const Subset &subset, const Subsets &excluded)
def get_restraints
get the restraints in a list
A decorator for a particle representing an atom.
This class allows to create filter functions that can be passed to the CrossLinkDataBase in this way:...
def get_movers
Get all need data to construct a mover in IMP.pmi.dof class.
def get_particle_pairs
Get a list of tuples containing the particle pairs.
def create_psi
This is called internally.
A decorator for a particle with x,y,z coordinates.
def create_sigma
This is called internally.
int get_state_index(Hierarchy h)
Walk up the hierarchy to find the current state.
def plot_violations
Create CMM files, one for each state, of all cross-links.
Modify a set of continuous variables using a normal distribution.
Score a pair of particles based on the distance between their centers.
Classes for writing output files and processing them.
double get_distance(const SphereD< D > &a, const SphereD< D > &b)
Return the distance between the two spheres if they are disjoint.
Basic functionality that is expected to be used by a wide variety of IMP users.
General purpose algebraic and geometric methods that are expected to be used by a wide variety of IMP...
def create_restraints_for_rmf
create dummy harmonic restraints for each XL but don't add to model Makes it easy to see each contrib...
The general base class for IMP exceptions.
Setup cross-link distance restraints at atomic level The "atomic" aspect is that it models the partic...
Residue get_residue(Atom d, bool nothrow=false)
Return the Residue containing this atom.
Calculate the -Log of a list of restraints.
def get_restraint_sets
get the restraint set
Applies a PairScore to a Pair.
def get_output
Get the output of the restraint to be used by the IMP.pmi.output object.
def get_restraint_for_rmf
get the dummy restraints to be displayed in the rmf file
Functionality for loading, creating, manipulating and scoring atomic structures.
std::string get_chain_id(Hierarchy h)
Walk up the hierarchy to determine the chain id.
def load_nuisances_from_stat_file
Read a stat file and load all the sigmas.
Select hierarchy particles identified by the biological name.
this class handles a cross-link dataset and do filtering operations, adding cross-links, merge datasets...
def set_psi_is_sampled
Switch on/off the sampling of psi particles.
Inferential scoring building on methods developed as part of the Inferential Structure Determination ...
A restraint for cysteine cross-linking data.