[5ceb7d0] | 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 |
---|
[e6408d0] | 17 | dimension, or 1.0 if no volume normalization is required. |
---|
[5ceb7d0] | 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 | |
---|
[d5ac45f] | 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 | |
---|
[5ceb7d0] | 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 |
---|
[17bbadd] | 91 | the kernel functions. Note that *effect_radius* and *volfraction* |
---|
| 92 | must occur first in structure factor calculations. |
---|
[5ceb7d0] | 93 | |
---|
[17bbadd] | 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. |
---|
[5ceb7d0] | 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 | |
---|
[a5b8477] | 125 | A :class:`modelinfo.ModelInfo` structure is constructed from the kernel meta |
---|
| 126 | data and returned to the caller. |
---|
[5ceb7d0] | 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 |
---|
[a5b8477] | 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]. |
---|
[5ceb7d0] | 158 | """ |
---|
| 159 | from __future__ import print_function |
---|
| 160 | |
---|
[7891a2a] | 161 | # TODO: determine which functions are useful outside of generate |
---|
[69aa451] | 162 | #__all__ = ["model_info", "make_doc", "make_source", "convert_type"] |
---|
[5ceb7d0] | 163 | |
---|
| 164 | import sys |
---|
[7891a2a] | 165 | from os.path import abspath, dirname, join as joinpath, exists, isdir, getmtime |
---|
[5ceb7d0] | 166 | import re |
---|
| 167 | import string |
---|
[78d3341] | 168 | import warnings |
---|
[5ceb7d0] | 169 | |
---|
[7ae2b7f] | 170 | import numpy as np # type: ignore |
---|
[5ceb7d0] | 171 | |
---|
[6d6508e] | 172 | from .modelinfo import Parameter |
---|
[68e7f9d] | 173 | from .custom import load_custom_kernel_module |
---|
[fcd7bbd] | 174 | |
---|
[f619de7] | 175 | try: |
---|
[f2f67a6] | 176 | from typing import Tuple, Sequence, Iterator, Dict |
---|
[f619de7] | 177 | from .modelinfo import ModelInfo |
---|
| 178 | except ImportError: |
---|
| 179 | pass |
---|
| 180 | |
---|
[c2c51a2] | 181 | SIBLING_DIR = 'sasmodels-data' |
---|
| 182 | PACKAGE_PATH = abspath(dirname(__file__)) |
---|
| 183 | SIBLING_PATH = abspath(joinpath(PACKAGE_PATH, '..', 'sasmodels-data')) |
---|
| 184 | DATA_PATH = SIBLING_PATH if isdir(SIBLING_PATH) else PACKAGE_PATH |
---|
| 185 | MODEL_PATH = joinpath(DATA_PATH, 'models') |
---|
[5ceb7d0] | 186 | |
---|
| 187 | F16 = np.dtype('float16') |
---|
| 188 | F32 = np.dtype('float32') |
---|
| 189 | F64 = np.dtype('float64') |
---|
| 190 | try: # CRUFT: older numpy does not support float128 |
---|
| 191 | F128 = np.dtype('float128') |
---|
| 192 | except TypeError: |
---|
| 193 | F128 = None |
---|
| 194 | |
---|
| 195 | # Conversion from units defined in the parameter table for each model |
---|
| 196 | # to units displayed in the sphinx documentation. |
---|
| 197 | RST_UNITS = { |
---|
| 198 | "Ang": "|Ang|", |
---|
| 199 | "1/Ang": "|Ang^-1|", |
---|
| 200 | "1/Ang^2": "|Ang^-2|", |
---|
| 201 | "1e-6/Ang^2": "|1e-6Ang^-2|", |
---|
| 202 | "degrees": "degree", |
---|
| 203 | "1/cm": "|cm^-1|", |
---|
| 204 | "Ang/cm": "|Ang*cm^-1|", |
---|
| 205 | "g/cm3": "|g/cm^3|", |
---|
| 206 | "mg/m2": "|mg/m^2|", |
---|
| 207 | "": "None", |
---|
| 208 | } |
---|
| 209 | |
---|
| 210 | # Headers for the parameters tables in th sphinx documentation |
---|
| 211 | PARTABLE_HEADERS = [ |
---|
| 212 | "Parameter", |
---|
| 213 | "Description", |
---|
| 214 | "Units", |
---|
| 215 | "Default value", |
---|
| 216 | ] |
---|
| 217 | |
---|
| 218 | # Minimum width for a default value (this is shorter than the column header |
---|
| 219 | # width, so will be ignored). |
---|
| 220 | PARTABLE_VALUE_WIDTH = 10 |
---|
| 221 | |
---|
| 222 | # Documentation header for the module, giving the model name, its short |
---|
| 223 | # description and its parameter table. The remainder of the doc comes |
---|
| 224 | # from the module docstring. |
---|
| 225 | DOC_HEADER = """.. _%(id)s: |
---|
| 226 | |
---|
| 227 | %(name)s |
---|
| 228 | ======================================================= |
---|
| 229 | |
---|
| 230 | %(title)s |
---|
| 231 | |
---|
| 232 | %(parameters)s |
---|
| 233 | |
---|
| 234 | %(returns)s |
---|
| 235 | |
---|
| 236 | %(docs)s |
---|
| 237 | """ |
---|
| 238 | |
---|
[7891a2a] | 239 | |
---|
[5ceb7d0] | 240 | def format_units(units): |
---|
[f619de7] | 241 | # type: (str) -> str |
---|
[5ceb7d0] | 242 | """ |
---|
| 243 | Convert units into ReStructured Text format. |
---|
| 244 | """ |
---|
| 245 | return "string" if isinstance(units, list) else RST_UNITS.get(units, units) |
---|
| 246 | |
---|
[7891a2a] | 247 | |
---|
[5ceb7d0] | 248 | def make_partable(pars): |
---|
[f619de7] | 249 | # type: (List[Parameter]) -> str |
---|
[5ceb7d0] | 250 | """ |
---|
| 251 | Generate the parameter table to include in the sphinx documentation. |
---|
| 252 | """ |
---|
| 253 | column_widths = [ |
---|
[fcd7bbd] | 254 | max(len(p.name) for p in pars), |
---|
| 255 | max(len(p.description) for p in pars), |
---|
| 256 | max(len(format_units(p.units)) for p in pars), |
---|
[5ceb7d0] | 257 | PARTABLE_VALUE_WIDTH, |
---|
| 258 | ] |
---|
| 259 | column_widths = [max(w, len(h)) |
---|
| 260 | for w, h in zip(column_widths, PARTABLE_HEADERS)] |
---|
| 261 | |
---|
| 262 | sep = " ".join("="*w for w in column_widths) |
---|
| 263 | lines = [ |
---|
| 264 | sep, |
---|
| 265 | " ".join("%-*s" % (w, h) |
---|
| 266 | for w, h in zip(column_widths, PARTABLE_HEADERS)), |
---|
| 267 | sep, |
---|
| 268 | ] |
---|
| 269 | for p in pars: |
---|
| 270 | lines.append(" ".join([ |
---|
[fcd7bbd] | 271 | "%-*s" % (column_widths[0], p.name), |
---|
| 272 | "%-*s" % (column_widths[1], p.description), |
---|
| 273 | "%-*s" % (column_widths[2], format_units(p.units)), |
---|
| 274 | "%*g" % (column_widths[3], p.default), |
---|
[5ceb7d0] | 275 | ])) |
---|
| 276 | lines.append(sep) |
---|
| 277 | return "\n".join(lines) |
---|
| 278 | |
---|
[7891a2a] | 279 | |
---|
[5ceb7d0] | 280 | def _search(search_path, filename): |
---|
[f619de7] | 281 | # type: (List[str], str) -> str |
---|
[5ceb7d0] | 282 | """ |
---|
| 283 | Find *filename* in *search_path*. |
---|
| 284 | |
---|
| 285 | Raises ValueError if file does not exist. |
---|
| 286 | """ |
---|
| 287 | for path in search_path: |
---|
| 288 | target = joinpath(path, filename) |
---|
| 289 | if exists(target): |
---|
| 290 | return target |
---|
| 291 | raise ValueError("%r not found in %s" % (filename, search_path)) |
---|
| 292 | |
---|
[d5ac45f] | 293 | |
---|
[17bbadd] | 294 | def model_sources(model_info): |
---|
[f619de7] | 295 | # type: (ModelInfo) -> List[str] |
---|
[5ceb7d0] | 296 | """ |
---|
| 297 | Return a list of the sources file paths for the module. |
---|
| 298 | """ |
---|
[7891a2a] | 299 | search_path = [dirname(model_info.filename), MODEL_PATH] |
---|
[6d6508e] | 300 | return [_search(search_path, f) for f in model_info.source] |
---|
[5ceb7d0] | 301 | |
---|
| 302 | |
---|
[69aa451] | 303 | def timestamp(model_info): |
---|
[f619de7] | 304 | # type: (ModelInfo) -> int |
---|
[69aa451] | 305 | """ |
---|
| 306 | Return a timestamp for the model corresponding to the most recently |
---|
| 307 | changed file or dependency. |
---|
[f2f67a6] | 308 | |
---|
| 309 | Note that this does not look at the time stamps for the OpenCL header |
---|
| 310 | information since that need not trigger a recompile of the DLL. |
---|
[69aa451] | 311 | """ |
---|
| 312 | source_files = (model_sources(model_info) |
---|
| 313 | + model_templates() |
---|
[6d6508e] | 314 | + [model_info.filename]) |
---|
[69aa451] | 315 | newest = max(getmtime(f) for f in source_files) |
---|
| 316 | return newest |
---|
| 317 | |
---|
[7891a2a] | 318 | |
---|
[f2f67a6] | 319 | def model_templates(): |
---|
| 320 | # type: () -> List[str] |
---|
| 321 | # TODO: fails DRY; templates appear two places. |
---|
| 322 | # should instead have model_info contain a list of paths |
---|
| 323 | # Note: kernel_iq.cl is not on this list because changing it need not |
---|
| 324 | # trigger a recompile of the dll. |
---|
[7891a2a] | 325 | return [joinpath(DATA_PATH, filename) |
---|
[f2f67a6] | 326 | for filename in ('kernel_header.c', 'kernel_iq.c')] |
---|
| 327 | |
---|
[5ceb7d0] | 328 | |
---|
| 329 | def convert_type(source, dtype): |
---|
[f619de7] | 330 | # type: (str, np.dtype) -> str |
---|
[5ceb7d0] | 331 | """ |
---|
| 332 | Convert code from double precision to the desired type. |
---|
| 333 | |
---|
| 334 | Floating point constants are tagged with 'f' for single precision or 'L' |
---|
| 335 | for long double precision. |
---|
| 336 | """ |
---|
| 337 | if dtype == F16: |
---|
| 338 | fbytes = 2 |
---|
[1e2a1ba] | 339 | source = _convert_type(source, "half", "f") |
---|
[5ceb7d0] | 340 | elif dtype == F32: |
---|
| 341 | fbytes = 4 |
---|
| 342 | source = _convert_type(source, "float", "f") |
---|
| 343 | elif dtype == F64: |
---|
| 344 | fbytes = 8 |
---|
[d5ac45f] | 345 | # no need to convert if it is already double |
---|
[5ceb7d0] | 346 | elif dtype == F128: |
---|
| 347 | fbytes = 16 |
---|
| 348 | source = _convert_type(source, "long double", "L") |
---|
| 349 | else: |
---|
[7891a2a] | 350 | raise ValueError("Unexpected dtype in source conversion: %s" % dtype) |
---|
| 351 | return ("#define FLOAT_SIZE %d\n" % fbytes)+source |
---|
[5ceb7d0] | 352 | |
---|
| 353 | |
---|
| 354 | def _convert_type(source, type_name, constant_flag): |
---|
[f619de7] | 355 | # type: (str, str, str) -> str |
---|
[5ceb7d0] | 356 | """ |
---|
| 357 | Replace 'double' with *type_name* in *source*, tagging floating point |
---|
| 358 | constants with *constant_flag*. |
---|
| 359 | """ |
---|
| 360 | # Convert double keyword to float/long double/half. |
---|
| 361 | # Accept an 'n' # parameter for vector # values, where n is 2, 4, 8 or 16. |
---|
| 362 | # Assume complex numbers are represented as cdouble which is typedef'd |
---|
| 363 | # to double2. |
---|
| 364 | source = re.sub(r'(^|[^a-zA-Z0-9_]c?)double(([248]|16)?($|[^a-zA-Z0-9_]))', |
---|
| 365 | r'\1%s\2'%type_name, source) |
---|
| 366 | # Convert floating point constants to single by adding 'f' to the end, |
---|
| 367 | # or long double with an 'L' suffix. OS/X complains if you don't do this. |
---|
| 368 | source = re.sub(r'[^a-zA-Z_](\d*[.]\d+|\d+[.]\d*)([eE][+-]?\d+)?', |
---|
| 369 | r'\g<0>%s'%constant_flag, source) |
---|
| 370 | return source |
---|
| 371 | |
---|
| 372 | |
---|
[17bbadd] | 373 | def kernel_name(model_info, is_2d): |
---|
[f619de7] | 374 | # type: (ModelInfo, bool) -> str |
---|
[5ceb7d0] | 375 | """ |
---|
| 376 | Name of the exported kernel symbol. |
---|
| 377 | """ |
---|
[6d6508e] | 378 | return model_info.name + "_" + ("Iqxy" if is_2d else "Iq") |
---|
[5ceb7d0] | 379 | |
---|
| 380 | |
---|
| 381 | def indent(s, depth): |
---|
[f619de7] | 382 | # type: (str, int) -> str |
---|
[5ceb7d0] | 383 | """ |
---|
| 384 | Indent a string of text with *depth* additional spaces on each line. |
---|
| 385 | """ |
---|
| 386 | spaces = " "*depth |
---|
| 387 | sep = "\n" + spaces |
---|
| 388 | return spaces + sep.join(s.split("\n")) |
---|
| 389 | |
---|
| 390 | |
---|
[f619de7] | 391 | _template_cache = {} # type: Dict[str, Tuple[int, str, str]] |
---|
[d5ac45f] | 392 | def load_template(filename): |
---|
[f619de7] | 393 | # type: (str) -> str |
---|
[7891a2a] | 394 | path = joinpath(DATA_PATH, filename) |
---|
[d5ac45f] | 395 | mtime = getmtime(path) |
---|
| 396 | if filename not in _template_cache or mtime > _template_cache[filename][0]: |
---|
| 397 | with open(path) as fid: |
---|
[303d8d6] | 398 | _template_cache[filename] = (mtime, fid.read(), path) |
---|
[da63656] | 399 | return _template_cache[filename][1], path |
---|
[d5ac45f] | 400 | |
---|
[303d8d6] | 401 | |
---|
[03cac08] | 402 | _FN_TEMPLATE = """\ |
---|
| 403 | double %(name)s(%(pars)s); |
---|
| 404 | double %(name)s(%(pars)s) { |
---|
[da63656] | 405 | #line %(line)d "%(filename)s" |
---|
[03cac08] | 406 | %(body)s |
---|
| 407 | } |
---|
| 408 | |
---|
| 409 | """ |
---|
[da63656] | 410 | def _gen_fn(name, pars, body, filename, line): |
---|
| 411 | # type: (str, List[Parameter], str, str, int) -> str |
---|
[5ceb7d0] | 412 | """ |
---|
[d5ac45f] | 413 | Generate a function given pars and body. |
---|
| 414 | |
---|
| 415 | Returns the following string:: |
---|
[5ceb7d0] | 416 | |
---|
[d5ac45f] | 417 | double fn(double a, double b, ...); |
---|
| 418 | double fn(double a, double b, ...) { |
---|
| 419 | .... |
---|
| 420 | } |
---|
[5ceb7d0] | 421 | """ |
---|
[60eab2a] | 422 | par_decl = ', '.join(p.as_function_argument() for p in pars) if pars else 'void' |
---|
[da63656] | 423 | return _FN_TEMPLATE % { |
---|
| 424 | 'name': name, 'pars': par_decl, 'body': body, |
---|
| 425 | 'filename': filename.replace('\\', '\\\\'), 'line': line, |
---|
| 426 | } |
---|
[d5ac45f] | 427 | |
---|
[17bbadd] | 428 | |
---|
[03cac08] | 429 | def _call_pars(prefix, pars): |
---|
[f619de7] | 430 | # type: (str, List[Parameter]) -> List[str] |
---|
[03cac08] | 431 | """ |
---|
| 432 | Return a list of *prefix.parameter* from parameter items. |
---|
| 433 | """ |
---|
[69aa451] | 434 | return [p.as_call_reference(prefix) for p in pars] |
---|
[d5ac45f] | 435 | |
---|
[17bbadd] | 436 | |
---|
[03cac08] | 437 | _IQXY_PATTERN = re.compile("^((inline|static) )? *(double )? *Iqxy *([(]|$)", |
---|
| 438 | flags=re.MULTILINE) |
---|
| 439 | def _have_Iqxy(sources): |
---|
[f619de7] | 440 | # type: (List[str]) -> bool |
---|
[03cac08] | 441 | """ |
---|
| 442 | Return true if any file defines Iqxy. |
---|
[d5ac45f] | 443 | |
---|
[03cac08] | 444 | Note this is not a C parser, and so can be easily confused by |
---|
| 445 | non-standard syntax. Also, it will incorrectly identify the following |
---|
| 446 | as having Iqxy:: |
---|
| 447 | |
---|
| 448 | /* |
---|
| 449 | double Iqxy(qx, qy, ...) { ... fill this in later ... } |
---|
| 450 | */ |
---|
| 451 | |
---|
| 452 | If you want to comment out an Iqxy function, use // on the front of the |
---|
| 453 | line instead. |
---|
| 454 | """ |
---|
[da63656] | 455 | for code, path in sources: |
---|
[03cac08] | 456 | if _IQXY_PATTERN.search(code): |
---|
| 457 | return True |
---|
| 458 | else: |
---|
| 459 | return False |
---|
[d5ac45f] | 460 | |
---|
[17bbadd] | 461 | |
---|
[da63656] | 462 | def _add_source(source, code, path): |
---|
| 463 | """ |
---|
| 464 | Add a file to the list of source code chunks, tagged with path and line. |
---|
| 465 | """ |
---|
[7891a2a] | 466 | path = path.replace('\\', '\\\\') |
---|
| 467 | source.append('#line 1 "%s"' % path) |
---|
[da63656] | 468 | source.append(code) |
---|
[5ceb7d0] | 469 | |
---|
[17bbadd] | 470 | |
---|
| 471 | def make_source(model_info): |
---|
[f619de7] | 472 | # type: (ModelInfo) -> str |
---|
[5ceb7d0] | 473 | """ |
---|
[17bbadd] | 474 | Generate the OpenCL/ctypes kernel from the module info. |
---|
| 475 | |
---|
[f619de7] | 476 | Uses source files found in the given search path. Returns None if this |
---|
| 477 | is a pure python model, with no C source components. |
---|
[5ceb7d0] | 478 | """ |
---|
[6d6508e] | 479 | if callable(model_info.Iq): |
---|
[f619de7] | 480 | raise ValueError("can't compile python model") |
---|
[17bbadd] | 481 | |
---|
[5ceb7d0] | 482 | # TODO: need something other than volume to indicate dispersion parameters |
---|
| 483 | # No volume normalization despite having a volume parameter. |
---|
| 484 | # Thickness is labelled a volume in order to trigger polydispersity. |
---|
| 485 | # May want a separate dispersion flag, or perhaps a separate category for |
---|
| 486 | # disperse, but not volume. Volume parameters also use relative values |
---|
| 487 | # for the distribution rather than the absolute values used by angular |
---|
| 488 | # dispersion. Need to be careful that necessary parameters are available |
---|
| 489 | # for computing volume even if we allow non-disperse volume parameters. |
---|
| 490 | |
---|
[6d6508e] | 491 | partable = model_info.parameters |
---|
[5ceb7d0] | 492 | |
---|
[03cac08] | 493 | # Load templates and user code |
---|
| 494 | kernel_header = load_template('kernel_header.c') |
---|
[f2f67a6] | 495 | dll_code = load_template('kernel_iq.c') |
---|
| 496 | ocl_code = load_template('kernel_iq.cl') |
---|
[ae2b6b5] | 497 | #ocl_code = load_template('kernel_iq_local.cl') |
---|
[da63656] | 498 | user_code = [(f, open(f).read()) for f in model_sources(model_info)] |
---|
[5ceb7d0] | 499 | |
---|
[03cac08] | 500 | # Build initial sources |
---|
[da63656] | 501 | source = [] |
---|
| 502 | _add_source(source, *kernel_header) |
---|
| 503 | for path, code in user_code: |
---|
| 504 | _add_source(source, code, path) |
---|
[5ceb7d0] | 505 | |
---|
[69aa451] | 506 | # Make parameters for q, qx, qy so that we can use them in declarations |
---|
| 507 | q, qx, qy = [Parameter(name=v) for v in ('q', 'qx', 'qy')] |
---|
[d5ac45f] | 508 | # Generate form_volume function, etc. from body only |
---|
[f619de7] | 509 | if isinstance(model_info.form_volume, str): |
---|
[d19962c] | 510 | pars = partable.form_volume_parameters |
---|
[da63656] | 511 | source.append(_gen_fn('form_volume', pars, model_info.form_volume, |
---|
| 512 | model_info.filename, model_info._form_volume_line)) |
---|
[f619de7] | 513 | if isinstance(model_info.Iq, str): |
---|
[d19962c] | 514 | pars = [q] + partable.iq_parameters |
---|
[da63656] | 515 | source.append(_gen_fn('Iq', pars, model_info.Iq, |
---|
| 516 | model_info.filename, model_info._Iq_line)) |
---|
[f619de7] | 517 | if isinstance(model_info.Iqxy, str): |
---|
[d19962c] | 518 | pars = [qx, qy] + partable.iqxy_parameters |
---|
[da63656] | 519 | source.append(_gen_fn('Iqxy', pars, model_info.Iqxy, |
---|
| 520 | model_info.filename, model_info._Iqxy_line)) |
---|
[d5ac45f] | 521 | |
---|
[03cac08] | 522 | # Define the parameter table |
---|
| 523 | source.append("#define PARAMETER_TABLE \\") |
---|
[69aa451] | 524 | source.append("\\\n".join(p.as_definition() |
---|
[d19962c] | 525 | for p in partable.kernel_parameters)) |
---|
[03cac08] | 526 | |
---|
| 527 | # Define the function calls |
---|
[d19962c] | 528 | if partable.form_volume_parameters: |
---|
[d2bb604] | 529 | refs = _call_pars("_v.", partable.form_volume_parameters) |
---|
[7891a2a] | 530 | call_volume = "#define CALL_VOLUME(_v) form_volume(%s)"%(",".join(refs)) |
---|
[d5ac45f] | 531 | else: |
---|
| 532 | # Model doesn't have volume. We could make the kernel run a little |
---|
| 533 | # faster by not using/transferring the volume normalizations, but |
---|
| 534 | # the ifdef's reduce readability more than is worthwhile. |
---|
[5ff1b03] | 535 | call_volume = "#define CALL_VOLUME(v) 1.0" |
---|
[03cac08] | 536 | source.append(call_volume) |
---|
| 537 | |
---|
[d2bb604] | 538 | refs = ["_q[_i]"] + _call_pars("_v.", partable.iq_parameters) |
---|
| 539 | call_iq = "#define CALL_IQ(_q,_i,_v) Iq(%s)" % (",".join(refs)) |
---|
[03cac08] | 540 | if _have_Iqxy(user_code): |
---|
| 541 | # Call 2D model |
---|
[f2f67a6] | 542 | refs = ["q[2*_i]", "q[2*_i+1]"] + _call_pars("_v.", partable.iqxy_parameters) |
---|
[d2bb604] | 543 | call_iqxy = "#define CALL_IQ(_q,_i,_v) Iqxy(%s)" % (",".join(refs)) |
---|
[03cac08] | 544 | else: |
---|
| 545 | # Call 1D model with sqrt(qx^2 + qy^2) |
---|
| 546 | warnings.warn("Creating Iqxy = Iq(sqrt(qx^2 + qy^2))") |
---|
| 547 | # still defined:: refs = ["q[i]"] + _call_pars("v", iq_parameters) |
---|
[d2bb604] | 548 | pars_sqrt = ["sqrt(_q[2*_i]*_q[2*_i]+_q[2*_i+1]*_q[2*_i+1])"] + refs[1:] |
---|
| 549 | call_iqxy = "#define CALL_IQ(_q,_i,_v) Iq(%s)" % (",".join(pars_sqrt)) |
---|
[03cac08] | 550 | |
---|
| 551 | # Fill in definitions for numbers of parameters |
---|
[d19962c] | 552 | source.append("#define MAX_PD %s"%partable.max_pd) |
---|
| 553 | source.append("#define NPARS %d"%partable.npars) |
---|
[03cac08] | 554 | |
---|
| 555 | # TODO: allow mixed python/opencl kernels? |
---|
| 556 | |
---|
[f2f67a6] | 557 | source.append("#if defined(USE_OPENCL)") |
---|
[da63656] | 558 | source.extend(_add_kernels(ocl_code[0], call_iq, call_iqxy, model_info.name)) |
---|
[f2f67a6] | 559 | source.append("#else /* !USE_OPENCL */") |
---|
[da63656] | 560 | source.extend(_add_kernels(dll_code[0], call_iq, call_iqxy, model_info.name)) |
---|
[f2f67a6] | 561 | source.append("#endif /* !USE_OPENCL */") |
---|
[03cac08] | 562 | return '\n'.join(source) |
---|
[5ceb7d0] | 563 | |
---|
[7891a2a] | 564 | |
---|
[f2f67a6] | 565 | def _add_kernels(kernel_code, call_iq, call_iqxy, name): |
---|
| 566 | # type: (str, str, str, str) -> List[str] |
---|
| 567 | source = [ |
---|
| 568 | # define the Iq kernel |
---|
| 569 | "#define KERNEL_NAME %s_Iq"%name, |
---|
| 570 | call_iq, |
---|
| 571 | kernel_code, |
---|
| 572 | "#undef CALL_IQ", |
---|
| 573 | "#undef KERNEL_NAME", |
---|
| 574 | |
---|
| 575 | # define the Iqxy kernel from the same source with different #defines |
---|
| 576 | "#define KERNEL_NAME %s_Iqxy"%name, |
---|
| 577 | call_iqxy, |
---|
| 578 | kernel_code, |
---|
| 579 | "#undef CALL_IQ", |
---|
| 580 | "#undef KERNEL_NAME", |
---|
| 581 | ] |
---|
| 582 | return source |
---|
| 583 | |
---|
[4d76711] | 584 | |
---|
[68e7f9d] | 585 | def load_kernel_module(model_name): |
---|
[f619de7] | 586 | # type: (str) -> module |
---|
[f2f67a6] | 587 | """ |
---|
| 588 | Return the kernel module named in *model_name*. |
---|
| 589 | |
---|
| 590 | If the name ends in *.py* then load it as a custom model using |
---|
| 591 | :func:`sasmodels.custom.load_custom_kernel_module`, otherwise |
---|
| 592 | load it from :mod:`sasmodels.models`. |
---|
| 593 | """ |
---|
[68e7f9d] | 594 | if model_name.endswith('.py'): |
---|
| 595 | kernel_module = load_custom_kernel_module(model_name) |
---|
| 596 | else: |
---|
| 597 | from sasmodels import models |
---|
| 598 | __import__('sasmodels.models.'+model_name) |
---|
| 599 | kernel_module = getattr(models, model_name, None) |
---|
| 600 | return kernel_module |
---|
| 601 | |
---|
[5ceb7d0] | 602 | |
---|
| 603 | section_marker = re.compile(r'\A(?P<first>[%s])(?P=first)*\Z' |
---|
[7891a2a] | 604 | % re.escape(string.punctuation)) |
---|
[5ceb7d0] | 605 | def _convert_section_titles_to_boldface(lines): |
---|
[f619de7] | 606 | # type: (Sequence[str]) -> Iterator[str] |
---|
[5ceb7d0] | 607 | """ |
---|
| 608 | Do the actual work of identifying and converting section headings. |
---|
| 609 | """ |
---|
| 610 | prior = None |
---|
| 611 | for line in lines: |
---|
| 612 | if prior is None: |
---|
| 613 | prior = line |
---|
| 614 | elif section_marker.match(line): |
---|
| 615 | if len(line) >= len(prior): |
---|
| 616 | yield "".join(("**", prior, "**")) |
---|
| 617 | prior = None |
---|
| 618 | else: |
---|
| 619 | yield prior |
---|
| 620 | prior = line |
---|
| 621 | else: |
---|
| 622 | yield prior |
---|
| 623 | prior = line |
---|
| 624 | if prior is not None: |
---|
| 625 | yield prior |
---|
| 626 | |
---|
[7891a2a] | 627 | |
---|
[5ceb7d0] | 628 | def convert_section_titles_to_boldface(s): |
---|
[f619de7] | 629 | # type: (str) -> str |
---|
[5ceb7d0] | 630 | """ |
---|
| 631 | Use explicit bold-face rather than section headings so that the table of |
---|
| 632 | contents is not polluted with section names from the model documentation. |
---|
| 633 | |
---|
| 634 | Sections are identified as the title line followed by a line of punctuation |
---|
| 635 | at least as long as the title line. |
---|
| 636 | """ |
---|
| 637 | return "\n".join(_convert_section_titles_to_boldface(s.split('\n'))) |
---|
| 638 | |
---|
[7891a2a] | 639 | |
---|
[17bbadd] | 640 | def make_doc(model_info): |
---|
[f619de7] | 641 | # type: (ModelInfo) -> str |
---|
[5ceb7d0] | 642 | """ |
---|
| 643 | Return the documentation for the model. |
---|
| 644 | """ |
---|
| 645 | Iq_units = "The returned value is scaled to units of |cm^-1| |sr^-1|, absolute scale." |
---|
| 646 | Sq_units = "The returned value is a dimensionless structure factor, $S(q)$." |
---|
[6d6508e] | 647 | docs = convert_section_titles_to_boldface(model_info.docs) |
---|
[a5b8477] | 648 | pars = make_partable(model_info.parameters.COMMON |
---|
| 649 | + model_info.parameters.kernel_parameters) |
---|
[6d6508e] | 650 | subst = dict(id=model_info.id.replace('_', '-'), |
---|
| 651 | name=model_info.name, |
---|
| 652 | title=model_info.title, |
---|
[a5b8477] | 653 | parameters=pars, |
---|
[6d6508e] | 654 | returns=Sq_units if model_info.structure_factor else Iq_units, |
---|
[5ceb7d0] | 655 | docs=docs) |
---|
| 656 | return DOC_HEADER % subst |
---|
| 657 | |
---|
| 658 | |
---|
| 659 | def demo_time(): |
---|
[f619de7] | 660 | # type: () -> None |
---|
[5ceb7d0] | 661 | """ |
---|
| 662 | Show how long it takes to process a model. |
---|
| 663 | """ |
---|
| 664 | import datetime |
---|
[6d6508e] | 665 | from .modelinfo import make_model_info |
---|
| 666 | from .models import cylinder |
---|
| 667 | |
---|
[5ceb7d0] | 668 | tic = datetime.datetime.now() |
---|
[17bbadd] | 669 | make_source(make_model_info(cylinder)) |
---|
[5ceb7d0] | 670 | toc = (datetime.datetime.now() - tic).total_seconds() |
---|
| 671 | print("time: %g"%toc) |
---|
| 672 | |
---|
[7891a2a] | 673 | |
---|
[5ceb7d0] | 674 | def main(): |
---|
[f619de7] | 675 | # type: () -> None |
---|
[5ceb7d0] | 676 | """ |
---|
| 677 | Program which prints the source produced by the model. |
---|
| 678 | """ |
---|
[d19962c] | 679 | import sys |
---|
[6d6508e] | 680 | from .modelinfo import make_model_info |
---|
| 681 | |
---|
[5ceb7d0] | 682 | if len(sys.argv) <= 1: |
---|
| 683 | print("usage: python -m sasmodels.generate modelname") |
---|
| 684 | else: |
---|
| 685 | name = sys.argv[1] |
---|
[68e7f9d] | 686 | kernel_module = load_kernel_module(name) |
---|
| 687 | model_info = make_model_info(kernel_module) |
---|
[17bbadd] | 688 | source = make_source(model_info) |
---|
[5ceb7d0] | 689 | print(source) |
---|
| 690 | |
---|
[7891a2a] | 691 | |
---|
[5ceb7d0] | 692 | if __name__ == "__main__": |
---|
| 693 | main() |
---|