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