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, or 1.0 if no volume normalization is required. |
---|
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 | #define INVALID(v) (expr) returns False if v.parameter is invalid |
---|
25 | for some parameter or other (e.g., v.bell_radius < v.radius). If |
---|
26 | necessary, the expression can call a function. |
---|
27 | |
---|
28 | These functions are defined in a kernel module .py script and an associated |
---|
29 | set of .c files. The model constructor will use them to create models with |
---|
30 | polydispersity across volume and orientation parameters, and provide |
---|
31 | scale and background parameters for each model. |
---|
32 | |
---|
33 | *Iq*, *Iqxy*, *Imagnetic* and *form_volume* should be stylized C-99 |
---|
34 | functions written for OpenCL. All functions need prototype declarations |
---|
35 | even if the are defined before they are used. OpenCL does not support |
---|
36 | *#include* preprocessor directives, so instead the list of includes needs |
---|
37 | to be given as part of the metadata in the kernel module definition. |
---|
38 | The included files should be listed using a path relative to the kernel |
---|
39 | module, or if using "lib/file.c" if it is one of the standard includes |
---|
40 | provided with the sasmodels source. The includes need to be listed in |
---|
41 | order so that functions are defined before they are used. |
---|
42 | |
---|
43 | Floating point values should be declared as *double*. For single precision |
---|
44 | calculations, *double* will be replaced by *float*. The single precision |
---|
45 | conversion will also tag floating point constants with "f" to make them |
---|
46 | single precision constants. When using integral values in floating point |
---|
47 | expressions, they should be expressed as floating point values by including |
---|
48 | a decimal point. This includes 0., 1. and 2. |
---|
49 | |
---|
50 | OpenCL has a *sincos* function which can improve performance when both |
---|
51 | the *sin* and *cos* values are needed for a particular argument. Since |
---|
52 | this function does not exist in C99, all use of *sincos* should be |
---|
53 | replaced by the macro *SINCOS(value, sn, cn)* where *sn* and *cn* are |
---|
54 | previously declared *double* variables. When compiled for systems without |
---|
55 | OpenCL, *SINCOS* will be replaced by *sin* and *cos* calls. If *value* is |
---|
56 | an expression, it will appear twice in this case; whether or not it will be |
---|
57 | evaluated twice depends on the quality of the compiler. |
---|
58 | |
---|
59 | If the input parameters are invalid, the scattering calculator should |
---|
60 | return a negative number. Particularly with polydispersity, there are |
---|
61 | some sets of shape parameters which lead to nonsensical forms, such |
---|
62 | as a capped cylinder where the cap radius is smaller than the |
---|
63 | cylinder radius. The polydispersity calculation will ignore these points, |
---|
64 | effectively chopping the parameter weight distributions at the boundary |
---|
65 | of the infeasible region. The resulting scattering will be set to |
---|
66 | background. This will work correctly even when polydispersity is off. |
---|
67 | |
---|
68 | *ER* and *VR* are python functions which operate on parameter vectors. |
---|
69 | The constructor code will generate the necessary vectors for computing |
---|
70 | them with the desired polydispersity. |
---|
71 | The kernel module must set variables defining the kernel meta data: |
---|
72 | |
---|
73 | *id* is an implicit variable formed from the filename. It will be |
---|
74 | a valid python identifier, and will be used as the reference into |
---|
75 | the html documentation, with '_' replaced by '-'. |
---|
76 | |
---|
77 | *name* is the model name as displayed to the user. If it is missing, |
---|
78 | it will be constructed from the id. |
---|
79 | |
---|
80 | *title* is a short description of the model, suitable for a tool tip, |
---|
81 | or a one line model summary in a table of models. |
---|
82 | |
---|
83 | *description* is an extended description of the model to be displayed |
---|
84 | while the model parameters are being edited. |
---|
85 | |
---|
86 | *parameters* is the list of parameters. Parameters in the kernel |
---|
87 | functions must appear in the same order as they appear in the |
---|
88 | parameters list. Two additional parameters, *scale* and *background* |
---|
89 | are added to the beginning of the parameter list. They will show up |
---|
90 | in the documentation as model parameters, but they are never sent to |
---|
91 | the kernel functions. Note that *effect_radius* and *volfraction* |
---|
92 | must occur first in structure factor calculations. |
---|
93 | |
---|
94 | *category* is the default category for the model. The category is |
---|
95 | two level structure, with the form "group:section", indicating where |
---|
96 | in the manual the model will be located. Models are alphabetical |
---|
97 | within their section. |
---|
98 | |
---|
99 | *source* is the list of C-99 source files that must be joined to |
---|
100 | create the OpenCL kernel functions. The files defining the functions |
---|
101 | need to be listed before the files which use the functions. |
---|
102 | |
---|
103 | *ER* is a python function defining the effective radius. If it is |
---|
104 | not present, the effective radius is 0. |
---|
105 | |
---|
106 | *VR* is a python function defining the volume ratio. If it is not |
---|
107 | present, the volume ratio is 1. |
---|
108 | |
---|
109 | *form_volume*, *Iq*, *Iqxy*, *Imagnetic* are strings containing the |
---|
110 | C source code for the body of the volume, Iq, and Iqxy functions |
---|
111 | respectively. These can also be defined in the last source file. |
---|
112 | |
---|
113 | *Iq* and *Iqxy* also be instead be python functions defining the |
---|
114 | kernel. If they are marked as *Iq.vectorized = True* then the |
---|
115 | kernel is passed the entire *q* vector at once, otherwise it is |
---|
116 | passed values one *q* at a time. The performance improvement of |
---|
117 | this step is significant. |
---|
118 | |
---|
119 | *demo* is a dictionary of parameter=value defining a set of |
---|
120 | parameters to use by default when *compare* is called. Any |
---|
121 | parameter not set in *demo* gets the initial value from the |
---|
122 | parameter list. *demo* is mostly needed to set the default |
---|
123 | polydispersity values for tests. |
---|
124 | |
---|
125 | A :class:`modelinfo.ModelInfo` structure is constructed from the kernel meta |
---|
126 | data and returned to the caller. |
---|
127 | |
---|
128 | The doc string at the start of the kernel module will be used to |
---|
129 | construct the model documentation web pages. Embedded figures should |
---|
130 | appear in the subdirectory "img" beside the model definition, and tagged |
---|
131 | with the kernel module name to avoid collision with other models. Some |
---|
132 | file systems are case-sensitive, so only use lower case characters for |
---|
133 | file names and extensions. |
---|
134 | |
---|
135 | Code follows the C99 standard with the following extensions and conditions:: |
---|
136 | |
---|
137 | M_PI_180 = pi/180 |
---|
138 | M_4PI_3 = 4pi/3 |
---|
139 | square(x) = x*x |
---|
140 | cube(x) = x*x*x |
---|
141 | sinc(x) = sin(x)/x, with sin(0)/0 -> 1 |
---|
142 | all double precision constants must include the decimal point |
---|
143 | all double declarations may be converted to half, float, or long double |
---|
144 | FLOAT_SIZE is the number of bytes in the converted variables |
---|
145 | |
---|
146 | :func:`load_kernel_module` loads the model definition file and |
---|
147 | :modelinfo:`make_model_info` parses it. :func:`make_source` |
---|
148 | converts C-based model definitions to C source code, including the |
---|
149 | polydispersity integral. :func:`model_sources` returns the list of |
---|
150 | source files the model depends on, and :func:`timestamp` returns |
---|
151 | the latest time stamp amongst the source files (so you can check if |
---|
152 | the model needs to be rebuilt). |
---|
153 | |
---|
154 | The function :func:`make_doc` extracts the doc string and adds the |
---|
155 | parameter table to the top. *make_figure* in *sasmodels/doc/genmodel* |
---|
156 | creates the default figure for the model. [These two sets of code |
---|
157 | should mignrate into docs.py so docs can be updated in one place]. |
---|
158 | """ |
---|
159 | from __future__ import print_function |
---|
160 | |
---|
161 | # TODO: determine which functions are useful outside of generate |
---|
162 | #__all__ = ["model_info", "make_doc", "make_source", "convert_type"] |
---|
163 | |
---|
164 | import sys |
---|
165 | from os.path import abspath, dirname, join as joinpath, exists, isdir, getmtime |
---|
166 | import re |
---|
167 | import string |
---|
168 | import warnings |
---|
169 | |
---|
170 | import numpy as np # type: ignore |
---|
171 | |
---|
172 | from .modelinfo import Parameter |
---|
173 | from .custom import load_custom_kernel_module |
---|
174 | |
---|
175 | try: |
---|
176 | from typing import Tuple, Sequence, Iterator, Dict |
---|
177 | from .modelinfo import ModelInfo |
---|
178 | except ImportError: |
---|
179 | pass |
---|
180 | |
---|
181 | def get_data_path(external_dir, target_file): |
---|
182 | path = abspath(dirname(__file__)) |
---|
183 | if exists(joinpath(path, target_file)): |
---|
184 | return path |
---|
185 | |
---|
186 | # check next to exe/zip file |
---|
187 | exepath = dirname(sys.executable) |
---|
188 | path = joinpath(exepath, external_dir) |
---|
189 | if exists(joinpath(path, target_file)): |
---|
190 | return path |
---|
191 | |
---|
192 | # check in py2app Contents/Resources |
---|
193 | path = joinpath(exepath, '..', 'Resources', external_dir) |
---|
194 | if exists(joinpath(path, target_file)): |
---|
195 | return abspath(path) |
---|
196 | |
---|
197 | raise RuntimeError('Could not find '+joinpath(external_dir, target_file)) |
---|
198 | |
---|
199 | EXTERNAL_DIR = 'sasmodels-data' |
---|
200 | DATA_PATH = get_data_path(EXTERNAL_DIR, 'kernel_template.c') |
---|
201 | MODEL_PATH = joinpath(DATA_PATH, 'models') |
---|
202 | |
---|
203 | F16 = np.dtype('float16') |
---|
204 | F32 = np.dtype('float32') |
---|
205 | F64 = np.dtype('float64') |
---|
206 | try: # CRUFT: older numpy does not support float128 |
---|
207 | F128 = np.dtype('float128') |
---|
208 | except TypeError: |
---|
209 | F128 = None |
---|
210 | |
---|
211 | # Conversion from units defined in the parameter table for each model |
---|
212 | # to units displayed in the sphinx documentation. |
---|
213 | RST_UNITS = { |
---|
214 | "Ang": "|Ang|", |
---|
215 | "1/Ang": "|Ang^-1|", |
---|
216 | "1/Ang^2": "|Ang^-2|", |
---|
217 | "1e-6/Ang^2": "|1e-6Ang^-2|", |
---|
218 | "degrees": "degree", |
---|
219 | "1/cm": "|cm^-1|", |
---|
220 | "Ang/cm": "|Ang*cm^-1|", |
---|
221 | "g/cm3": "|g/cm^3|", |
---|
222 | "mg/m2": "|mg/m^2|", |
---|
223 | "": "None", |
---|
224 | } |
---|
225 | |
---|
226 | # Headers for the parameters tables in th sphinx documentation |
---|
227 | PARTABLE_HEADERS = [ |
---|
228 | "Parameter", |
---|
229 | "Description", |
---|
230 | "Units", |
---|
231 | "Default value", |
---|
232 | ] |
---|
233 | |
---|
234 | # Minimum width for a default value (this is shorter than the column header |
---|
235 | # width, so will be ignored). |
---|
236 | PARTABLE_VALUE_WIDTH = 10 |
---|
237 | |
---|
238 | # Documentation header for the module, giving the model name, its short |
---|
239 | # description and its parameter table. The remainder of the doc comes |
---|
240 | # from the module docstring. |
---|
241 | DOC_HEADER = """.. _%(id)s: |
---|
242 | |
---|
243 | %(name)s |
---|
244 | ======================================================= |
---|
245 | |
---|
246 | %(title)s |
---|
247 | |
---|
248 | %(parameters)s |
---|
249 | |
---|
250 | %(returns)s |
---|
251 | |
---|
252 | %(docs)s |
---|
253 | """ |
---|
254 | |
---|
255 | |
---|
256 | def format_units(units): |
---|
257 | # type: (str) -> str |
---|
258 | """ |
---|
259 | Convert units into ReStructured Text format. |
---|
260 | """ |
---|
261 | return "string" if isinstance(units, list) else RST_UNITS.get(units, units) |
---|
262 | |
---|
263 | |
---|
264 | def make_partable(pars): |
---|
265 | # type: (List[Parameter]) -> str |
---|
266 | """ |
---|
267 | Generate the parameter table to include in the sphinx documentation. |
---|
268 | """ |
---|
269 | column_widths = [ |
---|
270 | max(len(p.name) for p in pars), |
---|
271 | max(len(p.description) for p in pars), |
---|
272 | max(len(format_units(p.units)) for p in pars), |
---|
273 | PARTABLE_VALUE_WIDTH, |
---|
274 | ] |
---|
275 | column_widths = [max(w, len(h)) |
---|
276 | for w, h in zip(column_widths, PARTABLE_HEADERS)] |
---|
277 | |
---|
278 | sep = " ".join("="*w for w in column_widths) |
---|
279 | lines = [ |
---|
280 | sep, |
---|
281 | " ".join("%-*s" % (w, h) |
---|
282 | for w, h in zip(column_widths, PARTABLE_HEADERS)), |
---|
283 | sep, |
---|
284 | ] |
---|
285 | for p in pars: |
---|
286 | lines.append(" ".join([ |
---|
287 | "%-*s" % (column_widths[0], p.name), |
---|
288 | "%-*s" % (column_widths[1], p.description), |
---|
289 | "%-*s" % (column_widths[2], format_units(p.units)), |
---|
290 | "%*g" % (column_widths[3], p.default), |
---|
291 | ])) |
---|
292 | lines.append(sep) |
---|
293 | return "\n".join(lines) |
---|
294 | |
---|
295 | |
---|
296 | def _search(search_path, filename): |
---|
297 | # type: (List[str], str) -> str |
---|
298 | """ |
---|
299 | Find *filename* in *search_path*. |
---|
300 | |
---|
301 | Raises ValueError if file does not exist. |
---|
302 | """ |
---|
303 | for path in search_path: |
---|
304 | target = joinpath(path, filename) |
---|
305 | if exists(target): |
---|
306 | return target |
---|
307 | raise ValueError("%r not found in %s" % (filename, search_path)) |
---|
308 | |
---|
309 | |
---|
310 | def model_sources(model_info): |
---|
311 | # type: (ModelInfo) -> List[str] |
---|
312 | """ |
---|
313 | Return a list of the sources file paths for the module. |
---|
314 | """ |
---|
315 | search_path = [dirname(model_info.filename), MODEL_PATH] |
---|
316 | return [_search(search_path, f) for f in model_info.source] |
---|
317 | |
---|
318 | |
---|
319 | def timestamp(model_info): |
---|
320 | # type: (ModelInfo) -> int |
---|
321 | """ |
---|
322 | Return a timestamp for the model corresponding to the most recently |
---|
323 | changed file or dependency. |
---|
324 | |
---|
325 | Note that this does not look at the time stamps for the OpenCL header |
---|
326 | information since that need not trigger a recompile of the DLL. |
---|
327 | """ |
---|
328 | source_files = (model_sources(model_info) |
---|
329 | + model_templates() |
---|
330 | + [model_info.filename]) |
---|
331 | newest = max(getmtime(f) for f in source_files) |
---|
332 | return newest |
---|
333 | |
---|
334 | |
---|
335 | def model_templates(): |
---|
336 | # type: () -> List[str] |
---|
337 | # TODO: fails DRY; templates appear two places. |
---|
338 | # should instead have model_info contain a list of paths |
---|
339 | # Note: kernel_iq.cl is not on this list because changing it need not |
---|
340 | # trigger a recompile of the dll. |
---|
341 | return [joinpath(DATA_PATH, filename) |
---|
342 | for filename in ('kernel_header.c', 'kernel_iq.c')] |
---|
343 | |
---|
344 | |
---|
345 | def convert_type(source, dtype): |
---|
346 | # type: (str, np.dtype) -> str |
---|
347 | """ |
---|
348 | Convert code from double precision to the desired type. |
---|
349 | |
---|
350 | Floating point constants are tagged with 'f' for single precision or 'L' |
---|
351 | for long double precision. |
---|
352 | """ |
---|
353 | if dtype == F16: |
---|
354 | fbytes = 2 |
---|
355 | source = _convert_type(source, "half", "f") |
---|
356 | elif dtype == F32: |
---|
357 | fbytes = 4 |
---|
358 | source = _convert_type(source, "float", "f") |
---|
359 | elif dtype == F64: |
---|
360 | fbytes = 8 |
---|
361 | # no need to convert if it is already double |
---|
362 | elif dtype == F128: |
---|
363 | fbytes = 16 |
---|
364 | source = _convert_type(source, "long double", "L") |
---|
365 | else: |
---|
366 | raise ValueError("Unexpected dtype in source conversion: %s" % dtype) |
---|
367 | return ("#define FLOAT_SIZE %d\n" % fbytes)+source |
---|
368 | |
---|
369 | |
---|
370 | def _convert_type(source, type_name, constant_flag): |
---|
371 | # type: (str, str, str) -> str |
---|
372 | """ |
---|
373 | Replace 'double' with *type_name* in *source*, tagging floating point |
---|
374 | constants with *constant_flag*. |
---|
375 | """ |
---|
376 | # Convert double keyword to float/long double/half. |
---|
377 | # Accept an 'n' # parameter for vector # values, where n is 2, 4, 8 or 16. |
---|
378 | # Assume complex numbers are represented as cdouble which is typedef'd |
---|
379 | # to double2. |
---|
380 | source = re.sub(r'(^|[^a-zA-Z0-9_]c?)double(([248]|16)?($|[^a-zA-Z0-9_]))', |
---|
381 | r'\1%s\2'%type_name, source) |
---|
382 | # Convert floating point constants to single by adding 'f' to the end, |
---|
383 | # or long double with an 'L' suffix. OS/X complains if you don't do this. |
---|
384 | source = re.sub(r'[^a-zA-Z_](\d*[.]\d+|\d+[.]\d*)([eE][+-]?\d+)?', |
---|
385 | r'\g<0>%s'%constant_flag, source) |
---|
386 | return source |
---|
387 | |
---|
388 | |
---|
389 | def kernel_name(model_info, is_2d): |
---|
390 | # type: (ModelInfo, bool) -> str |
---|
391 | """ |
---|
392 | Name of the exported kernel symbol. |
---|
393 | """ |
---|
394 | return model_info.name + "_" + ("Iqxy" if is_2d else "Iq") |
---|
395 | |
---|
396 | |
---|
397 | def indent(s, depth): |
---|
398 | # type: (str, int) -> str |
---|
399 | """ |
---|
400 | Indent a string of text with *depth* additional spaces on each line. |
---|
401 | """ |
---|
402 | spaces = " "*depth |
---|
403 | sep = "\n" + spaces |
---|
404 | return spaces + sep.join(s.split("\n")) |
---|
405 | |
---|
406 | |
---|
407 | _template_cache = {} # type: Dict[str, Tuple[int, str, str]] |
---|
408 | def load_template(filename): |
---|
409 | # type: (str) -> str |
---|
410 | path = joinpath(DATA_PATH, filename) |
---|
411 | mtime = getmtime(path) |
---|
412 | if filename not in _template_cache or mtime > _template_cache[filename][0]: |
---|
413 | with open(path) as fid: |
---|
414 | _template_cache[filename] = (mtime, fid.read(), path) |
---|
415 | return _template_cache[filename][1], path |
---|
416 | |
---|
417 | |
---|
418 | _FN_TEMPLATE = """\ |
---|
419 | double %(name)s(%(pars)s); |
---|
420 | double %(name)s(%(pars)s) { |
---|
421 | #line %(line)d "%(filename)s" |
---|
422 | %(body)s |
---|
423 | } |
---|
424 | |
---|
425 | """ |
---|
426 | def _gen_fn(name, pars, body, filename, line): |
---|
427 | # type: (str, List[Parameter], str, str, int) -> str |
---|
428 | """ |
---|
429 | Generate a function given pars and body. |
---|
430 | |
---|
431 | Returns the following string:: |
---|
432 | |
---|
433 | double fn(double a, double b, ...); |
---|
434 | double fn(double a, double b, ...) { |
---|
435 | .... |
---|
436 | } |
---|
437 | """ |
---|
438 | par_decl = ', '.join(p.as_function_argument() for p in pars) if pars else 'void' |
---|
439 | return _FN_TEMPLATE % { |
---|
440 | 'name': name, 'pars': par_decl, 'body': body, |
---|
441 | 'filename': filename.replace('\\', '\\\\'), 'line': line, |
---|
442 | } |
---|
443 | |
---|
444 | |
---|
445 | def _call_pars(prefix, pars): |
---|
446 | # type: (str, List[Parameter]) -> List[str] |
---|
447 | """ |
---|
448 | Return a list of *prefix.parameter* from parameter items. |
---|
449 | """ |
---|
450 | return [p.as_call_reference(prefix) for p in pars] |
---|
451 | |
---|
452 | |
---|
453 | # type in IQXY pattern could be single, float, double, long double, ... |
---|
454 | _IQXY_PATTERN = re.compile("^((inline|static) )? *([a-z ]+ )? *Iqxy *([(]|$)", |
---|
455 | flags=re.MULTILINE) |
---|
456 | def _have_Iqxy(sources): |
---|
457 | # type: (List[str]) -> bool |
---|
458 | """ |
---|
459 | Return true if any file defines Iqxy. |
---|
460 | |
---|
461 | Note this is not a C parser, and so can be easily confused by |
---|
462 | non-standard syntax. Also, it will incorrectly identify the following |
---|
463 | as having Iqxy:: |
---|
464 | |
---|
465 | /* |
---|
466 | double Iqxy(qx, qy, ...) { ... fill this in later ... } |
---|
467 | */ |
---|
468 | |
---|
469 | If you want to comment out an Iqxy function, use // on the front of the |
---|
470 | line instead. |
---|
471 | """ |
---|
472 | for path, code in sources: |
---|
473 | if _IQXY_PATTERN.search(code): |
---|
474 | return True |
---|
475 | else: |
---|
476 | return False |
---|
477 | |
---|
478 | |
---|
479 | def _add_source(source, code, path): |
---|
480 | """ |
---|
481 | Add a file to the list of source code chunks, tagged with path and line. |
---|
482 | """ |
---|
483 | path = path.replace('\\', '\\\\') |
---|
484 | source.append('#line 1 "%s"' % path) |
---|
485 | source.append(code) |
---|
486 | |
---|
487 | |
---|
488 | def make_source(model_info): |
---|
489 | # type: (ModelInfo) -> str |
---|
490 | """ |
---|
491 | Generate the OpenCL/ctypes kernel from the module info. |
---|
492 | |
---|
493 | Uses source files found in the given search path. Returns None if this |
---|
494 | is a pure python model, with no C source components. |
---|
495 | """ |
---|
496 | if callable(model_info.Iq): |
---|
497 | raise ValueError("can't compile python model") |
---|
498 | |
---|
499 | # TODO: need something other than volume to indicate dispersion parameters |
---|
500 | # No volume normalization despite having a volume parameter. |
---|
501 | # Thickness is labelled a volume in order to trigger polydispersity. |
---|
502 | # May want a separate dispersion flag, or perhaps a separate category for |
---|
503 | # disperse, but not volume. Volume parameters also use relative values |
---|
504 | # for the distribution rather than the absolute values used by angular |
---|
505 | # dispersion. Need to be careful that necessary parameters are available |
---|
506 | # for computing volume even if we allow non-disperse volume parameters. |
---|
507 | |
---|
508 | partable = model_info.parameters |
---|
509 | |
---|
510 | # Load templates and user code |
---|
511 | kernel_header = load_template('kernel_header.c') |
---|
512 | dll_code = load_template('kernel_iq.c') |
---|
513 | ocl_code = load_template('kernel_iq.cl') |
---|
514 | #ocl_code = load_template('kernel_iq_local.cl') |
---|
515 | user_code = [(f, open(f).read()) for f in model_sources(model_info)] |
---|
516 | |
---|
517 | # Build initial sources |
---|
518 | source = [] |
---|
519 | _add_source(source, *kernel_header) |
---|
520 | for path, code in user_code: |
---|
521 | _add_source(source, code, path) |
---|
522 | |
---|
523 | # Make parameters for q, qx, qy so that we can use them in declarations |
---|
524 | q, qx, qy = [Parameter(name=v) for v in ('q', 'qx', 'qy')] |
---|
525 | # Generate form_volume function, etc. from body only |
---|
526 | if isinstance(model_info.form_volume, str): |
---|
527 | pars = partable.form_volume_parameters |
---|
528 | source.append(_gen_fn('form_volume', pars, model_info.form_volume, |
---|
529 | model_info.filename, model_info._form_volume_line)) |
---|
530 | if isinstance(model_info.Iq, str): |
---|
531 | pars = [q] + partable.iq_parameters |
---|
532 | source.append(_gen_fn('Iq', pars, model_info.Iq, |
---|
533 | model_info.filename, model_info._Iq_line)) |
---|
534 | if isinstance(model_info.Iqxy, str): |
---|
535 | pars = [qx, qy] + partable.iqxy_parameters |
---|
536 | source.append(_gen_fn('Iqxy', pars, model_info.Iqxy, |
---|
537 | model_info.filename, model_info._Iqxy_line)) |
---|
538 | |
---|
539 | # Define the parameter table |
---|
540 | source.append("#define PARAMETER_TABLE \\") |
---|
541 | source.append("\\\n".join(p.as_definition() |
---|
542 | for p in partable.kernel_parameters)) |
---|
543 | |
---|
544 | # Define the function calls |
---|
545 | if partable.form_volume_parameters: |
---|
546 | refs = _call_pars("_v.", partable.form_volume_parameters) |
---|
547 | call_volume = "#define CALL_VOLUME(_v) form_volume(%s)"%(",".join(refs)) |
---|
548 | else: |
---|
549 | # Model doesn't have volume. We could make the kernel run a little |
---|
550 | # faster by not using/transferring the volume normalizations, but |
---|
551 | # the ifdef's reduce readability more than is worthwhile. |
---|
552 | call_volume = "#define CALL_VOLUME(v) 1.0" |
---|
553 | source.append(call_volume) |
---|
554 | |
---|
555 | refs = ["_q[_i]"] + _call_pars("_v.", partable.iq_parameters) |
---|
556 | call_iq = "#define CALL_IQ(_q,_i,_v) Iq(%s)" % (",".join(refs)) |
---|
557 | if _have_Iqxy(user_code): |
---|
558 | # Call 2D model |
---|
559 | refs = ["q[2*_i]", "q[2*_i+1]"] + _call_pars("_v.", partable.iqxy_parameters) |
---|
560 | call_iqxy = "#define CALL_IQ(_q,_i,_v) Iqxy(%s)" % (",".join(refs)) |
---|
561 | else: |
---|
562 | # Call 1D model with sqrt(qx^2 + qy^2) |
---|
563 | warnings.warn("Creating Iqxy = Iq(sqrt(qx^2 + qy^2))") |
---|
564 | # still defined:: refs = ["q[i]"] + _call_pars("v", iq_parameters) |
---|
565 | pars_sqrt = ["sqrt(_q[2*_i]*_q[2*_i]+_q[2*_i+1]*_q[2*_i+1])"] + refs[1:] |
---|
566 | call_iqxy = "#define CALL_IQ(_q,_i,_v) Iq(%s)" % (",".join(pars_sqrt)) |
---|
567 | |
---|
568 | # Fill in definitions for numbers of parameters |
---|
569 | source.append("#define MAX_PD %s"%partable.max_pd) |
---|
570 | source.append("#define NPARS %d"%partable.npars) |
---|
571 | |
---|
572 | # TODO: allow mixed python/opencl kernels? |
---|
573 | |
---|
574 | source.append("#if defined(USE_OPENCL)") |
---|
575 | source.extend(_add_kernels(ocl_code[0], call_iq, call_iqxy, model_info.name)) |
---|
576 | source.append("#else /* !USE_OPENCL */") |
---|
577 | source.extend(_add_kernels(dll_code[0], call_iq, call_iqxy, model_info.name)) |
---|
578 | source.append("#endif /* !USE_OPENCL */") |
---|
579 | return '\n'.join(source) |
---|
580 | |
---|
581 | |
---|
582 | def _add_kernels(kernel_code, call_iq, call_iqxy, name): |
---|
583 | # type: (str, str, str, str) -> List[str] |
---|
584 | source = [ |
---|
585 | # define the Iq kernel |
---|
586 | "#define KERNEL_NAME %s_Iq"%name, |
---|
587 | call_iq, |
---|
588 | kernel_code, |
---|
589 | "#undef CALL_IQ", |
---|
590 | "#undef KERNEL_NAME", |
---|
591 | |
---|
592 | # define the Iqxy kernel from the same source with different #defines |
---|
593 | "#define KERNEL_NAME %s_Iqxy"%name, |
---|
594 | call_iqxy, |
---|
595 | kernel_code, |
---|
596 | "#undef CALL_IQ", |
---|
597 | "#undef KERNEL_NAME", |
---|
598 | ] |
---|
599 | return source |
---|
600 | |
---|
601 | |
---|
602 | def load_kernel_module(model_name): |
---|
603 | # type: (str) -> module |
---|
604 | """ |
---|
605 | Return the kernel module named in *model_name*. |
---|
606 | |
---|
607 | If the name ends in *.py* then load it as a custom model using |
---|
608 | :func:`sasmodels.custom.load_custom_kernel_module`, otherwise |
---|
609 | load it from :mod:`sasmodels.models`. |
---|
610 | """ |
---|
611 | if model_name.endswith('.py'): |
---|
612 | kernel_module = load_custom_kernel_module(model_name) |
---|
613 | else: |
---|
614 | from sasmodels import models |
---|
615 | __import__('sasmodels.models.'+model_name) |
---|
616 | kernel_module = getattr(models, model_name, None) |
---|
617 | return kernel_module |
---|
618 | |
---|
619 | |
---|
620 | section_marker = re.compile(r'\A(?P<first>[%s])(?P=first)*\Z' |
---|
621 | % re.escape(string.punctuation)) |
---|
622 | def _convert_section_titles_to_boldface(lines): |
---|
623 | # type: (Sequence[str]) -> Iterator[str] |
---|
624 | """ |
---|
625 | Do the actual work of identifying and converting section headings. |
---|
626 | """ |
---|
627 | prior = None |
---|
628 | for line in lines: |
---|
629 | if prior is None: |
---|
630 | prior = line |
---|
631 | elif section_marker.match(line): |
---|
632 | if len(line) >= len(prior): |
---|
633 | yield "".join(("**", prior, "**")) |
---|
634 | prior = None |
---|
635 | else: |
---|
636 | yield prior |
---|
637 | prior = line |
---|
638 | else: |
---|
639 | yield prior |
---|
640 | prior = line |
---|
641 | if prior is not None: |
---|
642 | yield prior |
---|
643 | |
---|
644 | |
---|
645 | def convert_section_titles_to_boldface(s): |
---|
646 | # type: (str) -> str |
---|
647 | """ |
---|
648 | Use explicit bold-face rather than section headings so that the table of |
---|
649 | contents is not polluted with section names from the model documentation. |
---|
650 | |
---|
651 | Sections are identified as the title line followed by a line of punctuation |
---|
652 | at least as long as the title line. |
---|
653 | """ |
---|
654 | return "\n".join(_convert_section_titles_to_boldface(s.split('\n'))) |
---|
655 | |
---|
656 | |
---|
657 | def make_doc(model_info): |
---|
658 | # type: (ModelInfo) -> str |
---|
659 | """ |
---|
660 | Return the documentation for the model. |
---|
661 | """ |
---|
662 | Iq_units = "The returned value is scaled to units of |cm^-1| |sr^-1|, absolute scale." |
---|
663 | Sq_units = "The returned value is a dimensionless structure factor, $S(q)$." |
---|
664 | docs = convert_section_titles_to_boldface(model_info.docs) |
---|
665 | pars = make_partable(model_info.parameters.COMMON |
---|
666 | + model_info.parameters.kernel_parameters) |
---|
667 | subst = dict(id=model_info.id.replace('_', '-'), |
---|
668 | name=model_info.name, |
---|
669 | title=model_info.title, |
---|
670 | parameters=pars, |
---|
671 | returns=Sq_units if model_info.structure_factor else Iq_units, |
---|
672 | docs=docs) |
---|
673 | return DOC_HEADER % subst |
---|
674 | |
---|
675 | |
---|
676 | def make_html(model_info): |
---|
677 | """ |
---|
678 | Convert model docs directly to html. |
---|
679 | """ |
---|
680 | from . import rst2html |
---|
681 | return rst2html.convert(make_doc(model_info), title=model_info['name']) |
---|
682 | |
---|
683 | def demo_time(): |
---|
684 | # type: () -> None |
---|
685 | """ |
---|
686 | Show how long it takes to process a model. |
---|
687 | """ |
---|
688 | import datetime |
---|
689 | from .modelinfo import make_model_info |
---|
690 | from .models import cylinder |
---|
691 | |
---|
692 | tic = datetime.datetime.now() |
---|
693 | make_source(make_model_info(cylinder)) |
---|
694 | toc = (datetime.datetime.now() - tic).total_seconds() |
---|
695 | print("time: %g"%toc) |
---|
696 | |
---|
697 | |
---|
698 | def main(): |
---|
699 | # type: () -> None |
---|
700 | """ |
---|
701 | Program which prints the source produced by the model. |
---|
702 | """ |
---|
703 | import sys |
---|
704 | from .modelinfo import make_model_info |
---|
705 | |
---|
706 | if len(sys.argv) <= 1: |
---|
707 | print("usage: python -m sasmodels.generate modelname") |
---|
708 | else: |
---|
709 | name = sys.argv[1] |
---|
710 | kernel_module = load_kernel_module(name) |
---|
711 | model_info = make_model_info(kernel_module) |
---|
712 | source = make_source(model_info) |
---|
713 | print(source) |
---|
714 | |
---|
715 | |
---|
716 | if __name__ == "__main__": |
---|
717 | main() |
---|