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