/[escript]/trunk/downunder/py_src/forwardmodels.py
ViewVC logotype

Contents of /trunk/downunder/py_src/forwardmodels.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 4050 - (show annotations)
Wed Oct 31 01:01:24 2012 UTC (7 years ago) by caltinay
File MIME type: text/x-python
File size: 11366 byte(s)
Changed initial Hessian in magnetic test and removed some debug output.

1
2 ##############################################################################
3 #
4 # Copyright (c) 2003-2012 by University of Queensland
5 # http://www.uq.edu.au
6 #
7 # Primary Business: Queensland, Australia
8 # Licensed under the Open Software License version 3.0
9 # http://www.opensource.org/licenses/osl-3.0.php
10 #
11 # Development until 2012 by Earth Systems Science Computational Center (ESSCC)
12 # Development since 2012 by School of Earth Sciences
13 #
14 ##############################################################################
15
16 """Collection of forward models that define the inversion problem"""
17
18 __copyright__="""Copyright (c) 2003-2012 by University of Queensland
19 http://www.uq.edu.au
20 Primary Business: Queensland, Australia"""
21 __license__="""Licensed under the Open Software License version 3.0
22 http://www.opensource.org/licenses/osl-3.0.php"""
23 __url__="https://launchpad.net/escript-finley"
24
25 __all__ = ['ForwardModel','GravityModel']
26
27 from esys.escript import unitsSI as U
28 from esys.escript.linearPDEs import LinearSinglePDE, LinearPDE
29 from esys.escript.util import *
30 from esys.escript import Data, Vector, Scalar, Function
31 from math import pi as PI
32
33 class ForwardModel(object):
34 """
35 An abstract forward model that can be plugged into a cost function.
36 Subclasses need to implement `getValue()`, `getGradient()`, and possibly
37 `getArguments()`.
38 """
39 def __init__(self):
40 pass
41
42 def getArguments(self, x):
43 return ()
44
45 def getValue(self, x, *args):
46 raise NotImplementedError
47
48 def getGradient(self, x, *args):
49 raise NotImplementedError
50
51 class ForwardModelWithPotential(ForwardModel):
52 """
53 Base class for a forward model using a potential such as magnetic or
54 gravity. It defines a cost function
55
56 defect = 1/2 sum_s integrate( weight_i[s] * ( r_i - data_i[s] )**2 )
57
58 where s runs over the survey, weight_i are weighting factors, data_i are
59 the data, and r_i are the results produced by the forward model.
60 It is assumed that the forward model is produced through postprocessing
61 of the solution of a potential PDE.
62 """
63 def __init__(self, domain, weight, data, fix_all_faces=False, tol=1e-8):
64 """
65 initialization.
66
67 :param domain: domain of the model
68 :type domain: `esys.escript.Domain`
69 :param weight: data weighting factors
70 :type weight: `Vector` or list of `Vector`
71 :param data: data
72 :type data: `Vector` or list of `Vector`
73 :param fix_all_faces: if ``true`` all faces of the domain are fixed
74 otherwise only the top surface
75 :type fix_all_faces: ``bool``
76 :param tol: tolerance of underlying PDE
77 :type tol: positive ``float``
78
79 """
80 super(ForwardModelWithPotential, self).__init__()
81 self.__domain = domain
82
83 try:
84 n=len(weight)
85 m=len(data)
86 if m != n:
87 raise ValueError("Length of weight and g must be the same.")
88 self.__weight = weight
89 self.__data = data
90 except TypeError:
91 self.__weight = [weight]
92 self.__data = [data]
93
94 A=0
95 for s in xrange(len(self.__weight)):
96 A2 = integrate(inner(self.__weight[s], self.__data[s]**2))
97 if A2 < 0:
98 raise ValueError("Negative weighting factor for survey %s"%s)
99 A=max(A2, A)
100 if not A > 0:
101 raise ValueError("No reference data set.")
102
103 BX = boundingBox(domain)
104 DIM = domain.getDim()
105 x = domain.getX()
106 self.__pde=LinearSinglePDE(domain)
107 self.__pde.getSolverOptions().setTolerance(tol)
108
109 if fix_all_faces:
110 constraint=whereZero(x[DIM-1]-BX[DIM-1][1])+whereZero(x[DIM-1]-BX[DIM-1][0])
111 for i in xrange(DIM-1):
112 constraint=constraint+whereZero(x[i]-BX[i][1])+whereZero(x[i]-BX[i][0])
113 else:
114 constraint=whereZero(x[DIM-1]-BX[DIM-1][1])
115 self.__pde.setValue(q=constraint)
116
117 def getDomain(self):
118 """
119 Returns the domain of the forward model.
120 """
121 return self.__domain
122
123 def getPDE(self):
124 """
125 Return the underlying PDE.
126
127 :rtype: `LinearPDE`
128 """
129 return self.__pde
130
131 def getDefect(self, result):
132 """
133 Returns the defect value.
134
135 :param result: a result vector
136 :type result: `Vector`
137 :rtype: ``float``
138 """
139 A=0.
140 for s in xrange(len(self.__weight)):
141 A = inner(self.__weight[s], (result-self.__data[s])**2) + A
142 return 0.5*integrate(A)
143
144 def getSurvey(self, index=None):
145 """
146 Returns the pair (g_index, weight_index), where g_i is the gravity
147 anomaly of survey i, weight_i is the weighting factor for survey i.
148 If index is None, all surveys will be returned in a pair of lists.
149 """
150 if index is None:
151 return self.__data, self.__weight
152 if index>=len(self.__data):
153 raise IndexError("Forward model only has %d surveys"%len(self.__data))
154 return self.__data[index], self.__weight[index]
155
156
157 class GravityModel(ForwardModelWithPotential):
158 """
159 Forward Model for gravity inversion as described in the inversion
160 cookbook.
161 """
162 def __init__(self, domain, chi, g, fix_all_faces=True, gravity_constant=U.Gravitational_Constant, tol=1e-8):
163 """
164 Creates a new gravity model on the given domain with one or more
165 surveys (chi, g).
166
167 :param domain: domain of the model
168 :type domain: `esys.escript.Domain`
169 :param chi: data weighting factors
170 :type chi: `Vector` or list of `Vector`
171 :param g: gravity anomaly data
172 :type g: `Vector` or list of `Vector`
173 :param fix_all_faces: if ``true`` all faces of the domain are fixed
174 otherwise only the top surface
175 :type fix_all_faces: ``bool``
176 :param tol: tolerance of underlying PDE
177 :type tol: positive ``float``
178 """
179 super(GravityModel, self).__init__(domain, chi, g, fix_all_faces, tol)
180
181 self.__G = gravity_constant
182 self.getPDE().setValue(A=kronecker(self.getDomain()))
183
184 def getArguments(self, rho):
185 """
186 Returns precomputed values shared by getValue() and getGradient().
187
188 :param rho: a suggestion for the density distribution
189 :type rho: `Scalar`
190 :return: gravity potential and corresponding gravity field.
191 :rtype: ``Scalar``, ``Vector``
192 """
193 phi = self.getPotential(rho)
194 gravity_force = -grad(phi)
195 return phi, gravity_force
196
197 def getPotential(self, rho):
198 """
199 Calculates the gravity potential for a given density distribution.
200
201 :param rho: a suggestion for the density distribution
202 :type rho: `Scalar`
203 :return: gravity potential
204 :rtype: ``Scalar``
205 """
206 pde=self.getPDE()
207
208 pde.resetRightHandSideCoefficients()
209 pde.setValue(Y=-4.*PI*self.__G*rho)
210 phi=pde.getSolution()
211
212 return phi
213
214 def getValue(self, rho, phi, gravity_force):
215 """
216 Returns the value of the defect
217
218 :param rho: density distribution
219 :type rho: `Scalar`
220 :param phi: corresponding potential
221 :type phi: `Scalar`
222 :param gravity_force: gravity force
223 :type gravity_force: `Vector`
224 :rtype: ``float``
225 """
226 return self.getDefect(gravity_force)
227
228 def getGradient(self, rho, phi, gravity_force):
229 """
230 Returns the gradient of the defect with respect to density.
231
232 :param rho: density distribution
233 :type rho: `Scalar`
234 :param phi: corresponding potential
235 :type phi: `Scalar`
236 :param gravity_force: gravity force
237 :type gravity_force: `Vector`
238 :rtype: `Scalar`
239 """
240 pde=self.getPDE()
241 g, chi = self.getSurvey()
242
243 Z=0.
244 for s in xrange(len(chi)):
245 Z = chi[s] * (g[s]-gravity_force) + Z
246
247 pde.resetRightHandSideCoefficients()
248 pde.setValue(X=Z)
249 ZT=pde.getSolution()
250 return ZT*(-4*PI*self.__G)
251
252
253 class MagneticModel(ForwardModelWithPotential):
254 """
255 Forward Model for magnetic inversion as described in the inversion
256 cookbook.
257 """
258 def __init__(self, domain, chi, B, background_field, fix_all_faces=True, tol=1e-8):
259 """
260 Creates a new magnetic model on the given domain with one or more
261 surveys (chi, B).
262
263 :param domain: domain of the model
264 :type domain: `Domain`
265 :param chi: data weighting factors
266 :type chi: `Vector` or list of `Vector`
267 :param B: magnetic field data
268 :type B: `Vector` or list of `Vector`
269 :param fix_all_faces: if ``true`` all faces of the domain are fixed
270 otherwise only the top surface
271 :type fix_all_faces: ``bool``
272 :param tol: tolerance of underlying PDE
273 :type tol: positive ``float``
274 """
275 super(MagneticModel, self).__init__(domain, chi, B, fix_all_faces, tol)
276 self.__background_field=interpolate(background_field, Function(self.getDomain()))
277 self.getPDE().setValue(A=kronecker(self.getDomain()))
278
279 def getArguments(self, k):
280 """
281 Returns precomputed values shared by getValue() and getGradient().
282
283 :param k: susceptibility
284 :type k: `Scalar`
285 :return: scalar magnetic potential and corresponding magnetic field
286 :rtype: ``Scalar``, ``Vector``
287 """
288 phi = self.getPotential(k)
289 magnetic_field = (1+k) * self.__background_field -grad(phi)
290 return phi, magnetic_field
291
292 def getPotential(self, k):
293 """
294 Calculates the magnetic potential for a given susceptibility.
295
296 :param k: susceptibility
297 :type k: `Scalar`
298 :return: magnetic potential
299 :rtype: ``Scalar``
300 """
301 pde=self.getPDE()
302
303 pde.resetRightHandSideCoefficients()
304 pde.setValue(X = (1+k)* self.__background_field)
305 phi=pde.getSolution()
306
307 return phi
308
309 def getValue(self, k, phi, magnetic_field):
310 """
311 Returns the value of the defect.
312
313 :param k: susceptibility
314 :type k: `Scalar`
315 :param phi: corresponding potential
316 :type phi: `Scalar`
317 :param magnetic_field: magnetic field
318 :type magnetic_field: `Vector`
319 :rtype: ``float``
320 """
321 return self.getDefect(magnetic_field)
322
323 def getGradient(self, k, phi, magnetic_field):
324 """
325 Returns the gradient of the defect with respect to susceptibility.
326
327 :param k: susceptibility
328 :type k: `Scalar`
329 :param phi: corresponding potential
330 :type phi: `Scalar`
331 :param magnetic_field: magnetic field
332 :type magnetic_field: `Vector`
333 :rtype: `Scalar`
334 """
335 pde=self.getPDE()
336 B, chi = self.getSurvey()
337
338 Y=0.
339 for s in xrange(len(chi)):
340 Y = chi[s] * (magnetic_field-B[s]) + Y
341
342 pde.resetRightHandSideCoefficients()
343 pde.setValue(X=Y)
344 YT=pde.getSolution()
345 return inner(Y-grad(YT),self.__background_field)
346

  ViewVC Help
Powered by ViewVC 1.1.26