1 | """ |
---|
2 | SAS model constructor. |
---|
3 | |
---|
4 | Small angle scattering models are defined by a set of kernel functions: |
---|
5 | |
---|
6 | *Iq(q, p1, p2, ...)* returns the scattering at q for a form with |
---|
7 | particular dimensions averaged over all orientations. |
---|
8 | |
---|
9 | *Iqxy(qx, qy, p1, p2, ...)* returns the scattering at qx,qy for a form |
---|
10 | with particular dimensions for a single orientation. |
---|
11 | |
---|
12 | *Imagnetic(qx, qy, result[], p1, p2, ...)* returns the scattering for the |
---|
13 | polarized neutron spin states (up-up, up-down, down-up, down-down) for |
---|
14 | a form with particular dimensions for a single orientation. |
---|
15 | |
---|
16 | *form_volume(p1, p2, ...)* returns the volume of the form with particular |
---|
17 | dimension. |
---|
18 | |
---|
19 | *ER(p1, p2, ...)* returns the effective radius of the form with |
---|
20 | particular dimensions. |
---|
21 | |
---|
22 | *VR(p1, p2, ...)* returns the volume ratio for core-shell style forms. |
---|
23 | |
---|
24 | These functions are defined in a kernel module .py script and an associated |
---|
25 | set of .c files. The model constructor will use them to create models with |
---|
26 | polydispersity across volume and orientation parameters, and provide |
---|
27 | scale and background parameters for each model. |
---|
28 | |
---|
29 | *Iq*, *Iqxy*, *Imagnetic* and *form_volume* should be stylized C-99 |
---|
30 | functions written for OpenCL. All functions need prototype declarations |
---|
31 | even if the are defined before they are used. OpenCL does not support |
---|
32 | *#include* preprocessor directives, so instead the list of includes needs |
---|
33 | to be given as part of the metadata in the kernel module definition. |
---|
34 | The included files should be listed using a path relative to the kernel |
---|
35 | module, or if using "lib/file.c" if it is one of the standard includes |
---|
36 | provided with the sasmodels source. The includes need to be listed in |
---|
37 | order so that functions are defined before they are used. |
---|
38 | |
---|
39 | Floating point values should be declared as *double*. For single precision |
---|
40 | calculations, *double* will be replaced by *float*. The single precision |
---|
41 | conversion will also tag floating point constants with "f" to make them |
---|
42 | single precision constants. When using integral values in floating point |
---|
43 | expressions, they should be expressed as floating point values by including |
---|
44 | a decimal point. This includes 0., 1. and 2. |
---|
45 | |
---|
46 | OpenCL has a *sincos* function which can improve performance when both |
---|
47 | the *sin* and *cos* values are needed for a particular argument. Since |
---|
48 | this function does not exist in C99, all use of *sincos* should be |
---|
49 | replaced by the macro *SINCOS(value,sn,cn)* where *sn* and *cn* are |
---|
50 | previously declared *double* variables. When compiled for systems without |
---|
51 | OpenCL, *SINCOS* will be replaced by *sin* and *cos* calls. If *value* is |
---|
52 | an expression, it will appear twice in this case; whether or not it will be |
---|
53 | evaluated twice depends on the quality of the compiler. |
---|
54 | |
---|
55 | If the input parameters are invalid, the scattering calculator should |
---|
56 | return a negative number. Particularly with polydispersity, there are |
---|
57 | some sets of shape parameters which lead to nonsensical forms, such |
---|
58 | as a capped cylinder where the cap radius is smaller than the |
---|
59 | cylinder radius. The polydispersity calculation will ignore these points, |
---|
60 | effectively chopping the parameter weight distributions at the boundary |
---|
61 | of the infeasible region. The resulting scattering will be set to |
---|
62 | background. This will work correctly even when polydispersity is off. |
---|
63 | |
---|
64 | *ER* and *VR* are python functions which operate on parameter vectors. |
---|
65 | The constructor code will generate the necessary vectors for computing |
---|
66 | them with the desired polydispersity. |
---|
67 | |
---|
68 | The available kernel parameters are defined as a list, with each parameter |
---|
69 | defined as a sublist with the following elements: |
---|
70 | |
---|
71 | *name* is the name that will be used in the call to the kernel |
---|
72 | function and the name that will be displayed to the user. Names |
---|
73 | should be lower case, with words separated by underscore. If |
---|
74 | acronyms are used, the whole acronym should be upper case. |
---|
75 | |
---|
76 | *units* should be one of *degrees* for angles, *Ang* for lengths, |
---|
77 | *1e-6/Ang^2* for SLDs. |
---|
78 | |
---|
79 | *default value* will be the initial value for the model when it |
---|
80 | is selected, or when an initial value is not otherwise specified. |
---|
81 | |
---|
82 | [*lb*, *ub*] are the hard limits on the parameter value, used to limit |
---|
83 | the polydispersity density function. In the fit, the parameter limits |
---|
84 | given to the fit are the limits on the central value of the parameter. |
---|
85 | If there is polydispersity, it will evaluate parameter values outside |
---|
86 | the fit limits, but not outside the hard limits specified in the model. |
---|
87 | If there are no limits, use +/-inf imported from numpy. |
---|
88 | |
---|
89 | *type* indicates how the parameter will be used. "volume" parameters |
---|
90 | will be used in all functions. "orientation" parameters will be used |
---|
91 | in *Iqxy* and *Imagnetic*. "magnetic* parameters will be used in |
---|
92 | *Imagnetic* only. If *type* is the empty string, the parameter will |
---|
93 | be used in all of *Iq*, *Iqxy* and *Imagnetic*. |
---|
94 | |
---|
95 | *description* is a short description of the parameter. This will |
---|
96 | be displayed in the parameter table and used as a tool tip for the |
---|
97 | parameter value in the user interface. |
---|
98 | |
---|
99 | The kernel module must set variables defining the kernel meta data: |
---|
100 | |
---|
101 | *name* is the model name |
---|
102 | |
---|
103 | *title* is a short description of the model, suitable for a tool tip, |
---|
104 | or a one line model summary in a table of models. |
---|
105 | |
---|
106 | *description* is an extended description of the model to be displayed |
---|
107 | while the model parameters are being edited. |
---|
108 | |
---|
109 | *parameters* is the list of parameters. Parameters in the kernel |
---|
110 | functions must appear in the same order as they appear in the |
---|
111 | parameters list. Two additional parameters, *scale* and *background* |
---|
112 | are added to the beginning of the parameter list. They will show up |
---|
113 | in the documentation as model parameters, but they are never sent to |
---|
114 | the kernel functions. |
---|
115 | |
---|
116 | *source* is the list of C-99 source files that must be joined to |
---|
117 | create the OpenCL kernel functions. The files defining the functions |
---|
118 | need to be listed before the files which use the functions. |
---|
119 | |
---|
120 | *ER* is a python function defining the effective radius. If it is |
---|
121 | not present, the effective radius is 0. |
---|
122 | |
---|
123 | *VR* is a python function defining the volume ratio. If it is not |
---|
124 | present, the volume ratio is 1. |
---|
125 | |
---|
126 | *form_volume*, *Iq*, *Iqxy*, *Imagnetic* are strings containing the |
---|
127 | C source code for the body of the volume, Iq, and Iqxy functions |
---|
128 | respectively. These can also be defined in the last source file. |
---|
129 | |
---|
130 | *Iq* and *Iqxy* also be instead be python functions defining the |
---|
131 | kernel. If they are marked as *Iq.vectorized = True* then the |
---|
132 | kernel is passed the entire *q* vector at once, otherwise it is |
---|
133 | passed values one *q* at a time. The performance improvement of |
---|
134 | this step is significant. |
---|
135 | |
---|
136 | An *info* dictionary is constructed from the kernel meta data and |
---|
137 | returned to the caller. |
---|
138 | |
---|
139 | Additional fields can be defined in the kernel definition file that |
---|
140 | are not needed for sas modelling. |
---|
141 | |
---|
142 | *demo* is a dictionary of parameter=value defining a set of |
---|
143 | parameters to use by default when *compare* is called. |
---|
144 | |
---|
145 | *oldname* is the name of the model in sasview before sasmodels |
---|
146 | was split into its own package, and *oldpars* is a dictionary |
---|
147 | of *parameter: old_parameter* pairs defining the new names for |
---|
148 | the parameters. This is used by *compare* to check the values |
---|
149 | of the new model against the values of the old model before |
---|
150 | you are ready to add the new model to sasmodels. |
---|
151 | |
---|
152 | The model evaluator, function call sequence consists of q inputs and the return vector, |
---|
153 | followed by the loop value/weight vector, followed by the values for |
---|
154 | the non-polydisperse parameters, followed by the lengths of the |
---|
155 | polydispersity loops. To construct the call for 1D models, the |
---|
156 | categories *fixed-1d* and *pd-1d* list the names of the parameters |
---|
157 | of the non-polydisperse and the polydisperse parameters respectively. |
---|
158 | Similarly, *fixed-2d* and *pd-2d* provide parameter names for 2D models. |
---|
159 | The *pd-rel* category is a set of those parameters which give |
---|
160 | polydispersitiy as a portion of the value (so a 10% length dispersity |
---|
161 | would use a polydispersity value of 0.1) rather than absolute |
---|
162 | dispersity such as an angle plus or minus 15 degrees. |
---|
163 | |
---|
164 | The *volume* category lists the volume parameters in order for calls |
---|
165 | to volume within the kernel (used for volume normalization) and for |
---|
166 | calls to ER and VR for effective radius and volume ratio respectively. |
---|
167 | |
---|
168 | The *orientation* and *magnetic* categories list the orientation and |
---|
169 | magnetic parameters. These are used by the sasview interface. The |
---|
170 | blank category is for parameters such as scale which don't have any |
---|
171 | other marking. |
---|
172 | |
---|
173 | The doc string at the start of the kernel module will be used to |
---|
174 | construct the model documentation web pages. Embedded figures should |
---|
175 | appear in the subdirectory "img" beside the model definition, and tagged |
---|
176 | with the kernel module name to avoid collision with other models. Some |
---|
177 | file systems are case-sensitive, so only use lower case characters for |
---|
178 | file names and extensions. |
---|
179 | |
---|
180 | |
---|
181 | The function :func:`make` loads the metadata from the module and returns |
---|
182 | the kernel source. The function :func:`doc` extracts the doc string |
---|
183 | and adds the parameter table to the top. The function :func:`sources` |
---|
184 | returns a list of files required by the model. |
---|
185 | """ |
---|
186 | |
---|
187 | # TODO: identify model files which have changed since loading and reload them. |
---|
188 | |
---|
189 | __all__ = ["make, doc", "sources", "use_single"] |
---|
190 | |
---|
191 | import sys |
---|
192 | import os |
---|
193 | import os.path |
---|
194 | import re |
---|
195 | |
---|
196 | import numpy as np |
---|
197 | |
---|
198 | F64 = np.dtype('float64') |
---|
199 | F32 = np.dtype('float32') |
---|
200 | |
---|
201 | # Scale and background, which are parameters common to every form factor |
---|
202 | COMMON_PARAMETERS = [ |
---|
203 | [ "scale", "", 1, [0, np.inf], "", "Source intensity" ], |
---|
204 | [ "background", "1/cm", 0, [0, np.inf], "", "Source background" ], |
---|
205 | ] |
---|
206 | |
---|
207 | |
---|
208 | # Conversion from units defined in the parameter table for each model |
---|
209 | # to units displayed in the sphinx documentation. |
---|
210 | RST_UNITS = { |
---|
211 | "Ang": "|Ang|", |
---|
212 | "1/Ang^2": "|Ang^-2|", |
---|
213 | "1e-6/Ang^2": "|1e-6Ang^-2|", |
---|
214 | "degrees": "degree", |
---|
215 | "1/cm": "|cm^-1|", |
---|
216 | "": "None", |
---|
217 | } |
---|
218 | |
---|
219 | # Headers for the parameters tables in th sphinx documentation |
---|
220 | PARTABLE_HEADERS = [ |
---|
221 | "Parameter", |
---|
222 | "Description", |
---|
223 | "Units", |
---|
224 | "Default value", |
---|
225 | ] |
---|
226 | |
---|
227 | # Minimum width for a default value (this is shorter than the column header |
---|
228 | # width, so will be ignored). |
---|
229 | PARTABLE_VALUE_WIDTH = 10 |
---|
230 | |
---|
231 | # Header included before every kernel. |
---|
232 | # This makes sure that the appropriate math constants are defined, and does |
---|
233 | # whatever is required to make the kernel compile as pure C rather than |
---|
234 | # as an OpenCL kernel. |
---|
235 | KERNEL_HEADER = """\ |
---|
236 | // GENERATED CODE --- DO NOT EDIT --- |
---|
237 | // Code is produced by sasmodels.gen from sasmodels/models/MODEL.c |
---|
238 | |
---|
239 | #ifdef __OPENCL_VERSION__ |
---|
240 | # define USE_OPENCL |
---|
241 | #endif |
---|
242 | |
---|
243 | // If opencl is not available, then we are compiling a C function |
---|
244 | // Note: if using a C++ compiler, then define kernel as extern "C" |
---|
245 | #ifndef USE_OPENCL |
---|
246 | # ifdef __cplusplus |
---|
247 | #include <cmath> |
---|
248 | #if defined(_MSC_VER) |
---|
249 | #define kernel extern "C" __declspec( dllexport ) |
---|
250 | #else |
---|
251 | #define kernel extern "C" |
---|
252 | #endif |
---|
253 | using namespace std; |
---|
254 | inline void SINCOS(double angle, double &svar, double &cvar) |
---|
255 | { svar=sin(angle); cvar=cos(angle); } |
---|
256 | # else |
---|
257 | #include <math.h> |
---|
258 | #if defined(_MSC_VER) |
---|
259 | #define kernel __declspec( dllexport ) |
---|
260 | #else |
---|
261 | #define kernel |
---|
262 | #endif |
---|
263 | #define SINCOS(angle,svar,cvar) do {svar=sin(angle);cvar=cos(angle);} while (0) |
---|
264 | # endif |
---|
265 | # define global |
---|
266 | # define local |
---|
267 | # define constant const |
---|
268 | # define powr(a,b) pow(a,b) |
---|
269 | #else |
---|
270 | # ifdef USE_SINCOS |
---|
271 | # define SINCOS(angle,svar,cvar) svar=sincos(angle,&cvar) |
---|
272 | # else |
---|
273 | # define SINCOS(angle,svar,cvar) do {svar=sin(angle);cvar=cos(angle);} while (0) |
---|
274 | # endif |
---|
275 | #endif |
---|
276 | |
---|
277 | // Standard mathematical constants: |
---|
278 | // M_E, M_LOG2E, M_LOG10E, M_LN2, M_LN10, M_PI, M_PI_2=pi/2, M_PI_4=pi/4, |
---|
279 | // M_1_PI=1/pi, M_2_PI=2/pi, M_2_SQRTPI=2/sqrt(pi), SQRT2, SQRT1_2=sqrt(1/2) |
---|
280 | // OpenCL defines M_constant_F for float constants, and nothing if double |
---|
281 | // is not enabled on the card, which is why these constants may be missing |
---|
282 | #ifndef M_PI |
---|
283 | # define M_PI 3.141592653589793 |
---|
284 | #endif |
---|
285 | #ifndef M_PI_2 |
---|
286 | # define M_PI_2 1.570796326794897 |
---|
287 | #endif |
---|
288 | #ifndef M_PI_4 |
---|
289 | # define M_PI_4 0.7853981633974483 |
---|
290 | #endif |
---|
291 | |
---|
292 | // Non-standard pi/180, used for converting between degrees and radians |
---|
293 | #ifndef M_PI_180 |
---|
294 | # define M_PI_180 0.017453292519943295 |
---|
295 | #endif |
---|
296 | """ |
---|
297 | |
---|
298 | |
---|
299 | # The I(q) kernel and the I(qx, qy) kernel have one and two q parameters |
---|
300 | # respectively, so the template builder will need to do extra work to |
---|
301 | # declare, initialize and pass the q parameters. |
---|
302 | KERNEL_1D = { |
---|
303 | 'fn': "Iq", |
---|
304 | 'q_par_decl': "global const double *q,", |
---|
305 | 'qinit': "const double qi = q[i];", |
---|
306 | 'qcall': "qi", |
---|
307 | 'qwork': ["q"], |
---|
308 | } |
---|
309 | |
---|
310 | KERNEL_2D = { |
---|
311 | 'fn': "Iqxy", |
---|
312 | 'q_par_decl': "global const double *qx,\n global const double *qy,", |
---|
313 | 'qinit': "const double qxi = qx[i];\n const double qyi = qy[i];", |
---|
314 | 'qcall': "qxi, qyi", |
---|
315 | 'qwork': ["qx", "qy"], |
---|
316 | } |
---|
317 | |
---|
318 | # Generic kernel template for the polydispersity loop. |
---|
319 | # This defines the opencl kernel that is available to the host. The same |
---|
320 | # structure is used for Iq and Iqxy kernels, so extra flexibility is needed |
---|
321 | # for q parameters. The polydispersity loop is built elsewhere and |
---|
322 | # substituted into this template. |
---|
323 | KERNEL_TEMPLATE = """\ |
---|
324 | kernel void %(name)s( |
---|
325 | %(q_par_decl)s |
---|
326 | global double *result, |
---|
327 | #ifdef USE_OPENCL |
---|
328 | global double *loops_g, |
---|
329 | #else |
---|
330 | const int Nq, |
---|
331 | #endif |
---|
332 | local double *loops, |
---|
333 | const double cutoff, |
---|
334 | %(par_decl)s |
---|
335 | ) |
---|
336 | { |
---|
337 | #ifdef USE_OPENCL |
---|
338 | // copy loops info to local memory |
---|
339 | event_t e = async_work_group_copy(loops, loops_g, (%(pd_length)s)*2, 0); |
---|
340 | wait_group_events(1, &e); |
---|
341 | |
---|
342 | int i = get_global_id(0); |
---|
343 | int Nq = get_global_size(0); |
---|
344 | #endif |
---|
345 | |
---|
346 | #ifdef USE_OPENCL |
---|
347 | if (i < Nq) |
---|
348 | #else |
---|
349 | #pragma omp parallel for |
---|
350 | for (int i=0; i < Nq; i++) |
---|
351 | #endif |
---|
352 | { |
---|
353 | %(qinit)s |
---|
354 | double ret=0.0, norm=0.0; |
---|
355 | double vol=0.0, norm_vol=0.0; |
---|
356 | %(loops)s |
---|
357 | if (vol*norm_vol != 0.0) { |
---|
358 | ret *= norm_vol/vol; |
---|
359 | } |
---|
360 | result[i] = scale*ret/norm+background; |
---|
361 | } |
---|
362 | } |
---|
363 | """ |
---|
364 | |
---|
365 | # Polydispersity loop level. |
---|
366 | # This pulls the parameter value and weight from the looping vector in order |
---|
367 | # in preperation for a nested loop. |
---|
368 | LOOP_OPEN="""\ |
---|
369 | for (int %(name)s_i=0; %(name)s_i < N%(name)s; %(name)s_i++) { |
---|
370 | const double %(name)s = loops[2*(%(name)s_i%(offset)s)]; |
---|
371 | const double %(name)s_w = loops[2*(%(name)s_i%(offset)s)+1];\ |
---|
372 | """ |
---|
373 | |
---|
374 | |
---|
375 | |
---|
376 | ########################################################## |
---|
377 | # # |
---|
378 | # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # |
---|
379 | # !! !! # |
---|
380 | # !! KEEP THIS CODE CONSISTENT WITH PYKERNEL.PY !! # |
---|
381 | # !! !! # |
---|
382 | # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # |
---|
383 | # # |
---|
384 | ########################################################## |
---|
385 | |
---|
386 | |
---|
387 | # Polydispersity loop body. |
---|
388 | # This computes the weight, and if it is sufficient, calls the scattering |
---|
389 | # function and adds it to the total. If there is a volume normalization, |
---|
390 | # it will also be added here. |
---|
391 | LOOP_BODY="""\ |
---|
392 | const double weight = %(weight_product)s; |
---|
393 | if (weight > cutoff) { |
---|
394 | const double I = %(fn)s(%(qcall)s, %(pcall)s); |
---|
395 | if (I>=0.0) { // scattering cannot be negative |
---|
396 | ret += weight*I%(sasview_spherical)s; |
---|
397 | norm += weight; |
---|
398 | %(volume_norm)s |
---|
399 | } |
---|
400 | //else { printf("exclude qx,qy,I:%%g,%%g,%%g\\n",%(qcall)s,I); } |
---|
401 | } |
---|
402 | //else { printf("exclude weight:%%g\\n",weight); }\ |
---|
403 | """ |
---|
404 | |
---|
405 | # Use this when integrating over orientation |
---|
406 | SPHERICAL_CORRECTION="""\ |
---|
407 | // Correction factor for spherical integration p(theta) I(q) sin(theta) dtheta |
---|
408 | double spherical_correction = (Ntheta>1 ? fabs(sin(M_PI_180*theta)) : 1.0);\ |
---|
409 | """ |
---|
410 | # Use this to reproduce sasview behaviour |
---|
411 | SASVIEW_SPHERICAL_CORRECTION="""\ |
---|
412 | // Correction factor for spherical integration p(theta) I(q) sin(theta) dtheta |
---|
413 | double spherical_correction = (Ntheta>1 ? fabs(cos(M_PI_180*theta))*M_PI_2 : 1.0);\ |
---|
414 | """ |
---|
415 | |
---|
416 | # Volume normalization. |
---|
417 | # If there are "volume" polydispersity parameters, then these will be used |
---|
418 | # to call the form_volume function from the user supplied kernel, and accumulate |
---|
419 | # a normalized weight. |
---|
420 | VOLUME_NORM="""const double vol_weight = %(vol_weight)s; |
---|
421 | vol += vol_weight*form_volume(%(vol_pars)s); |
---|
422 | norm_vol += vol_weight;\ |
---|
423 | """ |
---|
424 | |
---|
425 | # functions defined as strings in the .py module |
---|
426 | WORK_FUNCTION="""\ |
---|
427 | double %(name)s(%(pars)s); |
---|
428 | double %(name)s(%(pars)s) |
---|
429 | { |
---|
430 | %(body)s |
---|
431 | }\ |
---|
432 | """ |
---|
433 | |
---|
434 | # Documentation header for the module, giving the model name, its short |
---|
435 | # description and its parameter table. The remainder of the doc comes |
---|
436 | # from the module docstring. |
---|
437 | DOC_HEADER=""".. _%(name)s: |
---|
438 | |
---|
439 | %(label)s |
---|
440 | ======================================================= |
---|
441 | |
---|
442 | %(title)s |
---|
443 | |
---|
444 | %(parameters)s |
---|
445 | |
---|
446 | The returned value is scaled to units of |cm^-1|. |
---|
447 | |
---|
448 | %(docs)s |
---|
449 | """ |
---|
450 | |
---|
451 | def indent(s, depth): |
---|
452 | """ |
---|
453 | Indent a string of text with *depth* additional spaces on each line. |
---|
454 | """ |
---|
455 | spaces = " "*depth |
---|
456 | sep = "\n"+spaces |
---|
457 | return spaces + sep.join(s.split("\n")) |
---|
458 | |
---|
459 | |
---|
460 | def kernel_name(info, is_2D): |
---|
461 | """ |
---|
462 | Name of the exported kernel symbol. |
---|
463 | """ |
---|
464 | return info['name'] + "_" + ("Iqxy" if is_2D else "Iq") |
---|
465 | |
---|
466 | |
---|
467 | def use_single(source): |
---|
468 | """ |
---|
469 | Convert code from double precision to single precision. |
---|
470 | """ |
---|
471 | # Convert double keyword to float. Accept an 'n' parameter for vector |
---|
472 | # values, where n is 2, 4, 8 or 16. Assume complex numbers are represented |
---|
473 | # as cdouble which is typedef'd to double2. |
---|
474 | source = re.sub(r'(^|[^a-zA-Z0-9_]c?)double(([248]|16)?($|[^a-zA-Z0-9_]))', |
---|
475 | r'\1float\2', source) |
---|
476 | # Convert floating point constants to single by adding 'f' to the end. |
---|
477 | # OS/X driver complains if you don't do this. |
---|
478 | source = re.sub(r'[^a-zA-Z_](\d*[.]\d+|\d+[.]\d*)([eE][+-]?\d+)?', |
---|
479 | r'\g<0>f', source) |
---|
480 | return source |
---|
481 | |
---|
482 | |
---|
483 | def make_kernel(info, is_2D): |
---|
484 | """ |
---|
485 | Build a kernel call from metadata supplied by the user. |
---|
486 | |
---|
487 | *info* is the json object defined in the kernel file. |
---|
488 | |
---|
489 | *form* is either "Iq" or "Iqxy". |
---|
490 | |
---|
491 | This does not create a complete OpenCL kernel source, only the top |
---|
492 | level kernel call with polydispersity and a call to the appropriate |
---|
493 | Iq or Iqxy function. |
---|
494 | """ |
---|
495 | |
---|
496 | # If we are building the Iqxy kernel, we need to propagate qx,qy |
---|
497 | # parameters, otherwise we can |
---|
498 | dim = "2d" if is_2D else "1d" |
---|
499 | fixed_pars = info['partype']['fixed-'+dim] |
---|
500 | pd_pars = info['partype']['pd-'+dim] |
---|
501 | vol_pars = info['partype']['volume'] |
---|
502 | q_pars = KERNEL_2D if is_2D else KERNEL_1D |
---|
503 | fn = q_pars['fn'] |
---|
504 | |
---|
505 | if len(pd_pars) > 0: |
---|
506 | # Build polydispersity loops |
---|
507 | depth = 4 |
---|
508 | offset = "" |
---|
509 | loop_head = [] |
---|
510 | loop_end = [] |
---|
511 | for name in pd_pars: |
---|
512 | subst = { 'name': name, 'offset': offset } |
---|
513 | loop_head.append(indent(LOOP_OPEN%subst, depth)) |
---|
514 | loop_end.insert(0, (" "*depth) + "}") |
---|
515 | offset += '+N'+name |
---|
516 | depth += 2 |
---|
517 | |
---|
518 | # The volume parameters in the inner loop are used to call the volume() |
---|
519 | # function in the kernel, with the parameters defined in vol_pars and the |
---|
520 | # weight product defined in weight. If there are no volume parameters, |
---|
521 | # then there will be no volume normalization. |
---|
522 | if vol_pars: |
---|
523 | subst = { |
---|
524 | 'vol_weight': "*".join(p+"_w" for p in vol_pars), |
---|
525 | 'vol_pars': ", ".join(vol_pars), |
---|
526 | } |
---|
527 | volume_norm = VOLUME_NORM%subst |
---|
528 | else: |
---|
529 | volume_norm = "" |
---|
530 | |
---|
531 | # Define the inner loop function call |
---|
532 | # The parameters to the f(q,p1,p2...) call should occur in the same |
---|
533 | # order as given in the parameter info structure. This may be different |
---|
534 | # from the parameter order in the call to the kernel since the kernel |
---|
535 | # call places all fixed parameters before all polydisperse parameters. |
---|
536 | fq_pars = [p[0] for p in info['parameters'][len(COMMON_PARAMETERS):] |
---|
537 | if p[0] in set(fixed_pars+pd_pars)] |
---|
538 | if False and "theta" in pd_pars: |
---|
539 | spherical_correction = [indent(SPHERICAL_CORRECTION, depth)] |
---|
540 | weights = [p+"_w" for p in pd_pars]+['spherical_correction'] |
---|
541 | sasview_spherical = "" |
---|
542 | elif True and "theta" in pd_pars: |
---|
543 | spherical_correction = [indent(SASVIEW_SPHERICAL_CORRECTION,depth)] |
---|
544 | weights = [p+"_w" for p in pd_pars] |
---|
545 | sasview_spherical = "*spherical_correction" |
---|
546 | else: |
---|
547 | spherical_correction = [] |
---|
548 | weights = [p+"_w" for p in pd_pars] |
---|
549 | sasview_spherical = "" |
---|
550 | subst = { |
---|
551 | 'weight_product': "*".join(weights), |
---|
552 | 'volume_norm': volume_norm, |
---|
553 | 'fn': fn, |
---|
554 | 'qcall': q_pars['qcall'], |
---|
555 | 'pcall': ", ".join(fq_pars), # skip scale and background |
---|
556 | 'sasview_spherical': sasview_spherical, |
---|
557 | } |
---|
558 | loop_body = [indent(LOOP_BODY%subst, depth)] |
---|
559 | loops = "\n".join(loop_head+spherical_correction+loop_body+loop_end) |
---|
560 | |
---|
561 | # declarations for non-pd followed by pd pars |
---|
562 | # e.g., |
---|
563 | # const double sld, |
---|
564 | # const int Nradius |
---|
565 | fixed_par_decl = ",\n ".join("const double %s"%p for p in fixed_pars) |
---|
566 | pd_par_decl = ",\n ".join("const int N%s"%p for p in pd_pars) |
---|
567 | if fixed_par_decl and pd_par_decl: |
---|
568 | par_decl = ",\n ".join((fixed_par_decl, pd_par_decl)) |
---|
569 | elif fixed_par_decl: |
---|
570 | par_decl = fixed_par_decl |
---|
571 | else: |
---|
572 | par_decl = pd_par_decl |
---|
573 | |
---|
574 | # Finally, put the pieces together in the kernel. |
---|
575 | subst = { |
---|
576 | # kernel name is, e.g., cylinder_Iq |
---|
577 | 'name': kernel_name(info, is_2D), |
---|
578 | # to declare, e.g., global double q[], |
---|
579 | 'q_par_decl': q_pars['q_par_decl'], |
---|
580 | # to declare, e.g., double sld, int Nradius, int Nlength |
---|
581 | 'par_decl': par_decl, |
---|
582 | # to copy global to local pd pars we need, e.g., Nradius+Nlength |
---|
583 | 'pd_length': "+".join('N'+p for p in pd_pars), |
---|
584 | # the q initializers, e.g., double qi = q[i]; |
---|
585 | 'qinit': q_pars['qinit'], |
---|
586 | # the actual polydispersity loop |
---|
587 | 'loops': loops, |
---|
588 | } |
---|
589 | kernel = KERNEL_TEMPLATE%subst |
---|
590 | |
---|
591 | # If the working function is defined in the kernel metadata as a |
---|
592 | # string, translate the string to an actual function definition |
---|
593 | # and put it before the kernel. |
---|
594 | if info[fn]: |
---|
595 | subst = { |
---|
596 | 'name': fn, |
---|
597 | 'pars': ", ".join("double "+p for p in q_pars['qwork']+fq_pars), |
---|
598 | 'body': info[fn], |
---|
599 | } |
---|
600 | kernel = "\n".join((WORK_FUNCTION%subst, kernel)) |
---|
601 | return kernel |
---|
602 | |
---|
603 | def make_partable(pars): |
---|
604 | """ |
---|
605 | Generate the parameter table to include in the sphinx documentation. |
---|
606 | """ |
---|
607 | pars = COMMON_PARAMETERS + pars |
---|
608 | column_widths = [ |
---|
609 | max(len(p[0]) for p in pars), |
---|
610 | max(len(p[-1]) for p in pars), |
---|
611 | max(len(RST_UNITS[p[1]]) for p in pars), |
---|
612 | PARTABLE_VALUE_WIDTH, |
---|
613 | ] |
---|
614 | column_widths = [max(w, len(h)) |
---|
615 | for w,h in zip(column_widths, PARTABLE_HEADERS)] |
---|
616 | |
---|
617 | sep = " ".join("="*w for w in column_widths) |
---|
618 | lines = [ |
---|
619 | sep, |
---|
620 | " ".join("%-*s"%(w,h) for w,h in zip(column_widths, PARTABLE_HEADERS)), |
---|
621 | sep, |
---|
622 | ] |
---|
623 | for p in pars: |
---|
624 | lines.append(" ".join([ |
---|
625 | "%-*s"%(column_widths[0],p[0]), |
---|
626 | "%-*s"%(column_widths[1],p[-1]), |
---|
627 | "%-*s"%(column_widths[2],RST_UNITS[p[1]]), |
---|
628 | "%*g"%(column_widths[3],p[2]), |
---|
629 | ])) |
---|
630 | lines.append(sep) |
---|
631 | return "\n".join(lines) |
---|
632 | |
---|
633 | def _search(search_path, filename): |
---|
634 | """ |
---|
635 | Find *filename* in *search_path*. |
---|
636 | |
---|
637 | Raises ValueError if file does not exist. |
---|
638 | """ |
---|
639 | for path in search_path: |
---|
640 | target = os.path.join(path, filename) |
---|
641 | if os.path.exists(target): |
---|
642 | return target |
---|
643 | raise ValueError("%r not found in %s"%(filename, search_path)) |
---|
644 | |
---|
645 | def sources(info): |
---|
646 | """ |
---|
647 | Return a list of the sources file paths for the module. |
---|
648 | """ |
---|
649 | from os.path import abspath, dirname, join as joinpath |
---|
650 | search_path = [ dirname(info['filename']), |
---|
651 | abspath(joinpath(dirname(__file__),'models')) ] |
---|
652 | return [_search(search_path, f) for f in info['source']] |
---|
653 | |
---|
654 | def make_model(info): |
---|
655 | """ |
---|
656 | Generate the code for the kernel defined by info, using source files |
---|
657 | found in the given search path. |
---|
658 | """ |
---|
659 | source = [open(f).read() for f in sources(info)] |
---|
660 | # If the form volume is defined as a string, then wrap it in a |
---|
661 | # function definition and place it after the external sources but |
---|
662 | # before the kernel functions. If the kernel functions are strings, |
---|
663 | # they will be translated in the make_kernel call. |
---|
664 | if info['form_volume']: |
---|
665 | subst = { |
---|
666 | 'name': "form_volume", |
---|
667 | 'pars': ", ".join("double "+p for p in info['partype']['volume']), |
---|
668 | 'body': info['form_volume'], |
---|
669 | } |
---|
670 | source.append(WORK_FUNCTION%subst) |
---|
671 | kernel_Iq = make_kernel(info, is_2D=False) if not callable(info['Iq']) else "" |
---|
672 | kernel_Iqxy = make_kernel(info, is_2D=True) if not callable(info['Iqxy']) else "" |
---|
673 | kernel = "\n\n".join([KERNEL_HEADER]+source+[kernel_Iq, kernel_Iqxy]) |
---|
674 | return kernel |
---|
675 | |
---|
676 | def categorize_parameters(pars): |
---|
677 | """ |
---|
678 | Build parameter categories out of the the parameter definitions. |
---|
679 | |
---|
680 | Returns a dictionary of categories. |
---|
681 | """ |
---|
682 | partype = { |
---|
683 | 'volume': [], 'orientation': [], 'magnetic': [], '': [], |
---|
684 | 'fixed-1d': [], 'fixed-2d': [], 'pd-1d': [], 'pd-2d': [], |
---|
685 | 'pd-rel': set(), |
---|
686 | } |
---|
687 | |
---|
688 | for p in pars: |
---|
689 | name,ptype = p[0],p[4] |
---|
690 | if ptype == 'volume': |
---|
691 | partype['pd-1d'].append(name) |
---|
692 | partype['pd-2d'].append(name) |
---|
693 | partype['pd-rel'].add(name) |
---|
694 | elif ptype == 'magnetic': |
---|
695 | partype['fixed-2d'].append(name) |
---|
696 | elif ptype == 'orientation': |
---|
697 | partype['pd-2d'].append(name) |
---|
698 | elif ptype == '': |
---|
699 | partype['fixed-1d'].append(name) |
---|
700 | partype['fixed-2d'].append(name) |
---|
701 | else: |
---|
702 | raise ValueError("unknown parameter type %r"%ptype) |
---|
703 | partype[ptype].append(name) |
---|
704 | |
---|
705 | return partype |
---|
706 | |
---|
707 | def make(kernel_module): |
---|
708 | """ |
---|
709 | Build an OpenCL/ctypes function from the definition in *kernel_module*. |
---|
710 | |
---|
711 | The module can be loaded with a normal python import statement if you |
---|
712 | know which module you need, or with __import__('sasmodels.model.'+name) |
---|
713 | if the name is in a string. |
---|
714 | """ |
---|
715 | # TODO: allow Iq and Iqxy to be defined in python |
---|
716 | from os.path import abspath |
---|
717 | #print kernelfile |
---|
718 | info = dict( |
---|
719 | filename = abspath(kernel_module.__file__), |
---|
720 | name = kernel_module.name, |
---|
721 | title = kernel_module.title, |
---|
722 | description = kernel_module.description, |
---|
723 | parameters = COMMON_PARAMETERS + kernel_module.parameters, |
---|
724 | source = getattr(kernel_module, 'source', []), |
---|
725 | oldname = kernel_module.oldname, |
---|
726 | oldpars = kernel_module.oldpars, |
---|
727 | ) |
---|
728 | # Fill in attributes which default to None |
---|
729 | info.update((k,getattr(kernel_module, k, None)) |
---|
730 | for k in ('ER', 'VR', 'form_volume', 'Iq', 'Iqxy')) |
---|
731 | # Fill in the derived attributes |
---|
732 | info['limits'] = dict((p[0],p[3]) for p in info['parameters']) |
---|
733 | info['partype'] = categorize_parameters(info['parameters']) |
---|
734 | info['defaults'] = dict((p[0],p[2]) for p in info['parameters']) |
---|
735 | |
---|
736 | source = make_model(info) |
---|
737 | |
---|
738 | return source, info |
---|
739 | |
---|
740 | def doc(kernel_module): |
---|
741 | """ |
---|
742 | Return the documentation for the model. |
---|
743 | """ |
---|
744 | subst = dict(name=kernel_module.name.replace('_','-'), |
---|
745 | label=" ".join(kernel_module.name.split('_')).capitalize(), |
---|
746 | title=kernel_module.title, |
---|
747 | parameters=make_partable(kernel_module.parameters), |
---|
748 | docs=kernel_module.__doc__) |
---|
749 | return DOC_HEADER%subst |
---|
750 | |
---|
751 | |
---|
752 | |
---|
753 | def demo_time(): |
---|
754 | import datetime |
---|
755 | from .models import cylinder |
---|
756 | toc = lambda: (datetime.datetime.now()-tic).total_seconds() |
---|
757 | tic = datetime.datetime.now() |
---|
758 | source, info = make(cylinder) |
---|
759 | print "time:",toc() |
---|
760 | |
---|
761 | def main(): |
---|
762 | if len(sys.argv) <= 1: |
---|
763 | print "usage: python -m sasmodels.generate modelname" |
---|
764 | else: |
---|
765 | name = sys.argv[1] |
---|
766 | import sasmodels.models |
---|
767 | __import__('sasmodels.models.'+name) |
---|
768 | model = getattr(sasmodels.models, name) |
---|
769 | source, info = make(model); print source |
---|
770 | #print doc(model) |
---|
771 | |
---|
772 | if __name__ == "__main__": |
---|
773 | main() |
---|