IMP logo
IMP Reference Guide  2.13.0
The Integrative Modeling Platform
restraints/saxs.py
1 """@namespace IMP.pmi.restraints.saxs
2 Restraints for handling small angle x-ray (SAXS) data.
3 """
4 
5 from __future__ import print_function
6 import math
7 import IMP
8 import IMP.core
9 import IMP.algebra
10 import IMP.atom
11 import IMP.container
12 import IMP.pmi.tools
13 import IMP.pmi.restraints
14 import IMP.saxs
15 import warnings
16 
17 class SAXSRestraint(IMP.pmi.restraints.RestraintBase):
18  _include_in_rmf = True
19 
20  """Basic SAXS restraint."""
21 
22  def __init__(self, input_objects, saxs_datafile, weight=1.0,
23  ff_type=IMP.saxs.HEAVY_ATOMS, label=None, maxq="standard"):
24  """Builds the restraint.
25  @param input_objects A list of hierarchies or PMI objects that the
26  SAXS restraint will be applied to. This hierarchy MUST be
27  atomic. You can pass a list of CA atom particles to evaluate
28  at residue resolution
29  @param saxs_datafile the SAXS .dat file.
30  @param weight Restraint score coefficient
31  @param ff_type the form factor to use, of the following types:
32  - IMP.saxs.HEAVY_ATOMS: use form factors with implicit
33  hydrogens
34  - IMP.saxs.ALL_ATOMS: use individual form factors for all
35  atoms. Does not build missing hydrogens.
36  - IMP.saxs.CA_ATOMS: use residue based form factors
37  centered at CA atoms
38  @param label Label for the restraint in outputs
39 
40  @param maxq - maximum q value that the restraint will be evaluated at
41  Default vaules for ff_type = ALL_ATOMS : 0.5. HEAVY_ATOMS : 0.4,
42  CA_ATOMS and RESIDUES = 0.15. These values were eyeballed
43  by comparing ALL_ATOM calculated SAXS profiles to those calculated
44  with the reduced representations, so could be improved.
45  """
46  # Get all hierarchies.
47  hiers = IMP.pmi.tools.input_adaptor(input_objects,
48  flatten=True)
49  model = list(hiers)[0].get_model()
50  super(SAXSRestraint, self).__init__(model, label=label, weight=weight)
51 
52  # Determine maxq to compare computed and experimental profiles
53  if maxq == "standard":
54  if ff_type == IMP.saxs.CA_ATOMS or ff_type == IMP.saxs.RESIDUES:
55  maxq = 0.15
56  elif ff_type == IMP.saxs.HEAVY_ATOMS:
57  maxq = 0.4
58  else:
59  maxq = 0.5
60  elif type(maxq) == float:
61  if maxq < 0.01 or maxq > 4.0:
62  raise Exception("SAXSRestraint: maxq must be set between 0.01 and 4.0")
63  if (ff_type == IMP.saxs.CA_ATOMS or ff_type == IMP.saxs.RESIDUES) and maxq > 0.15:
64  warnings.warn("SAXSRestraint: for residue-resolved form "
65  "factors, a maxq > 0.15 is not recommended!",
67  else:
68  raise Exception("SAXSRestraint: maxq must be set to a number between 0.01 and 4.0")
69 
70  # Depending on the type of FF used, get the correct particles
71  # from the hierarchies list and create an IMP::saxs::Profile()
72  # at the appropriate maxq.
73  if ff_type == IMP.saxs.RESIDUES:
74  self.particles = IMP.atom.Selection(
75  hiers, resolution=1).get_selected_particles()
76  self.profile = IMP.saxs.Profile(saxs_datafile, False, maxq)
77  elif ff_type == IMP.saxs.CA_ATOMS:
78  self.particles = IMP.atom.Selection(
79  hiers, atom_type=IMP.atom.AT_CA).get_selected_particles()
80  self.profile = IMP.saxs.Profile(saxs_datafile, False, maxq)
81  elif ff_type == IMP.saxs.HEAVY_ATOMS or ff_type == IMP.saxs.ALL_ATOMS:
82  self.particles = IMP.atom.Selection(
83  hiers, resolution=0).get_selected_particles()
84  self.profile = IMP.saxs.Profile(saxs_datafile, False, maxq)
85  else:
86  raise Exception("SAXSRestraint: Must provide an IMP.saxs atom type: RESIDUES, CA_ATOMS, HEAVY_ATOMS or ALL_ATOMS")
87 
88  if len(self.particles) == 0:
89  raise Exception("SAXSRestraint: There are no selected particles")
90 
91  self.restraint = IMP.saxs.Restraint(self.particles, self.profile,
92  ff_type)
93  self.rs.add_restraint(self.restraint)
94 
95 
96 class SAXSISDRestraint(IMP.pmi.restraints.RestraintBase):
97 
98  """Basic SAXS restraint using ISD."""
99 
100  import IMP.isd
101  try:
102  import IMP.isd2
103  except:
104  print("Module isd2 not installed. Cannot use SAXSISDRestraint")
105 
106  def __init__(self, representation, profile, resolution=0, weight=1,
107  ff_type=IMP.saxs.HEAVY_ATOMS, label=None):
108 
109  model = representation.prot.get_model()
110  super(SAXSISDRestraint, self).__init__(model, label=label,
111  weight=weight)
112 
113  self.taumaxtrans = 0.05
114  self.prof = IMP.saxs.Profile(profile)
115 
116  self.atoms = IMP.pmi.tools.select(
117  representation,
118  resolution=resolution)
119 
120  # gamma nuisance
121  self.gamma = IMP.pmi.tools.SetupNuisance(
122  self.model, 1., 0., None, False).get_particle()
123 
124  # sigma nuisance
125  self.sigma = IMP.pmi.tools.SetupNuisance(self.model, 10.0, 0., None, False
126  ).get_particle()
127 
128  # tau nuisance, optimized
129  self.tau = IMP.pmi.tools.SetupNuisance(self.model, 1., 0., None, False,
130  ).get_particle()
131 
132  # c1 and c2, optimized
133  self.c1 = IMP.pmi.tools.SetupNuisance(self.model, 1.0, 0.95, 1.05,
134  True).get_particle()
135  self.c2 = IMP.pmi.tools.SetupNuisance(self.model, 0.0, -2., 4.,
136  True).get_particle()
137 
138  # weight, optimized
139  self.w = IMP.pmi.tools.SetupWeight(self.model).get_particle()
140  IMP.isd.Weight(self.w).set_weights_are_optimized(False)
141 
142  # take identity covariance matrix for the start
143  self.cov = [[1 if i == j else 0 for j in range(self.prof.size())]
144  for i in range(self.prof.size())]
145 
146  print("create saxs restraint")
147  self.saxs = IMP.isd2.SAXSRestraint(self.prof, self.sigma, self.tau,
148  self.gamma, self.w, self.c1,
149  self.c2)
150  self.saxs.add_scatterer(self.atoms, self.cov, ff_type)
151 
152  self.rs.add_restraint(self.saxs)
153 
154  # self.saxs_stuff={'nuis':(sigma,gamma),'cov':cov,
155  # 'exp':prof,'th':tmp}
156 
157  self.rs2 = self._create_restraint_set('Prior')
158  # jeffreys restraints for nuisances
159  j1 = IMP.isd.JeffreysRestraint(self.model, self.sigma)
160  self.rs2.add_restraint(j1)
161  j2 = IMP.isd.JeffreysRestraint(self.model, self.tau)
162  self.rs2.add_restraint(j2)
163  j3 = IMP.isd.JeffreysRestraint(self.model, self.gamma)
164  self.rs2.add_restraint(j3)
165 
166  pw = IMP.isd.Weight(self.w)
167  pw.set_weights(pw.get_unit_simplex().get_barycenter())
168  pw.set_weights_are_optimized(True)
169 
170  def optimize_sigma(self):
171  """Set sigma to the value that maximizes its conditional likelihood"""
172  self.model.update()
173  sigma2hat = self.saxs.get_sigmasq_scale_parameter() \
174  / (self.saxs.get_sigmasq_shape_parameter() + 1)
175  IMP.isd.Scale(self.sigma).set_scale(math.sqrt(sigma2hat))
176 
177  def optimize_gamma(self):
178  """Set gamma to the value that maximizes its conditional likelihood"""
179  self.model.update()
180  gammahat = math.exp(self.saxs.get_loggamma_variance_parameter() *
181  self.saxs.get_loggamma_jOg_parameter())
182  IMP.isd.Scale(self.gamma).set_scale(gammahat)
183 
184  def optimize_tau(self, ltaumin=-2, ltaumax=3, npoints=100):
185  values = []
186  self.model.update()
187  IMP.atom.write_pdb(self.atoms, 'tauvals.pdb')
188  fl = open('tauvals.txt', 'w')
189  for tauval in self._logspace(ltaumin, ltaumax, npoints):
190  IMP.isd.Scale(self.tau).set_scale(tauval)
191  try:
192  values.append((self.model.evaluate(False), tauval))
193  except:
194  pass
195  fl.write('%G %G\n' % (values[-1][1], values[-1][0]))
196  values.sort()
197  ltcenter = math.log(values[0][1]) / math.log(10)
198  spacing = (ltaumax - ltaumin) / float(npoints)
199  values = []
200  for tauval in self._logspace(
201  ltcenter - 2 * spacing, ltcenter + 2 * spacing,
202  npoints):
203  IMP.isd.Scale(self.tau).set_scale(tauval)
204  values.append((self.model.evaluate(False), tauval))
205  fl.write('%G %G\n' % (values[-1][1], values[-1][0]))
206  values.sort()
207  IMP.isd.Scale(self.tau).set_scale(values[0][1])
208 
209  def get_gamma_value(self):
210  """Get value of gamma."""
211  return self.gamma.get_scale()
212 
213  def set_taumaxtrans(self, taumaxtrans):
214  self.taumaxtrans = taumaxtrans
215 
216  def draw_sigma(self):
217  """Draw 1/sigma2 from gamma distribution."""
218  self.model.update()
219  self.saxs.draw_sigma()
220 
221  def draw_gamma(self):
222  """Draw gamma from lognormal distribution."""
223  self.model.update()
224  self.saxs.draw_gamma()
225 
226  def update_covariance_matrix(self):
227  c1 = IMP.isd.Nuisance(self.c1).get_nuisance()
228  c2 = IMP.isd.Nuisance(self.c2).get_nuisance()
229  # tau = IMP.isd.Nuisance(self.tau).get_nuisance()
230  tau = 1.0
231  self.cov = IMP.isd2.compute_relative_covariance(self.atoms, c1, c2,
232  tau, self.prof)
233  # for i in xrange(len(self.cov)):
234  # for j in xrange(len(self.cov)):
235  # self.cov[i][j] = self.cov[i][j]/tau**2
236  self.saxs.set_cov(0, self.cov)
237 
238  def write_covariance_matrix(self, fname):
239  fl = open(fname, 'w')
240  for line in self.cov:
241  for i in line:
242  fl.write('%G ' % i)
243  fl.write('\n')
244 
245  def get_output(self):
246  output = super(SAXSISDRestraint, self).get_output()
247  suffix = self._get_label_suffix()
248  output["SAXSISDRestraint_Sigma" +
249  suffix] = str(self.sigma.get_scale())
250  output["SAXSISDRestraint_Tau" + suffix] = str(self.tau.get_scale())
251  output["SAXSISDRestraint_Gamma" +
252  suffix] = str(self.gamma.get_scale())
253  return output
254 
255  @staticmethod
256  def _logspace(a, b, num=100):
257  """Mimick numpy's logspace function"""
258  for i in range(num):
259  val = a + float(b - a) / float(num - 1) * i
260  yield 10 ** val
Add weights to a particle.
Definition: Weight.h:29
Various classes to hold sets of particles.
def optimize_gamma
Set gamma to the value that maximizes its conditional likelihood.
Calculate score based on fit to SAXS profile.
Miscellaneous utilities.
Definition: tools.py:1
void write_pdb(const Selection &mhd, TextOutput out, unsigned int model=1)
Add scale parameter to particle.
Definition: Scale.h:24
Classes to handle different kinds of restraints.
def input_adaptor
Adapt things for PMI (degrees of freedom, restraints, ...) Returns list of list of hierarchies...
Definition: tools.py:917
def optimize_sigma
Set sigma to the value that maximizes its conditional likelihood.
def draw_gamma
Draw gamma from lognormal distribution.
Add nuisance parameter to particle.
Definition: Nuisance.h:25
Basic SAXS restraint using ISD.
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...
The general base class for IMP exceptions.
Definition: exception.h:49
def draw_sigma
Draw 1/sigma2 from gamma distribution.
Functionality for loading, creating, manipulating and scoring atomic structures.
Select hierarchy particles identified by the biological name.
Definition: Selection.h:66
Support for small angle X-ray scattering (SAXS) data.
Warning for probably incorrect input parameters.
Inferential scoring building on methods developed as part of the Inferential Structure Determination ...