[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 |
---|
[785cbec] | 147 | :func:`modelinfo.make_model_info` parses it. :func:`make_source` |
---|
[a5b8477] | 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 |
---|
| 168 | |
---|
[7ae2b7f] | 169 | import numpy as np # type: ignore |
---|
[5ceb7d0] | 170 | |
---|
[6d6508e] | 171 | from .modelinfo import Parameter |
---|
[68e7f9d] | 172 | from .custom import load_custom_kernel_module |
---|
[fcd7bbd] | 173 | |
---|
[f619de7] | 174 | try: |
---|
[f2f67a6] | 175 | from typing import Tuple, Sequence, Iterator, Dict |
---|
[f619de7] | 176 | from .modelinfo import ModelInfo |
---|
| 177 | except ImportError: |
---|
| 178 | pass |
---|
| 179 | |
---|
[a5da1f2] | 180 | def get_data_path(external_dir, target_file): |
---|
| 181 | path = abspath(dirname(__file__)) |
---|
| 182 | if exists(joinpath(path, target_file)): |
---|
| 183 | return path |
---|
| 184 | |
---|
| 185 | # check next to exe/zip file |
---|
| 186 | exepath = dirname(sys.executable) |
---|
| 187 | path = joinpath(exepath, external_dir) |
---|
| 188 | if exists(joinpath(path, target_file)): |
---|
| 189 | return path |
---|
| 190 | |
---|
| 191 | # check in py2app Contents/Resources |
---|
| 192 | path = joinpath(exepath, '..', 'Resources', external_dir) |
---|
| 193 | if exists(joinpath(path, target_file)): |
---|
| 194 | return abspath(path) |
---|
| 195 | |
---|
| 196 | raise RuntimeError('Could not find '+joinpath(external_dir, target_file)) |
---|
| 197 | |
---|
| 198 | EXTERNAL_DIR = 'sasmodels-data' |
---|
| 199 | DATA_PATH = get_data_path(EXTERNAL_DIR, 'kernel_template.c') |
---|
[c2c51a2] | 200 | MODEL_PATH = joinpath(DATA_PATH, 'models') |
---|
[5ceb7d0] | 201 | |
---|
| 202 | F16 = np.dtype('float16') |
---|
| 203 | F32 = np.dtype('float32') |
---|
| 204 | F64 = np.dtype('float64') |
---|
| 205 | try: # CRUFT: older numpy does not support float128 |
---|
| 206 | F128 = np.dtype('float128') |
---|
| 207 | except TypeError: |
---|
| 208 | F128 = None |
---|
| 209 | |
---|
| 210 | # Conversion from units defined in the parameter table for each model |
---|
| 211 | # to units displayed in the sphinx documentation. |
---|
| 212 | RST_UNITS = { |
---|
| 213 | "Ang": "|Ang|", |
---|
| 214 | "1/Ang": "|Ang^-1|", |
---|
| 215 | "1/Ang^2": "|Ang^-2|", |
---|
| 216 | "1e-6/Ang^2": "|1e-6Ang^-2|", |
---|
| 217 | "degrees": "degree", |
---|
| 218 | "1/cm": "|cm^-1|", |
---|
| 219 | "Ang/cm": "|Ang*cm^-1|", |
---|
[52ec91e] | 220 | "g/cm^3": "|g/cm^3|", |
---|
| 221 | "mg/m^2": "|mg/m^2|", |
---|
[5ceb7d0] | 222 | "": "None", |
---|
| 223 | } |
---|
| 224 | |
---|
| 225 | # Headers for the parameters tables in th sphinx documentation |
---|
| 226 | PARTABLE_HEADERS = [ |
---|
| 227 | "Parameter", |
---|
| 228 | "Description", |
---|
| 229 | "Units", |
---|
| 230 | "Default value", |
---|
| 231 | ] |
---|
| 232 | |
---|
| 233 | # Minimum width for a default value (this is shorter than the column header |
---|
| 234 | # width, so will be ignored). |
---|
| 235 | PARTABLE_VALUE_WIDTH = 10 |
---|
| 236 | |
---|
| 237 | # Documentation header for the module, giving the model name, its short |
---|
| 238 | # description and its parameter table. The remainder of the doc comes |
---|
| 239 | # from the module docstring. |
---|
| 240 | DOC_HEADER = """.. _%(id)s: |
---|
| 241 | |
---|
| 242 | %(name)s |
---|
| 243 | ======================================================= |
---|
| 244 | |
---|
| 245 | %(title)s |
---|
| 246 | |
---|
| 247 | %(parameters)s |
---|
| 248 | |
---|
| 249 | %(returns)s |
---|
| 250 | |
---|
| 251 | %(docs)s |
---|
| 252 | """ |
---|
| 253 | |
---|
[7891a2a] | 254 | |
---|
[5ceb7d0] | 255 | def format_units(units): |
---|
[f619de7] | 256 | # type: (str) -> str |
---|
[5ceb7d0] | 257 | """ |
---|
| 258 | Convert units into ReStructured Text format. |
---|
| 259 | """ |
---|
| 260 | return "string" if isinstance(units, list) else RST_UNITS.get(units, units) |
---|
| 261 | |
---|
[7891a2a] | 262 | |
---|
[5ceb7d0] | 263 | def make_partable(pars): |
---|
[f619de7] | 264 | # type: (List[Parameter]) -> str |
---|
[5ceb7d0] | 265 | """ |
---|
| 266 | Generate the parameter table to include in the sphinx documentation. |
---|
| 267 | """ |
---|
| 268 | column_widths = [ |
---|
[fcd7bbd] | 269 | max(len(p.name) for p in pars), |
---|
| 270 | max(len(p.description) for p in pars), |
---|
| 271 | max(len(format_units(p.units)) for p in pars), |
---|
[5ceb7d0] | 272 | PARTABLE_VALUE_WIDTH, |
---|
| 273 | ] |
---|
| 274 | column_widths = [max(w, len(h)) |
---|
| 275 | for w, h in zip(column_widths, PARTABLE_HEADERS)] |
---|
| 276 | |
---|
| 277 | sep = " ".join("="*w for w in column_widths) |
---|
| 278 | lines = [ |
---|
| 279 | sep, |
---|
| 280 | " ".join("%-*s" % (w, h) |
---|
| 281 | for w, h in zip(column_widths, PARTABLE_HEADERS)), |
---|
| 282 | sep, |
---|
| 283 | ] |
---|
| 284 | for p in pars: |
---|
| 285 | lines.append(" ".join([ |
---|
[fcd7bbd] | 286 | "%-*s" % (column_widths[0], p.name), |
---|
| 287 | "%-*s" % (column_widths[1], p.description), |
---|
| 288 | "%-*s" % (column_widths[2], format_units(p.units)), |
---|
| 289 | "%*g" % (column_widths[3], p.default), |
---|
[5ceb7d0] | 290 | ])) |
---|
| 291 | lines.append(sep) |
---|
| 292 | return "\n".join(lines) |
---|
| 293 | |
---|
[7891a2a] | 294 | |
---|
[5ceb7d0] | 295 | def _search(search_path, filename): |
---|
[f619de7] | 296 | # type: (List[str], str) -> str |
---|
[5ceb7d0] | 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 | |
---|
[d5ac45f] | 308 | |
---|
[17bbadd] | 309 | def model_sources(model_info): |
---|
[f619de7] | 310 | # type: (ModelInfo) -> List[str] |
---|
[5ceb7d0] | 311 | """ |
---|
| 312 | Return a list of the sources file paths for the module. |
---|
| 313 | """ |
---|
[7891a2a] | 314 | search_path = [dirname(model_info.filename), MODEL_PATH] |
---|
[6d6508e] | 315 | return [_search(search_path, f) for f in model_info.source] |
---|
[5ceb7d0] | 316 | |
---|
| 317 | |
---|
[0dc34c3] | 318 | def dll_timestamp(model_info): |
---|
[f619de7] | 319 | # type: (ModelInfo) -> int |
---|
[69aa451] | 320 | """ |
---|
| 321 | Return a timestamp for the model corresponding to the most recently |
---|
| 322 | changed file or dependency. |
---|
| 323 | """ |
---|
[0dc34c3] | 324 | # TODO: fails DRY; templates appear two places. |
---|
| 325 | model_templates = [joinpath(DATA_PATH, filename) |
---|
| 326 | for filename in ('kernel_header.c', 'kernel_iq.c')] |
---|
[69aa451] | 327 | source_files = (model_sources(model_info) |
---|
[0dc34c3] | 328 | + model_templates |
---|
[6d6508e] | 329 | + [model_info.filename]) |
---|
[0dc34c3] | 330 | # Note: file may not exist when it is a standard model from library.zip |
---|
| 331 | times = [getmtime(f) for f in source_files if exists(f)] |
---|
| 332 | newest = max(times) if times else 0 |
---|
[69aa451] | 333 | return newest |
---|
| 334 | |
---|
[0dc34c3] | 335 | def ocl_timestamp(model_info): |
---|
| 336 | # type: (ModelInfo) -> int |
---|
| 337 | """ |
---|
| 338 | Return a timestamp for the model corresponding to the most recently |
---|
| 339 | changed file or dependency. |
---|
[7891a2a] | 340 | |
---|
[0dc34c3] | 341 | Note that this does not look at the time stamps for the OpenCL header |
---|
| 342 | information since that need not trigger a recompile of the DLL. |
---|
| 343 | """ |
---|
[f2f67a6] | 344 | # TODO: fails DRY; templates appear two places. |
---|
[0dc34c3] | 345 | model_templates = [joinpath(DATA_PATH, filename) |
---|
| 346 | for filename in ('kernel_header.c', 'kernel_iq.cl')] |
---|
| 347 | source_files = (model_sources(model_info) |
---|
| 348 | + model_templates |
---|
| 349 | + [model_info.filename]) |
---|
| 350 | # Note: file may not exist when it is a standard model from library.zip |
---|
| 351 | times = [getmtime(f) for f in source_files if exists(f)] |
---|
| 352 | newest = max(times) if times else 0 |
---|
| 353 | return newest |
---|
[f2f67a6] | 354 | |
---|
[5ceb7d0] | 355 | |
---|
| 356 | def convert_type(source, dtype): |
---|
[f619de7] | 357 | # type: (str, np.dtype) -> str |
---|
[5ceb7d0] | 358 | """ |
---|
| 359 | Convert code from double precision to the desired type. |
---|
| 360 | |
---|
| 361 | Floating point constants are tagged with 'f' for single precision or 'L' |
---|
| 362 | for long double precision. |
---|
| 363 | """ |
---|
| 364 | if dtype == F16: |
---|
| 365 | fbytes = 2 |
---|
[1e2a1ba] | 366 | source = _convert_type(source, "half", "f") |
---|
[5ceb7d0] | 367 | elif dtype == F32: |
---|
| 368 | fbytes = 4 |
---|
| 369 | source = _convert_type(source, "float", "f") |
---|
| 370 | elif dtype == F64: |
---|
| 371 | fbytes = 8 |
---|
[d5ac45f] | 372 | # no need to convert if it is already double |
---|
[5ceb7d0] | 373 | elif dtype == F128: |
---|
| 374 | fbytes = 16 |
---|
| 375 | source = _convert_type(source, "long double", "L") |
---|
| 376 | else: |
---|
[7891a2a] | 377 | raise ValueError("Unexpected dtype in source conversion: %s" % dtype) |
---|
| 378 | return ("#define FLOAT_SIZE %d\n" % fbytes)+source |
---|
[5ceb7d0] | 379 | |
---|
| 380 | |
---|
| 381 | def _convert_type(source, type_name, constant_flag): |
---|
[f619de7] | 382 | # type: (str, str, str) -> str |
---|
[5ceb7d0] | 383 | """ |
---|
| 384 | Replace 'double' with *type_name* in *source*, tagging floating point |
---|
| 385 | constants with *constant_flag*. |
---|
| 386 | """ |
---|
| 387 | # Convert double keyword to float/long double/half. |
---|
| 388 | # Accept an 'n' # parameter for vector # values, where n is 2, 4, 8 or 16. |
---|
| 389 | # Assume complex numbers are represented as cdouble which is typedef'd |
---|
| 390 | # to double2. |
---|
| 391 | source = re.sub(r'(^|[^a-zA-Z0-9_]c?)double(([248]|16)?($|[^a-zA-Z0-9_]))', |
---|
| 392 | r'\1%s\2'%type_name, source) |
---|
| 393 | # Convert floating point constants to single by adding 'f' to the end, |
---|
| 394 | # or long double with an 'L' suffix. OS/X complains if you don't do this. |
---|
| 395 | source = re.sub(r'[^a-zA-Z_](\d*[.]\d+|\d+[.]\d*)([eE][+-]?\d+)?', |
---|
| 396 | r'\g<0>%s'%constant_flag, source) |
---|
| 397 | return source |
---|
| 398 | |
---|
| 399 | |
---|
[32e3c9b] | 400 | def kernel_name(model_info, variant): |
---|
| 401 | # type: (ModelInfo, str) -> str |
---|
[5ceb7d0] | 402 | """ |
---|
| 403 | Name of the exported kernel symbol. |
---|
[32e3c9b] | 404 | |
---|
| 405 | *variant* is "Iq", "Iqxy" or "Imagnetic". |
---|
[5ceb7d0] | 406 | """ |
---|
[32e3c9b] | 407 | return model_info.name + "_" + variant |
---|
[5ceb7d0] | 408 | |
---|
| 409 | |
---|
| 410 | def indent(s, depth): |
---|
[f619de7] | 411 | # type: (str, int) -> str |
---|
[5ceb7d0] | 412 | """ |
---|
| 413 | Indent a string of text with *depth* additional spaces on each line. |
---|
| 414 | """ |
---|
| 415 | spaces = " "*depth |
---|
| 416 | sep = "\n" + spaces |
---|
| 417 | return spaces + sep.join(s.split("\n")) |
---|
| 418 | |
---|
| 419 | |
---|
[f619de7] | 420 | _template_cache = {} # type: Dict[str, Tuple[int, str, str]] |
---|
[d5ac45f] | 421 | def load_template(filename): |
---|
[f619de7] | 422 | # type: (str) -> str |
---|
[7891a2a] | 423 | path = joinpath(DATA_PATH, filename) |
---|
[d5ac45f] | 424 | mtime = getmtime(path) |
---|
| 425 | if filename not in _template_cache or mtime > _template_cache[filename][0]: |
---|
| 426 | with open(path) as fid: |
---|
[303d8d6] | 427 | _template_cache[filename] = (mtime, fid.read(), path) |
---|
[da63656] | 428 | return _template_cache[filename][1], path |
---|
[d5ac45f] | 429 | |
---|
[303d8d6] | 430 | |
---|
[03cac08] | 431 | _FN_TEMPLATE = """\ |
---|
| 432 | double %(name)s(%(pars)s); |
---|
| 433 | double %(name)s(%(pars)s) { |
---|
[da63656] | 434 | #line %(line)d "%(filename)s" |
---|
[03cac08] | 435 | %(body)s |
---|
| 436 | } |
---|
| 437 | |
---|
| 438 | """ |
---|
[da63656] | 439 | def _gen_fn(name, pars, body, filename, line): |
---|
| 440 | # type: (str, List[Parameter], str, str, int) -> str |
---|
[5ceb7d0] | 441 | """ |
---|
[d5ac45f] | 442 | Generate a function given pars and body. |
---|
| 443 | |
---|
| 444 | Returns the following string:: |
---|
[5ceb7d0] | 445 | |
---|
[d5ac45f] | 446 | double fn(double a, double b, ...); |
---|
| 447 | double fn(double a, double b, ...) { |
---|
| 448 | .... |
---|
| 449 | } |
---|
[5ceb7d0] | 450 | """ |
---|
[60eab2a] | 451 | par_decl = ', '.join(p.as_function_argument() for p in pars) if pars else 'void' |
---|
[da63656] | 452 | return _FN_TEMPLATE % { |
---|
| 453 | 'name': name, 'pars': par_decl, 'body': body, |
---|
| 454 | 'filename': filename.replace('\\', '\\\\'), 'line': line, |
---|
| 455 | } |
---|
[d5ac45f] | 456 | |
---|
[17bbadd] | 457 | |
---|
[03cac08] | 458 | def _call_pars(prefix, pars): |
---|
[f619de7] | 459 | # type: (str, List[Parameter]) -> List[str] |
---|
[03cac08] | 460 | """ |
---|
| 461 | Return a list of *prefix.parameter* from parameter items. |
---|
| 462 | """ |
---|
[69aa451] | 463 | return [p.as_call_reference(prefix) for p in pars] |
---|
[d5ac45f] | 464 | |
---|
[17bbadd] | 465 | |
---|
[a738209] | 466 | # type in IQXY pattern could be single, float, double, long double, ... |
---|
| 467 | _IQXY_PATTERN = re.compile("^((inline|static) )? *([a-z ]+ )? *Iqxy *([(]|$)", |
---|
[03cac08] | 468 | flags=re.MULTILINE) |
---|
| 469 | def _have_Iqxy(sources): |
---|
[f619de7] | 470 | # type: (List[str]) -> bool |
---|
[03cac08] | 471 | """ |
---|
| 472 | Return true if any file defines Iqxy. |
---|
[d5ac45f] | 473 | |
---|
[03cac08] | 474 | Note this is not a C parser, and so can be easily confused by |
---|
| 475 | non-standard syntax. Also, it will incorrectly identify the following |
---|
| 476 | as having Iqxy:: |
---|
| 477 | |
---|
| 478 | /* |
---|
| 479 | double Iqxy(qx, qy, ...) { ... fill this in later ... } |
---|
| 480 | */ |
---|
| 481 | |
---|
| 482 | If you want to comment out an Iqxy function, use // on the front of the |
---|
| 483 | line instead. |
---|
| 484 | """ |
---|
[a738209] | 485 | for path, code in sources: |
---|
[03cac08] | 486 | if _IQXY_PATTERN.search(code): |
---|
| 487 | return True |
---|
| 488 | else: |
---|
| 489 | return False |
---|
[d5ac45f] | 490 | |
---|
[17bbadd] | 491 | |
---|
[da63656] | 492 | def _add_source(source, code, path): |
---|
| 493 | """ |
---|
| 494 | Add a file to the list of source code chunks, tagged with path and line. |
---|
| 495 | """ |
---|
[7891a2a] | 496 | path = path.replace('\\', '\\\\') |
---|
| 497 | source.append('#line 1 "%s"' % path) |
---|
[da63656] | 498 | source.append(code) |
---|
[5ceb7d0] | 499 | |
---|
[17bbadd] | 500 | def make_source(model_info): |
---|
[a4280bd] | 501 | # type: (ModelInfo) -> Dict[str, str] |
---|
[5ceb7d0] | 502 | """ |
---|
[17bbadd] | 503 | Generate the OpenCL/ctypes kernel from the module info. |
---|
| 504 | |
---|
[f619de7] | 505 | Uses source files found in the given search path. Returns None if this |
---|
| 506 | is a pure python model, with no C source components. |
---|
[5ceb7d0] | 507 | """ |
---|
[6d6508e] | 508 | if callable(model_info.Iq): |
---|
[739aad4] | 509 | raise ValueError("can't compile python model") |
---|
| 510 | #return None |
---|
[17bbadd] | 511 | |
---|
[5ceb7d0] | 512 | # TODO: need something other than volume to indicate dispersion parameters |
---|
| 513 | # No volume normalization despite having a volume parameter. |
---|
| 514 | # Thickness is labelled a volume in order to trigger polydispersity. |
---|
| 515 | # May want a separate dispersion flag, or perhaps a separate category for |
---|
| 516 | # disperse, but not volume. Volume parameters also use relative values |
---|
| 517 | # for the distribution rather than the absolute values used by angular |
---|
| 518 | # dispersion. Need to be careful that necessary parameters are available |
---|
| 519 | # for computing volume even if we allow non-disperse volume parameters. |
---|
| 520 | |
---|
[6d6508e] | 521 | partable = model_info.parameters |
---|
[5ceb7d0] | 522 | |
---|
[03cac08] | 523 | # Load templates and user code |
---|
| 524 | kernel_header = load_template('kernel_header.c') |
---|
[f2f67a6] | 525 | dll_code = load_template('kernel_iq.c') |
---|
| 526 | ocl_code = load_template('kernel_iq.cl') |
---|
[ae2b6b5] | 527 | #ocl_code = load_template('kernel_iq_local.cl') |
---|
[da63656] | 528 | user_code = [(f, open(f).read()) for f in model_sources(model_info)] |
---|
[5ceb7d0] | 529 | |
---|
[03cac08] | 530 | # Build initial sources |
---|
[da63656] | 531 | source = [] |
---|
| 532 | _add_source(source, *kernel_header) |
---|
| 533 | for path, code in user_code: |
---|
| 534 | _add_source(source, code, path) |
---|
[5ceb7d0] | 535 | |
---|
[69aa451] | 536 | # Make parameters for q, qx, qy so that we can use them in declarations |
---|
| 537 | q, qx, qy = [Parameter(name=v) for v in ('q', 'qx', 'qy')] |
---|
[d5ac45f] | 538 | # Generate form_volume function, etc. from body only |
---|
[f619de7] | 539 | if isinstance(model_info.form_volume, str): |
---|
[d19962c] | 540 | pars = partable.form_volume_parameters |
---|
[da63656] | 541 | source.append(_gen_fn('form_volume', pars, model_info.form_volume, |
---|
| 542 | model_info.filename, model_info._form_volume_line)) |
---|
[f619de7] | 543 | if isinstance(model_info.Iq, str): |
---|
[d19962c] | 544 | pars = [q] + partable.iq_parameters |
---|
[da63656] | 545 | source.append(_gen_fn('Iq', pars, model_info.Iq, |
---|
| 546 | model_info.filename, model_info._Iq_line)) |
---|
[f619de7] | 547 | if isinstance(model_info.Iqxy, str): |
---|
[d19962c] | 548 | pars = [qx, qy] + partable.iqxy_parameters |
---|
[da63656] | 549 | source.append(_gen_fn('Iqxy', pars, model_info.Iqxy, |
---|
| 550 | model_info.filename, model_info._Iqxy_line)) |
---|
[d5ac45f] | 551 | |
---|
[03cac08] | 552 | # Define the parameter table |
---|
[b966a96] | 553 | # TODO: plug in current line number |
---|
| 554 | source.append('#line 542 "sasmodels/generate.py"') |
---|
[03cac08] | 555 | source.append("#define PARAMETER_TABLE \\") |
---|
[69aa451] | 556 | source.append("\\\n".join(p.as_definition() |
---|
[d19962c] | 557 | for p in partable.kernel_parameters)) |
---|
[03cac08] | 558 | |
---|
| 559 | # Define the function calls |
---|
[d19962c] | 560 | if partable.form_volume_parameters: |
---|
[d2bb604] | 561 | refs = _call_pars("_v.", partable.form_volume_parameters) |
---|
[7891a2a] | 562 | call_volume = "#define CALL_VOLUME(_v) form_volume(%s)"%(",".join(refs)) |
---|
[d5ac45f] | 563 | else: |
---|
| 564 | # Model doesn't have volume. We could make the kernel run a little |
---|
| 565 | # faster by not using/transferring the volume normalizations, but |
---|
| 566 | # the ifdef's reduce readability more than is worthwhile. |
---|
[5ff1b03] | 567 | call_volume = "#define CALL_VOLUME(v) 1.0" |
---|
[03cac08] | 568 | source.append(call_volume) |
---|
| 569 | |
---|
[d2bb604] | 570 | refs = ["_q[_i]"] + _call_pars("_v.", partable.iq_parameters) |
---|
| 571 | call_iq = "#define CALL_IQ(_q,_i,_v) Iq(%s)" % (",".join(refs)) |
---|
[32e3c9b] | 572 | if _have_Iqxy(user_code) or isinstance(model_info.Iqxy, str): |
---|
[03cac08] | 573 | # Call 2D model |
---|
[32e3c9b] | 574 | refs = ["_q[2*_i]", "_q[2*_i+1]"] + _call_pars("_v.", partable.iqxy_parameters) |
---|
[d2bb604] | 575 | call_iqxy = "#define CALL_IQ(_q,_i,_v) Iqxy(%s)" % (",".join(refs)) |
---|
[03cac08] | 576 | else: |
---|
| 577 | # Call 1D model with sqrt(qx^2 + qy^2) |
---|
[2c74c11] | 578 | #warnings.warn("Creating Iqxy = Iq(sqrt(qx^2 + qy^2))") |
---|
[03cac08] | 579 | # still defined:: refs = ["q[i]"] + _call_pars("v", iq_parameters) |
---|
[d2bb604] | 580 | pars_sqrt = ["sqrt(_q[2*_i]*_q[2*_i]+_q[2*_i+1]*_q[2*_i+1])"] + refs[1:] |
---|
| 581 | call_iqxy = "#define CALL_IQ(_q,_i,_v) Iq(%s)" % (",".join(pars_sqrt)) |
---|
[03cac08] | 582 | |
---|
[32e3c9b] | 583 | magpars = [k-2 for k,p in enumerate(partable.call_parameters) |
---|
| 584 | if p.type == 'sld'] |
---|
| 585 | |
---|
[03cac08] | 586 | # Fill in definitions for numbers of parameters |
---|
[d19962c] | 587 | source.append("#define MAX_PD %s"%partable.max_pd) |
---|
[a4280bd] | 588 | source.append("#define NUM_PARS %d"%partable.npars) |
---|
[9eb3632] | 589 | source.append("#define NUM_VALUES %d" % partable.nvalues) |
---|
[a4280bd] | 590 | source.append("#define NUM_MAGNETIC %d" % partable.nmagnetic) |
---|
[32e3c9b] | 591 | source.append("#define MAGNETIC_PARS %s"%",".join(str(k) for k in magpars)) |
---|
[a4280bd] | 592 | for k,v in enumerate(magpars[:3]): |
---|
| 593 | source.append("#define MAGNETIC_PAR%d %d"%(k+1, v)) |
---|
[03cac08] | 594 | |
---|
| 595 | # TODO: allow mixed python/opencl kernels? |
---|
| 596 | |
---|
[a4280bd] | 597 | ocl = kernels(ocl_code, call_iq, call_iqxy, model_info.name) |
---|
| 598 | dll = kernels(dll_code, call_iq, call_iqxy, model_info.name) |
---|
| 599 | result = { |
---|
| 600 | 'dll': '\n'.join(source+dll[0]+dll[1]+dll[2]), |
---|
| 601 | 'opencl': '\n'.join(source+ocl[0]+ocl[1]+ocl[2]), |
---|
| 602 | } |
---|
| 603 | |
---|
| 604 | return result |
---|
[5ceb7d0] | 605 | |
---|
[7891a2a] | 606 | |
---|
[a4280bd] | 607 | def kernels(kernel, call_iq, call_iqxy, name): |
---|
[b966a96] | 608 | # type: ([str,str], str, str, str) -> List[str] |
---|
| 609 | code = kernel[0] |
---|
| 610 | path = kernel[1].replace('\\', '\\\\') |
---|
[9eb3632] | 611 | iq = [ |
---|
[f2f67a6] | 612 | # define the Iq kernel |
---|
[32e3c9b] | 613 | "#define KERNEL_NAME %s_Iq" % name, |
---|
[f2f67a6] | 614 | call_iq, |
---|
[a4280bd] | 615 | '#line 1 "%s Iq"' % path, |
---|
[b966a96] | 616 | code, |
---|
[f2f67a6] | 617 | "#undef CALL_IQ", |
---|
| 618 | "#undef KERNEL_NAME", |
---|
[9eb3632] | 619 | ] |
---|
[f2f67a6] | 620 | |
---|
[9eb3632] | 621 | iqxy = [ |
---|
[f2f67a6] | 622 | # define the Iqxy kernel from the same source with different #defines |
---|
[32e3c9b] | 623 | "#define KERNEL_NAME %s_Iqxy" % name, |
---|
[f2f67a6] | 624 | call_iqxy, |
---|
[a4280bd] | 625 | '#line 1 "%s Iqxy"' % path, |
---|
[b966a96] | 626 | code, |
---|
[32e3c9b] | 627 | "#undef CALL_IQ", |
---|
| 628 | "#undef KERNEL_NAME", |
---|
[9eb3632] | 629 | ] |
---|
[32e3c9b] | 630 | |
---|
[9eb3632] | 631 | imagnetic = [ |
---|
[32e3c9b] | 632 | # define the Imagnetic kernel |
---|
| 633 | "#define KERNEL_NAME %s_Imagnetic" % name, |
---|
| 634 | "#define MAGNETIC 1", |
---|
[f2f67a6] | 635 | call_iqxy, |
---|
[a4280bd] | 636 | '#line 1 "%s Imagnetic"' % path, |
---|
[b966a96] | 637 | code, |
---|
[32e3c9b] | 638 | "#undef MAGNETIC", |
---|
[f2f67a6] | 639 | "#undef CALL_IQ", |
---|
| 640 | "#undef KERNEL_NAME", |
---|
| 641 | ] |
---|
[a4280bd] | 642 | |
---|
| 643 | return iq, iqxy, imagnetic |
---|
[f2f67a6] | 644 | |
---|
[4d76711] | 645 | |
---|
[68e7f9d] | 646 | def load_kernel_module(model_name): |
---|
[f619de7] | 647 | # type: (str) -> module |
---|
[f2f67a6] | 648 | """ |
---|
| 649 | Return the kernel module named in *model_name*. |
---|
| 650 | |
---|
| 651 | If the name ends in *.py* then load it as a custom model using |
---|
| 652 | :func:`sasmodels.custom.load_custom_kernel_module`, otherwise |
---|
| 653 | load it from :mod:`sasmodels.models`. |
---|
| 654 | """ |
---|
[68e7f9d] | 655 | if model_name.endswith('.py'): |
---|
| 656 | kernel_module = load_custom_kernel_module(model_name) |
---|
| 657 | else: |
---|
| 658 | from sasmodels import models |
---|
| 659 | __import__('sasmodels.models.'+model_name) |
---|
| 660 | kernel_module = getattr(models, model_name, None) |
---|
| 661 | return kernel_module |
---|
| 662 | |
---|
[5ceb7d0] | 663 | |
---|
| 664 | section_marker = re.compile(r'\A(?P<first>[%s])(?P=first)*\Z' |
---|
[7891a2a] | 665 | % re.escape(string.punctuation)) |
---|
[5ceb7d0] | 666 | def _convert_section_titles_to_boldface(lines): |
---|
[f619de7] | 667 | # type: (Sequence[str]) -> Iterator[str] |
---|
[5ceb7d0] | 668 | """ |
---|
| 669 | Do the actual work of identifying and converting section headings. |
---|
| 670 | """ |
---|
| 671 | prior = None |
---|
| 672 | for line in lines: |
---|
| 673 | if prior is None: |
---|
| 674 | prior = line |
---|
| 675 | elif section_marker.match(line): |
---|
| 676 | if len(line) >= len(prior): |
---|
| 677 | yield "".join(("**", prior, "**")) |
---|
| 678 | prior = None |
---|
| 679 | else: |
---|
| 680 | yield prior |
---|
| 681 | prior = line |
---|
| 682 | else: |
---|
| 683 | yield prior |
---|
| 684 | prior = line |
---|
| 685 | if prior is not None: |
---|
| 686 | yield prior |
---|
| 687 | |
---|
[7891a2a] | 688 | |
---|
[5ceb7d0] | 689 | def convert_section_titles_to_boldface(s): |
---|
[f619de7] | 690 | # type: (str) -> str |
---|
[5ceb7d0] | 691 | """ |
---|
| 692 | Use explicit bold-face rather than section headings so that the table of |
---|
| 693 | contents is not polluted with section names from the model documentation. |
---|
| 694 | |
---|
| 695 | Sections are identified as the title line followed by a line of punctuation |
---|
| 696 | at least as long as the title line. |
---|
| 697 | """ |
---|
| 698 | return "\n".join(_convert_section_titles_to_boldface(s.split('\n'))) |
---|
| 699 | |
---|
[7891a2a] | 700 | |
---|
[17bbadd] | 701 | def make_doc(model_info): |
---|
[f619de7] | 702 | # type: (ModelInfo) -> str |
---|
[5ceb7d0] | 703 | """ |
---|
| 704 | Return the documentation for the model. |
---|
| 705 | """ |
---|
| 706 | Iq_units = "The returned value is scaled to units of |cm^-1| |sr^-1|, absolute scale." |
---|
| 707 | Sq_units = "The returned value is a dimensionless structure factor, $S(q)$." |
---|
[6592f56] | 708 | docs = model_info.docs if model_info.docs is not None else "" |
---|
| 709 | docs = convert_section_titles_to_boldface(docs) |
---|
[a5b8477] | 710 | pars = make_partable(model_info.parameters.COMMON |
---|
| 711 | + model_info.parameters.kernel_parameters) |
---|
[6d6508e] | 712 | subst = dict(id=model_info.id.replace('_', '-'), |
---|
| 713 | name=model_info.name, |
---|
| 714 | title=model_info.title, |
---|
[a5b8477] | 715 | parameters=pars, |
---|
[6d6508e] | 716 | returns=Sq_units if model_info.structure_factor else Iq_units, |
---|
[5ceb7d0] | 717 | docs=docs) |
---|
| 718 | return DOC_HEADER % subst |
---|
| 719 | |
---|
| 720 | |
---|
[6592f56] | 721 | # TODO: need a single source for rst_prolog; it is also in doc/rst_prolog |
---|
| 722 | RST_PROLOG = """\ |
---|
| 723 | .. |Ang| unicode:: U+212B |
---|
| 724 | .. |Ang^-1| replace:: |Ang|\ :sup:`-1` |
---|
| 725 | .. |Ang^2| replace:: |Ang|\ :sup:`2` |
---|
| 726 | .. |Ang^-2| replace:: |Ang|\ :sup:`-2` |
---|
| 727 | .. |1e-6Ang^-2| replace:: 10\ :sup:`-6`\ |Ang|\ :sup:`-2` |
---|
| 728 | .. |Ang^3| replace:: |Ang|\ :sup:`3` |
---|
| 729 | .. |Ang^-3| replace:: |Ang|\ :sup:`-3` |
---|
| 730 | .. |Ang^-4| replace:: |Ang|\ :sup:`-4` |
---|
| 731 | .. |cm^-1| replace:: cm\ :sup:`-1` |
---|
| 732 | .. |cm^2| replace:: cm\ :sup:`2` |
---|
| 733 | .. |cm^-2| replace:: cm\ :sup:`-2` |
---|
| 734 | .. |cm^3| replace:: cm\ :sup:`3` |
---|
| 735 | .. |1e15cm^3| replace:: 10\ :sup:`15`\ cm\ :sup:`3` |
---|
| 736 | .. |cm^-3| replace:: cm\ :sup:`-3` |
---|
| 737 | .. |sr^-1| replace:: sr\ :sup:`-1` |
---|
| 738 | .. |P0| replace:: P\ :sub:`0`\ |
---|
| 739 | |
---|
| 740 | .. |equiv| unicode:: U+2261 |
---|
| 741 | .. |noteql| unicode:: U+2260 |
---|
| 742 | .. |TM| unicode:: U+2122 |
---|
| 743 | |
---|
| 744 | .. |cdot| unicode:: U+00B7 |
---|
| 745 | .. |deg| unicode:: U+00B0 |
---|
| 746 | .. |g/cm^3| replace:: g\ |cdot|\ cm\ :sup:`-3` |
---|
| 747 | .. |mg/m^2| replace:: mg\ |cdot|\ m\ :sup:`-2` |
---|
| 748 | .. |fm^2| replace:: fm\ :sup:`2` |
---|
| 749 | .. |Ang*cm^-1| replace:: |Ang|\ |cdot|\ cm\ :sup:`-1` |
---|
| 750 | """ |
---|
| 751 | |
---|
| 752 | # TODO: make a better fake reference role |
---|
| 753 | RST_ROLES = """\ |
---|
| 754 | .. role:: ref |
---|
| 755 | |
---|
| 756 | .. role:: numref |
---|
| 757 | |
---|
| 758 | """ |
---|
| 759 | |
---|
[001d9f5] | 760 | def make_html(model_info): |
---|
| 761 | """ |
---|
| 762 | Convert model docs directly to html. |
---|
| 763 | """ |
---|
| 764 | from . import rst2html |
---|
[6592f56] | 765 | |
---|
| 766 | rst = make_doc(model_info) |
---|
| 767 | return rst2html.rst2html("".join((RST_ROLES, RST_PROLOG, rst))) |
---|
| 768 | |
---|
| 769 | def view_html(model_name): |
---|
| 770 | from . import rst2html |
---|
| 771 | from . import modelinfo |
---|
| 772 | kernel_module = load_kernel_module(model_name) |
---|
| 773 | info = modelinfo.make_model_info(kernel_module) |
---|
| 774 | url = "file://"+dirname(info.filename)+"/" |
---|
| 775 | rst2html.wxview(make_html(info), url=url) |
---|
[001d9f5] | 776 | |
---|
[5ceb7d0] | 777 | def demo_time(): |
---|
[f619de7] | 778 | # type: () -> None |
---|
[5ceb7d0] | 779 | """ |
---|
| 780 | Show how long it takes to process a model. |
---|
| 781 | """ |
---|
| 782 | import datetime |
---|
[6d6508e] | 783 | from .modelinfo import make_model_info |
---|
| 784 | from .models import cylinder |
---|
| 785 | |
---|
[5ceb7d0] | 786 | tic = datetime.datetime.now() |
---|
[17bbadd] | 787 | make_source(make_model_info(cylinder)) |
---|
[5ceb7d0] | 788 | toc = (datetime.datetime.now() - tic).total_seconds() |
---|
| 789 | print("time: %g"%toc) |
---|
| 790 | |
---|
[7891a2a] | 791 | |
---|
[5ceb7d0] | 792 | def main(): |
---|
[f619de7] | 793 | # type: () -> None |
---|
[5ceb7d0] | 794 | """ |
---|
| 795 | Program which prints the source produced by the model. |
---|
| 796 | """ |
---|
[d19962c] | 797 | import sys |
---|
[6d6508e] | 798 | from .modelinfo import make_model_info |
---|
| 799 | |
---|
[5ceb7d0] | 800 | if len(sys.argv) <= 1: |
---|
| 801 | print("usage: python -m sasmodels.generate modelname") |
---|
| 802 | else: |
---|
| 803 | name = sys.argv[1] |
---|
[68e7f9d] | 804 | kernel_module = load_kernel_module(name) |
---|
| 805 | model_info = make_model_info(kernel_module) |
---|
[17bbadd] | 806 | source = make_source(model_info) |
---|
[a4280bd] | 807 | print(source['dll']) |
---|
[5ceb7d0] | 808 | |
---|
[7891a2a] | 809 | |
---|
[5ceb7d0] | 810 | if __name__ == "__main__": |
---|
| 811 | main() |
---|