[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 | |
---|
[108e70e] | 9 | *Iqac(qab, qc, p1, p2, ...)* returns the scattering at qab, qc |
---|
| 10 | for a rotationally symmetric form with particular dimensions. |
---|
| 11 | qab, qc are determined from shape orientation and scattering angles. |
---|
| 12 | This call is used if the shape has orientation parameters theta and phi. |
---|
[5ceb7d0] | 13 | |
---|
[108e70e] | 14 | *Iqabc(qa, qb, qc, p1, p2, ...)* returns the scattering at qa, qb, qc |
---|
| 15 | for a form with particular dimensions. qa, qb, qc are determined from |
---|
| 16 | shape orientation and scattering angles. This call is used if the shape |
---|
| 17 | has orientation parameters theta, phi and psi. |
---|
| 18 | |
---|
| 19 | *Iqxy(qx, qy, p1, p2, ...)* returns the scattering at qx, qy. Use this |
---|
| 20 | to create an arbitrary 2D theory function, needed for q-dependent |
---|
| 21 | background functions and for models with non-uniform magnetism. |
---|
[5ceb7d0] | 22 | |
---|
| 23 | *form_volume(p1, p2, ...)* returns the volume of the form with particular |
---|
[e6408d0] | 24 | dimension, or 1.0 if no volume normalization is required. |
---|
[5ceb7d0] | 25 | |
---|
[39a06c9] | 26 | *shell_volume(p1, p2, ...)* returns the volume of the shell for forms |
---|
| 27 | which are hollow. |
---|
[5ceb7d0] | 28 | |
---|
[a34b811] | 29 | *radius_effective(mode, p1, p2, ...)* returns the effective radius of |
---|
[39a06c9] | 30 | the form with particular dimensions. Mode determines the type of |
---|
| 31 | effective radius returned, with mode=1 for equivalent volume. |
---|
[5ceb7d0] | 32 | |
---|
[d5ac45f] | 33 | #define INVALID(v) (expr) returns False if v.parameter is invalid |
---|
| 34 | for some parameter or other (e.g., v.bell_radius < v.radius). If |
---|
| 35 | necessary, the expression can call a function. |
---|
| 36 | |
---|
[5ceb7d0] | 37 | These functions are defined in a kernel module .py script and an associated |
---|
| 38 | set of .c files. The model constructor will use them to create models with |
---|
| 39 | polydispersity across volume and orientation parameters, and provide |
---|
| 40 | scale and background parameters for each model. |
---|
| 41 | |
---|
[108e70e] | 42 | C code should be stylized C-99 functions written for OpenCL. All functions |
---|
| 43 | need prototype declarations even if the are defined before they are used. |
---|
| 44 | Although OpenCL supports *#include* preprocessor directives, the list of |
---|
| 45 | includes should be given as part of the metadata in the kernel module |
---|
| 46 | definition. The included files should be listed using a path relative to the |
---|
| 47 | kernel module, or if using "lib/file.c" if it is one of the standard includes |
---|
| 48 | provided with the sasmodels source. The includes need to be listed in order |
---|
| 49 | so that functions are defined before they are used. |
---|
[5ceb7d0] | 50 | |
---|
| 51 | Floating point values should be declared as *double*. For single precision |
---|
| 52 | calculations, *double* will be replaced by *float*. The single precision |
---|
| 53 | conversion will also tag floating point constants with "f" to make them |
---|
| 54 | single precision constants. When using integral values in floating point |
---|
| 55 | expressions, they should be expressed as floating point values by including |
---|
| 56 | a decimal point. This includes 0., 1. and 2. |
---|
| 57 | |
---|
| 58 | OpenCL has a *sincos* function which can improve performance when both |
---|
| 59 | the *sin* and *cos* values are needed for a particular argument. Since |
---|
| 60 | this function does not exist in C99, all use of *sincos* should be |
---|
| 61 | replaced by the macro *SINCOS(value, sn, cn)* where *sn* and *cn* are |
---|
| 62 | previously declared *double* variables. When compiled for systems without |
---|
| 63 | OpenCL, *SINCOS* will be replaced by *sin* and *cos* calls. If *value* is |
---|
| 64 | an expression, it will appear twice in this case; whether or not it will be |
---|
| 65 | evaluated twice depends on the quality of the compiler. |
---|
| 66 | |
---|
| 67 | If the input parameters are invalid, the scattering calculator should |
---|
| 68 | return a negative number. Particularly with polydispersity, there are |
---|
| 69 | some sets of shape parameters which lead to nonsensical forms, such |
---|
| 70 | as a capped cylinder where the cap radius is smaller than the |
---|
| 71 | cylinder radius. The polydispersity calculation will ignore these points, |
---|
| 72 | effectively chopping the parameter weight distributions at the boundary |
---|
| 73 | of the infeasible region. The resulting scattering will be set to |
---|
| 74 | background. This will work correctly even when polydispersity is off. |
---|
| 75 | |
---|
| 76 | The kernel module must set variables defining the kernel meta data: |
---|
| 77 | |
---|
| 78 | *id* is an implicit variable formed from the filename. It will be |
---|
| 79 | a valid python identifier, and will be used as the reference into |
---|
| 80 | the html documentation, with '_' replaced by '-'. |
---|
| 81 | |
---|
| 82 | *name* is the model name as displayed to the user. If it is missing, |
---|
| 83 | it will be constructed from the id. |
---|
| 84 | |
---|
| 85 | *title* is a short description of the model, suitable for a tool tip, |
---|
| 86 | or a one line model summary in a table of models. |
---|
| 87 | |
---|
| 88 | *description* is an extended description of the model to be displayed |
---|
| 89 | while the model parameters are being edited. |
---|
| 90 | |
---|
| 91 | *parameters* is the list of parameters. Parameters in the kernel |
---|
| 92 | functions must appear in the same order as they appear in the |
---|
| 93 | parameters list. Two additional parameters, *scale* and *background* |
---|
| 94 | are added to the beginning of the parameter list. They will show up |
---|
| 95 | in the documentation as model parameters, but they are never sent to |
---|
[17bbadd] | 96 | the kernel functions. Note that *effect_radius* and *volfraction* |
---|
| 97 | must occur first in structure factor calculations. |
---|
[5ceb7d0] | 98 | |
---|
[17bbadd] | 99 | *category* is the default category for the model. The category is |
---|
| 100 | two level structure, with the form "group:section", indicating where |
---|
| 101 | in the manual the model will be located. Models are alphabetical |
---|
| 102 | within their section. |
---|
[5ceb7d0] | 103 | |
---|
| 104 | *source* is the list of C-99 source files that must be joined to |
---|
| 105 | create the OpenCL kernel functions. The files defining the functions |
---|
| 106 | need to be listed before the files which use the functions. |
---|
| 107 | |
---|
[108e70e] | 108 | *form_volume*, *Iq*, *Iqac*, *Iqabc* are strings containing |
---|
| 109 | the C source code for the body of the volume, Iq, and Iqac functions |
---|
[5ceb7d0] | 110 | respectively. These can also be defined in the last source file. |
---|
| 111 | |
---|
[108e70e] | 112 | *Iq*, *Iqac*, *Iqabc* also be instead be python functions defining the |
---|
[5ceb7d0] | 113 | kernel. If they are marked as *Iq.vectorized = True* then the |
---|
| 114 | kernel is passed the entire *q* vector at once, otherwise it is |
---|
| 115 | passed values one *q* at a time. The performance improvement of |
---|
| 116 | this step is significant. |
---|
| 117 | |
---|
| 118 | *demo* is a dictionary of parameter=value defining a set of |
---|
| 119 | parameters to use by default when *compare* is called. Any |
---|
| 120 | parameter not set in *demo* gets the initial value from the |
---|
| 121 | parameter list. *demo* is mostly needed to set the default |
---|
| 122 | polydispersity values for tests. |
---|
| 123 | |
---|
[a5b8477] | 124 | A :class:`modelinfo.ModelInfo` structure is constructed from the kernel meta |
---|
| 125 | data and returned to the caller. |
---|
[5ceb7d0] | 126 | |
---|
| 127 | The doc string at the start of the kernel module will be used to |
---|
| 128 | construct the model documentation web pages. Embedded figures should |
---|
| 129 | appear in the subdirectory "img" beside the model definition, and tagged |
---|
| 130 | with the kernel module name to avoid collision with other models. Some |
---|
| 131 | file systems are case-sensitive, so only use lower case characters for |
---|
| 132 | file names and extensions. |
---|
| 133 | |
---|
| 134 | Code follows the C99 standard with the following extensions and conditions:: |
---|
| 135 | |
---|
| 136 | M_PI_180 = pi/180 |
---|
| 137 | M_4PI_3 = 4pi/3 |
---|
| 138 | square(x) = x*x |
---|
| 139 | cube(x) = x*x*x |
---|
[1e7b0db0] | 140 | sas_sinx_x(x) = sin(x)/x, with sin(0)/0 -> 1 |
---|
[5ceb7d0] | 141 | all double precision constants must include the decimal point |
---|
| 142 | all double declarations may be converted to half, float, or long double |
---|
| 143 | FLOAT_SIZE is the number of bytes in the converted variables |
---|
[a5b8477] | 144 | |
---|
| 145 | :func:`load_kernel_module` loads the model definition file and |
---|
[785cbec] | 146 | :func:`modelinfo.make_model_info` parses it. :func:`make_source` |
---|
[a5b8477] | 147 | converts C-based model definitions to C source code, including the |
---|
| 148 | polydispersity integral. :func:`model_sources` returns the list of |
---|
| 149 | source files the model depends on, and :func:`timestamp` returns |
---|
| 150 | the latest time stamp amongst the source files (so you can check if |
---|
| 151 | the model needs to be rebuilt). |
---|
| 152 | |
---|
| 153 | The function :func:`make_doc` extracts the doc string and adds the |
---|
| 154 | parameter table to the top. *make_figure* in *sasmodels/doc/genmodel* |
---|
| 155 | creates the default figure for the model. [These two sets of code |
---|
| 156 | should mignrate into docs.py so docs can be updated in one place]. |
---|
[5ceb7d0] | 157 | """ |
---|
| 158 | from __future__ import print_function |
---|
| 159 | |
---|
[7891a2a] | 160 | # TODO: determine which functions are useful outside of generate |
---|
[69aa451] | 161 | #__all__ = ["model_info", "make_doc", "make_source", "convert_type"] |
---|
[5ceb7d0] | 162 | |
---|
| 163 | import sys |
---|
[a22d104] | 164 | from os import environ |
---|
| 165 | from os.path import abspath, dirname, join as joinpath, exists, getmtime, sep |
---|
[5ceb7d0] | 166 | import re |
---|
| 167 | import string |
---|
[7fcdc9f] | 168 | from zlib import crc32 |
---|
[9ee2756] | 169 | from inspect import currentframe, getframeinfo |
---|
[108e70e] | 170 | import logging |
---|
[5ceb7d0] | 171 | |
---|
[7ae2b7f] | 172 | import numpy as np # type: ignore |
---|
[5ceb7d0] | 173 | |
---|
[6d6508e] | 174 | from .modelinfo import Parameter |
---|
[68e7f9d] | 175 | from .custom import load_custom_kernel_module |
---|
[fcd7bbd] | 176 | |
---|
[2d81cfe] | 177 | # pylint: disable=unused-import |
---|
[f619de7] | 178 | try: |
---|
[f2f67a6] | 179 | from typing import Tuple, Sequence, Iterator, Dict |
---|
[f619de7] | 180 | from .modelinfo import ModelInfo |
---|
| 181 | except ImportError: |
---|
| 182 | pass |
---|
[2d81cfe] | 183 | # pylint: enable=unused-import |
---|
[f619de7] | 184 | |
---|
[108e70e] | 185 | logger = logging.getLogger(__name__) |
---|
| 186 | |
---|
[4991048] | 187 | # jitter projection to use in the kernel code. See explore/jitter.py |
---|
| 188 | # for details. To change it from a program, set generate.PROJECTION. |
---|
| 189 | PROJECTION = 1 |
---|
| 190 | |
---|
[a5da1f2] | 191 | def get_data_path(external_dir, target_file): |
---|
[b297ba9] | 192 | """ |
---|
| 193 | Search for the target file relative in the installed application. |
---|
| 194 | |
---|
| 195 | Search first in the location of the generate module in case we are |
---|
| 196 | running directly from the distribution. Search next to the python |
---|
| 197 | executable for windows installs. Search in the ../Resources directory |
---|
| 198 | next to the executable for Mac OS/X installs. |
---|
| 199 | """ |
---|
[a5da1f2] | 200 | path = abspath(dirname(__file__)) |
---|
| 201 | if exists(joinpath(path, target_file)): |
---|
| 202 | return path |
---|
| 203 | |
---|
| 204 | # check next to exe/zip file |
---|
| 205 | exepath = dirname(sys.executable) |
---|
| 206 | path = joinpath(exepath, external_dir) |
---|
| 207 | if exists(joinpath(path, target_file)): |
---|
| 208 | return path |
---|
| 209 | |
---|
| 210 | # check in py2app Contents/Resources |
---|
| 211 | path = joinpath(exepath, '..', 'Resources', external_dir) |
---|
| 212 | if exists(joinpath(path, target_file)): |
---|
| 213 | return abspath(path) |
---|
| 214 | |
---|
| 215 | raise RuntimeError('Could not find '+joinpath(external_dir, target_file)) |
---|
| 216 | |
---|
| 217 | EXTERNAL_DIR = 'sasmodels-data' |
---|
[6cbdcd4] | 218 | DATA_PATH = get_data_path(EXTERNAL_DIR, 'kernel_iq.c') |
---|
[c2c51a2] | 219 | MODEL_PATH = joinpath(DATA_PATH, 'models') |
---|
[5ceb7d0] | 220 | |
---|
| 221 | F16 = np.dtype('float16') |
---|
| 222 | F32 = np.dtype('float32') |
---|
| 223 | F64 = np.dtype('float64') |
---|
| 224 | try: # CRUFT: older numpy does not support float128 |
---|
| 225 | F128 = np.dtype('float128') |
---|
| 226 | except TypeError: |
---|
| 227 | F128 = None |
---|
| 228 | |
---|
| 229 | # Conversion from units defined in the parameter table for each model |
---|
[30b60d2] | 230 | # to units displayed in the sphinx documentation. |
---|
[573ffab] | 231 | # This section associates the unit with the macro to use to produce the LaTex |
---|
| 232 | # code. The macro itself needs to be defined in sasmodels/doc/rst_prolog. |
---|
| 233 | # |
---|
| 234 | # NOTE: there is an RST_PROLOG at the end of this file which is NOT |
---|
[b297ba9] | 235 | # used for the bundled documentation. Still as long as we are defining the |
---|
| 236 | # macros in two places any new addition should define the macro in both places. |
---|
[5ceb7d0] | 237 | RST_UNITS = { |
---|
| 238 | "Ang": "|Ang|", |
---|
| 239 | "1/Ang": "|Ang^-1|", |
---|
| 240 | "1/Ang^2": "|Ang^-2|", |
---|
[462a115] | 241 | "Ang^3": "|Ang^3|", |
---|
[573ffab] | 242 | "Ang^2": "|Ang^2|", |
---|
[462a115] | 243 | "1e15/cm^3": "|1e15cm^3|", |
---|
| 244 | "Ang^3/mol": "|Ang^3|/mol", |
---|
[5ceb7d0] | 245 | "1e-6/Ang^2": "|1e-6Ang^-2|", |
---|
| 246 | "degrees": "degree", |
---|
| 247 | "1/cm": "|cm^-1|", |
---|
| 248 | "Ang/cm": "|Ang*cm^-1|", |
---|
[52ec91e] | 249 | "g/cm^3": "|g/cm^3|", |
---|
| 250 | "mg/m^2": "|mg/m^2|", |
---|
[5ceb7d0] | 251 | "": "None", |
---|
| 252 | } |
---|
| 253 | |
---|
| 254 | # Headers for the parameters tables in th sphinx documentation |
---|
| 255 | PARTABLE_HEADERS = [ |
---|
| 256 | "Parameter", |
---|
| 257 | "Description", |
---|
| 258 | "Units", |
---|
| 259 | "Default value", |
---|
| 260 | ] |
---|
| 261 | |
---|
| 262 | # Minimum width for a default value (this is shorter than the column header |
---|
| 263 | # width, so will be ignored). |
---|
| 264 | PARTABLE_VALUE_WIDTH = 10 |
---|
| 265 | |
---|
| 266 | # Documentation header for the module, giving the model name, its short |
---|
| 267 | # description and its parameter table. The remainder of the doc comes |
---|
| 268 | # from the module docstring. |
---|
| 269 | DOC_HEADER = """.. _%(id)s: |
---|
| 270 | |
---|
| 271 | %(name)s |
---|
| 272 | ======================================================= |
---|
| 273 | |
---|
| 274 | %(title)s |
---|
| 275 | |
---|
| 276 | %(parameters)s |
---|
| 277 | |
---|
| 278 | %(returns)s |
---|
| 279 | |
---|
| 280 | %(docs)s |
---|
| 281 | """ |
---|
| 282 | |
---|
[7891a2a] | 283 | |
---|
[ff31782] | 284 | def set_integration_size(info, n): |
---|
| 285 | # type: (ModelInfo, int) -> None |
---|
| 286 | """ |
---|
| 287 | Update the model definition, replacing the gaussian integration with |
---|
| 288 | a gaussian integration of a different size. |
---|
| 289 | |
---|
| 290 | Note: this really ought to be a method in modelinfo, but that leads to |
---|
| 291 | import loops. |
---|
| 292 | """ |
---|
[d86f0fc] | 293 | if info.source and any(lib.startswith('lib/gauss') for lib in info.source): |
---|
[ff31782] | 294 | from .gengauss import gengauss |
---|
[d86f0fc] | 295 | path = joinpath(MODEL_PATH, "lib", "gauss%d.c"%n) |
---|
| 296 | if not exists(path): |
---|
[ff31782] | 297 | gengauss(n, path) |
---|
| 298 | info.source = ["lib/gauss%d.c"%n if lib.startswith('lib/gauss') |
---|
[d86f0fc] | 299 | else lib for lib in info.source] |
---|
[ff31782] | 300 | |
---|
[5ceb7d0] | 301 | def format_units(units): |
---|
[f619de7] | 302 | # type: (str) -> str |
---|
[5ceb7d0] | 303 | """ |
---|
| 304 | Convert units into ReStructured Text format. |
---|
| 305 | """ |
---|
| 306 | return "string" if isinstance(units, list) else RST_UNITS.get(units, units) |
---|
| 307 | |
---|
[7891a2a] | 308 | |
---|
[5ceb7d0] | 309 | def make_partable(pars): |
---|
[f619de7] | 310 | # type: (List[Parameter]) -> str |
---|
[5ceb7d0] | 311 | """ |
---|
| 312 | Generate the parameter table to include in the sphinx documentation. |
---|
| 313 | """ |
---|
| 314 | column_widths = [ |
---|
[fcd7bbd] | 315 | max(len(p.name) for p in pars), |
---|
| 316 | max(len(p.description) for p in pars), |
---|
| 317 | max(len(format_units(p.units)) for p in pars), |
---|
[5ceb7d0] | 318 | PARTABLE_VALUE_WIDTH, |
---|
| 319 | ] |
---|
| 320 | column_widths = [max(w, len(h)) |
---|
| 321 | for w, h in zip(column_widths, PARTABLE_HEADERS)] |
---|
| 322 | |
---|
[d86f0fc] | 323 | underbar = " ".join("="*w for w in column_widths) |
---|
[5ceb7d0] | 324 | lines = [ |
---|
[d86f0fc] | 325 | underbar, |
---|
[5ceb7d0] | 326 | " ".join("%-*s" % (w, h) |
---|
| 327 | for w, h in zip(column_widths, PARTABLE_HEADERS)), |
---|
[d86f0fc] | 328 | underbar, |
---|
[5ceb7d0] | 329 | ] |
---|
| 330 | for p in pars: |
---|
| 331 | lines.append(" ".join([ |
---|
[fcd7bbd] | 332 | "%-*s" % (column_widths[0], p.name), |
---|
| 333 | "%-*s" % (column_widths[1], p.description), |
---|
| 334 | "%-*s" % (column_widths[2], format_units(p.units)), |
---|
| 335 | "%*g" % (column_widths[3], p.default), |
---|
[5ceb7d0] | 336 | ])) |
---|
[d86f0fc] | 337 | lines.append(underbar) |
---|
[5ceb7d0] | 338 | return "\n".join(lines) |
---|
| 339 | |
---|
[7891a2a] | 340 | |
---|
[5ceb7d0] | 341 | def _search(search_path, filename): |
---|
[f619de7] | 342 | # type: (List[str], str) -> str |
---|
[5ceb7d0] | 343 | """ |
---|
| 344 | Find *filename* in *search_path*. |
---|
| 345 | |
---|
| 346 | Raises ValueError if file does not exist. |
---|
| 347 | """ |
---|
| 348 | for path in search_path: |
---|
| 349 | target = joinpath(path, filename) |
---|
| 350 | if exists(target): |
---|
| 351 | return target |
---|
| 352 | raise ValueError("%r not found in %s" % (filename, search_path)) |
---|
| 353 | |
---|
[d5ac45f] | 354 | |
---|
[17bbadd] | 355 | def model_sources(model_info): |
---|
[f619de7] | 356 | # type: (ModelInfo) -> List[str] |
---|
[5ceb7d0] | 357 | """ |
---|
| 358 | Return a list of the sources file paths for the module. |
---|
| 359 | """ |
---|
[7891a2a] | 360 | search_path = [dirname(model_info.filename), MODEL_PATH] |
---|
[6d6508e] | 361 | return [_search(search_path, f) for f in model_info.source] |
---|
[5ceb7d0] | 362 | |
---|
| 363 | |
---|
[0dc34c3] | 364 | def dll_timestamp(model_info): |
---|
[f619de7] | 365 | # type: (ModelInfo) -> int |
---|
[69aa451] | 366 | """ |
---|
| 367 | Return a timestamp for the model corresponding to the most recently |
---|
| 368 | changed file or dependency. |
---|
| 369 | """ |
---|
[0dc34c3] | 370 | # TODO: fails DRY; templates appear two places. |
---|
| 371 | model_templates = [joinpath(DATA_PATH, filename) |
---|
| 372 | for filename in ('kernel_header.c', 'kernel_iq.c')] |
---|
[69aa451] | 373 | source_files = (model_sources(model_info) |
---|
[0dc34c3] | 374 | + model_templates |
---|
[6d6508e] | 375 | + [model_info.filename]) |
---|
[0dc34c3] | 376 | # Note: file may not exist when it is a standard model from library.zip |
---|
| 377 | times = [getmtime(f) for f in source_files if exists(f)] |
---|
| 378 | newest = max(times) if times else 0 |
---|
[69aa451] | 379 | return newest |
---|
| 380 | |
---|
[0dc34c3] | 381 | def ocl_timestamp(model_info): |
---|
| 382 | # type: (ModelInfo) -> int |
---|
| 383 | """ |
---|
| 384 | Return a timestamp for the model corresponding to the most recently |
---|
| 385 | changed file or dependency. |
---|
[7891a2a] | 386 | |
---|
[0dc34c3] | 387 | Note that this does not look at the time stamps for the OpenCL header |
---|
| 388 | information since that need not trigger a recompile of the DLL. |
---|
| 389 | """ |
---|
[f2f67a6] | 390 | # TODO: fails DRY; templates appear two places. |
---|
[0dc34c3] | 391 | model_templates = [joinpath(DATA_PATH, filename) |
---|
[6cbdcd4] | 392 | for filename in ('kernel_header.c', 'kernel_iq.c')] |
---|
[0dc34c3] | 393 | source_files = (model_sources(model_info) |
---|
| 394 | + model_templates |
---|
| 395 | + [model_info.filename]) |
---|
| 396 | # Note: file may not exist when it is a standard model from library.zip |
---|
| 397 | times = [getmtime(f) for f in source_files if exists(f)] |
---|
| 398 | newest = max(times) if times else 0 |
---|
| 399 | return newest |
---|
[f2f67a6] | 400 | |
---|
[7fcdc9f] | 401 | def tag_source(source): |
---|
| 402 | # type: (str) -> str |
---|
| 403 | """ |
---|
| 404 | Return a unique tag for the source code. |
---|
| 405 | """ |
---|
| 406 | # Note: need 0xffffffff&val to force an unsigned 32-bit number |
---|
[6773b02] | 407 | try: |
---|
| 408 | source = source.encode('utf8') |
---|
| 409 | except AttributeError: # bytes has no encode attribute in python 3 |
---|
| 410 | pass |
---|
[7fcdc9f] | 411 | return "%08X"%(0xffffffff&crc32(source)) |
---|
[5ceb7d0] | 412 | |
---|
| 413 | def convert_type(source, dtype): |
---|
[f619de7] | 414 | # type: (str, np.dtype) -> str |
---|
[5ceb7d0] | 415 | """ |
---|
| 416 | Convert code from double precision to the desired type. |
---|
| 417 | |
---|
| 418 | Floating point constants are tagged with 'f' for single precision or 'L' |
---|
| 419 | for long double precision. |
---|
| 420 | """ |
---|
[2e49f9e] | 421 | source = _fix_tgmath_int(source) |
---|
[5ceb7d0] | 422 | if dtype == F16: |
---|
| 423 | fbytes = 2 |
---|
[1e2a1ba] | 424 | source = _convert_type(source, "half", "f") |
---|
[5ceb7d0] | 425 | elif dtype == F32: |
---|
| 426 | fbytes = 4 |
---|
| 427 | source = _convert_type(source, "float", "f") |
---|
| 428 | elif dtype == F64: |
---|
| 429 | fbytes = 8 |
---|
[d5ac45f] | 430 | # no need to convert if it is already double |
---|
[5ceb7d0] | 431 | elif dtype == F128: |
---|
| 432 | fbytes = 16 |
---|
| 433 | source = _convert_type(source, "long double", "L") |
---|
| 434 | else: |
---|
[7891a2a] | 435 | raise ValueError("Unexpected dtype in source conversion: %s" % dtype) |
---|
| 436 | return ("#define FLOAT_SIZE %d\n" % fbytes)+source |
---|
[5ceb7d0] | 437 | |
---|
| 438 | |
---|
| 439 | def _convert_type(source, type_name, constant_flag): |
---|
[f619de7] | 440 | # type: (str, str, str) -> str |
---|
[5ceb7d0] | 441 | """ |
---|
| 442 | Replace 'double' with *type_name* in *source*, tagging floating point |
---|
| 443 | constants with *constant_flag*. |
---|
| 444 | """ |
---|
| 445 | # Convert double keyword to float/long double/half. |
---|
| 446 | # Accept an 'n' # parameter for vector # values, where n is 2, 4, 8 or 16. |
---|
| 447 | # Assume complex numbers are represented as cdouble which is typedef'd |
---|
| 448 | # to double2. |
---|
| 449 | source = re.sub(r'(^|[^a-zA-Z0-9_]c?)double(([248]|16)?($|[^a-zA-Z0-9_]))', |
---|
| 450 | r'\1%s\2'%type_name, source) |
---|
[2e49f9e] | 451 | source = _tag_float(source, constant_flag) |
---|
| 452 | return source |
---|
| 453 | |
---|
| 454 | TGMATH_INT_RE = re.compile(r""" |
---|
| 455 | (?: # Non-capturing match; not lookbehind since pattern length is variable |
---|
| 456 | \b # word boundary |
---|
| 457 | # various math functions |
---|
| 458 | (a?(sin|cos|tan)h? | atan2 |
---|
| 459 | | erfc? | tgamma |
---|
| 460 | | exp(2|10|m1)? | log(2|10|1p)? | pow[nr]? | sqrt | rsqrt | rootn |
---|
| 461 | | fabs | fmax | fmin |
---|
| 462 | ) |
---|
| 463 | \s*[(]\s* # open parenthesis |
---|
| 464 | ) |
---|
| 465 | [+-]?(0|[1-9]\d*) # integer |
---|
| 466 | (?= # lookahead match: don't want to move from end of int |
---|
| 467 | \s*[,)] # comma or close parenthesis for end of argument |
---|
| 468 | ) # end lookahead |
---|
| 469 | """, re.VERBOSE) |
---|
| 470 | def _fix_tgmath_int(source): |
---|
| 471 | # type: (str) -> str |
---|
| 472 | """ |
---|
| 473 | Replace f(integer) with f(integer.) for sin, cos, pow, etc. |
---|
| 474 | |
---|
| 475 | OS X OpenCL complains that it can't resolve the type generic calls to |
---|
| 476 | the standard math functions when they are called with integer constants, |
---|
| 477 | but this does not happen with the Windows Intel driver for example. |
---|
| 478 | To avoid confusion on the matrix marketplace, automatically promote |
---|
| 479 | integers to floats if we recognize them in the source. |
---|
| 480 | |
---|
| 481 | The specific functions we look for are: |
---|
| 482 | |
---|
| 483 | trigonometric: sin, asin, sinh, asinh, etc., and atan2 |
---|
| 484 | exponential: exp, exp2, exp10, expm1, log, log2, log10, logp1 |
---|
| 485 | power: pow, pown, powr, sqrt, rsqrt, rootn |
---|
| 486 | special: erf, erfc, tgamma |
---|
| 487 | float: fabs, fmin, fmax |
---|
| 488 | |
---|
| 489 | Note that we don't convert the second argument of dual argument |
---|
| 490 | functions: atan2, fmax, fmin, pow, powr. This could potentially |
---|
| 491 | be a problem for pow(x, 2), but that case seems to work without change. |
---|
| 492 | """ |
---|
| 493 | out = TGMATH_INT_RE.sub(r'\g<0>.', source) |
---|
| 494 | return out |
---|
| 495 | |
---|
| 496 | |
---|
| 497 | # Floating point regular expression |
---|
| 498 | # |
---|
| 499 | # Define parts: |
---|
| 500 | # |
---|
| 501 | # E = [eE][+-]?\d+ : Exponent |
---|
| 502 | # P = [.] : Decimal separator |
---|
| 503 | # N = [1-9]\d* : Natural number, no leading zeros |
---|
| 504 | # Z = 0 : Zero |
---|
| 505 | # F = \d+ : Fractional number, maybe leading zeros |
---|
| 506 | # F? = \d* : Optional fractional number |
---|
| 507 | # |
---|
| 508 | # We want to reject bare natural numbers and bare decimal points, so we |
---|
| 509 | # need to tediously outline the cases where we have either a fraction or |
---|
| 510 | # an exponent: |
---|
| 511 | # |
---|
| 512 | # ( ZP | ZPF | ZE | ZPE | ZPFE | NP | NPF | NE | NPE | NPFE | PF | PFE ) |
---|
| 513 | # |
---|
| 514 | # |
---|
| 515 | # We can then join cases by making parts optional. The following are |
---|
| 516 | # some ways to do this: |
---|
| 517 | # |
---|
| 518 | # ( (Z|N)(P|PF|E|PE|PFE) | PFE? ) # Split on lead |
---|
| 519 | # => ( (Z|N)(PF?|(PF?)?E) | PFE? ) |
---|
| 520 | # ( ((Z|N)PF?|PF)E? | (Z|N)E) # Split on point |
---|
| 521 | # ( (ZP|ZPF|NP|NPF|PF) | (Z|ZP|ZPF|N|NP|NPF|PF)E ) # Split on E |
---|
| 522 | # => ( ((Z|N)PF?|PF) | ((Z|N)(PF?)? | PF) E ) |
---|
| 523 | FLOAT_RE = re.compile(r""" |
---|
| 524 | (?<!\w) # use negative lookbehind since '.' confuses \b test |
---|
| 525 | # use split on lead to match float ( (Z|N)(PF?|(PF?)?E) | PFE? ) |
---|
| 526 | ( ( 0 | [1-9]\d* ) # ( ( Z | N ) |
---|
| 527 | ([.]\d* | ([.]\d*)? [eE][+-]?\d+ ) # (PF? | (PF?)? E ) |
---|
| 528 | | [.]\d+ ([eE][+-]?\d+)? # | PF (E)? |
---|
| 529 | ) # ) |
---|
| 530 | (?!\w) # use negative lookahead since '.' confuses \b test |
---|
| 531 | """, re.VERBOSE) |
---|
| 532 | def _tag_float(source, constant_flag): |
---|
[5ceb7d0] | 533 | # Convert floating point constants to single by adding 'f' to the end, |
---|
| 534 | # or long double with an 'L' suffix. OS/X complains if you don't do this. |
---|
[2e49f9e] | 535 | out = FLOAT_RE.sub(r'\g<0>%s'%constant_flag, source) |
---|
| 536 | #print("in",repr(source),"out",repr(out), constant_flag) |
---|
| 537 | return out |
---|
| 538 | |
---|
| 539 | def test_tag_float(): |
---|
[b297ba9] | 540 | """Check that floating point constants are identified and tagged with 'f'""" |
---|
[2e49f9e] | 541 | |
---|
[bb4b509] | 542 | cases = """ |
---|
[2e49f9e] | 543 | ZP : 0. |
---|
| 544 | ZPF : 0.0,0.01,0.1 |
---|
| 545 | Z E: 0e+001 |
---|
| 546 | ZP E: 0.E0 |
---|
| 547 | ZPFE: 0.13e-031 |
---|
| 548 | NP : 1., 12. |
---|
| 549 | NPF : 1.0001, 1.1, 1.0 |
---|
| 550 | N E: 1e0, 37E-080 |
---|
| 551 | NP E: 1.e0, 37.E-080 |
---|
| 552 | NPFE: 845.017e+22 |
---|
| 553 | PF : .1, .0, .0100 |
---|
| 554 | PFE: .6e+9, .82E-004 |
---|
| 555 | # isolated cases |
---|
| 556 | 0. |
---|
| 557 | 1e0 |
---|
| 558 | 0.13e-013 |
---|
| 559 | # untouched |
---|
| 560 | struct3.e3, 03.05.67, 37 |
---|
| 561 | # expressions |
---|
| 562 | 3.75+-1.6e-7-27+13.2 |
---|
| 563 | a3.e2 - 0. |
---|
| 564 | 4*atan(1) |
---|
| 565 | 4.*atan(1.) |
---|
| 566 | """ |
---|
| 567 | |
---|
[bb4b509] | 568 | output = """ |
---|
[2e49f9e] | 569 | ZP : 0.f |
---|
| 570 | ZPF : 0.0f,0.01f,0.1f |
---|
| 571 | Z E: 0e+001f |
---|
| 572 | ZP E: 0.E0f |
---|
| 573 | ZPFE: 0.13e-031f |
---|
| 574 | NP : 1.f, 12.f |
---|
| 575 | NPF : 1.0001f, 1.1f, 1.0f |
---|
| 576 | N E: 1e0f, 37E-080f |
---|
| 577 | NP E: 1.e0f, 37.E-080f |
---|
| 578 | NPFE: 845.017e+22f |
---|
| 579 | PF : .1f, .0f, .0100f |
---|
| 580 | PFE: .6e+9f, .82E-004f |
---|
| 581 | # isolated cases |
---|
| 582 | 0.f |
---|
| 583 | 1e0f |
---|
| 584 | 0.13e-013f |
---|
| 585 | # untouched |
---|
| 586 | struct3.e3, 03.05.67, 37 |
---|
| 587 | # expressions |
---|
| 588 | 3.75f+-1.6e-7f-27+13.2f |
---|
| 589 | a3.e2 - 0.f |
---|
| 590 | 4*atan(1) |
---|
| 591 | 4.f*atan(1.f) |
---|
| 592 | """ |
---|
| 593 | |
---|
| 594 | for case_in, case_out in zip(cases.split('\n'), output.split('\n')): |
---|
| 595 | out = _tag_float(case_in, 'f') |
---|
| 596 | assert case_out == out, "%r => %r"%(case_in, out) |
---|
[5ceb7d0] | 597 | |
---|
| 598 | |
---|
[32e3c9b] | 599 | def kernel_name(model_info, variant): |
---|
| 600 | # type: (ModelInfo, str) -> str |
---|
[5ceb7d0] | 601 | """ |
---|
| 602 | Name of the exported kernel symbol. |
---|
[32e3c9b] | 603 | |
---|
| 604 | *variant* is "Iq", "Iqxy" or "Imagnetic". |
---|
[5ceb7d0] | 605 | """ |
---|
[32e3c9b] | 606 | return model_info.name + "_" + variant |
---|
[5ceb7d0] | 607 | |
---|
| 608 | |
---|
| 609 | def indent(s, depth): |
---|
[f619de7] | 610 | # type: (str, int) -> str |
---|
[5ceb7d0] | 611 | """ |
---|
| 612 | Indent a string of text with *depth* additional spaces on each line. |
---|
| 613 | """ |
---|
| 614 | spaces = " "*depth |
---|
[d86f0fc] | 615 | interline_separator = "\n" + spaces |
---|
| 616 | return spaces + interline_separator.join(s.split("\n")) |
---|
[5ceb7d0] | 617 | |
---|
| 618 | |
---|
[f619de7] | 619 | _template_cache = {} # type: Dict[str, Tuple[int, str, str]] |
---|
[d5ac45f] | 620 | def load_template(filename): |
---|
[f619de7] | 621 | # type: (str) -> str |
---|
[d86f0fc] | 622 | """ |
---|
| 623 | Load template file from sasmodels resource directory. |
---|
| 624 | """ |
---|
[7891a2a] | 625 | path = joinpath(DATA_PATH, filename) |
---|
[d5ac45f] | 626 | mtime = getmtime(path) |
---|
| 627 | if filename not in _template_cache or mtime > _template_cache[filename][0]: |
---|
| 628 | with open(path) as fid: |
---|
[303d8d6] | 629 | _template_cache[filename] = (mtime, fid.read(), path) |
---|
[da63656] | 630 | return _template_cache[filename][1], path |
---|
[d5ac45f] | 631 | |
---|
[303d8d6] | 632 | |
---|
[03cac08] | 633 | _FN_TEMPLATE = """\ |
---|
| 634 | double %(name)s(%(pars)s); |
---|
| 635 | double %(name)s(%(pars)s) { |
---|
[da63656] | 636 | #line %(line)d "%(filename)s" |
---|
[03cac08] | 637 | %(body)s |
---|
| 638 | } |
---|
| 639 | |
---|
| 640 | """ |
---|
[108e70e] | 641 | def _gen_fn(model_info, name, pars): |
---|
| 642 | # type: (ModelInfo, str, List[Parameter]) -> str |
---|
[5ceb7d0] | 643 | """ |
---|
[d5ac45f] | 644 | Generate a function given pars and body. |
---|
| 645 | |
---|
| 646 | Returns the following string:: |
---|
[5ceb7d0] | 647 | |
---|
[d5ac45f] | 648 | double fn(double a, double b, ...); |
---|
| 649 | double fn(double a, double b, ...) { |
---|
| 650 | .... |
---|
| 651 | } |
---|
[5ceb7d0] | 652 | """ |
---|
[60eab2a] | 653 | par_decl = ', '.join(p.as_function_argument() for p in pars) if pars else 'void' |
---|
[108e70e] | 654 | body = getattr(model_info, name) |
---|
| 655 | filename = model_info.filename |
---|
| 656 | # Note: if symbol is defined strangely in the module then default it to 1 |
---|
| 657 | lineno = model_info.lineno.get(name, 1) |
---|
[da63656] | 658 | return _FN_TEMPLATE % { |
---|
| 659 | 'name': name, 'pars': par_decl, 'body': body, |
---|
[108e70e] | 660 | 'filename': filename.replace('\\', '\\\\'), 'line': lineno, |
---|
[da63656] | 661 | } |
---|
[d5ac45f] | 662 | |
---|
[17bbadd] | 663 | |
---|
[03cac08] | 664 | def _call_pars(prefix, pars): |
---|
[f619de7] | 665 | # type: (str, List[Parameter]) -> List[str] |
---|
[03cac08] | 666 | """ |
---|
[bb4b509] | 667 | Return a list of *prefix+parameter* from parameter items. |
---|
| 668 | |
---|
| 669 | *prefix* should be "v." if v is a struct. |
---|
[03cac08] | 670 | """ |
---|
[69aa451] | 671 | return [p.as_call_reference(prefix) for p in pars] |
---|
[d5ac45f] | 672 | |
---|
[17bbadd] | 673 | |
---|
[01c8d9e] | 674 | _IQXY_PATTERN = re.compile(r"(^|\s)double\s+I(?P<mode>q(ac|abc|xy))\s*[(]", |
---|
[03cac08] | 675 | flags=re.MULTILINE) |
---|
[108e70e] | 676 | def find_xy_mode(source): |
---|
[f619de7] | 677 | # type: (List[str]) -> bool |
---|
[03cac08] | 678 | """ |
---|
[108e70e] | 679 | Return the xy mode as qa, qac, qabc or qxy. |
---|
[d5ac45f] | 680 | |
---|
[03cac08] | 681 | Note this is not a C parser, and so can be easily confused by |
---|
| 682 | non-standard syntax. Also, it will incorrectly identify the following |
---|
[108e70e] | 683 | as having 2D models:: |
---|
[03cac08] | 684 | |
---|
| 685 | /* |
---|
[108e70e] | 686 | double Iqac(qab, qc, ...) { ... fill this in later ... } |
---|
| 687 | */ |
---|
| 688 | |
---|
| 689 | If you want to comment out the function, use // on the front of the |
---|
| 690 | line:: |
---|
| 691 | |
---|
| 692 | /* |
---|
| 693 | // double Iqac(qab, qc, ...) { ... fill this in later ... } |
---|
[03cac08] | 694 | */ |
---|
| 695 | |
---|
| 696 | """ |
---|
[108e70e] | 697 | for code in source: |
---|
| 698 | m = _IQXY_PATTERN.search(code) |
---|
| 699 | if m is not None: |
---|
| 700 | return m.group('mode') |
---|
| 701 | return 'qa' |
---|
[d5ac45f] | 702 | |
---|
[c036ddb] | 703 | # Note: not presently used. Need to know whether Fq is available before |
---|
| 704 | # trying to compile the source. Leave the code here in case we decide that |
---|
| 705 | # define have_Fq for each form factor is too tedious and error prone. |
---|
[01c8d9e] | 706 | _FQ_PATTERN = re.compile(r"(^|\s)void\s+Fq[(]", flags=re.MULTILINE) |
---|
[c036ddb] | 707 | def contains_Fq(source): |
---|
| 708 | # type: (List[str]) -> bool |
---|
| 709 | """ |
---|
| 710 | Return True if C source defines "void Fq(". |
---|
| 711 | """ |
---|
[01c8d9e] | 712 | for code in source: |
---|
[cd28947] | 713 | if _FQ_PATTERN.search(code) is not None: |
---|
[01c8d9e] | 714 | return True |
---|
| 715 | return False |
---|
[17bbadd] | 716 | |
---|
[b297ba9] | 717 | _SHELL_VOLUME_PATTERN = re.compile(r"(^|\s)double\s+shell_volume[(]", |
---|
| 718 | flags=re.MULTILINE) |
---|
[e44432d] | 719 | def contains_shell_volume(source): |
---|
| 720 | # type: (List[str]) -> bool |
---|
| 721 | """ |
---|
[cd28947] | 722 | Return True if C source defines "double shell_volume(". |
---|
[e44432d] | 723 | """ |
---|
| 724 | for code in source: |
---|
[cd28947] | 725 | if _SHELL_VOLUME_PATTERN.search(code) is not None: |
---|
[e44432d] | 726 | return True |
---|
| 727 | return False |
---|
| 728 | |
---|
[108e70e] | 729 | def _add_source(source, code, path, lineno=1): |
---|
[da63656] | 730 | """ |
---|
| 731 | Add a file to the list of source code chunks, tagged with path and line. |
---|
| 732 | """ |
---|
[7891a2a] | 733 | path = path.replace('\\', '\\\\') |
---|
[108e70e] | 734 | source.append('#line %d "%s"' % (lineno, path)) |
---|
[da63656] | 735 | source.append(code) |
---|
[5ceb7d0] | 736 | |
---|
[17bbadd] | 737 | def make_source(model_info): |
---|
[a4280bd] | 738 | # type: (ModelInfo) -> Dict[str, str] |
---|
[5ceb7d0] | 739 | """ |
---|
[17bbadd] | 740 | Generate the OpenCL/ctypes kernel from the module info. |
---|
| 741 | |
---|
[f619de7] | 742 | Uses source files found in the given search path. Returns None if this |
---|
| 743 | is a pure python model, with no C source components. |
---|
[5ceb7d0] | 744 | """ |
---|
[6d6508e] | 745 | if callable(model_info.Iq): |
---|
[739aad4] | 746 | raise ValueError("can't compile python model") |
---|
| 747 | #return None |
---|
[17bbadd] | 748 | |
---|
[5ceb7d0] | 749 | # TODO: need something other than volume to indicate dispersion parameters |
---|
| 750 | # No volume normalization despite having a volume parameter. |
---|
| 751 | # Thickness is labelled a volume in order to trigger polydispersity. |
---|
| 752 | # May want a separate dispersion flag, or perhaps a separate category for |
---|
| 753 | # disperse, but not volume. Volume parameters also use relative values |
---|
| 754 | # for the distribution rather than the absolute values used by angular |
---|
| 755 | # dispersion. Need to be careful that necessary parameters are available |
---|
| 756 | # for computing volume even if we allow non-disperse volume parameters. |
---|
[6d6508e] | 757 | partable = model_info.parameters |
---|
[c036ddb] | 758 | |
---|
[03cac08] | 759 | # Load templates and user code |
---|
| 760 | kernel_header = load_template('kernel_header.c') |
---|
[9ee2756] | 761 | kernel_code = load_template('kernel_iq.c') |
---|
[da63656] | 762 | user_code = [(f, open(f).read()) for f in model_sources(model_info)] |
---|
[c036ddb] | 763 | |
---|
[03cac08] | 764 | # Build initial sources |
---|
[da63656] | 765 | source = [] |
---|
| 766 | _add_source(source, *kernel_header) |
---|
| 767 | for path, code in user_code: |
---|
| 768 | _add_source(source, code, path) |
---|
[108e70e] | 769 | if model_info.c_code: |
---|
| 770 | _add_source(source, model_info.c_code, model_info.filename, |
---|
| 771 | lineno=model_info.lineno.get('c_code', 1)) |
---|
| 772 | |
---|
[69aa451] | 773 | # Make parameters for q, qx, qy so that we can use them in declarations |
---|
[108e70e] | 774 | q, qx, qy, qab, qa, qb, qc \ |
---|
| 775 | = [Parameter(name=v) for v in 'q qx qy qab qa qb qc'.split()] |
---|
[c036ddb] | 776 | |
---|
[d5ac45f] | 777 | # Generate form_volume function, etc. from body only |
---|
[f619de7] | 778 | if isinstance(model_info.form_volume, str): |
---|
[d19962c] | 779 | pars = partable.form_volume_parameters |
---|
[108e70e] | 780 | source.append(_gen_fn(model_info, 'form_volume', pars)) |
---|
[e44432d] | 781 | if isinstance(model_info.shell_volume, str): |
---|
| 782 | pars = partable.form_volume_parameters |
---|
| 783 | source.append(_gen_fn(model_info, 'shell_volume', pars)) |
---|
[f619de7] | 784 | if isinstance(model_info.Iq, str): |
---|
[d19962c] | 785 | pars = [q] + partable.iq_parameters |
---|
[108e70e] | 786 | source.append(_gen_fn(model_info, 'Iq', pars)) |
---|
[f619de7] | 787 | if isinstance(model_info.Iqxy, str): |
---|
[108e70e] | 788 | pars = [qx, qy] + partable.iq_parameters + partable.orientation_parameters |
---|
| 789 | source.append(_gen_fn(model_info, 'Iqxy', pars)) |
---|
| 790 | if isinstance(model_info.Iqac, str): |
---|
| 791 | pars = [qab, qc] + partable.iq_parameters |
---|
| 792 | source.append(_gen_fn(model_info, 'Iqac', pars)) |
---|
| 793 | if isinstance(model_info.Iqabc, str): |
---|
| 794 | pars = [qa, qb, qc] + partable.iq_parameters |
---|
| 795 | source.append(_gen_fn(model_info, 'Iqabc', pars)) |
---|
| 796 | |
---|
[e44432d] | 797 | # Check for shell_volume in source |
---|
| 798 | is_hollow = contains_shell_volume(source) |
---|
| 799 | |
---|
[108e70e] | 800 | # What kind of 2D model do we need? Is it consistent with the parameters? |
---|
| 801 | xy_mode = find_xy_mode(source) |
---|
| 802 | if xy_mode == 'qabc' and not partable.is_asymmetric: |
---|
| 803 | raise ValueError("asymmetric oriented models need to define Iqabc") |
---|
| 804 | elif xy_mode == 'qac' and partable.is_asymmetric: |
---|
| 805 | raise ValueError("symmetric oriented models need to define Iqac") |
---|
| 806 | elif not partable.orientation_parameters and xy_mode in ('qac', 'qabc'): |
---|
| 807 | raise ValueError("Unexpected function I%s for unoriented shape"%xy_mode) |
---|
| 808 | elif partable.orientation_parameters and xy_mode not in ('qac', 'qabc'): |
---|
| 809 | if xy_mode == 'qxy': |
---|
| 810 | logger.warn("oriented shapes should define Iqac or Iqabc") |
---|
| 811 | else: |
---|
[b297ba9] | 812 | raise ValueError("Expected Iqac or Iqabc for oriented shape") |
---|
[d5ac45f] | 813 | |
---|
[03cac08] | 814 | # Define the parameter table |
---|
[9ee2756] | 815 | lineno = getframeinfo(currentframe()).lineno + 2 |
---|
| 816 | source.append('#line %d "sasmodels/generate.py"'%lineno) |
---|
| 817 | #source.append('introduce breakage in generate to test lineno reporting') |
---|
[03cac08] | 818 | source.append("#define PARAMETER_TABLE \\") |
---|
[69aa451] | 819 | source.append("\\\n".join(p.as_definition() |
---|
[d19962c] | 820 | for p in partable.kernel_parameters)) |
---|
[03cac08] | 821 | # Define the function calls |
---|
[a34b811] | 822 | call_radius_effective = "#define CALL_RADIUS_EFFECTIVE(_mode, _v) 0.0" |
---|
[d19962c] | 823 | if partable.form_volume_parameters: |
---|
[d2bb604] | 824 | refs = _call_pars("_v.", partable.form_volume_parameters) |
---|
[e44432d] | 825 | if is_hollow: |
---|
[b297ba9] | 826 | call_volume = ( |
---|
| 827 | "#define CALL_VOLUME(_form, _shell, _v) " |
---|
| 828 | "do { _form = form_volume(%s); _shell = shell_volume(%s); } " |
---|
| 829 | "while (0)") % ((",".join(refs),)*2) |
---|
[e44432d] | 830 | else: |
---|
[b297ba9] | 831 | call_volume = ( |
---|
| 832 | "#define CALL_VOLUME(_form, _shell, _v) " |
---|
| 833 | "do { _form = _shell = form_volume(%s); } " |
---|
| 834 | "while (0)") % (",".join(refs)) |
---|
[a34b811] | 835 | if model_info.radius_effective_modes: |
---|
| 836 | call_radius_effective = ( |
---|
| 837 | "#define CALL_RADIUS_EFFECTIVE(_mode, _v) " |
---|
| 838 | "radius_effective(_mode, %s)") % (",".join(refs)) |
---|
[d5ac45f] | 839 | else: |
---|
| 840 | # Model doesn't have volume. We could make the kernel run a little |
---|
| 841 | # faster by not using/transferring the volume normalizations, but |
---|
| 842 | # the ifdef's reduce readability more than is worthwhile. |
---|
[b297ba9] | 843 | call_volume = ( |
---|
| 844 | "#define CALL_VOLUME(_form, _shell, _v) " |
---|
| 845 | "do { _form = _shell = 1.0; } while (0)") |
---|
[03cac08] | 846 | source.append(call_volume) |
---|
[a34b811] | 847 | source.append(call_radius_effective) |
---|
[8698a0d] | 848 | model_refs = _call_pars("_v.", partable.iq_parameters) |
---|
[c036ddb] | 849 | |
---|
| 850 | if model_info.have_Fq: |
---|
| 851 | pars = ",".join(["_q", "&_F1", "&_F2",] + model_refs) |
---|
| 852 | call_iq = "#define CALL_FQ(_q, _F1, _F2, _v) Fq(%s)" % pars |
---|
| 853 | clear_iq = "#undef CALL_FQ" |
---|
| 854 | else: |
---|
[01c8d9e] | 855 | pars = ",".join(["_q"] + model_refs) |
---|
| 856 | call_iq = "#define CALL_IQ(_q, _v) Iq(%s)" % pars |
---|
[c036ddb] | 857 | clear_iq = "#undef CALL_IQ" |
---|
[9ee2756] | 858 | if xy_mode == 'qabc': |
---|
| 859 | pars = ",".join(["_qa", "_qb", "_qc"] + model_refs) |
---|
[108e70e] | 860 | call_iqxy = "#define CALL_IQ_ABC(_qa,_qb,_qc,_v) Iqabc(%s)" % pars |
---|
[9ee2756] | 861 | clear_iqxy = "#undef CALL_IQ_ABC" |
---|
| 862 | elif xy_mode == 'qac': |
---|
| 863 | pars = ",".join(["_qa", "_qc"] + model_refs) |
---|
[108e70e] | 864 | call_iqxy = "#define CALL_IQ_AC(_qa,_qc,_v) Iqac(%s)" % pars |
---|
[9ee2756] | 865 | clear_iqxy = "#undef CALL_IQ_AC" |
---|
[c036ddb] | 866 | elif xy_mode == 'qa' and not model_info.have_Fq: |
---|
[8698a0d] | 867 | pars = ",".join(["_qa"] + model_refs) |
---|
| 868 | call_iqxy = "#define CALL_IQ_A(_qa,_v) Iq(%s)" % pars |
---|
| 869 | clear_iqxy = "#undef CALL_IQ_A" |
---|
[c036ddb] | 870 | elif xy_mode == 'qa' and model_info.have_Fq: |
---|
| 871 | pars = ",".join(["_qa", "&_F1", "&_F2",] + model_refs) |
---|
| 872 | # Note: uses rare C construction (expr1, expr2) which computes |
---|
| 873 | # expr1 then expr2 and evaluates to expr2. This allows us to |
---|
| 874 | # leave it looking like a function even though it is returning |
---|
| 875 | # its values by reference. |
---|
| 876 | call_iqxy = "#define CALL_FQ_A(_qa,_F1,_F2,_v) (Fq(%s),_F2)" % pars |
---|
| 877 | clear_iqxy = "#undef CALL_FQ_A" |
---|
[108e70e] | 878 | elif xy_mode == 'qxy': |
---|
| 879 | orientation_refs = _call_pars("_v.", partable.orientation_parameters) |
---|
| 880 | pars = ",".join(["_qx", "_qy"] + model_refs + orientation_refs) |
---|
| 881 | call_iqxy = "#define CALL_IQ_XY(_qx,_qy,_v) Iqxy(%s)" % pars |
---|
| 882 | clear_iqxy = "#undef CALL_IQ_XY" |
---|
| 883 | if partable.orientation_parameters: |
---|
| 884 | call_iqxy += "\n#define HAVE_THETA" |
---|
| 885 | clear_iqxy += "\n#undef HAVE_THETA" |
---|
| 886 | if partable.is_asymmetric: |
---|
| 887 | call_iqxy += "\n#define HAVE_PSI" |
---|
| 888 | clear_iqxy += "\n#undef HAVE_PSI" |
---|
| 889 | |
---|
[03cac08] | 890 | |
---|
[bb4b509] | 891 | magpars = [k-2 for k, p in enumerate(partable.call_parameters) |
---|
[32e3c9b] | 892 | if p.type == 'sld'] |
---|
[03cac08] | 893 | # Fill in definitions for numbers of parameters |
---|
[d19962c] | 894 | source.append("#define MAX_PD %s"%partable.max_pd) |
---|
[a4280bd] | 895 | source.append("#define NUM_PARS %d"%partable.npars) |
---|
[9eb3632] | 896 | source.append("#define NUM_VALUES %d" % partable.nvalues) |
---|
[a4280bd] | 897 | source.append("#define NUM_MAGNETIC %d" % partable.nmagnetic) |
---|
[32e3c9b] | 898 | source.append("#define MAGNETIC_PARS %s"%",".join(str(k) for k in magpars)) |
---|
[4991048] | 899 | source.append("#define PROJECTION %d"%PROJECTION) |
---|
[b297ba9] | 900 | wrappers = _kernels(kernel_code, call_iq, clear_iq, |
---|
| 901 | call_iqxy, clear_iqxy, model_info.name) |
---|
| 902 | code = '\n'.join(source + wrappers[0] + wrappers[1] + wrappers[2]) |
---|
[01c8d9e] | 903 | |
---|
[b297ba9] | 904 | # Note: Identical code for dll and opencl. This may not always be the case |
---|
| 905 | # so leave them as separate entries in the returned value. |
---|
| 906 | result = {'dll': code, 'opencl': code} |
---|
[a4280bd] | 907 | return result |
---|
[5ceb7d0] | 908 | |
---|
[7891a2a] | 909 | |
---|
[c036ddb] | 910 | def _kernels(kernel, call_iq, clear_iq, call_iqxy, clear_iqxy, name): |
---|
[b966a96] | 911 | # type: ([str,str], str, str, str) -> List[str] |
---|
| 912 | code = kernel[0] |
---|
| 913 | path = kernel[1].replace('\\', '\\\\') |
---|
[9eb3632] | 914 | iq = [ |
---|
[f2f67a6] | 915 | # define the Iq kernel |
---|
[32e3c9b] | 916 | "#define KERNEL_NAME %s_Iq" % name, |
---|
[f2f67a6] | 917 | call_iq, |
---|
[a4280bd] | 918 | '#line 1 "%s Iq"' % path, |
---|
[b966a96] | 919 | code, |
---|
[c036ddb] | 920 | clear_iq, |
---|
[f2f67a6] | 921 | "#undef KERNEL_NAME", |
---|
[9eb3632] | 922 | ] |
---|
[f2f67a6] | 923 | |
---|
[9eb3632] | 924 | iqxy = [ |
---|
[f2f67a6] | 925 | # define the Iqxy kernel from the same source with different #defines |
---|
[32e3c9b] | 926 | "#define KERNEL_NAME %s_Iqxy" % name, |
---|
[f2f67a6] | 927 | call_iqxy, |
---|
[a4280bd] | 928 | '#line 1 "%s Iqxy"' % path, |
---|
[b966a96] | 929 | code, |
---|
[8698a0d] | 930 | clear_iqxy, |
---|
[32e3c9b] | 931 | "#undef KERNEL_NAME", |
---|
[bb4b509] | 932 | ] |
---|
[32e3c9b] | 933 | |
---|
[9eb3632] | 934 | imagnetic = [ |
---|
[32e3c9b] | 935 | # define the Imagnetic kernel |
---|
| 936 | "#define KERNEL_NAME %s_Imagnetic" % name, |
---|
| 937 | "#define MAGNETIC 1", |
---|
[f2f67a6] | 938 | call_iqxy, |
---|
[a4280bd] | 939 | '#line 1 "%s Imagnetic"' % path, |
---|
[b966a96] | 940 | code, |
---|
[8698a0d] | 941 | clear_iqxy, |
---|
[32e3c9b] | 942 | "#undef MAGNETIC", |
---|
[f2f67a6] | 943 | "#undef KERNEL_NAME", |
---|
| 944 | ] |
---|
[a4280bd] | 945 | |
---|
| 946 | return iq, iqxy, imagnetic |
---|
[f2f67a6] | 947 | |
---|
[4d76711] | 948 | |
---|
[68e7f9d] | 949 | def load_kernel_module(model_name): |
---|
[f619de7] | 950 | # type: (str) -> module |
---|
[f2f67a6] | 951 | """ |
---|
| 952 | Return the kernel module named in *model_name*. |
---|
| 953 | |
---|
| 954 | If the name ends in *.py* then load it as a custom model using |
---|
| 955 | :func:`sasmodels.custom.load_custom_kernel_module`, otherwise |
---|
| 956 | load it from :mod:`sasmodels.models`. |
---|
| 957 | """ |
---|
[68e7f9d] | 958 | if model_name.endswith('.py'): |
---|
| 959 | kernel_module = load_custom_kernel_module(model_name) |
---|
| 960 | else: |
---|
[a22d104] | 961 | try: |
---|
| 962 | from sasmodels import models |
---|
| 963 | __import__('sasmodels.models.'+model_name) |
---|
| 964 | kernel_module = getattr(models, model_name, None) |
---|
[2f733b1] | 965 | except ImportError: |
---|
| 966 | # If the model isn't a built in model, try the plugin directory |
---|
[f9c8474] | 967 | plugin_path = environ.get('SAS_MODELPATH', None) |
---|
[a22d104] | 968 | if plugin_path is not None: |
---|
| 969 | file_name = model_name.split(sep)[-1] |
---|
| 970 | model_name = plugin_path + sep + file_name + ".py" |
---|
[2f733b1] | 971 | kernel_module = load_custom_kernel_module(model_name) |
---|
| 972 | else: |
---|
| 973 | raise |
---|
[68e7f9d] | 974 | return kernel_module |
---|
| 975 | |
---|
[5ceb7d0] | 976 | |
---|
| 977 | section_marker = re.compile(r'\A(?P<first>[%s])(?P=first)*\Z' |
---|
[7891a2a] | 978 | % re.escape(string.punctuation)) |
---|
[5ceb7d0] | 979 | def _convert_section_titles_to_boldface(lines): |
---|
[f619de7] | 980 | # type: (Sequence[str]) -> Iterator[str] |
---|
[5ceb7d0] | 981 | """ |
---|
| 982 | Do the actual work of identifying and converting section headings. |
---|
| 983 | """ |
---|
| 984 | prior = None |
---|
| 985 | for line in lines: |
---|
| 986 | if prior is None: |
---|
| 987 | prior = line |
---|
| 988 | elif section_marker.match(line): |
---|
| 989 | if len(line) >= len(prior): |
---|
| 990 | yield "".join(("**", prior, "**")) |
---|
| 991 | prior = None |
---|
| 992 | else: |
---|
| 993 | yield prior |
---|
| 994 | prior = line |
---|
| 995 | else: |
---|
| 996 | yield prior |
---|
| 997 | prior = line |
---|
| 998 | if prior is not None: |
---|
| 999 | yield prior |
---|
| 1000 | |
---|
[7891a2a] | 1001 | |
---|
[5ceb7d0] | 1002 | def convert_section_titles_to_boldface(s): |
---|
[f619de7] | 1003 | # type: (str) -> str |
---|
[5ceb7d0] | 1004 | """ |
---|
| 1005 | Use explicit bold-face rather than section headings so that the table of |
---|
| 1006 | contents is not polluted with section names from the model documentation. |
---|
| 1007 | |
---|
| 1008 | Sections are identified as the title line followed by a line of punctuation |
---|
| 1009 | at least as long as the title line. |
---|
| 1010 | """ |
---|
| 1011 | return "\n".join(_convert_section_titles_to_boldface(s.split('\n'))) |
---|
| 1012 | |
---|
[7891a2a] | 1013 | |
---|
[17bbadd] | 1014 | def make_doc(model_info): |
---|
[f619de7] | 1015 | # type: (ModelInfo) -> str |
---|
[5ceb7d0] | 1016 | """ |
---|
| 1017 | Return the documentation for the model. |
---|
| 1018 | """ |
---|
| 1019 | Iq_units = "The returned value is scaled to units of |cm^-1| |sr^-1|, absolute scale." |
---|
| 1020 | Sq_units = "The returned value is a dimensionless structure factor, $S(q)$." |
---|
[6592f56] | 1021 | docs = model_info.docs if model_info.docs is not None else "" |
---|
| 1022 | docs = convert_section_titles_to_boldface(docs) |
---|
[6e45516] | 1023 | if model_info.structure_factor: |
---|
| 1024 | pars = model_info.parameters.kernel_parameters |
---|
| 1025 | else: |
---|
[b6dab59] | 1026 | pars = (model_info.parameters.common_parameters |
---|
| 1027 | + model_info.parameters.kernel_parameters) |
---|
[6e45516] | 1028 | partable = make_partable(pars) |
---|
[6d6508e] | 1029 | subst = dict(id=model_info.id.replace('_', '-'), |
---|
| 1030 | name=model_info.name, |
---|
| 1031 | title=model_info.title, |
---|
[6e45516] | 1032 | parameters=partable, |
---|
[6d6508e] | 1033 | returns=Sq_units if model_info.structure_factor else Iq_units, |
---|
[5ceb7d0] | 1034 | docs=docs) |
---|
| 1035 | return DOC_HEADER % subst |
---|
| 1036 | |
---|
| 1037 | |
---|
[6592f56] | 1038 | # TODO: need a single source for rst_prolog; it is also in doc/rst_prolog |
---|
[bb4b509] | 1039 | RST_PROLOG = r"""\ |
---|
[6592f56] | 1040 | .. |Ang| unicode:: U+212B |
---|
| 1041 | .. |Ang^-1| replace:: |Ang|\ :sup:`-1` |
---|
| 1042 | .. |Ang^2| replace:: |Ang|\ :sup:`2` |
---|
| 1043 | .. |Ang^-2| replace:: |Ang|\ :sup:`-2` |
---|
| 1044 | .. |1e-6Ang^-2| replace:: 10\ :sup:`-6`\ |Ang|\ :sup:`-2` |
---|
| 1045 | .. |Ang^3| replace:: |Ang|\ :sup:`3` |
---|
| 1046 | .. |Ang^-3| replace:: |Ang|\ :sup:`-3` |
---|
| 1047 | .. |Ang^-4| replace:: |Ang|\ :sup:`-4` |
---|
| 1048 | .. |cm^-1| replace:: cm\ :sup:`-1` |
---|
| 1049 | .. |cm^2| replace:: cm\ :sup:`2` |
---|
| 1050 | .. |cm^-2| replace:: cm\ :sup:`-2` |
---|
| 1051 | .. |cm^3| replace:: cm\ :sup:`3` |
---|
| 1052 | .. |1e15cm^3| replace:: 10\ :sup:`15`\ cm\ :sup:`3` |
---|
| 1053 | .. |cm^-3| replace:: cm\ :sup:`-3` |
---|
| 1054 | .. |sr^-1| replace:: sr\ :sup:`-1` |
---|
| 1055 | |
---|
| 1056 | .. |cdot| unicode:: U+00B7 |
---|
| 1057 | .. |deg| unicode:: U+00B0 |
---|
| 1058 | .. |g/cm^3| replace:: g\ |cdot|\ cm\ :sup:`-3` |
---|
| 1059 | .. |mg/m^2| replace:: mg\ |cdot|\ m\ :sup:`-2` |
---|
| 1060 | .. |fm^2| replace:: fm\ :sup:`2` |
---|
| 1061 | .. |Ang*cm^-1| replace:: |Ang|\ |cdot|\ cm\ :sup:`-1` |
---|
| 1062 | """ |
---|
| 1063 | |
---|
| 1064 | # TODO: make a better fake reference role |
---|
| 1065 | RST_ROLES = """\ |
---|
| 1066 | .. role:: ref |
---|
| 1067 | |
---|
| 1068 | .. role:: numref |
---|
| 1069 | |
---|
| 1070 | """ |
---|
| 1071 | |
---|
[001d9f5] | 1072 | def make_html(model_info): |
---|
[e65c3ba] | 1073 | # type: (ModelInfo) -> str |
---|
[001d9f5] | 1074 | """ |
---|
| 1075 | Convert model docs directly to html. |
---|
| 1076 | """ |
---|
| 1077 | from . import rst2html |
---|
[6592f56] | 1078 | |
---|
| 1079 | rst = make_doc(model_info) |
---|
| 1080 | return rst2html.rst2html("".join((RST_ROLES, RST_PROLOG, rst))) |
---|
| 1081 | |
---|
| 1082 | def view_html(model_name): |
---|
[e65c3ba] | 1083 | # type: (str) -> None |
---|
| 1084 | """ |
---|
| 1085 | Load the model definition and view its help. |
---|
| 1086 | """ |
---|
[6592f56] | 1087 | from . import modelinfo |
---|
| 1088 | kernel_module = load_kernel_module(model_name) |
---|
| 1089 | info = modelinfo.make_model_info(kernel_module) |
---|
[234c532] | 1090 | view_html_from_info(info) |
---|
| 1091 | |
---|
| 1092 | def view_html_from_info(info): |
---|
[e65c3ba] | 1093 | # type: (ModelInfo) -> None |
---|
| 1094 | """ |
---|
| 1095 | View the help for a loaded model definition. |
---|
| 1096 | """ |
---|
[234c532] | 1097 | from . import rst2html |
---|
[6592f56] | 1098 | url = "file://"+dirname(info.filename)+"/" |
---|
[c4e3215] | 1099 | rst2html.view_html(make_html(info), url=url) |
---|
[001d9f5] | 1100 | |
---|
[5ceb7d0] | 1101 | def demo_time(): |
---|
[f619de7] | 1102 | # type: () -> None |
---|
[5ceb7d0] | 1103 | """ |
---|
| 1104 | Show how long it takes to process a model. |
---|
| 1105 | """ |
---|
| 1106 | import datetime |
---|
[6d6508e] | 1107 | from .modelinfo import make_model_info |
---|
| 1108 | from .models import cylinder |
---|
| 1109 | |
---|
[5ceb7d0] | 1110 | tic = datetime.datetime.now() |
---|
[17bbadd] | 1111 | make_source(make_model_info(cylinder)) |
---|
[5ceb7d0] | 1112 | toc = (datetime.datetime.now() - tic).total_seconds() |
---|
| 1113 | print("time: %g"%toc) |
---|
| 1114 | |
---|
[7891a2a] | 1115 | |
---|
[5ceb7d0] | 1116 | def main(): |
---|
[f619de7] | 1117 | # type: () -> None |
---|
[5ceb7d0] | 1118 | """ |
---|
| 1119 | Program which prints the source produced by the model. |
---|
| 1120 | """ |
---|
[6d6508e] | 1121 | from .modelinfo import make_model_info |
---|
| 1122 | |
---|
[5ceb7d0] | 1123 | if len(sys.argv) <= 1: |
---|
| 1124 | print("usage: python -m sasmodels.generate modelname") |
---|
| 1125 | else: |
---|
| 1126 | name = sys.argv[1] |
---|
[68e7f9d] | 1127 | kernel_module = load_kernel_module(name) |
---|
| 1128 | model_info = make_model_info(kernel_module) |
---|
[17bbadd] | 1129 | source = make_source(model_info) |
---|
[c036ddb] | 1130 | print(source['dll']) |
---|
[5ceb7d0] | 1131 | |
---|
[7891a2a] | 1132 | |
---|
[5ceb7d0] | 1133 | if __name__ == "__main__": |
---|
| 1134 | main() |
---|