1 | #!/usr/bin/env python |
---|
2 | r""" |
---|
3 | Show numerical precision of various expressions. |
---|
4 | |
---|
5 | Evaluates the same function(s) in single and double precision and compares |
---|
6 | the results to 500 digit mpmath evaluation of the same function. |
---|
7 | |
---|
8 | Note: a quick way to generation C and python code for taylor series |
---|
9 | expansions from sympy: |
---|
10 | |
---|
11 | import sympy as sp |
---|
12 | x = sp.var("x") |
---|
13 | f = sp.sin(x)/x |
---|
14 | t = sp.series(f, n=12).removeO() # taylor series with no O(x^n) term |
---|
15 | p = sp.horner(t) # Horner representation |
---|
16 | p = p.replace(x**2, sp.var("xsq") # simplify if alternate terms are zero |
---|
17 | p = p.n(15) # evaluate coefficients to 15 digits (optional) |
---|
18 | c_code = sp.ccode(p, assign_to=sp.var("p")) # convert to c code |
---|
19 | py_code = c[:-1] # strip semicolon to convert c to python |
---|
20 | |
---|
21 | # mpmath has pade() rational function approximation, which might work |
---|
22 | # better than the taylor series for some functions: |
---|
23 | P, Q = mp.pade(sp.Poly(t.n(15),x).coeffs(), L, M) |
---|
24 | P = sum(a*x**n for n,a in enumerate(reversed(P))) |
---|
25 | Q = sum(a*x**n for n,a in enumerate(reversed(Q))) |
---|
26 | c_code = sp.ccode(sp.horner(P)/sp.horner(Q), assign_to=sp.var("p")) |
---|
27 | |
---|
28 | # There are richardson and shanks series accelerators in both sympy |
---|
29 | # and mpmath that may be helpful. |
---|
30 | """ |
---|
31 | from __future__ import division, print_function |
---|
32 | |
---|
33 | import sys |
---|
34 | import os |
---|
35 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) |
---|
36 | |
---|
37 | import numpy as np |
---|
38 | from numpy import pi, inf |
---|
39 | import scipy.special |
---|
40 | try: |
---|
41 | from mpmath import mp |
---|
42 | except ImportError: |
---|
43 | # CRUFT: mpmath split out into its own package |
---|
44 | from sympy.mpmath import mp |
---|
45 | #import matplotlib; matplotlib.use('TkAgg') |
---|
46 | import pylab |
---|
47 | |
---|
48 | from sasmodels import core, data, direct_model, modelinfo |
---|
49 | |
---|
50 | class Comparator(object): |
---|
51 | def __init__(self, name, mp_function, np_function, ocl_function, xaxis, limits): |
---|
52 | self.name = name |
---|
53 | self.mp_function = mp_function |
---|
54 | self.np_function = np_function |
---|
55 | self.ocl_function = ocl_function |
---|
56 | self.xaxis = xaxis |
---|
57 | self.limits = limits |
---|
58 | |
---|
59 | def __repr__(self): |
---|
60 | return "Comparator(%s)"%self.name |
---|
61 | |
---|
62 | def call_mpmath(self, vec, bits=500): |
---|
63 | """ |
---|
64 | Direct calculation using mpmath extended precision library. |
---|
65 | """ |
---|
66 | with mp.workprec(bits): |
---|
67 | return [self.mp_function(mp.mpf(x)) for x in vec] |
---|
68 | |
---|
69 | def call_numpy(self, x, dtype): |
---|
70 | """ |
---|
71 | Direct calculation using numpy/scipy. |
---|
72 | """ |
---|
73 | x = np.asarray(x, dtype) |
---|
74 | return self.np_function(x) |
---|
75 | |
---|
76 | def call_ocl(self, x, dtype, platform='ocl'): |
---|
77 | """ |
---|
78 | Calculation using sasmodels ocl libraries. |
---|
79 | """ |
---|
80 | x = np.asarray(x, dtype) |
---|
81 | model = core.build_model(self.ocl_function, dtype=dtype) |
---|
82 | calculator = direct_model.DirectModel(data.empty_data1D(x), model) |
---|
83 | return calculator(background=0) |
---|
84 | |
---|
85 | def run(self, xrange="log", diff="relative"): |
---|
86 | r""" |
---|
87 | Compare accuracy of different methods for computing f. |
---|
88 | |
---|
89 | *xrange* is:: |
---|
90 | |
---|
91 | log: [10^-3,10^5] |
---|
92 | logq: [10^-4, 10^1] |
---|
93 | linear: [1,1000] |
---|
94 | zoom: [1000,1010] |
---|
95 | neg: [-100,100] |
---|
96 | |
---|
97 | *diff* is "relative", "absolute" or "none" |
---|
98 | |
---|
99 | *x_bits* is the precision with which the x values are specified. The |
---|
100 | default 23 should reproduce the equivalent of a single precisio |
---|
101 | """ |
---|
102 | linear = not xrange.startswith("log") |
---|
103 | if xrange == "zoom": |
---|
104 | lin_min, lin_max, lin_steps = 1000, 1010, 2000 |
---|
105 | elif xrange == "neg": |
---|
106 | lin_min, lin_max, lin_steps = -100.1, 100.1, 2000 |
---|
107 | elif xrange == "linear": |
---|
108 | lin_min, lin_max, lin_steps = 1, 1000, 2000 |
---|
109 | lin_min, lin_max, lin_steps = 0.001, 2, 2000 |
---|
110 | elif xrange == "log": |
---|
111 | log_min, log_max, log_steps = -3, 5, 400 |
---|
112 | elif xrange == "logq": |
---|
113 | log_min, log_max, log_steps = -4, 1, 400 |
---|
114 | else: |
---|
115 | raise ValueError("unknown range "+xrange) |
---|
116 | with mp.workprec(500): |
---|
117 | # Note: we make sure that we are comparing apples to apples... |
---|
118 | # The x points are set using single precision so that we are |
---|
119 | # examining the accuracy of the transformation from x to f(x) |
---|
120 | # rather than x to f(nearest(x)) where nearest(x) is the nearest |
---|
121 | # value to x in the given precision. |
---|
122 | if linear: |
---|
123 | lin_min = max(lin_min, self.limits[0]) |
---|
124 | lin_max = min(lin_max, self.limits[1]) |
---|
125 | qrf = np.linspace(lin_min, lin_max, lin_steps, dtype='single') |
---|
126 | #qrf = np.linspace(lin_min, lin_max, lin_steps, dtype='double') |
---|
127 | qr = [mp.mpf(float(v)) for v in qrf] |
---|
128 | #qr = mp.linspace(lin_min, lin_max, lin_steps) |
---|
129 | else: |
---|
130 | log_min = np.log10(max(10**log_min, self.limits[0])) |
---|
131 | log_max = np.log10(min(10**log_max, self.limits[1])) |
---|
132 | qrf = np.logspace(log_min, log_max, log_steps, dtype='single') |
---|
133 | #qrf = np.logspace(log_min, log_max, log_steps, dtype='double') |
---|
134 | qr = [mp.mpf(float(v)) for v in qrf] |
---|
135 | #qr = [10**v for v in mp.linspace(log_min, log_max, log_steps)] |
---|
136 | |
---|
137 | target = self.call_mpmath(qr, bits=500) |
---|
138 | pylab.subplot(121) |
---|
139 | self.compare(qr, 'single', target, linear, diff) |
---|
140 | pylab.legend(loc='best') |
---|
141 | pylab.subplot(122) |
---|
142 | self.compare(qr, 'double', target, linear, diff) |
---|
143 | pylab.legend(loc='best') |
---|
144 | pylab.suptitle(self.name + " compared to 500-bit mpmath") |
---|
145 | |
---|
146 | def compare(self, x, precision, target, linear=False, diff="relative"): |
---|
147 | r""" |
---|
148 | Compare the different computation methods using the given precision. |
---|
149 | """ |
---|
150 | if precision == 'single': |
---|
151 | #n=11; plotdiff(x, target, self.call_mpmath(x, n), 'mp %d bits'%n, diff=diff) |
---|
152 | #n=23; plotdiff(x, target, self.call_mpmath(x, n), 'mp %d bits'%n, diff=diff) |
---|
153 | pass |
---|
154 | elif precision == 'double': |
---|
155 | #n=53; plotdiff(x, target, self.call_mpmath(x, n), 'mp %d bits'%n, diff=diff) |
---|
156 | #n=83; plotdiff(x, target, self.call_mpmath(x, n), 'mp %d bits'%n, diff=diff) |
---|
157 | pass |
---|
158 | plotdiff(x, target, self.call_numpy(x, precision), 'numpy '+precision, diff=diff) |
---|
159 | plotdiff(x, target, self.call_ocl(x, precision, 0), 'OpenCL '+precision, diff=diff) |
---|
160 | pylab.xlabel(self.xaxis) |
---|
161 | if diff == "relative": |
---|
162 | pylab.ylabel("relative error") |
---|
163 | elif diff == "absolute": |
---|
164 | pylab.ylabel("absolute error") |
---|
165 | else: |
---|
166 | pylab.ylabel(self.name) |
---|
167 | pylab.semilogx(x, target, '-', label="true value") |
---|
168 | if linear: |
---|
169 | pylab.xscale('linear') |
---|
170 | |
---|
171 | def plotdiff(x, target, actual, label, diff): |
---|
172 | """ |
---|
173 | Plot the computed value. |
---|
174 | |
---|
175 | Use relative error if SHOW_DIFF, otherwise just plot the value directly. |
---|
176 | """ |
---|
177 | if diff == "relative": |
---|
178 | err = np.array([abs((t-a)/t) for t, a in zip(target, actual)], 'd') |
---|
179 | #err = np.clip(err, 0, 1) |
---|
180 | pylab.loglog(x, err, '-', label=label) |
---|
181 | elif diff == "absolute": |
---|
182 | err = np.array([abs((t-a)) for t, a in zip(target, actual)], 'd') |
---|
183 | pylab.loglog(x, err, '-', label=label) |
---|
184 | else: |
---|
185 | limits = np.min(target), np.max(target) |
---|
186 | pylab.semilogx(x, np.clip(actual, *limits), '-', label=label) |
---|
187 | |
---|
188 | def make_ocl(function, name, source=[]): |
---|
189 | class Kernel(object): |
---|
190 | pass |
---|
191 | Kernel.__file__ = name+".py" |
---|
192 | Kernel.name = name |
---|
193 | Kernel.parameters = [] |
---|
194 | Kernel.source = source |
---|
195 | Kernel.Iq = function |
---|
196 | model_info = modelinfo.make_model_info(Kernel) |
---|
197 | return model_info |
---|
198 | |
---|
199 | |
---|
200 | # =============== FUNCTION DEFINITIONS ================ |
---|
201 | |
---|
202 | FUNCTIONS = {} |
---|
203 | def add_function(name, mp_function, np_function, ocl_function, |
---|
204 | shortname=None, xaxis="x", limits=(-inf, inf)): |
---|
205 | if shortname is None: |
---|
206 | shortname = name.replace('(x)', '').replace(' ', '') |
---|
207 | FUNCTIONS[shortname] = Comparator(name, mp_function, np_function, ocl_function, xaxis, limits) |
---|
208 | |
---|
209 | add_function( |
---|
210 | name="J0(x)", |
---|
211 | mp_function=mp.j0, |
---|
212 | np_function=scipy.special.j0, |
---|
213 | ocl_function=make_ocl("return sas_J0(q);", "sas_J0", ["lib/polevl.c", "lib/sas_J0.c"]), |
---|
214 | ) |
---|
215 | add_function( |
---|
216 | name="J1(x)", |
---|
217 | mp_function=mp.j1, |
---|
218 | np_function=scipy.special.j1, |
---|
219 | ocl_function=make_ocl("return sas_J1(q);", "sas_J1", ["lib/polevl.c", "lib/sas_J1.c"]), |
---|
220 | ) |
---|
221 | add_function( |
---|
222 | name="JN(-3, x)", |
---|
223 | mp_function=lambda x: mp.besselj(-3, x), |
---|
224 | np_function=lambda x: scipy.special.jn(-3, x), |
---|
225 | ocl_function=make_ocl("return sas_JN(-3, q);", "sas_JN", |
---|
226 | ["lib/polevl.c", "lib/sas_J0.c", "lib/sas_J1.c", "lib/sas_JN.c"]), |
---|
227 | shortname="J-3", |
---|
228 | ) |
---|
229 | add_function( |
---|
230 | name="JN(3, x)", |
---|
231 | mp_function=lambda x: mp.besselj(3, x), |
---|
232 | np_function=lambda x: scipy.special.jn(3, x), |
---|
233 | ocl_function=make_ocl("return sas_JN(3, q);", "sas_JN", |
---|
234 | ["lib/polevl.c", "lib/sas_J0.c", "lib/sas_J1.c", "lib/sas_JN.c"]), |
---|
235 | shortname="J3", |
---|
236 | ) |
---|
237 | add_function( |
---|
238 | name="JN(2, x)", |
---|
239 | mp_function=lambda x: mp.besselj(2, x), |
---|
240 | np_function=lambda x: scipy.special.jn(2, x), |
---|
241 | ocl_function=make_ocl("return sas_JN(2, q);", "sas_JN", |
---|
242 | ["lib/polevl.c", "lib/sas_J0.c", "lib/sas_J1.c", "lib/sas_JN.c"]), |
---|
243 | shortname="J2", |
---|
244 | ) |
---|
245 | add_function( |
---|
246 | name="2 J1(x)/x", |
---|
247 | mp_function=lambda x: 2*mp.j1(x)/x, |
---|
248 | np_function=lambda x: 2*scipy.special.j1(x)/x, |
---|
249 | ocl_function=make_ocl("return sas_2J1x_x(q);", "sas_2J1x_x", ["lib/polevl.c", "lib/sas_J1.c"]), |
---|
250 | ) |
---|
251 | add_function( |
---|
252 | name="J1(x)", |
---|
253 | mp_function=mp.j1, |
---|
254 | np_function=scipy.special.j1, |
---|
255 | ocl_function=make_ocl("return sas_J1(q);", "sas_J1", ["lib/polevl.c", "lib/sas_J1.c"]), |
---|
256 | ) |
---|
257 | add_function( |
---|
258 | name="Si(x)", |
---|
259 | mp_function=mp.si, |
---|
260 | np_function=lambda x: scipy.special.sici(x)[0], |
---|
261 | ocl_function=make_ocl("return sas_Si(q);", "sas_Si", ["lib/sas_Si.c"]), |
---|
262 | ) |
---|
263 | #import fnlib |
---|
264 | #add_function( |
---|
265 | # name="fnlibJ1", |
---|
266 | # mp_function=mp.j1, |
---|
267 | # np_function=fnlib.J1, |
---|
268 | # ocl_function=make_ocl("return sas_J1(q);", "sas_J1", ["lib/polevl.c", "lib/sas_J1.c"]), |
---|
269 | #) |
---|
270 | add_function( |
---|
271 | name="sin(x)", |
---|
272 | mp_function=mp.sin, |
---|
273 | np_function=np.sin, |
---|
274 | #ocl_function=make_ocl("double sn, cn; SINCOS(q,sn,cn); return sn;", "sas_sin"), |
---|
275 | ocl_function=make_ocl("return sin(q);", "sas_sin"), |
---|
276 | ) |
---|
277 | add_function( |
---|
278 | name="sin(x)/x", |
---|
279 | mp_function=lambda x: mp.sin(x)/x if x != 0 else 1, |
---|
280 | ## scipy sinc function is inaccurate and has an implied pi*x term |
---|
281 | #np_function=lambda x: scipy.special.sinc(x/pi), |
---|
282 | ## numpy sin(x)/x needs to check for x=0 |
---|
283 | np_function=lambda x: np.sin(x)/x, |
---|
284 | ocl_function=make_ocl("return sas_sinx_x(q);", "sas_sinc"), |
---|
285 | ) |
---|
286 | add_function( |
---|
287 | name="cos(x)", |
---|
288 | mp_function=mp.cos, |
---|
289 | np_function=np.cos, |
---|
290 | #ocl_function=make_ocl("double sn, cn; SINCOS(q,sn,cn); return cn;", "sas_cos"), |
---|
291 | ocl_function=make_ocl("return cos(q);", "sas_cos"), |
---|
292 | ) |
---|
293 | add_function( |
---|
294 | name="gamma(x)", |
---|
295 | mp_function=mp.gamma, |
---|
296 | np_function=scipy.special.gamma, |
---|
297 | ocl_function=make_ocl("return sas_gamma(q);", "sas_gamma", ["lib/sas_gamma.c"]), |
---|
298 | limits=(-3.1, 10), |
---|
299 | ) |
---|
300 | add_function( |
---|
301 | name="erf(x)", |
---|
302 | mp_function=mp.erf, |
---|
303 | np_function=scipy.special.erf, |
---|
304 | ocl_function=make_ocl("return sas_erf(q);", "sas_erf", ["lib/polevl.c", "lib/sas_erf.c"]), |
---|
305 | limits=(-5., 5.), |
---|
306 | ) |
---|
307 | add_function( |
---|
308 | name="erfc(x)", |
---|
309 | mp_function=mp.erfc, |
---|
310 | np_function=scipy.special.erfc, |
---|
311 | ocl_function=make_ocl("return sas_erfc(q);", "sas_erfc", ["lib/polevl.c", "lib/sas_erf.c"]), |
---|
312 | limits=(-5., 5.), |
---|
313 | ) |
---|
314 | add_function( |
---|
315 | name="expm1(x)", |
---|
316 | mp_function=mp.expm1, |
---|
317 | np_function=np.expm1, |
---|
318 | ocl_function=make_ocl("return expm1(q);", "sas_expm1"), |
---|
319 | limits=(-5., 5.), |
---|
320 | ) |
---|
321 | add_function( |
---|
322 | name="arctan(x)", |
---|
323 | mp_function=mp.atan, |
---|
324 | np_function=np.arctan, |
---|
325 | ocl_function=make_ocl("return atan(q);", "sas_arctan"), |
---|
326 | ) |
---|
327 | add_function( |
---|
328 | name="3 j1(x)/x", |
---|
329 | mp_function=lambda x: 3*(mp.sin(x)/x - mp.cos(x))/(x*x), |
---|
330 | # Note: no taylor expansion near 0 |
---|
331 | np_function=lambda x: 3*(np.sin(x)/x - np.cos(x))/(x*x), |
---|
332 | ocl_function=make_ocl("return sas_3j1x_x(q);", "sas_j1c", ["lib/sas_3j1x_x.c"]), |
---|
333 | ) |
---|
334 | add_function( |
---|
335 | name="(1-cos(x))/x^2", |
---|
336 | mp_function=lambda x: (1 - mp.cos(x))/(x*x), |
---|
337 | np_function=lambda x: (1 - np.cos(x))/(x*x), |
---|
338 | ocl_function=make_ocl("return (1-cos(q))/q/q;", "sas_1mcosx_x2"), |
---|
339 | ) |
---|
340 | add_function( |
---|
341 | name="(1-sin(x)/x)/x", |
---|
342 | mp_function=lambda x: 1/x - mp.sin(x)/(x*x), |
---|
343 | np_function=lambda x: 1/x - np.sin(x)/(x*x), |
---|
344 | ocl_function=make_ocl("return (1-sas_sinx_x(q))/q;", "sas_1msinx_x_x"), |
---|
345 | ) |
---|
346 | add_function( |
---|
347 | name="(1/2-sin(x)/x+(1-cos(x))/x^2)/x", |
---|
348 | mp_function=lambda x: (0.5 - mp.sin(x)/x + (1-mp.cos(x))/(x*x))/x, |
---|
349 | np_function=lambda x: (0.5 - np.sin(x)/x + (1-np.cos(x))/(x*x))/x, |
---|
350 | ocl_function=make_ocl("return (0.5-sin(q)/q + (1-cos(q))/q/q)/q;", "sas_T2"), |
---|
351 | ) |
---|
352 | add_function( |
---|
353 | name="fmod_2pi", |
---|
354 | mp_function=lambda x: mp.fmod(x, 2*mp.pi), |
---|
355 | np_function=lambda x: np.fmod(x, 2*np.pi), |
---|
356 | ocl_function=make_ocl("return fmod(q, 2*M_PI);", "sas_fmod"), |
---|
357 | ) |
---|
358 | add_function( |
---|
359 | name="gauss_coil", |
---|
360 | mp_function=lambda x: 2*(mp.exp(-x**2) + x**2 - 1)/x**4, |
---|
361 | np_function=lambda x: 2*(np.expm1(-x**2) + x**2)/x**4, |
---|
362 | ocl_function=make_ocl(""" |
---|
363 | const double qsq = q*q; |
---|
364 | // For double: use O(5) Pade with 0.5 cutoff (10 mad + 1 divide) |
---|
365 | // For single: use O(7) Taylor with 0.8 cutoff (7 mad) |
---|
366 | if (qsq < 0.0) { |
---|
367 | const double x = qsq; |
---|
368 | if (0) { // 0.36 single |
---|
369 | // PadeApproximant[2*Exp[-x^2] + x^2-1)/x^4, {x, 0, 4}] |
---|
370 | return (x*x/180. + 1.)/((1./30.*x + 1./3.)*x + 1); |
---|
371 | } else if (0) { // 1.0 for single |
---|
372 | // padeapproximant[2*exp[-x^2] + x^2-1)/x^4, {x, 0, 6}] |
---|
373 | const double A1=1./24., A2=1./84, A3=-1./3360; |
---|
374 | const double B1=3./8., B2=3./56., B3=1./336.; |
---|
375 | return (((A3*x + A2)*x + A1)*x + 1.)/(((B3*x + B2)*x + B1)*x + 1.); |
---|
376 | } else if (0) { // 1.0 for single, 0.25 for double |
---|
377 | // PadeApproximant[2*Exp[-x^2] + x^2-1)/x^4, {x, 0, 8}] |
---|
378 | const double A1=1./15., A2=1./60, A3=0., A4=1./75600.; |
---|
379 | const double B1=2./5., B2=1./15., B3=1./180., B4=1./5040.; |
---|
380 | return ((((A4*x + A3)*x + A2)*x + A1)*x + 1.) |
---|
381 | /((((B4*x + B3)*x + B2)*x + B1)*x + 1.); |
---|
382 | } else { // 1.0 for single, 0.5 for double |
---|
383 | // PadeApproximant[2*Exp[-x^2] + x^2-1)/x^4, {x, 0, 8}] |
---|
384 | const double A1=1./12., A2=2./99., A3=1./2640., A4=1./23760., A5=-1./1995840.; |
---|
385 | const double B1=5./12., B2=5./66., B3=1./132., B4=1./2376., B5=1./95040.; |
---|
386 | return (((((A5*x + A4)*x + A3)*x + A2)*x + A1)*x + 1.) |
---|
387 | /(((((B5*x + B4)*x + B3)*x + B2)*x + B1)*x + 1.); |
---|
388 | } |
---|
389 | } else if (qsq < 0.8) { |
---|
390 | const double x = qsq; |
---|
391 | const double C0 = +1.; |
---|
392 | const double C1 = -1./3.; |
---|
393 | const double C2 = +1./12.; |
---|
394 | const double C3 = -1./60.; |
---|
395 | const double C4 = +1./360.; |
---|
396 | const double C5 = -1./2520.; |
---|
397 | const double C6 = +1./20160.; |
---|
398 | const double C7 = -1./181440.; |
---|
399 | //return ((((C5*x + C4)*x + C3)*x + C2)*x + C1)*x + C0; |
---|
400 | //return (((((C6*x + C5)*x + C4)*x + C3)*x + C2)*x + C1)*x + C0; |
---|
401 | return ((((((C7*x + C6)*x + C5)*x + C4)*x + C3)*x + C2)*x + C1)*x + C0; |
---|
402 | } else { |
---|
403 | return 2.*(expm1(-qsq) + qsq)/(qsq*qsq); |
---|
404 | } |
---|
405 | """, "sas_debye"), |
---|
406 | ) |
---|
407 | |
---|
408 | RADIUS=3000 |
---|
409 | LENGTH=30 |
---|
410 | THETA=45 |
---|
411 | def mp_cyl(x): |
---|
412 | f = mp.mpf |
---|
413 | theta = f(THETA)*mp.pi/f(180) |
---|
414 | qr = x * f(RADIUS)*mp.sin(theta) |
---|
415 | qh = x * f(LENGTH)/f(2)*mp.cos(theta) |
---|
416 | be = f(2)*mp.j1(qr)/qr |
---|
417 | si = mp.sin(qh)/qh |
---|
418 | background = f(0) |
---|
419 | #background = f(1)/f(1000) |
---|
420 | volume = mp.pi*f(RADIUS)**f(2)*f(LENGTH) |
---|
421 | contrast = f(5) |
---|
422 | units = f(1)/f(10000) |
---|
423 | #return be |
---|
424 | #return si |
---|
425 | return units*(volume*contrast*be*si)**f(2)/volume + background |
---|
426 | def np_cyl(x): |
---|
427 | f = np.float64 if x.dtype == np.float64 else np.float32 |
---|
428 | theta = f(THETA)*f(np.pi)/f(180) |
---|
429 | qr = x * f(RADIUS)*np.sin(theta) |
---|
430 | qh = x * f(LENGTH)/f(2)*np.cos(theta) |
---|
431 | be = f(2)*scipy.special.j1(qr)/qr |
---|
432 | si = np.sin(qh)/qh |
---|
433 | background = f(0) |
---|
434 | #background = f(1)/f(1000) |
---|
435 | volume = f(np.pi)*f(RADIUS)**2*f(LENGTH) |
---|
436 | contrast = f(5) |
---|
437 | units = f(1)/f(10000) |
---|
438 | #return be |
---|
439 | #return si |
---|
440 | return units*(volume*contrast*be*si)**f(2)/volume + background |
---|
441 | ocl_cyl = """\ |
---|
442 | double THETA = %(THETA).15e*M_PI_180; |
---|
443 | double qr = q*%(RADIUS).15e*sin(THETA); |
---|
444 | double qh = q*0.5*%(LENGTH).15e*cos(THETA); |
---|
445 | double be = sas_2J1x_x(qr); |
---|
446 | double si = sas_sinx_x(qh); |
---|
447 | double background = 0; |
---|
448 | //double background = 0.001; |
---|
449 | double volume = M_PI*square(%(RADIUS).15e)*%(LENGTH).15e; |
---|
450 | double contrast = 5.0; |
---|
451 | double units = 1e-4; |
---|
452 | //return be; |
---|
453 | //return si; |
---|
454 | return units*square(volume*contrast*be*si)/volume + background; |
---|
455 | """%{"LENGTH":LENGTH, "RADIUS": RADIUS, "THETA": THETA} |
---|
456 | add_function( |
---|
457 | name="cylinder(r=%g, l=%g, theta=%g)"%(RADIUS, LENGTH, THETA), |
---|
458 | mp_function=mp_cyl, |
---|
459 | np_function=np_cyl, |
---|
460 | ocl_function=make_ocl(ocl_cyl, "ocl_cyl", ["lib/polevl.c", "lib/sas_J1.c"]), |
---|
461 | shortname="cylinder", |
---|
462 | xaxis="$q/A^{-1}$", |
---|
463 | ) |
---|
464 | |
---|
465 | lanczos_gamma = """\ |
---|
466 | const double coeff[] = { |
---|
467 | 76.18009172947146, -86.50532032941677, |
---|
468 | 24.01409824083091, -1.231739572450155, |
---|
469 | 0.1208650973866179e-2,-0.5395239384953e-5 |
---|
470 | }; |
---|
471 | const double x = q; |
---|
472 | double tmp = x + 5.5; |
---|
473 | tmp -= (x + 0.5)*log(tmp); |
---|
474 | double ser = 1.000000000190015; |
---|
475 | for (int k=0; k < 6; k++) ser += coeff[k]/(x + k+1); |
---|
476 | return -tmp + log(2.5066282746310005*ser/x); |
---|
477 | """ |
---|
478 | add_function( |
---|
479 | name="log gamma(x)", |
---|
480 | mp_function=mp.loggamma, |
---|
481 | np_function=scipy.special.gammaln, |
---|
482 | ocl_function=make_ocl(lanczos_gamma, "lgamma"), |
---|
483 | ) |
---|
484 | |
---|
485 | replacement_expm1 = """\ |
---|
486 | double x = (double)q; // go back to float for single precision kernels |
---|
487 | // Adapted from the cephes math library. |
---|
488 | // Copyright 1984 - 1992 by Stephen L. Moshier |
---|
489 | if (x != x || x == 0.0) { |
---|
490 | return x; // NaN and +/- 0 |
---|
491 | } else if (x < -0.5 || x > 0.5) { |
---|
492 | return exp(x) - 1.0; |
---|
493 | } else { |
---|
494 | const double xsq = x*x; |
---|
495 | const double p = ((( |
---|
496 | +1.2617719307481059087798E-4)*xsq |
---|
497 | +3.0299440770744196129956E-2)*xsq |
---|
498 | +9.9999999999999999991025E-1); |
---|
499 | const double q = (((( |
---|
500 | +3.0019850513866445504159E-6)*xsq |
---|
501 | +2.5244834034968410419224E-3)*xsq |
---|
502 | +2.2726554820815502876593E-1)*xsq |
---|
503 | +2.0000000000000000000897E0); |
---|
504 | double r = x * p; |
---|
505 | r = r / (q - r); |
---|
506 | return r+r; |
---|
507 | } |
---|
508 | """ |
---|
509 | add_function( |
---|
510 | name="sas_expm1(x)", |
---|
511 | mp_function=mp.expm1, |
---|
512 | np_function=np.expm1, |
---|
513 | ocl_function=make_ocl(replacement_expm1, "sas_expm1"), |
---|
514 | ) |
---|
515 | |
---|
516 | # Alternate versions of 3 j1(x)/x, for posterity |
---|
517 | def taylor_3j1x_x(x): |
---|
518 | """ |
---|
519 | Calculation using taylor series. |
---|
520 | """ |
---|
521 | # Generate coefficients using the precision of the target value. |
---|
522 | n = 5 |
---|
523 | cinv = [3991680, -45360, 840, -30, 3] |
---|
524 | three = x.dtype.type(3) |
---|
525 | p = three/np.array(cinv, x.dtype) |
---|
526 | return np.polyval(p[-n:], x*x) |
---|
527 | add_function( |
---|
528 | name="3 j1(x)/x: taylor", |
---|
529 | mp_function=lambda x: 3*(mp.sin(x)/x - mp.cos(x))/(x*x), |
---|
530 | np_function=taylor_3j1x_x, |
---|
531 | ocl_function=make_ocl("return sas_3j1x_x(q);", "sas_j1c", ["lib/sas_3j1x_x.c"]), |
---|
532 | ) |
---|
533 | def trig_3j1x_x(x): |
---|
534 | r""" |
---|
535 | Direct calculation using linear combination of sin/cos. |
---|
536 | |
---|
537 | Use the following trig identity: |
---|
538 | |
---|
539 | .. math:: |
---|
540 | |
---|
541 | a \sin(x) + b \cos(x) = c \sin(x + \phi) |
---|
542 | |
---|
543 | where $c = \surd(a^2+b^2)$ and $\phi = \tan^{-1}(b/a) to calculate the |
---|
544 | numerator $\sin(x) - x\cos(x)$. |
---|
545 | """ |
---|
546 | one = x.dtype.type(1) |
---|
547 | three = x.dtype.type(3) |
---|
548 | c = np.sqrt(one + x*x) |
---|
549 | phi = np.arctan2(-x, one) |
---|
550 | return three*(c*np.sin(x+phi))/(x*x*x) |
---|
551 | add_function( |
---|
552 | name="3 j1(x)/x: trig", |
---|
553 | mp_function=lambda x: 3*(mp.sin(x)/x - mp.cos(x))/(x*x), |
---|
554 | np_function=trig_3j1x_x, |
---|
555 | ocl_function=make_ocl("return sas_3j1x_x(q);", "sas_j1c", ["lib/sas_3j1x_x.c"]), |
---|
556 | ) |
---|
557 | def np_2J1x_x(x): |
---|
558 | """ |
---|
559 | numpy implementation of 2J1(x)/x using single precision algorithm |
---|
560 | """ |
---|
561 | # pylint: disable=bad-continuation |
---|
562 | f = x.dtype.type |
---|
563 | ax = abs(x) |
---|
564 | if ax < f(8.0): |
---|
565 | y = x*x |
---|
566 | ans1 = f(2)*(f(72362614232.0) |
---|
567 | + y*(f(-7895059235.0) |
---|
568 | + y*(f(242396853.1) |
---|
569 | + y*(f(-2972611.439) |
---|
570 | + y*(f(15704.48260) |
---|
571 | + y*(f(-30.16036606))))))) |
---|
572 | ans2 = (f(144725228442.0) |
---|
573 | + y*(f(2300535178.0) |
---|
574 | + y*(f(18583304.74) |
---|
575 | + y*(f(99447.43394) |
---|
576 | + y*(f(376.9991397) |
---|
577 | + y))))) |
---|
578 | return ans1/ans2 |
---|
579 | else: |
---|
580 | y = f(64.0)/(ax*ax) |
---|
581 | xx = ax - f(2.356194491) |
---|
582 | ans1 = (f(1.0) |
---|
583 | + y*(f(0.183105e-2) |
---|
584 | + y*(f(-0.3516396496e-4) |
---|
585 | + y*(f(0.2457520174e-5) |
---|
586 | + y*f(-0.240337019e-6))))) |
---|
587 | ans2 = (f(0.04687499995) |
---|
588 | + y*(f(-0.2002690873e-3) |
---|
589 | + y*(f(0.8449199096e-5) |
---|
590 | + y*(f(-0.88228987e-6) |
---|
591 | + y*f(0.105787412e-6))))) |
---|
592 | sn, cn = np.sin(xx), np.cos(xx) |
---|
593 | ans = np.sqrt(f(0.636619772)/ax) * (cn*ans1 - (f(8.0)/ax)*sn*ans2) * f(2)/x |
---|
594 | return -ans if (x < f(0.0)) else ans |
---|
595 | add_function( |
---|
596 | name="2 J1(x)/x:alt", |
---|
597 | mp_function=lambda x: 2*mp.j1(x)/x, |
---|
598 | np_function=lambda x: np.asarray([np_2J1x_x(v) for v in x], x.dtype), |
---|
599 | ocl_function=make_ocl("return sas_2J1x_x(q);", "sas_2J1x_x", ["lib/polevl.c", "lib/sas_J1.c"]), |
---|
600 | ) |
---|
601 | |
---|
602 | ALL_FUNCTIONS = set(FUNCTIONS.keys()) |
---|
603 | ALL_FUNCTIONS.discard("loggamma") # OCL version not ready yet |
---|
604 | ALL_FUNCTIONS.discard("3j1/x:taylor") |
---|
605 | ALL_FUNCTIONS.discard("3j1/x:trig") |
---|
606 | ALL_FUNCTIONS.discard("2J1/x:alt") |
---|
607 | |
---|
608 | # =============== MAIN PROGRAM ================ |
---|
609 | |
---|
610 | def usage(): |
---|
611 | names = ", ".join(sorted(ALL_FUNCTIONS)) |
---|
612 | print("""\ |
---|
613 | usage: precision.py [-f/a/r] [-x<range>] "name" ... |
---|
614 | where |
---|
615 | -f indicates that the function value should be plotted, |
---|
616 | -a indicates that the absolute error should be plotted, |
---|
617 | -r indicates that the relative error should be plotted (default), |
---|
618 | -x<range> indicates the steps in x, where <range> is one of the following |
---|
619 | log indicates log stepping in [10^-3, 10^5] (default) |
---|
620 | logq indicates log stepping in [10^-4, 10^1] |
---|
621 | linear indicates linear stepping in [1, 1000] |
---|
622 | zoom indicates linear stepping in [1000, 1010] |
---|
623 | neg indicates linear stepping in [-100.1, 100.1] |
---|
624 | and name is "all" or one of: |
---|
625 | """+names) |
---|
626 | sys.exit(1) |
---|
627 | |
---|
628 | def main(): |
---|
629 | import sys |
---|
630 | diff = "relative" |
---|
631 | xrange = "log" |
---|
632 | options = [v for v in sys.argv[1:] if v.startswith('-')] |
---|
633 | for opt in options: |
---|
634 | if opt == '-f': |
---|
635 | diff = "none" |
---|
636 | elif opt == '-r': |
---|
637 | diff = "relative" |
---|
638 | elif opt == '-a': |
---|
639 | diff = "absolute" |
---|
640 | elif opt.startswith('-x'): |
---|
641 | xrange = opt[2:] |
---|
642 | else: |
---|
643 | usage() |
---|
644 | |
---|
645 | names = [v for v in sys.argv[1:] if not v.startswith('-')] |
---|
646 | if not names: |
---|
647 | usage() |
---|
648 | |
---|
649 | if names[0] == "all": |
---|
650 | cutoff = names[1] if len(names) > 1 else "" |
---|
651 | names = list(sorted(ALL_FUNCTIONS)) |
---|
652 | names = [k for k in names if k >= cutoff] |
---|
653 | if any(k not in FUNCTIONS for k in names): |
---|
654 | usage() |
---|
655 | multiple = len(names) > 1 |
---|
656 | pylab.interactive(multiple) |
---|
657 | for k in names: |
---|
658 | pylab.clf() |
---|
659 | comparator = FUNCTIONS[k] |
---|
660 | comparator.run(xrange=xrange, diff=diff) |
---|
661 | if multiple: |
---|
662 | raw_input() |
---|
663 | if not multiple: |
---|
664 | pylab.show() |
---|
665 | |
---|
666 | if __name__ == "__main__": |
---|
667 | main() |
---|