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 | *id* is an implicit variable formed from the filename. It will be |
---|
102 | a valid python identifier, and will be used as the reference into |
---|
103 | the html documentation, with '_' replaced by '-'. |
---|
104 | |
---|
105 | *name* is the model name as displayed to the user. If it is missing, |
---|
106 | it will be constructed from the id. |
---|
107 | |
---|
108 | *title* is a short description of the model, suitable for a tool tip, |
---|
109 | or a one line model summary in a table of models. |
---|
110 | |
---|
111 | *description* is an extended description of the model to be displayed |
---|
112 | while the model parameters are being edited. |
---|
113 | |
---|
114 | *parameters* is the list of parameters. Parameters in the kernel |
---|
115 | functions must appear in the same order as they appear in the |
---|
116 | parameters list. Two additional parameters, *scale* and *background* |
---|
117 | are added to the beginning of the parameter list. They will show up |
---|
118 | in the documentation as model parameters, but they are never sent to |
---|
119 | the kernel functions. |
---|
120 | |
---|
121 | *category* is the default category for the model. Models in the |
---|
122 | *structure-factor* category do not have *scale* and *background* |
---|
123 | added. |
---|
124 | |
---|
125 | *source* is the list of C-99 source files that must be joined to |
---|
126 | create the OpenCL kernel functions. The files defining the functions |
---|
127 | need to be listed before the files which use the functions. |
---|
128 | |
---|
129 | *ER* is a python function defining the effective radius. If it is |
---|
130 | not present, the effective radius is 0. |
---|
131 | |
---|
132 | *VR* is a python function defining the volume ratio. If it is not |
---|
133 | present, the volume ratio is 1. |
---|
134 | |
---|
135 | *form_volume*, *Iq*, *Iqxy*, *Imagnetic* are strings containing the |
---|
136 | C source code for the body of the volume, Iq, and Iqxy functions |
---|
137 | respectively. These can also be defined in the last source file. |
---|
138 | |
---|
139 | *Iq* and *Iqxy* also be instead be python functions defining the |
---|
140 | kernel. If they are marked as *Iq.vectorized = True* then the |
---|
141 | kernel is passed the entire *q* vector at once, otherwise it is |
---|
142 | passed values one *q* at a time. The performance improvement of |
---|
143 | this step is significant. |
---|
144 | |
---|
145 | *demo* is a dictionary of parameter=value defining a set of |
---|
146 | parameters to use by default when *compare* is called. Any |
---|
147 | parameter not set in *demo* gets the initial value from the |
---|
148 | parameter list. *demo* is mostly needed to set the default |
---|
149 | polydispersity values for tests. |
---|
150 | |
---|
151 | *oldname* is the name of the model in sasview before sasmodels |
---|
152 | was split into its own package, and *oldpars* is a dictionary |
---|
153 | of *parameter: old_parameter* pairs defining the new names for |
---|
154 | the parameters. This is used by *compare* to check the values |
---|
155 | of the new model against the values of the old model before |
---|
156 | you are ready to add the new model to sasmodels. |
---|
157 | |
---|
158 | |
---|
159 | An *info* dictionary is constructed from the kernel meta data and |
---|
160 | returned to the caller. |
---|
161 | |
---|
162 | The model evaluator, function call sequence consists of q inputs and the return vector, |
---|
163 | followed by the loop value/weight vector, followed by the values for |
---|
164 | the non-polydisperse parameters, followed by the lengths of the |
---|
165 | polydispersity loops. To construct the call for 1D models, the |
---|
166 | categories *fixed-1d* and *pd-1d* list the names of the parameters |
---|
167 | of the non-polydisperse and the polydisperse parameters respectively. |
---|
168 | Similarly, *fixed-2d* and *pd-2d* provide parameter names for 2D models. |
---|
169 | The *pd-rel* category is a set of those parameters which give |
---|
170 | polydispersitiy as a portion of the value (so a 10% length dispersity |
---|
171 | would use a polydispersity value of 0.1) rather than absolute |
---|
172 | dispersity such as an angle plus or minus 15 degrees. |
---|
173 | |
---|
174 | The *volume* category lists the volume parameters in order for calls |
---|
175 | to volume within the kernel (used for volume normalization) and for |
---|
176 | calls to ER and VR for effective radius and volume ratio respectively. |
---|
177 | |
---|
178 | The *orientation* and *magnetic* categories list the orientation and |
---|
179 | magnetic parameters. These are used by the sasview interface. The |
---|
180 | blank category is for parameters such as scale which don't have any |
---|
181 | other marking. |
---|
182 | |
---|
183 | The doc string at the start of the kernel module will be used to |
---|
184 | construct the model documentation web pages. Embedded figures should |
---|
185 | appear in the subdirectory "img" beside the model definition, and tagged |
---|
186 | with the kernel module name to avoid collision with other models. Some |
---|
187 | file systems are case-sensitive, so only use lower case characters for |
---|
188 | file names and extensions. |
---|
189 | |
---|
190 | |
---|
191 | The function :func:`make` loads the metadata from the module and returns |
---|
192 | the kernel source. The function :func:`doc` extracts the doc string |
---|
193 | and adds the parameter table to the top. The function :func:`sources` |
---|
194 | returns a list of files required by the model. |
---|
195 | """ |
---|
196 | |
---|
197 | # TODO: identify model files which have changed since loading and reload them. |
---|
198 | |
---|
199 | __all__ = ["make", "doc", "sources", "convert_type"] |
---|
200 | |
---|
201 | import sys |
---|
202 | from os.path import abspath, dirname, join as joinpath, exists, basename, \ |
---|
203 | splitext |
---|
204 | import re |
---|
205 | import string |
---|
206 | |
---|
207 | import numpy as np |
---|
208 | C_KERNEL_TEMPLATE_PATH = joinpath(dirname(__file__), 'kernel_template.c') |
---|
209 | |
---|
210 | F16 = np.dtype('float16') |
---|
211 | F32 = np.dtype('float32') |
---|
212 | F64 = np.dtype('float64') |
---|
213 | try: # CRUFT: older numpy does not support float128 |
---|
214 | F128 = np.dtype('float128') |
---|
215 | except TypeError: |
---|
216 | F128 = None |
---|
217 | |
---|
218 | |
---|
219 | # Scale and background, which are parameters common to every form factor |
---|
220 | COMMON_PARAMETERS = [ |
---|
221 | ["scale", "", 1, [0, np.inf], "", "Source intensity"], |
---|
222 | ["background", "1/cm", 0, [0, np.inf], "", "Source background"], |
---|
223 | ] |
---|
224 | |
---|
225 | |
---|
226 | # Conversion from units defined in the parameter table for each model |
---|
227 | # to units displayed in the sphinx documentation. |
---|
228 | RST_UNITS = { |
---|
229 | "Ang": "|Ang|", |
---|
230 | "1/Ang": "|Ang^-1|", |
---|
231 | "1/Ang^2": "|Ang^-2|", |
---|
232 | "1e-6/Ang^2": "|1e-6Ang^-2|", |
---|
233 | "degrees": "degree", |
---|
234 | "1/cm": "|cm^-1|", |
---|
235 | "": "None", |
---|
236 | } |
---|
237 | |
---|
238 | # Headers for the parameters tables in th sphinx documentation |
---|
239 | PARTABLE_HEADERS = [ |
---|
240 | "Parameter", |
---|
241 | "Description", |
---|
242 | "Units", |
---|
243 | "Default value", |
---|
244 | ] |
---|
245 | |
---|
246 | # Minimum width for a default value (this is shorter than the column header |
---|
247 | # width, so will be ignored). |
---|
248 | PARTABLE_VALUE_WIDTH = 10 |
---|
249 | |
---|
250 | # Documentation header for the module, giving the model name, its short |
---|
251 | # description and its parameter table. The remainder of the doc comes |
---|
252 | # from the module docstring. |
---|
253 | DOC_HEADER = """.. _%(id)s: |
---|
254 | |
---|
255 | %(name)s |
---|
256 | ======================================================= |
---|
257 | |
---|
258 | %(title)s |
---|
259 | |
---|
260 | %(parameters)s |
---|
261 | |
---|
262 | %(returns)s |
---|
263 | |
---|
264 | %(docs)s |
---|
265 | """ |
---|
266 | |
---|
267 | def format_units(par): |
---|
268 | return RST_UNITS.get(par, par) |
---|
269 | |
---|
270 | def make_partable(pars): |
---|
271 | """ |
---|
272 | Generate the parameter table to include in the sphinx documentation. |
---|
273 | """ |
---|
274 | column_widths = [ |
---|
275 | max(len(p[0]) for p in pars), |
---|
276 | max(len(p[-1]) for p in pars), |
---|
277 | max(len(format_units(p[1])) for p in pars), |
---|
278 | PARTABLE_VALUE_WIDTH, |
---|
279 | ] |
---|
280 | column_widths = [max(w, len(h)) |
---|
281 | for w, h in zip(column_widths, PARTABLE_HEADERS)] |
---|
282 | |
---|
283 | sep = " ".join("="*w for w in column_widths) |
---|
284 | lines = [ |
---|
285 | sep, |
---|
286 | " ".join("%-*s" % (w, h) for w, h in zip(column_widths, PARTABLE_HEADERS)), |
---|
287 | sep, |
---|
288 | ] |
---|
289 | for p in pars: |
---|
290 | lines.append(" ".join([ |
---|
291 | "%-*s" % (column_widths[0], p[0]), |
---|
292 | "%-*s" % (column_widths[1], p[-1]), |
---|
293 | "%-*s" % (column_widths[2], format_units(p[1])), |
---|
294 | "%*g" % (column_widths[3], p[2]), |
---|
295 | ])) |
---|
296 | lines.append(sep) |
---|
297 | return "\n".join(lines) |
---|
298 | |
---|
299 | def _search(search_path, filename): |
---|
300 | """ |
---|
301 | Find *filename* in *search_path*. |
---|
302 | |
---|
303 | Raises ValueError if file does not exist. |
---|
304 | """ |
---|
305 | for path in search_path: |
---|
306 | target = joinpath(path, filename) |
---|
307 | if exists(target): |
---|
308 | return target |
---|
309 | raise ValueError("%r not found in %s" % (filename, search_path)) |
---|
310 | |
---|
311 | def sources(info): |
---|
312 | """ |
---|
313 | Return a list of the sources file paths for the module. |
---|
314 | """ |
---|
315 | search_path = [dirname(info['filename']), |
---|
316 | abspath(joinpath(dirname(__file__), 'models'))] |
---|
317 | return [_search(search_path, f) for f in info['source']] |
---|
318 | |
---|
319 | # Pragmas for enable OpenCL features. Be sure to protect them so that they |
---|
320 | # still compile even if OpenCL is not present. |
---|
321 | _F16_PRAGMA = """\ |
---|
322 | #if defined(__OPENCL_VERSION__) && !defined(cl_khr_fp16) |
---|
323 | # pragma OPENCL EXTENSION cl_khr_fp16: enable |
---|
324 | #endif |
---|
325 | """ |
---|
326 | |
---|
327 | _F64_PRAGMA = """\ |
---|
328 | #if defined(__OPENCL_VERSION__) && !defined(cl_khr_fp64) |
---|
329 | # pragma OPENCL EXTENSION cl_khr_fp64: enable |
---|
330 | #endif |
---|
331 | """ |
---|
332 | |
---|
333 | def convert_type(source, dtype): |
---|
334 | """ |
---|
335 | Convert code from double precision to the desired type. |
---|
336 | """ |
---|
337 | if dtype == F16: |
---|
338 | source = _F16_PRAGMA + _convert_type(source, "half", "f") |
---|
339 | elif dtype == F32: |
---|
340 | source = _convert_type(source, "float", "f") |
---|
341 | elif dtype == F64: |
---|
342 | source = _F64_PRAGMA + source # Source is already double |
---|
343 | elif dtype == F128: |
---|
344 | source = _convert_type(source, "long double", "L") |
---|
345 | else: |
---|
346 | raise ValueError("Unexpected dtype in source conversion: %s"%dtype) |
---|
347 | return source |
---|
348 | |
---|
349 | |
---|
350 | def _convert_type(source, type_name, constant_flag): |
---|
351 | # Convert double keyword to float/long double/half. |
---|
352 | # Accept an 'n' # parameter for vector # values, where n is 2, 4, 8 or 16. |
---|
353 | # Assume complex numbers are represented as cdouble which is typedef'd |
---|
354 | # to double2. |
---|
355 | source = re.sub(r'(^|[^a-zA-Z0-9_]c?)double(([248]|16)?($|[^a-zA-Z0-9_]))', |
---|
356 | r'\1%s\2'%type_name, source) |
---|
357 | # Convert floating point constants to single by adding 'f' to the end, |
---|
358 | # or long double with an 'L' suffix. OS/X complains if you don't do this. |
---|
359 | source = re.sub(r'[^a-zA-Z_](\d*[.]\d+|\d+[.]\d*)([eE][+-]?\d+)?', |
---|
360 | r'\g<0>%s'%constant_flag, source) |
---|
361 | return source |
---|
362 | |
---|
363 | |
---|
364 | def kernel_name(info, is_2D): |
---|
365 | """ |
---|
366 | Name of the exported kernel symbol. |
---|
367 | """ |
---|
368 | return info['name'] + "_" + ("Iqxy" if is_2D else "Iq") |
---|
369 | |
---|
370 | |
---|
371 | def categorize_parameters(pars): |
---|
372 | """ |
---|
373 | Build parameter categories out of the the parameter definitions. |
---|
374 | |
---|
375 | Returns a dictionary of categories. |
---|
376 | """ |
---|
377 | partype = { |
---|
378 | 'volume': [], 'orientation': [], 'magnetic': [], '': [], |
---|
379 | 'fixed-1d': [], 'fixed-2d': [], 'pd-1d': [], 'pd-2d': [], |
---|
380 | 'pd-rel': set(), |
---|
381 | } |
---|
382 | |
---|
383 | for p in pars: |
---|
384 | name, ptype = p[0], p[4] |
---|
385 | if ptype == 'volume': |
---|
386 | partype['pd-1d'].append(name) |
---|
387 | partype['pd-2d'].append(name) |
---|
388 | partype['pd-rel'].add(name) |
---|
389 | elif ptype == 'magnetic': |
---|
390 | partype['fixed-2d'].append(name) |
---|
391 | elif ptype == 'orientation': |
---|
392 | partype['pd-2d'].append(name) |
---|
393 | elif ptype == '': |
---|
394 | partype['fixed-1d'].append(name) |
---|
395 | partype['fixed-2d'].append(name) |
---|
396 | else: |
---|
397 | raise ValueError("unknown parameter type %r" % ptype) |
---|
398 | partype[ptype].append(name) |
---|
399 | |
---|
400 | return partype |
---|
401 | |
---|
402 | def indent(s, depth): |
---|
403 | """ |
---|
404 | Indent a string of text with *depth* additional spaces on each line. |
---|
405 | """ |
---|
406 | spaces = " "*depth |
---|
407 | sep = "\n" + spaces |
---|
408 | return spaces + sep.join(s.split("\n")) |
---|
409 | |
---|
410 | |
---|
411 | def build_polydispersity_loops(pd_pars): |
---|
412 | """ |
---|
413 | Build polydispersity loops |
---|
414 | |
---|
415 | Returns loop opening and loop closing |
---|
416 | """ |
---|
417 | LOOP_OPEN = """\ |
---|
418 | for (int %(name)s_i=0; %(name)s_i < N%(name)s; %(name)s_i++) { |
---|
419 | const double %(name)s = loops[2*(%(name)s_i%(offset)s)]; |
---|
420 | const double %(name)s_w = loops[2*(%(name)s_i%(offset)s)+1];\ |
---|
421 | """ |
---|
422 | depth = 4 |
---|
423 | offset = "" |
---|
424 | loop_head = [] |
---|
425 | loop_end = [] |
---|
426 | for name in pd_pars: |
---|
427 | subst = {'name': name, 'offset': offset} |
---|
428 | loop_head.append(indent(LOOP_OPEN % subst, depth)) |
---|
429 | loop_end.insert(0, (" "*depth) + "}") |
---|
430 | offset += '+N' + name |
---|
431 | depth += 2 |
---|
432 | return "\n".join(loop_head), "\n".join(loop_end) |
---|
433 | |
---|
434 | C_KERNEL_TEMPLATE = None |
---|
435 | def make_model(info): |
---|
436 | """ |
---|
437 | Generate the code for the kernel defined by info, using source files |
---|
438 | found in the given search path. |
---|
439 | """ |
---|
440 | # TODO: need something other than volume to indicate dispersion parameters |
---|
441 | # No volume normalization despite having a volume parameter. |
---|
442 | # Thickness is labelled a volume in order to trigger polydispersity. |
---|
443 | # May want a separate dispersion flag, or perhaps a separate category for |
---|
444 | # disperse, but not volume. Volume parameters also use relative values |
---|
445 | # for the distribution rather than the absolute values used by angular |
---|
446 | # dispersion. Need to be careful that necessary parameters are available |
---|
447 | # for computing volume even if we allow non-disperse volume parameters. |
---|
448 | |
---|
449 | # Load template |
---|
450 | global C_KERNEL_TEMPLATE |
---|
451 | if C_KERNEL_TEMPLATE is None: |
---|
452 | with open(C_KERNEL_TEMPLATE_PATH) as fid: |
---|
453 | C_KERNEL_TEMPLATE = fid.read() |
---|
454 | |
---|
455 | # Load additional sources |
---|
456 | source = [open(f).read() for f in sources(info)] |
---|
457 | |
---|
458 | # Prepare defines |
---|
459 | defines = [] |
---|
460 | partype = info['partype'] |
---|
461 | pd_1d = partype['pd-1d'] |
---|
462 | pd_2d = partype['pd-2d'] |
---|
463 | fixed_1d = partype['fixed-1d'] |
---|
464 | fixed_2d = partype['fixed-1d'] |
---|
465 | |
---|
466 | iq_parameters = [p[0] |
---|
467 | for p in info['parameters'][2:] # skip scale, background |
---|
468 | if p[0] in set(fixed_1d + pd_1d)] |
---|
469 | iqxy_parameters = [p[0] |
---|
470 | for p in info['parameters'][2:] # skip scale, background |
---|
471 | if p[0] in set(fixed_2d + pd_2d)] |
---|
472 | volume_parameters = [p[0] |
---|
473 | for p in info['parameters'] |
---|
474 | if p[4] == 'volume'] |
---|
475 | |
---|
476 | # Fill in defintions for volume parameters |
---|
477 | if volume_parameters: |
---|
478 | defines.append(('VOLUME_PARAMETERS', |
---|
479 | ','.join(volume_parameters))) |
---|
480 | defines.append(('VOLUME_WEIGHT_PRODUCT', |
---|
481 | '*'.join(p + '_w' for p in volume_parameters))) |
---|
482 | |
---|
483 | # Generate form_volume function from body only |
---|
484 | if info['form_volume'] is not None: |
---|
485 | if volume_parameters: |
---|
486 | vol_par_decl = ', '.join('double ' + p for p in volume_parameters) |
---|
487 | else: |
---|
488 | vol_par_decl = 'void' |
---|
489 | defines.append(('VOLUME_PARAMETER_DECLARATIONS', |
---|
490 | vol_par_decl)) |
---|
491 | fn = """\ |
---|
492 | double form_volume(VOLUME_PARAMETER_DECLARATIONS); |
---|
493 | double form_volume(VOLUME_PARAMETER_DECLARATIONS) { |
---|
494 | %(body)s |
---|
495 | } |
---|
496 | """ % {'body':info['form_volume']} |
---|
497 | source.append(fn) |
---|
498 | |
---|
499 | # Fill in definitions for Iq parameters |
---|
500 | defines.append(('IQ_KERNEL_NAME', info['name'] + '_Iq')) |
---|
501 | defines.append(('IQ_PARAMETERS', ', '.join(iq_parameters))) |
---|
502 | if fixed_1d: |
---|
503 | defines.append(('IQ_FIXED_PARAMETER_DECLARATIONS', |
---|
504 | ', \\\n '.join('const double %s' % p for p in fixed_1d))) |
---|
505 | if pd_1d: |
---|
506 | defines.append(('IQ_WEIGHT_PRODUCT', |
---|
507 | '*'.join(p + '_w' for p in pd_1d))) |
---|
508 | defines.append(('IQ_DISPERSION_LENGTH_DECLARATIONS', |
---|
509 | ', \\\n '.join('const int N%s' % p for p in pd_1d))) |
---|
510 | defines.append(('IQ_DISPERSION_LENGTH_SUM', |
---|
511 | '+'.join('N' + p for p in pd_1d))) |
---|
512 | open_loops, close_loops = build_polydispersity_loops(pd_1d) |
---|
513 | defines.append(('IQ_OPEN_LOOPS', |
---|
514 | open_loops.replace('\n', ' \\\n'))) |
---|
515 | defines.append(('IQ_CLOSE_LOOPS', |
---|
516 | close_loops.replace('\n', ' \\\n'))) |
---|
517 | if info['Iq'] is not None: |
---|
518 | defines.append(('IQ_PARAMETER_DECLARATIONS', |
---|
519 | ', '.join('double ' + p for p in iq_parameters))) |
---|
520 | fn = """\ |
---|
521 | double Iq(double q, IQ_PARAMETER_DECLARATIONS); |
---|
522 | double Iq(double q, IQ_PARAMETER_DECLARATIONS) { |
---|
523 | %(body)s |
---|
524 | } |
---|
525 | """ % {'body':info['Iq']} |
---|
526 | source.append(fn) |
---|
527 | |
---|
528 | # Fill in definitions for Iqxy parameters |
---|
529 | defines.append(('IQXY_KERNEL_NAME', info['name'] + '_Iqxy')) |
---|
530 | defines.append(('IQXY_PARAMETERS', ', '.join(iqxy_parameters))) |
---|
531 | if fixed_2d: |
---|
532 | defines.append(('IQXY_FIXED_PARAMETER_DECLARATIONS', |
---|
533 | ', \\\n '.join('const double %s' % p for p in fixed_2d))) |
---|
534 | if pd_2d: |
---|
535 | defines.append(('IQXY_WEIGHT_PRODUCT', |
---|
536 | '*'.join(p + '_w' for p in pd_2d))) |
---|
537 | defines.append(('IQXY_DISPERSION_LENGTH_DECLARATIONS', |
---|
538 | ', \\\n '.join('const int N%s' % p for p in pd_2d))) |
---|
539 | defines.append(('IQXY_DISPERSION_LENGTH_SUM', |
---|
540 | '+'.join('N' + p for p in pd_2d))) |
---|
541 | open_loops, close_loops = build_polydispersity_loops(pd_2d) |
---|
542 | defines.append(('IQXY_OPEN_LOOPS', |
---|
543 | open_loops.replace('\n', ' \\\n'))) |
---|
544 | defines.append(('IQXY_CLOSE_LOOPS', |
---|
545 | close_loops.replace('\n', ' \\\n'))) |
---|
546 | if info['Iqxy'] is not None: |
---|
547 | defines.append(('IQXY_PARAMETER_DECLARATIONS', |
---|
548 | ', '.join('double ' + p for p in iqxy_parameters))) |
---|
549 | fn = """\ |
---|
550 | double Iqxy(double qx, double qy, IQXY_PARAMETER_DECLARATIONS); |
---|
551 | double Iqxy(double qx, double qy, IQXY_PARAMETER_DECLARATIONS) { |
---|
552 | %(body)s |
---|
553 | } |
---|
554 | """ % {'body':info['Iqxy']} |
---|
555 | source.append(fn) |
---|
556 | |
---|
557 | # Need to know if we have a theta parameter for Iqxy; it is not there |
---|
558 | # for the magnetic sphere model, for example, which has a magnetic |
---|
559 | # orientation but no shape orientation. |
---|
560 | if 'theta' in pd_2d: |
---|
561 | defines.append(('IQXY_HAS_THETA', '1')) |
---|
562 | |
---|
563 | #for d in defines: print(d) |
---|
564 | DEFINES = '\n'.join('#define %s %s' % (k, v) for k, v in defines) |
---|
565 | SOURCES = '\n\n'.join(source) |
---|
566 | return C_KERNEL_TEMPLATE % { |
---|
567 | 'DEFINES':DEFINES, |
---|
568 | 'SOURCES':SOURCES, |
---|
569 | } |
---|
570 | |
---|
571 | def make_info(kernel_module): |
---|
572 | """ |
---|
573 | Interpret the model definition file, categorizing the parameters. |
---|
574 | """ |
---|
575 | #print(kernelfile) |
---|
576 | category = getattr(kernel_module, 'category', None) |
---|
577 | parameters = COMMON_PARAMETERS + kernel_module.parameters |
---|
578 | # Default the demo parameters to the starting values for the individual |
---|
579 | # parameters if an explicit demo parameter set has not been specified. |
---|
580 | demo_parameters = getattr(kernel_module, 'demo', None) |
---|
581 | if demo_parameters is None: |
---|
582 | demo_parameters = dict((p[0],p[2]) for p in parameters) |
---|
583 | filename = abspath(kernel_module.__file__) |
---|
584 | kernel_id = splitext(basename(filename))[0] |
---|
585 | name = getattr(kernel_module, 'name', None) |
---|
586 | if name is None: |
---|
587 | name = " ".join(w.capitalize() for w in kernel_id.split('_')) |
---|
588 | info = dict( |
---|
589 | id = kernel_id, # string used to load the kernel |
---|
590 | filename=abspath(kernel_module.__file__), |
---|
591 | name=name, |
---|
592 | title=kernel_module.title, |
---|
593 | description=kernel_module.description, |
---|
594 | category=category, |
---|
595 | parameters=parameters, |
---|
596 | demo=demo_parameters, |
---|
597 | source=getattr(kernel_module, 'source', []), |
---|
598 | oldname=kernel_module.oldname, |
---|
599 | oldpars=kernel_module.oldpars, |
---|
600 | ) |
---|
601 | # Fill in attributes which default to None |
---|
602 | info.update((k, getattr(kernel_module, k, None)) |
---|
603 | for k in ('ER', 'VR', 'form_volume', 'Iq', 'Iqxy')) |
---|
604 | # Fill in the derived attributes |
---|
605 | info['limits'] = dict((p[0], p[3]) for p in info['parameters']) |
---|
606 | info['partype'] = categorize_parameters(info['parameters']) |
---|
607 | info['defaults'] = dict((p[0], p[2]) for p in info['parameters']) |
---|
608 | return info |
---|
609 | |
---|
610 | def make(kernel_module): |
---|
611 | """ |
---|
612 | Build an OpenCL/ctypes function from the definition in *kernel_module*. |
---|
613 | |
---|
614 | The module can be loaded with a normal python import statement if you |
---|
615 | know which module you need, or with __import__('sasmodels.model.'+name) |
---|
616 | if the name is in a string. |
---|
617 | """ |
---|
618 | info = make_info(kernel_module) |
---|
619 | # Assume if one part of the kernel is python then all parts are. |
---|
620 | source = make_model(info) if not callable(info['Iq']) else None |
---|
621 | return source, info |
---|
622 | |
---|
623 | section_marker = re.compile(r'\A(?P<first>[%s])(?P=first)*\Z' |
---|
624 | %re.escape(string.punctuation)) |
---|
625 | def _convert_section_titles_to_boldface(lines): |
---|
626 | prior = None |
---|
627 | for line in lines: |
---|
628 | if prior is None: |
---|
629 | prior = line |
---|
630 | elif section_marker.match(line): |
---|
631 | if len(line) >= len(prior): |
---|
632 | yield "".join( ("**",prior,"**") ) |
---|
633 | prior = None |
---|
634 | else: |
---|
635 | yield prior |
---|
636 | prior = line |
---|
637 | else: |
---|
638 | yield prior |
---|
639 | prior = line |
---|
640 | if prior is not None: |
---|
641 | yield prior |
---|
642 | |
---|
643 | def convert_section_titles_to_boldface(string): |
---|
644 | return "\n".join(_convert_section_titles_to_boldface(string.split('\n'))) |
---|
645 | |
---|
646 | def doc(kernel_module): |
---|
647 | """ |
---|
648 | Return the documentation for the model. |
---|
649 | """ |
---|
650 | Iq_units = "The returned value is scaled to units of |cm^-1| |sr^-1|, absolute scale." |
---|
651 | Sq_units = "The returned value is a dimensionless structure factor, $S(q)$." |
---|
652 | info = make_info(kernel_module) |
---|
653 | is_Sq = ("structure-factor" in info['category']) |
---|
654 | #docs = kernel_module.__doc__ |
---|
655 | docs = convert_section_titles_to_boldface(kernel_module.__doc__) |
---|
656 | subst = dict(id=info['id'].replace('_', '-'), |
---|
657 | name=info['name'], |
---|
658 | title=info['title'], |
---|
659 | parameters=make_partable(info['parameters']), |
---|
660 | returns=Sq_units if is_Sq else Iq_units, |
---|
661 | docs=docs) |
---|
662 | return DOC_HEADER % subst |
---|
663 | |
---|
664 | |
---|
665 | |
---|
666 | def demo_time(): |
---|
667 | from .models import cylinder |
---|
668 | import datetime |
---|
669 | tic = datetime.datetime.now() |
---|
670 | make(cylinder) |
---|
671 | toc = (datetime.datetime.now() - tic).total_seconds() |
---|
672 | print("time: %g"%toc) |
---|
673 | |
---|
674 | def main(): |
---|
675 | if len(sys.argv) <= 1: |
---|
676 | print("usage: python -m sasmodels.generate modelname") |
---|
677 | else: |
---|
678 | name = sys.argv[1] |
---|
679 | import sasmodels.models |
---|
680 | __import__('sasmodels.models.' + name) |
---|
681 | model = getattr(sasmodels.models, name) |
---|
682 | source, _ = make(model) |
---|
683 | print(source) |
---|
684 | |
---|
685 | if __name__ == "__main__": |
---|
686 | main() |
---|