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", "use_single", "use_long_double"] |
---|
200 | |
---|
201 | import sys |
---|
202 | from os.path import abspath, dirname, join as joinpath, exists, basename |
---|
203 | import re |
---|
204 | |
---|
205 | import numpy as np |
---|
206 | C_KERNEL_TEMPLATE_PATH = joinpath(dirname(__file__), 'kernel_template.c') |
---|
207 | |
---|
208 | F32 = np.dtype('float32') |
---|
209 | F64 = np.dtype('float64') |
---|
210 | try: # CRUFT: older numpy does not support float128 |
---|
211 | F128 = np.dtype('float128') |
---|
212 | except TypeError: |
---|
213 | F128 = None |
---|
214 | |
---|
215 | |
---|
216 | # Scale and background, which are parameters common to every form factor |
---|
217 | COMMON_PARAMETERS = [ |
---|
218 | ["scale", "", 1, [0, np.inf], "", "Source intensity"], |
---|
219 | ["background", "1/cm", 0, [0, np.inf], "", "Source background"], |
---|
220 | ] |
---|
221 | |
---|
222 | |
---|
223 | # Conversion from units defined in the parameter table for each model |
---|
224 | # to units displayed in the sphinx documentation. |
---|
225 | RST_UNITS = { |
---|
226 | "Ang": "|Ang|", |
---|
227 | "1/Ang": "|Ang^-1|", |
---|
228 | "1/Ang^2": "|Ang^-2|", |
---|
229 | "1e-6/Ang^2": "|1e-6Ang^-2|", |
---|
230 | "degrees": "degree", |
---|
231 | "1/cm": "|cm^-1|", |
---|
232 | "": "None", |
---|
233 | } |
---|
234 | |
---|
235 | # Headers for the parameters tables in th sphinx documentation |
---|
236 | PARTABLE_HEADERS = [ |
---|
237 | "Parameter", |
---|
238 | "Description", |
---|
239 | "Units", |
---|
240 | "Default value", |
---|
241 | ] |
---|
242 | |
---|
243 | # Minimum width for a default value (this is shorter than the column header |
---|
244 | # width, so will be ignored). |
---|
245 | PARTABLE_VALUE_WIDTH = 10 |
---|
246 | |
---|
247 | # Documentation header for the module, giving the model name, its short |
---|
248 | # description and its parameter table. The remainder of the doc comes |
---|
249 | # from the module docstring. |
---|
250 | DOC_HEADER = """.. _%(id)s: |
---|
251 | |
---|
252 | %(name)s |
---|
253 | ======================================================= |
---|
254 | |
---|
255 | %(title)s |
---|
256 | |
---|
257 | %(parameters)s |
---|
258 | |
---|
259 | The returned value is scaled to units of |cm^-1|. |
---|
260 | |
---|
261 | %(docs)s |
---|
262 | """ |
---|
263 | |
---|
264 | def format_units(par): |
---|
265 | return RST_UNITS.get(par, par) |
---|
266 | |
---|
267 | def make_partable(pars): |
---|
268 | """ |
---|
269 | Generate the parameter table to include in the sphinx documentation. |
---|
270 | """ |
---|
271 | column_widths = [ |
---|
272 | max(len(p[0]) for p in pars), |
---|
273 | max(len(p[-1]) for p in pars), |
---|
274 | max(len(format_units(p[1])) for p in pars), |
---|
275 | PARTABLE_VALUE_WIDTH, |
---|
276 | ] |
---|
277 | column_widths = [max(w, len(h)) |
---|
278 | for w, h in zip(column_widths, PARTABLE_HEADERS)] |
---|
279 | |
---|
280 | sep = " ".join("="*w for w in column_widths) |
---|
281 | lines = [ |
---|
282 | sep, |
---|
283 | " ".join("%-*s" % (w, h) for w, h in zip(column_widths, PARTABLE_HEADERS)), |
---|
284 | sep, |
---|
285 | ] |
---|
286 | for p in pars: |
---|
287 | lines.append(" ".join([ |
---|
288 | "%-*s" % (column_widths[0], p[0]), |
---|
289 | "%-*s" % (column_widths[1], p[-1]), |
---|
290 | "%-*s" % (column_widths[2], format_units(p[1])), |
---|
291 | "%*g" % (column_widths[3], p[2]), |
---|
292 | ])) |
---|
293 | lines.append(sep) |
---|
294 | return "\n".join(lines) |
---|
295 | |
---|
296 | def _search(search_path, filename): |
---|
297 | """ |
---|
298 | Find *filename* in *search_path*. |
---|
299 | |
---|
300 | Raises ValueError if file does not exist. |
---|
301 | """ |
---|
302 | for path in search_path: |
---|
303 | target = joinpath(path, filename) |
---|
304 | if exists(target): |
---|
305 | return target |
---|
306 | raise ValueError("%r not found in %s" % (filename, search_path)) |
---|
307 | |
---|
308 | def sources(info): |
---|
309 | """ |
---|
310 | Return a list of the sources file paths for the module. |
---|
311 | """ |
---|
312 | search_path = [dirname(info['filename']), |
---|
313 | abspath(joinpath(dirname(__file__), 'models'))] |
---|
314 | return [_search(search_path, f) for f in info['source']] |
---|
315 | |
---|
316 | def use_single(source): |
---|
317 | """ |
---|
318 | Convert code from double precision to single precision. |
---|
319 | """ |
---|
320 | # Convert double keyword to float. Accept an 'n' parameter for vector |
---|
321 | # values, where n is 2, 4, 8 or 16. Assume complex numbers are represented |
---|
322 | # as cdouble which is typedef'd to double2. |
---|
323 | source = re.sub(r'(^|[^a-zA-Z0-9_]c?)double(([248]|16)?($|[^a-zA-Z0-9_]))', |
---|
324 | r'\1float\2', source) |
---|
325 | # Convert floating point constants to single by adding 'f' to the end. |
---|
326 | # OS/X driver complains if you don't do this. |
---|
327 | source = re.sub(r'[^a-zA-Z_](\d*[.]\d+|\d+[.]\d*)([eE][+-]?\d+)?', |
---|
328 | r'\g<0>f', source) |
---|
329 | return source |
---|
330 | |
---|
331 | def use_long_double(source): |
---|
332 | """ |
---|
333 | Convert code from double precision to long double precision. |
---|
334 | """ |
---|
335 | # Convert double keyword to float. Accept an 'n' parameter for vector |
---|
336 | # values, where n is 2, 4, 8 or 16. Assume complex numbers are represented |
---|
337 | # as cdouble which is typedef'd to double2. |
---|
338 | source = re.sub(r'(^|[^a-zA-Z0-9_]c?)double(([248]|16)?($|[^a-zA-Z0-9_]))', |
---|
339 | r'\1long double\2', source) |
---|
340 | # Convert floating point constants to single by adding 'f' to the end. |
---|
341 | # OS/X driver complains if you don't do this. |
---|
342 | source = re.sub(r'[^a-zA-Z_](\d*[.]\d+|\d+[.]\d*)([eE][+-]?\d+)?', |
---|
343 | r'\g<0>L', source) |
---|
344 | return source |
---|
345 | |
---|
346 | |
---|
347 | def kernel_name(info, is_2D): |
---|
348 | """ |
---|
349 | Name of the exported kernel symbol. |
---|
350 | """ |
---|
351 | return info['name'] + "_" + ("Iqxy" if is_2D else "Iq") |
---|
352 | |
---|
353 | |
---|
354 | def categorize_parameters(pars): |
---|
355 | """ |
---|
356 | Build parameter categories out of the the parameter definitions. |
---|
357 | |
---|
358 | Returns a dictionary of categories. |
---|
359 | """ |
---|
360 | partype = { |
---|
361 | 'volume': [], 'orientation': [], 'magnetic': [], '': [], |
---|
362 | 'fixed-1d': [], 'fixed-2d': [], 'pd-1d': [], 'pd-2d': [], |
---|
363 | 'pd-rel': set(), |
---|
364 | } |
---|
365 | |
---|
366 | for p in pars: |
---|
367 | name, ptype = p[0], p[4] |
---|
368 | if ptype == 'volume': |
---|
369 | partype['pd-1d'].append(name) |
---|
370 | partype['pd-2d'].append(name) |
---|
371 | partype['pd-rel'].add(name) |
---|
372 | elif ptype == 'magnetic': |
---|
373 | partype['fixed-2d'].append(name) |
---|
374 | elif ptype == 'orientation': |
---|
375 | partype['pd-2d'].append(name) |
---|
376 | elif ptype == '': |
---|
377 | partype['fixed-1d'].append(name) |
---|
378 | partype['fixed-2d'].append(name) |
---|
379 | else: |
---|
380 | raise ValueError("unknown parameter type %r" % ptype) |
---|
381 | partype[ptype].append(name) |
---|
382 | |
---|
383 | return partype |
---|
384 | |
---|
385 | def indent(s, depth): |
---|
386 | """ |
---|
387 | Indent a string of text with *depth* additional spaces on each line. |
---|
388 | """ |
---|
389 | spaces = " "*depth |
---|
390 | sep = "\n" + spaces |
---|
391 | return spaces + sep.join(s.split("\n")) |
---|
392 | |
---|
393 | |
---|
394 | def build_polydispersity_loops(pd_pars): |
---|
395 | """ |
---|
396 | Build polydispersity loops |
---|
397 | |
---|
398 | Returns loop opening and loop closing |
---|
399 | """ |
---|
400 | LOOP_OPEN = """\ |
---|
401 | for (int %(name)s_i=0; %(name)s_i < N%(name)s; %(name)s_i++) { |
---|
402 | const double %(name)s = loops[2*(%(name)s_i%(offset)s)]; |
---|
403 | const double %(name)s_w = loops[2*(%(name)s_i%(offset)s)+1];\ |
---|
404 | """ |
---|
405 | depth = 4 |
---|
406 | offset = "" |
---|
407 | loop_head = [] |
---|
408 | loop_end = [] |
---|
409 | for name in pd_pars: |
---|
410 | subst = {'name': name, 'offset': offset} |
---|
411 | loop_head.append(indent(LOOP_OPEN % subst, depth)) |
---|
412 | loop_end.insert(0, (" "*depth) + "}") |
---|
413 | offset += '+N' + name |
---|
414 | depth += 2 |
---|
415 | return "\n".join(loop_head), "\n".join(loop_end) |
---|
416 | |
---|
417 | C_KERNEL_TEMPLATE = None |
---|
418 | def make_model(info): |
---|
419 | """ |
---|
420 | Generate the code for the kernel defined by info, using source files |
---|
421 | found in the given search path. |
---|
422 | """ |
---|
423 | # TODO: need something other than volume to indicate dispersion parameters |
---|
424 | # No volume normalization despite having a volume parameter. |
---|
425 | # Thickness is labelled a volume in order to trigger polydispersity. |
---|
426 | # May want a separate dispersion flag, or perhaps a separate category for |
---|
427 | # disperse, but not volume. Volume parameters also use relative values |
---|
428 | # for the distribution rather than the absolute values used by angular |
---|
429 | # dispersion. Need to be careful that necessary parameters are available |
---|
430 | # for computing volume even if we allow non-disperse volume parameters. |
---|
431 | |
---|
432 | # Load template |
---|
433 | global C_KERNEL_TEMPLATE |
---|
434 | if C_KERNEL_TEMPLATE is None: |
---|
435 | with open(C_KERNEL_TEMPLATE_PATH) as fid: |
---|
436 | C_KERNEL_TEMPLATE = fid.read() |
---|
437 | |
---|
438 | # Load additional sources |
---|
439 | source = [open(f).read() for f in sources(info)] |
---|
440 | |
---|
441 | # Prepare defines |
---|
442 | defines = [] |
---|
443 | partype = info['partype'] |
---|
444 | pd_1d = partype['pd-1d'] |
---|
445 | pd_2d = partype['pd-2d'] |
---|
446 | fixed_1d = partype['fixed-1d'] |
---|
447 | fixed_2d = partype['fixed-1d'] |
---|
448 | |
---|
449 | iq_parameters = [p[0] |
---|
450 | for p in info['parameters'][2:] # skip scale, background |
---|
451 | if p[0] in set(fixed_1d + pd_1d)] |
---|
452 | iqxy_parameters = [p[0] |
---|
453 | for p in info['parameters'][2:] # skip scale, background |
---|
454 | if p[0] in set(fixed_2d + pd_2d)] |
---|
455 | volume_parameters = [p[0] |
---|
456 | for p in info['parameters'] |
---|
457 | if p[4] == 'volume'] |
---|
458 | |
---|
459 | # Fill in defintions for volume parameters |
---|
460 | if volume_parameters: |
---|
461 | defines.append(('VOLUME_PARAMETERS', |
---|
462 | ','.join(volume_parameters))) |
---|
463 | defines.append(('VOLUME_WEIGHT_PRODUCT', |
---|
464 | '*'.join(p + '_w' for p in volume_parameters))) |
---|
465 | |
---|
466 | # Generate form_volume function from body only |
---|
467 | if info['form_volume'] is not None: |
---|
468 | if volume_parameters: |
---|
469 | vol_par_decl = ', '.join('double ' + p for p in volume_parameters) |
---|
470 | else: |
---|
471 | vol_par_decl = 'void' |
---|
472 | defines.append(('VOLUME_PARAMETER_DECLARATIONS', |
---|
473 | vol_par_decl)) |
---|
474 | fn = """\ |
---|
475 | double form_volume(VOLUME_PARAMETER_DECLARATIONS); |
---|
476 | double form_volume(VOLUME_PARAMETER_DECLARATIONS) { |
---|
477 | %(body)s |
---|
478 | } |
---|
479 | """ % {'body':info['form_volume']} |
---|
480 | source.append(fn) |
---|
481 | |
---|
482 | # Fill in definitions for Iq parameters |
---|
483 | defines.append(('IQ_KERNEL_NAME', info['name'] + '_Iq')) |
---|
484 | defines.append(('IQ_PARAMETERS', ', '.join(iq_parameters))) |
---|
485 | if fixed_1d: |
---|
486 | defines.append(('IQ_FIXED_PARAMETER_DECLARATIONS', |
---|
487 | ', \\\n '.join('const double %s' % p for p in fixed_1d))) |
---|
488 | if pd_1d: |
---|
489 | defines.append(('IQ_WEIGHT_PRODUCT', |
---|
490 | '*'.join(p + '_w' for p in pd_1d))) |
---|
491 | defines.append(('IQ_DISPERSION_LENGTH_DECLARATIONS', |
---|
492 | ', \\\n '.join('const int N%s' % p for p in pd_1d))) |
---|
493 | defines.append(('IQ_DISPERSION_LENGTH_SUM', |
---|
494 | '+'.join('N' + p for p in pd_1d))) |
---|
495 | open_loops, close_loops = build_polydispersity_loops(pd_1d) |
---|
496 | defines.append(('IQ_OPEN_LOOPS', |
---|
497 | open_loops.replace('\n', ' \\\n'))) |
---|
498 | defines.append(('IQ_CLOSE_LOOPS', |
---|
499 | close_loops.replace('\n', ' \\\n'))) |
---|
500 | if info['Iq'] is not None: |
---|
501 | defines.append(('IQ_PARAMETER_DECLARATIONS', |
---|
502 | ', '.join('double ' + p for p in iq_parameters))) |
---|
503 | fn = """\ |
---|
504 | double Iq(double q, IQ_PARAMETER_DECLARATIONS); |
---|
505 | double Iq(double q, IQ_PARAMETER_DECLARATIONS) { |
---|
506 | %(body)s |
---|
507 | } |
---|
508 | """ % {'body':info['Iq']} |
---|
509 | source.append(fn) |
---|
510 | |
---|
511 | # Fill in definitions for Iqxy parameters |
---|
512 | defines.append(('IQXY_KERNEL_NAME', info['name'] + '_Iqxy')) |
---|
513 | defines.append(('IQXY_PARAMETERS', ', '.join(iqxy_parameters))) |
---|
514 | if fixed_2d: |
---|
515 | defines.append(('IQXY_FIXED_PARAMETER_DECLARATIONS', |
---|
516 | ', \\\n '.join('const double %s' % p for p in fixed_2d))) |
---|
517 | if pd_2d: |
---|
518 | defines.append(('IQXY_WEIGHT_PRODUCT', |
---|
519 | '*'.join(p + '_w' for p in pd_2d))) |
---|
520 | defines.append(('IQXY_DISPERSION_LENGTH_DECLARATIONS', |
---|
521 | ', \\\n '.join('const int N%s' % p for p in pd_2d))) |
---|
522 | defines.append(('IQXY_DISPERSION_LENGTH_SUM', |
---|
523 | '+'.join('N' + p for p in pd_2d))) |
---|
524 | open_loops, close_loops = build_polydispersity_loops(pd_2d) |
---|
525 | defines.append(('IQXY_OPEN_LOOPS', |
---|
526 | open_loops.replace('\n', ' \\\n'))) |
---|
527 | defines.append(('IQXY_CLOSE_LOOPS', |
---|
528 | close_loops.replace('\n', ' \\\n'))) |
---|
529 | if info['Iqxy'] is not None: |
---|
530 | defines.append(('IQXY_PARAMETER_DECLARATIONS', |
---|
531 | ', '.join('double ' + p for p in iqxy_parameters))) |
---|
532 | fn = """\ |
---|
533 | double Iqxy(double qx, double qy, IQXY_PARAMETER_DECLARATIONS); |
---|
534 | double Iqxy(double qx, double qy, IQXY_PARAMETER_DECLARATIONS) { |
---|
535 | %(body)s |
---|
536 | } |
---|
537 | """ % {'body':info['Iqxy']} |
---|
538 | source.append(fn) |
---|
539 | |
---|
540 | # Need to know if we have a theta parameter for Iqxy; it is not there |
---|
541 | # for the magnetic sphere model, for example, which has a magnetic |
---|
542 | # orientation but no shape orientation. |
---|
543 | if 'theta' in pd_2d: |
---|
544 | defines.append(('IQXY_HAS_THETA', '1')) |
---|
545 | |
---|
546 | #for d in defines: print d |
---|
547 | DEFINES = '\n'.join('#define %s %s' % (k, v) for k, v in defines) |
---|
548 | SOURCES = '\n\n'.join(source) |
---|
549 | return C_KERNEL_TEMPLATE % { |
---|
550 | 'DEFINES':DEFINES, |
---|
551 | 'SOURCES':SOURCES, |
---|
552 | } |
---|
553 | |
---|
554 | def make_info(kernel_module): |
---|
555 | """ |
---|
556 | Interpret the model definition file, categorizing the parameters. |
---|
557 | """ |
---|
558 | #print kernelfile |
---|
559 | category = getattr(kernel_module, 'category', None) |
---|
560 | parameters = COMMON_PARAMETERS + kernel_module.parameters |
---|
561 | # Default the demo parameters to the starting values for the individual |
---|
562 | # parameters if an explicit demo parameter set has not been specified. |
---|
563 | demo_parameters = getattr(kernel_module, 'demo', None) |
---|
564 | if demo_parameters is None: |
---|
565 | demo_parameters = dict((p[0],p[2]) for p in parameters) |
---|
566 | filename = abspath(kernel_module.__file__) |
---|
567 | kernel_id = basename(filename)[:-3] |
---|
568 | name = getattr(kernel_module, 'name', None) |
---|
569 | if name is None: |
---|
570 | name = " ".join(w.capitalize() for w in kernel_id.split('_')) |
---|
571 | info = dict( |
---|
572 | id = kernel_id, # string used to load the kernel |
---|
573 | filename=abspath(kernel_module.__file__), |
---|
574 | name=name, |
---|
575 | title=kernel_module.title, |
---|
576 | description=kernel_module.description, |
---|
577 | category=category, |
---|
578 | parameters=parameters, |
---|
579 | demo=demo_parameters, |
---|
580 | source=getattr(kernel_module, 'source', []), |
---|
581 | oldname=kernel_module.oldname, |
---|
582 | oldpars=kernel_module.oldpars, |
---|
583 | ) |
---|
584 | # Fill in attributes which default to None |
---|
585 | info.update((k, getattr(kernel_module, k, None)) |
---|
586 | for k in ('ER', 'VR', 'form_volume', 'Iq', 'Iqxy')) |
---|
587 | # Fill in the derived attributes |
---|
588 | info['limits'] = dict((p[0], p[3]) for p in info['parameters']) |
---|
589 | info['partype'] = categorize_parameters(info['parameters']) |
---|
590 | info['defaults'] = dict((p[0], p[2]) for p in info['parameters']) |
---|
591 | return info |
---|
592 | |
---|
593 | def make(kernel_module): |
---|
594 | """ |
---|
595 | Build an OpenCL/ctypes function from the definition in *kernel_module*. |
---|
596 | |
---|
597 | The module can be loaded with a normal python import statement if you |
---|
598 | know which module you need, or with __import__('sasmodels.model.'+name) |
---|
599 | if the name is in a string. |
---|
600 | """ |
---|
601 | info = make_info(kernel_module) |
---|
602 | # Assume if one part of the kernel is python then all parts are. |
---|
603 | source = make_model(info) if not callable(info['Iq']) else None |
---|
604 | return source, info |
---|
605 | |
---|
606 | def doc(kernel_module): |
---|
607 | """ |
---|
608 | Return the documentation for the model. |
---|
609 | """ |
---|
610 | info = make_info(kernel_module) |
---|
611 | subst = dict(id=info['id'].replace('_', '-'), |
---|
612 | name=info['name'], |
---|
613 | title=info['title'], |
---|
614 | parameters=make_partable(info['parameters']), |
---|
615 | docs=kernel_module.__doc__) |
---|
616 | return DOC_HEADER % subst |
---|
617 | |
---|
618 | |
---|
619 | |
---|
620 | def demo_time(): |
---|
621 | from .models import cylinder |
---|
622 | import datetime |
---|
623 | tic = datetime.datetime.now() |
---|
624 | make(cylinder) |
---|
625 | toc = (datetime.datetime.now() - tic).total_seconds() |
---|
626 | print "time:", toc |
---|
627 | |
---|
628 | def main(): |
---|
629 | if len(sys.argv) <= 1: |
---|
630 | print "usage: python -m sasmodels.generate modelname" |
---|
631 | else: |
---|
632 | name = sys.argv[1] |
---|
633 | import sasmodels.models |
---|
634 | __import__('sasmodels.models.' + name) |
---|
635 | model = getattr(sasmodels.models, name) |
---|
636 | source, _ = make(model) |
---|
637 | print source |
---|
638 | |
---|
639 | if __name__ == "__main__": |
---|
640 | main() |
---|