IMP logo
IMP Reference Guide  2.16.0
The Integrative Modeling Platform
pmi/restraints/__init__.py
1 """@namespace IMP.pmi.restraints
2  Classes to handle different kinds of restraints.
3 
4 PMI restraints generally wrap IMP restraints. Typical features in PMI restraints are:
5  - Easy setup: for example, you can usually create one with a PMI [Molecule](@ref IMP::pmi::topology::Molecule) or a slice from one.
6  - Fast setup from data files. For example you can set up the [CrossLinkingMassSpectrometryRestraint](@ref IMP::pmi::restraints::crosslinking::CrossLinkingMassSpectrometryRestraint) by reading in a cross-link file into a [database](@ref IMP::pmi::io::crosslink::CrossLinkDataBase).
7  - Useful output: reporting functions which are put into log files when running [ReplicaExchange](@ref IMP::pmi::macros::ReplicaExchange0).
8 """ # noqa: E501
9 
10 import IMP
11 import IMP.pmi
12 import IMP.pmi.tools
13 
14 
15 class RestraintBase(object):
16  _include_in_rmf = False
17 
18  """Base class for PMI restraints, which wrap `IMP.Restraint`(s)."""
19 
20  def __init__(self, m, name=None, label=None, weight=1.,
21  restraint_set_class=IMP.RestraintSet):
22  """Constructor.
23  @param m The model object
24  @param name The name of the primary restraint set that is wrapped.
25  This is used for outputs and particle/restraint names
26  and should be set by the child class.
27  @param label A unique label to be used in outputs and
28  particle/restraint names.
29  @param weight The weight to apply to all internal restraints.
30  @param restraint_set_class The class to use for the restraint set
31  """
32  self.model = m
33  self.restraint_sets = []
34  self._label_is_set = False
35  self.weight = weight
36  self._label = None
37  self._label_suffix = ""
38  self.set_label(label)
39 
40  if not name:
41  self.name = self.__class__.__name__
42  else:
43  self.name = str(name)
44 
45  self.rs = self._create_restraint_set(name=None,
46  cls=restraint_set_class)
47 
48  def set_label(self, label):
49  """Set the unique label used in outputs and particle/restraint names.
50  @param label Label
51  """
52  if self._label_is_set:
53  raise ValueError("Label has already been set.")
54  if not label:
55  self._label = ""
56  self._label_suffix = ""
57  else:
58  self._label = str(label)
59  self._label_suffix = "_" + self._label
60  self._label_is_set = True
61 
62  @property
63  def label(self):
64  return self._label
65 
66  def set_weight(self, weight):
67  """Set the weight to apply to all internal restraints.
68  @param weight Weight
69  """
70  self.weight = weight
71  for rs in self.restraint_sets:
72  rs.set_weight(self.weight)
73 
74  def add_to_model(self):
75  """Add the restraint to the model."""
76  self._label_is_set = True
77  for rs in self.restraint_sets:
79  self.model, rs, add_to_rmf=self._include_in_rmf)
80 
81  def evaluate(self):
82  """Evaluate the score of the restraint."""
83  self._label_is_set = True
84  return self.weight * self.rs.unprotected_evaluate(None)
85 
86  def get_restraint_set(self):
87  """Get the primary restraint set."""
88  self._label_is_set = True
89  return self.rs
90 
91  def get_restraint(self):
92  """Get the primary restraint set. Identical to `get_restraint_set`."""
93  return self.get_restraint_set()
94 
95  def get_restraint_for_rmf(self):
96  """Get the restraint for visualization in an RMF file."""
97  self._label_is_set = True
98  return self.rs
99 
100  def get_particles_to_sample(self):
101  """Get any created particles which should be sampled."""
102  self._label_is_set = True
103  return {}
104 
105  def get_output(self):
106  """Get outputs to write to stat files."""
107  output = {}
108  score = self.evaluate()
109  output["_TotalScore"] = str(score)
110 
111  suffix = "_Score" + self._label_suffix
112  for rs in self.restraint_sets:
113  out_name = rs.get_name() + suffix
114  output[out_name] = str(
115  self.weight * rs.unprotected_evaluate(None))
116  return output
117 
118  def _create_restraint_set(self, name=None, cls=IMP.RestraintSet):
119  """Create ``IMP.RestraintSet``."""
120  if not name:
121  name = self.name
122  else:
123  name = self.name + "_" + str(name)
124  rs = cls(self.model, name)
125  rs.set_weight(self.weight)
126  self.restraint_sets.append(rs)
127  rs.set_was_used(True)
128  return rs
129 
130 
131 class _RestraintNuisanceMixin(object):
132 
133  """Mix-in to add nuisance particle creation functionality to restraint.
134 
135  This class must only be inherited if also inheriting
136  IMP.pmi.restraints.RestraintBase.
137  """
138 
139  def __init__(self, *args, **kwargs):
140  super(_RestraintNuisanceMixin, self).__init__(*args, **kwargs)
141  self.sampled_nuisances = {}
142  self.nuisances = {}
143 
144  def _create_nuisance(self, init_val, min_val, max_val, max_trans, name,
145  is_sampled=False):
146  """Create nuisance particle.
147  @param init_val Initial value of nuisance
148  @param min_val Minimum value of nuisance
149  @param max_val Maximum value of nuisance
150  @param max_trans Maximum move to apply to nuisance
151  @param name Name of particle
152  @param is_sampled Nuisance is a sampled particle
153  @see IMP.pmi.tools.SetupNuisance
154  """
155  nuis = IMP.pmi.tools.SetupNuisance(
156  self.model, init_val, min_val, max_val,
157  isoptimized=is_sampled).get_particle()
158  nuis_name = self.name + "_" + name
159  nuis.set_name(nuis_name)
160  self.nuisances[nuis_name] = nuis
161  if is_sampled:
162  self.sampled_nuisances[nuis_name] = (nuis, max_trans)
163  return nuis
164 
165  def get_particles_to_sample(self):
166  """Get any created particles which should be sampled."""
167  ps = super(_RestraintNuisanceMixin, self).get_particles_to_sample()
168  for name, (nuis, max_trans) in self.sampled_nuisances.items():
169  ps["Nuisances_" + name + self._label_suffix] = ([nuis], max_trans)
170  return ps
171 
172  def get_output(self):
173  """Get outputs to write to stat files."""
174  output = super(_RestraintNuisanceMixin, self).get_output()
175  for nuis_name, nuis in self.nuisances.items():
176  output[nuis_name + self._label_suffix] = str(nuis.get_scale())
177  return output
178 
179 
180 class _NuisancesBase(object):
181 
182  """This base class is used to provide nuisance setup and interface
183  for the ISD cross-link restraints"""
184 
185  sigma_dictionary = {}
186  psi_dictionary = {}
187 
188  def create_length(self):
189  """Create a nuisance on the length of the cross-link."""
190  lengthinit = 10.0
191  self.lengthissampled = True
192  lengthminnuis = 0.0000001
193  lengthmaxnuis = 1000.0
194  lengthmin = 6.0
195  lengthmax = 30.0
196  length = IMP.pmi.tools.SetupNuisance(self.m, lengthinit,
197  lengthminnuis, lengthmaxnuis,
198  self.lengthissampled
199  ).get_particle()
200  self.rslen.add_restraint(
202  self.m,
203  length,
204  1000000000.0,
205  lengthmax,
206  lengthmin))
207 
208  def create_sigma(self, resolution):
209  """Create a nuisance on the structural uncertainty."""
210  if isinstance(resolution, str):
211  sigmainit = 2.0
212  else:
213  sigmainit = resolution + 2.0
214  self.sigmaissampled = True
215  sigmaminnuis = 0.0000001
216  sigmamaxnuis = 1000.0
217  sigmamin = 0.01
218  sigmamax = 100.0
219  sigmatrans = 0.5
220  sigma = IMP.pmi.tools.SetupNuisance(self.m, sigmainit, sigmaminnuis,
221  sigmamaxnuis, self.sigmaissampled
222  ).get_particle()
223  self.sigma_dictionary[resolution] = (
224  sigma,
225  sigmatrans,
226  self.sigmaissampled)
227  self.rssig.add_restraint(
229  self.m,
230  sigma,
231  1000000000.0,
232  sigmamax,
233  sigmamin))
234  # self.rssig.add_restraint(IMP.isd.JeffreysRestraint(self.sigma))
235 
236  def get_sigma(self, resolution):
237  """Get the nuisance on structural uncertainty."""
238  if resolution not in self.sigma_dictionary:
239  self.create_sigma(resolution)
240  return self.sigma_dictionary[resolution]
241 
242  def create_psi(self, value):
243  """Create a nuisance on the inconsistency."""
244  if isinstance(value, str):
245  psiinit = 0.5
246  else:
247  psiinit = value
248  self.psiissampled = True
249  psiminnuis = 0.0000001
250  psimaxnuis = 0.4999999
251  psimin = 0.01
252  psimax = 0.49
253  psitrans = 0.1
254  psi = IMP.pmi.tools.SetupNuisance(self.m, psiinit,
255  psiminnuis, psimaxnuis,
256  self.psiissampled).get_particle()
257  self.psi_dictionary[value] = (
258  psi,
259  psitrans,
260  self.psiissampled)
261  self.rspsi.add_restraint(
263  self.m,
264  psi,
265  1000000000.0,
266  psimax,
267  psimin))
268  self.rspsi.add_restraint(IMP.isd.JeffreysRestraint(self.m, psi))
269 
270  def get_psi(self, value):
271  """Get the nuisance on the inconsistency."""
272  if value not in self.psi_dictionary:
273  self.create_psi(value)
274  return self.psi_dictionary[value]
Miscellaneous utilities.
Definition: tools.py:1
Uniform distribution with harmonic boundaries.
Definition: UniformPrior.h:20
Object used to hold a set of restraints.
Definition: RestraintSet.h:37
def add_restraint_to_model
Add a PMI restraint to the model.
Definition: tools.py:91
Python classes to represent, score, sample and analyze models.