[a7684e5] | 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 | |
---|
[823e620] | 9 | *Iqxy(qx, qy, p1, p2, ...)* returns the scattering at qx, qy for a form |
---|
[a7684e5] | 10 | with particular dimensions for a single orientation. |
---|
| 11 | |
---|
| 12 | *Imagnetic(qx, qy, result[], p1, p2, ...)* returns the scattering for the |
---|
| 13 | polarized neutron spin states (up-up, up-down, down-up, down-down) for |
---|
| 14 | a form with particular dimensions for a single orientation. |
---|
| 15 | |
---|
| 16 | *form_volume(p1, p2, ...)* returns the volume of the form with particular |
---|
| 17 | dimension. |
---|
| 18 | |
---|
| 19 | *ER(p1, p2, ...)* returns the effective radius of the form with |
---|
| 20 | particular dimensions. |
---|
| 21 | |
---|
| 22 | *VR(p1, p2, ...)* returns the volume ratio for core-shell style forms. |
---|
| 23 | |
---|
| 24 | These functions are defined in a kernel module .py script and an associated |
---|
| 25 | set of .c files. The model constructor will use them to create models with |
---|
| 26 | polydispersity across volume and orientation parameters, and provide |
---|
| 27 | scale and background parameters for each model. |
---|
| 28 | |
---|
| 29 | *Iq*, *Iqxy*, *Imagnetic* and *form_volume* should be stylized C-99 |
---|
[5d4777d] | 30 | functions written for OpenCL. All functions need prototype declarations |
---|
| 31 | even if the are defined before they are used. OpenCL does not support |
---|
| 32 | *#include* preprocessor directives, so instead the list of includes needs |
---|
| 33 | to be given as part of the metadata in the kernel module definition. |
---|
| 34 | The included files should be listed using a path relative to the kernel |
---|
| 35 | module, or if using "lib/file.c" if it is one of the standard includes |
---|
| 36 | provided with the sasmodels source. The includes need to be listed in |
---|
| 37 | order so that functions are defined before they are used. |
---|
| 38 | |
---|
[994d77f] | 39 | Floating point values should be declared as *double*. For single precision |
---|
| 40 | calculations, *double* will be replaced by *float*. The single precision |
---|
| 41 | conversion will also tag floating point constants with "f" to make them |
---|
| 42 | single precision constants. When using integral values in floating point |
---|
| 43 | expressions, they should be expressed as floating point values by including |
---|
| 44 | a decimal point. This includes 0., 1. and 2. |
---|
[5d4777d] | 45 | |
---|
| 46 | OpenCL has a *sincos* function which can improve performance when both |
---|
| 47 | the *sin* and *cos* values are needed for a particular argument. Since |
---|
| 48 | this function does not exist in C99, all use of *sincos* should be |
---|
[823e620] | 49 | replaced by the macro *SINCOS(value, sn, cn)* where *sn* and *cn* are |
---|
[994d77f] | 50 | previously declared *double* variables. When compiled for systems without |
---|
| 51 | OpenCL, *SINCOS* will be replaced by *sin* and *cos* calls. If *value* is |
---|
| 52 | an expression, it will appear twice in this case; whether or not it will be |
---|
| 53 | evaluated twice depends on the quality of the compiler. |
---|
[5d4777d] | 54 | |
---|
| 55 | If the input parameters are invalid, the scattering calculator should |
---|
| 56 | return a negative number. Particularly with polydispersity, there are |
---|
| 57 | some sets of shape parameters which lead to nonsensical forms, such |
---|
| 58 | as a capped cylinder where the cap radius is smaller than the |
---|
| 59 | cylinder radius. The polydispersity calculation will ignore these points, |
---|
| 60 | effectively chopping the parameter weight distributions at the boundary |
---|
| 61 | of the infeasible region. The resulting scattering will be set to |
---|
| 62 | background. This will work correctly even when polydispersity is off. |
---|
[a7684e5] | 63 | |
---|
| 64 | *ER* and *VR* are python functions which operate on parameter vectors. |
---|
| 65 | The constructor code will generate the necessary vectors for computing |
---|
| 66 | them with the desired polydispersity. |
---|
| 67 | |
---|
[ff7119b] | 68 | The available kernel parameters are defined as a list, with each parameter |
---|
| 69 | defined as a sublist with the following elements: |
---|
| 70 | |
---|
| 71 | *name* is the name that will be used in the call to the kernel |
---|
| 72 | function and the name that will be displayed to the user. Names |
---|
| 73 | should be lower case, with words separated by underscore. If |
---|
| 74 | acronyms are used, the whole acronym should be upper case. |
---|
| 75 | |
---|
| 76 | *units* should be one of *degrees* for angles, *Ang* for lengths, |
---|
| 77 | *1e-6/Ang^2* for SLDs. |
---|
| 78 | |
---|
| 79 | *default value* will be the initial value for the model when it |
---|
| 80 | is selected, or when an initial value is not otherwise specified. |
---|
| 81 | |
---|
| 82 | [*lb*, *ub*] are the hard limits on the parameter value, used to limit |
---|
| 83 | the polydispersity density function. In the fit, the parameter limits |
---|
| 84 | given to the fit are the limits on the central value of the parameter. |
---|
| 85 | If there is polydispersity, it will evaluate parameter values outside |
---|
| 86 | the fit limits, but not outside the hard limits specified in the model. |
---|
| 87 | If there are no limits, use +/-inf imported from numpy. |
---|
| 88 | |
---|
| 89 | *type* indicates how the parameter will be used. "volume" parameters |
---|
| 90 | will be used in all functions. "orientation" parameters will be used |
---|
| 91 | in *Iqxy* and *Imagnetic*. "magnetic* parameters will be used in |
---|
| 92 | *Imagnetic* only. If *type* is the empty string, the parameter will |
---|
| 93 | be used in all of *Iq*, *Iqxy* and *Imagnetic*. |
---|
| 94 | |
---|
| 95 | *description* is a short description of the parameter. This will |
---|
| 96 | be displayed in the parameter table and used as a tool tip for the |
---|
| 97 | parameter value in the user interface. |
---|
| 98 | |
---|
[a7684e5] | 99 | The kernel module must set variables defining the kernel meta data: |
---|
| 100 | |
---|
[cd3dba0] | 101 | *id* is an implicit variable formed from the filename. It will be |
---|
| 102 | a valid python identifier, and will be used as the reference into |
---|
| 103 | the html documentation, with '_' replaced by '-'. |
---|
| 104 | |
---|
| 105 | *name* is the model name as displayed to the user. If it is missing, |
---|
| 106 | it will be constructed from the id. |
---|
[a7684e5] | 107 | |
---|
| 108 | *title* is a short description of the model, suitable for a tool tip, |
---|
| 109 | or a one line model summary in a table of models. |
---|
| 110 | |
---|
| 111 | *description* is an extended description of the model to be displayed |
---|
| 112 | while the model parameters are being edited. |
---|
| 113 | |
---|
[ff7119b] | 114 | *parameters* is the list of parameters. Parameters in the kernel |
---|
| 115 | functions must appear in the same order as they appear in the |
---|
| 116 | parameters list. Two additional parameters, *scale* and *background* |
---|
| 117 | are added to the beginning of the parameter list. They will show up |
---|
| 118 | in the documentation as model parameters, but they are never sent to |
---|
| 119 | the kernel functions. |
---|
[a7684e5] | 120 | |
---|
[cd3dba0] | 121 | *category* is the default category for the model. Models in the |
---|
| 122 | *structure-factor* category do not have *scale* and *background* |
---|
| 123 | added. |
---|
| 124 | |
---|
[a7684e5] | 125 | *source* is the list of C-99 source files that must be joined to |
---|
| 126 | create the OpenCL kernel functions. The files defining the functions |
---|
| 127 | need to be listed before the files which use the functions. |
---|
| 128 | |
---|
| 129 | *ER* is a python function defining the effective radius. If it is |
---|
| 130 | not present, the effective radius is 0. |
---|
| 131 | |
---|
| 132 | *VR* is a python function defining the volume ratio. If it is not |
---|
| 133 | present, the volume ratio is 1. |
---|
| 134 | |
---|
[5d4777d] | 135 | *form_volume*, *Iq*, *Iqxy*, *Imagnetic* are strings containing the |
---|
| 136 | C source code for the body of the volume, Iq, and Iqxy functions |
---|
| 137 | respectively. These can also be defined in the last source file. |
---|
| 138 | |
---|
[a503bfd] | 139 | *Iq* and *Iqxy* also be instead be python functions defining the |
---|
| 140 | kernel. If they are marked as *Iq.vectorized = True* then the |
---|
| 141 | kernel is passed the entire *q* vector at once, otherwise it is |
---|
| 142 | passed values one *q* at a time. The performance improvement of |
---|
| 143 | this step is significant. |
---|
| 144 | |
---|
| 145 | *demo* is a dictionary of parameter=value defining a set of |
---|
[cd3dba0] | 146 | parameters to use by default when *compare* is called. Any |
---|
| 147 | parameter not set in *demo* gets the initial value from the |
---|
| 148 | parameter list. *demo* is mostly needed to set the default |
---|
| 149 | polydispersity values for tests. |
---|
[ff7119b] | 150 | |
---|
[a503bfd] | 151 | *oldname* is the name of the model in sasview before sasmodels |
---|
| 152 | was split into its own package, and *oldpars* is a dictionary |
---|
| 153 | of *parameter: old_parameter* pairs defining the new names for |
---|
| 154 | the parameters. This is used by *compare* to check the values |
---|
| 155 | of the new model against the values of the old model before |
---|
| 156 | you are ready to add the new model to sasmodels. |
---|
[ff7119b] | 157 | |
---|
[cd3dba0] | 158 | |
---|
| 159 | An *info* dictionary is constructed from the kernel meta data and |
---|
| 160 | returned to the caller. |
---|
| 161 | |
---|
[ff7119b] | 162 | The model evaluator, function call sequence consists of q inputs and the return vector, |
---|
| 163 | followed by the loop value/weight vector, followed by the values for |
---|
| 164 | the non-polydisperse parameters, followed by the lengths of the |
---|
| 165 | polydispersity loops. To construct the call for 1D models, the |
---|
| 166 | categories *fixed-1d* and *pd-1d* list the names of the parameters |
---|
| 167 | of the non-polydisperse and the polydisperse parameters respectively. |
---|
| 168 | Similarly, *fixed-2d* and *pd-2d* provide parameter names for 2D models. |
---|
| 169 | The *pd-rel* category is a set of those parameters which give |
---|
| 170 | polydispersitiy as a portion of the value (so a 10% length dispersity |
---|
| 171 | would use a polydispersity value of 0.1) rather than absolute |
---|
| 172 | dispersity such as an angle plus or minus 15 degrees. |
---|
| 173 | |
---|
| 174 | The *volume* category lists the volume parameters in order for calls |
---|
| 175 | to volume within the kernel (used for volume normalization) and for |
---|
| 176 | calls to ER and VR for effective radius and volume ratio respectively. |
---|
| 177 | |
---|
| 178 | The *orientation* and *magnetic* categories list the orientation and |
---|
| 179 | magnetic parameters. These are used by the sasview interface. The |
---|
| 180 | blank category is for parameters such as scale which don't have any |
---|
| 181 | other marking. |
---|
| 182 | |
---|
[a7684e5] | 183 | The doc string at the start of the kernel module will be used to |
---|
| 184 | construct the model documentation web pages. Embedded figures should |
---|
| 185 | appear in the subdirectory "img" beside the model definition, and tagged |
---|
| 186 | with the kernel module name to avoid collision with other models. Some |
---|
| 187 | file systems are case-sensitive, so only use lower case characters for |
---|
| 188 | file names and extensions. |
---|
| 189 | |
---|
| 190 | |
---|
| 191 | The function :func:`make` loads the metadata from the module and returns |
---|
[ff7119b] | 192 | the kernel source. The function :func:`doc` extracts the doc string |
---|
| 193 | and adds the parameter table to the top. The function :func:`sources` |
---|
| 194 | returns a list of files required by the model. |
---|
[a7684e5] | 195 | """ |
---|
[823e620] | 196 | from __future__ import print_function |
---|
[a7684e5] | 197 | |
---|
| 198 | # TODO: identify model files which have changed since loading and reload them. |
---|
| 199 | |
---|
[5d4777d] | 200 | import sys |
---|
[d138d43] | 201 | from os.path import abspath, dirname, join as joinpath, exists, basename, \ |
---|
| 202 | splitext |
---|
[994d77f] | 203 | import re |
---|
[e88bb78] | 204 | import string |
---|
[14de349] | 205 | |
---|
| 206 | import numpy as np |
---|
[190fc2b] | 207 | |
---|
| 208 | __all__ = ["make", "doc", "sources", "convert_type"] |
---|
| 209 | |
---|
[f734e7d] | 210 | C_KERNEL_TEMPLATE_PATH = joinpath(dirname(__file__), 'kernel_template.c') |
---|
[14de349] | 211 | |
---|
[5d316e9] | 212 | F16 = np.dtype('float16') |
---|
[14de349] | 213 | F32 = np.dtype('float32') |
---|
[e1ace4d] | 214 | F64 = np.dtype('float64') |
---|
| 215 | try: # CRUFT: older numpy does not support float128 |
---|
| 216 | F128 = np.dtype('float128') |
---|
| 217 | except TypeError: |
---|
| 218 | F128 = None |
---|
| 219 | |
---|
[ce27e21] | 220 | # Scale and background, which are parameters common to every form factor |
---|
| 221 | COMMON_PARAMETERS = [ |
---|
[33e91b1] | 222 | ["scale", "", 1, [0, np.inf], "", "Source intensity"], |
---|
| 223 | ["background", "1/cm", 0, [0, np.inf], "", "Source background"], |
---|
[ce27e21] | 224 | ] |
---|
| 225 | |
---|
[14de349] | 226 | # Conversion from units defined in the parameter table for each model |
---|
| 227 | # to units displayed in the sphinx documentation. |
---|
| 228 | RST_UNITS = { |
---|
| 229 | "Ang": "|Ang|", |
---|
[a5d0d00] | 230 | "1/Ang": "|Ang^-1|", |
---|
[14de349] | 231 | "1/Ang^2": "|Ang^-2|", |
---|
| 232 | "1e-6/Ang^2": "|1e-6Ang^-2|", |
---|
| 233 | "degrees": "degree", |
---|
| 234 | "1/cm": "|cm^-1|", |
---|
[0a4628d] | 235 | "Ang/cm": "|Ang*cm^-1|", |
---|
[14de349] | 236 | "": "None", |
---|
| 237 | } |
---|
| 238 | |
---|
| 239 | # Headers for the parameters tables in th sphinx documentation |
---|
| 240 | PARTABLE_HEADERS = [ |
---|
[19dcb933] | 241 | "Parameter", |
---|
| 242 | "Description", |
---|
[14de349] | 243 | "Units", |
---|
| 244 | "Default value", |
---|
| 245 | ] |
---|
| 246 | |
---|
[ff7119b] | 247 | # Minimum width for a default value (this is shorter than the column header |
---|
| 248 | # width, so will be ignored). |
---|
[14de349] | 249 | PARTABLE_VALUE_WIDTH = 10 |
---|
| 250 | |
---|
[a7684e5] | 251 | # Documentation header for the module, giving the model name, its short |
---|
| 252 | # description and its parameter table. The remainder of the doc comes |
---|
| 253 | # from the module docstring. |
---|
[cd3dba0] | 254 | DOC_HEADER = """.. _%(id)s: |
---|
[a7684e5] | 255 | |
---|
[cd3dba0] | 256 | %(name)s |
---|
[a7684e5] | 257 | ======================================================= |
---|
| 258 | |
---|
| 259 | %(title)s |
---|
| 260 | |
---|
| 261 | %(parameters)s |
---|
| 262 | |
---|
[eb69cce] | 263 | %(returns)s |
---|
[a7684e5] | 264 | |
---|
| 265 | %(docs)s |
---|
| 266 | """ |
---|
[ce27e21] | 267 | |
---|
[e66c9f9] | 268 | def format_units(units): |
---|
[190fc2b] | 269 | """ |
---|
| 270 | Convert units into ReStructured Text format. |
---|
| 271 | """ |
---|
[e66c9f9] | 272 | return "string" if isinstance(units, list) else RST_UNITS.get(units, units) |
---|
[4eac427] | 273 | |
---|
[19dcb933] | 274 | def make_partable(pars): |
---|
[ff7119b] | 275 | """ |
---|
| 276 | Generate the parameter table to include in the sphinx documentation. |
---|
| 277 | """ |
---|
[14de349] | 278 | column_widths = [ |
---|
| 279 | max(len(p[0]) for p in pars), |
---|
[19dcb933] | 280 | max(len(p[-1]) for p in pars), |
---|
[4eac427] | 281 | max(len(format_units(p[1])) for p in pars), |
---|
[14de349] | 282 | PARTABLE_VALUE_WIDTH, |
---|
| 283 | ] |
---|
| 284 | column_widths = [max(w, len(h)) |
---|
[33e91b1] | 285 | for w, h in zip(column_widths, PARTABLE_HEADERS)] |
---|
[14de349] | 286 | |
---|
| 287 | sep = " ".join("="*w for w in column_widths) |
---|
| 288 | lines = [ |
---|
| 289 | sep, |
---|
[e66c9f9] | 290 | " ".join("%-*s" % (w, h) |
---|
| 291 | for w, h in zip(column_widths, PARTABLE_HEADERS)), |
---|
[14de349] | 292 | sep, |
---|
| 293 | ] |
---|
| 294 | for p in pars: |
---|
| 295 | lines.append(" ".join([ |
---|
[33e91b1] | 296 | "%-*s" % (column_widths[0], p[0]), |
---|
| 297 | "%-*s" % (column_widths[1], p[-1]), |
---|
[4eac427] | 298 | "%-*s" % (column_widths[2], format_units(p[1])), |
---|
[33e91b1] | 299 | "%*g" % (column_widths[3], p[2]), |
---|
[14de349] | 300 | ])) |
---|
| 301 | lines.append(sep) |
---|
| 302 | return "\n".join(lines) |
---|
| 303 | |
---|
[32c160a] | 304 | def _search(search_path, filename): |
---|
| 305 | """ |
---|
| 306 | Find *filename* in *search_path*. |
---|
| 307 | |
---|
| 308 | Raises ValueError if file does not exist. |
---|
| 309 | """ |
---|
| 310 | for path in search_path: |
---|
[f734e7d] | 311 | target = joinpath(path, filename) |
---|
| 312 | if exists(target): |
---|
[32c160a] | 313 | return target |
---|
[33e91b1] | 314 | raise ValueError("%r not found in %s" % (filename, search_path)) |
---|
[14de349] | 315 | |
---|
[eafc9fa] | 316 | def model_sources(info): |
---|
[ff7119b] | 317 | """ |
---|
| 318 | Return a list of the sources file paths for the module. |
---|
| 319 | """ |
---|
[33e91b1] | 320 | search_path = [dirname(info['filename']), |
---|
| 321 | abspath(joinpath(dirname(__file__), 'models'))] |
---|
[5d4777d] | 322 | return [_search(search_path, f) for f in info['source']] |
---|
[ff7119b] | 323 | |
---|
[5d316e9] | 324 | # Pragmas for enable OpenCL features. Be sure to protect them so that they |
---|
| 325 | # still compile even if OpenCL is not present. |
---|
| 326 | _F16_PRAGMA = """\ |
---|
[e97170c] | 327 | #if defined(__OPENCL_VERSION__) && !defined(cl_khr_fp16) |
---|
[5d316e9] | 328 | # pragma OPENCL EXTENSION cl_khr_fp16: enable |
---|
| 329 | #endif |
---|
| 330 | """ |
---|
| 331 | |
---|
| 332 | _F64_PRAGMA = """\ |
---|
[e97170c] | 333 | #if defined(__OPENCL_VERSION__) && !defined(cl_khr_fp64) |
---|
[5d316e9] | 334 | # pragma OPENCL EXTENSION cl_khr_fp64: enable |
---|
| 335 | #endif |
---|
| 336 | """ |
---|
| 337 | |
---|
| 338 | def convert_type(source, dtype): |
---|
[ff7119b] | 339 | """ |
---|
[5d316e9] | 340 | Convert code from double precision to the desired type. |
---|
[190fc2b] | 341 | |
---|
| 342 | Floating point constants are tagged with 'f' for single precision or 'L' |
---|
| 343 | for long double precision. |
---|
[ff7119b] | 344 | """ |
---|
[5d316e9] | 345 | if dtype == F16: |
---|
| 346 | source = _F16_PRAGMA + _convert_type(source, "half", "f") |
---|
| 347 | elif dtype == F32: |
---|
| 348 | source = _convert_type(source, "float", "f") |
---|
| 349 | elif dtype == F64: |
---|
| 350 | source = _F64_PRAGMA + source # Source is already double |
---|
| 351 | elif dtype == F128: |
---|
| 352 | source = _convert_type(source, "long double", "L") |
---|
| 353 | else: |
---|
| 354 | raise ValueError("Unexpected dtype in source conversion: %s"%dtype) |
---|
[f734e7d] | 355 | return source |
---|
| 356 | |
---|
[5d316e9] | 357 | |
---|
| 358 | def _convert_type(source, type_name, constant_flag): |
---|
[190fc2b] | 359 | """ |
---|
| 360 | Replace 'double' with *type_name* in *source*, tagging floating point |
---|
| 361 | constants with *constant_flag*. |
---|
| 362 | """ |
---|
[5d316e9] | 363 | # Convert double keyword to float/long double/half. |
---|
| 364 | # Accept an 'n' # parameter for vector # values, where n is 2, 4, 8 or 16. |
---|
| 365 | # Assume complex numbers are represented as cdouble which is typedef'd |
---|
| 366 | # to double2. |
---|
[5edfe12] | 367 | source = re.sub(r'(^|[^a-zA-Z0-9_]c?)double(([248]|16)?($|[^a-zA-Z0-9_]))', |
---|
[5d316e9] | 368 | r'\1%s\2'%type_name, source) |
---|
| 369 | # Convert floating point constants to single by adding 'f' to the end, |
---|
| 370 | # or long double with an 'L' suffix. OS/X complains if you don't do this. |
---|
[5edfe12] | 371 | source = re.sub(r'[^a-zA-Z_](\d*[.]\d+|\d+[.]\d*)([eE][+-]?\d+)?', |
---|
[5d316e9] | 372 | r'\g<0>%s'%constant_flag, source) |
---|
[5edfe12] | 373 | return source |
---|
| 374 | |
---|
[f734e7d] | 375 | |
---|
[823e620] | 376 | def kernel_name(info, is_2d): |
---|
[f734e7d] | 377 | """ |
---|
| 378 | Name of the exported kernel symbol. |
---|
| 379 | """ |
---|
[823e620] | 380 | return info['name'] + "_" + ("Iqxy" if is_2d else "Iq") |
---|
[f734e7d] | 381 | |
---|
[14de349] | 382 | |
---|
[ce27e21] | 383 | def categorize_parameters(pars): |
---|
[14de349] | 384 | """ |
---|
[ce27e21] | 385 | Build parameter categories out of the the parameter definitions. |
---|
| 386 | |
---|
| 387 | Returns a dictionary of categories. |
---|
[14de349] | 388 | """ |
---|
[ce27e21] | 389 | partype = { |
---|
| 390 | 'volume': [], 'orientation': [], 'magnetic': [], '': [], |
---|
| 391 | 'fixed-1d': [], 'fixed-2d': [], 'pd-1d': [], 'pd-2d': [], |
---|
| 392 | 'pd-rel': set(), |
---|
[14de349] | 393 | } |
---|
| 394 | |
---|
[ce27e21] | 395 | for p in pars: |
---|
[33e91b1] | 396 | name, ptype = p[0], p[4] |
---|
[ce27e21] | 397 | if ptype == 'volume': |
---|
| 398 | partype['pd-1d'].append(name) |
---|
| 399 | partype['pd-2d'].append(name) |
---|
| 400 | partype['pd-rel'].add(name) |
---|
| 401 | elif ptype == 'magnetic': |
---|
| 402 | partype['fixed-2d'].append(name) |
---|
| 403 | elif ptype == 'orientation': |
---|
| 404 | partype['pd-2d'].append(name) |
---|
| 405 | elif ptype == '': |
---|
| 406 | partype['fixed-1d'].append(name) |
---|
| 407 | partype['fixed-2d'].append(name) |
---|
| 408 | else: |
---|
[33e91b1] | 409 | raise ValueError("unknown parameter type %r" % ptype) |
---|
[ce27e21] | 410 | partype[ptype].append(name) |
---|
[14de349] | 411 | |
---|
[ce27e21] | 412 | return partype |
---|
[14de349] | 413 | |
---|
[f734e7d] | 414 | def indent(s, depth): |
---|
| 415 | """ |
---|
| 416 | Indent a string of text with *depth* additional spaces on each line. |
---|
| 417 | """ |
---|
| 418 | spaces = " "*depth |
---|
[33e91b1] | 419 | sep = "\n" + spaces |
---|
[f734e7d] | 420 | return spaces + sep.join(s.split("\n")) |
---|
| 421 | |
---|
| 422 | |
---|
[823e620] | 423 | LOOP_OPEN = """\ |
---|
| 424 | for (int %(name)s_i=0; %(name)s_i < N%(name)s; %(name)s_i++) { |
---|
| 425 | const double %(name)s = loops[2*(%(name)s_i%(offset)s)]; |
---|
| 426 | const double %(name)s_w = loops[2*(%(name)s_i%(offset)s)+1];\ |
---|
| 427 | """ |
---|
[f734e7d] | 428 | def build_polydispersity_loops(pd_pars): |
---|
| 429 | """ |
---|
| 430 | Build polydispersity loops |
---|
| 431 | |
---|
| 432 | Returns loop opening and loop closing |
---|
| 433 | """ |
---|
| 434 | depth = 4 |
---|
| 435 | offset = "" |
---|
| 436 | loop_head = [] |
---|
| 437 | loop_end = [] |
---|
| 438 | for name in pd_pars: |
---|
[33e91b1] | 439 | subst = {'name': name, 'offset': offset} |
---|
| 440 | loop_head.append(indent(LOOP_OPEN % subst, depth)) |
---|
[f734e7d] | 441 | loop_end.insert(0, (" "*depth) + "}") |
---|
[33e91b1] | 442 | offset += '+N' + name |
---|
[f734e7d] | 443 | depth += 2 |
---|
| 444 | return "\n".join(loop_head), "\n".join(loop_end) |
---|
| 445 | |
---|
[33e91b1] | 446 | C_KERNEL_TEMPLATE = None |
---|
[f734e7d] | 447 | def make_model(info): |
---|
| 448 | """ |
---|
| 449 | Generate the code for the kernel defined by info, using source files |
---|
| 450 | found in the given search path. |
---|
| 451 | """ |
---|
| 452 | # TODO: need something other than volume to indicate dispersion parameters |
---|
| 453 | # No volume normalization despite having a volume parameter. |
---|
| 454 | # Thickness is labelled a volume in order to trigger polydispersity. |
---|
| 455 | # May want a separate dispersion flag, or perhaps a separate category for |
---|
| 456 | # disperse, but not volume. Volume parameters also use relative values |
---|
| 457 | # for the distribution rather than the absolute values used by angular |
---|
| 458 | # dispersion. Need to be careful that necessary parameters are available |
---|
| 459 | # for computing volume even if we allow non-disperse volume parameters. |
---|
| 460 | |
---|
| 461 | # Load template |
---|
| 462 | global C_KERNEL_TEMPLATE |
---|
| 463 | if C_KERNEL_TEMPLATE is None: |
---|
| 464 | with open(C_KERNEL_TEMPLATE_PATH) as fid: |
---|
| 465 | C_KERNEL_TEMPLATE = fid.read() |
---|
| 466 | |
---|
| 467 | # Load additional sources |
---|
[eafc9fa] | 468 | source = [open(f).read() for f in model_sources(info)] |
---|
[f734e7d] | 469 | |
---|
| 470 | # Prepare defines |
---|
| 471 | defines = [] |
---|
| 472 | partype = info['partype'] |
---|
| 473 | pd_1d = partype['pd-1d'] |
---|
| 474 | pd_2d = partype['pd-2d'] |
---|
| 475 | fixed_1d = partype['fixed-1d'] |
---|
| 476 | fixed_2d = partype['fixed-1d'] |
---|
| 477 | |
---|
| 478 | iq_parameters = [p[0] |
---|
[33e91b1] | 479 | for p in info['parameters'][2:] # skip scale, background |
---|
| 480 | if p[0] in set(fixed_1d + pd_1d)] |
---|
[f734e7d] | 481 | iqxy_parameters = [p[0] |
---|
[33e91b1] | 482 | for p in info['parameters'][2:] # skip scale, background |
---|
| 483 | if p[0] in set(fixed_2d + pd_2d)] |
---|
[f734e7d] | 484 | volume_parameters = [p[0] |
---|
[33e91b1] | 485 | for p in info['parameters'] |
---|
| 486 | if p[4] == 'volume'] |
---|
[f734e7d] | 487 | |
---|
| 488 | # Fill in defintions for volume parameters |
---|
| 489 | if volume_parameters: |
---|
| 490 | defines.append(('VOLUME_PARAMETERS', |
---|
| 491 | ','.join(volume_parameters))) |
---|
| 492 | defines.append(('VOLUME_WEIGHT_PRODUCT', |
---|
[33e91b1] | 493 | '*'.join(p + '_w' for p in volume_parameters))) |
---|
[f734e7d] | 494 | |
---|
| 495 | # Generate form_volume function from body only |
---|
| 496 | if info['form_volume'] is not None: |
---|
[6137124] | 497 | if volume_parameters: |
---|
[33e91b1] | 498 | vol_par_decl = ', '.join('double ' + p for p in volume_parameters) |
---|
[6137124] | 499 | else: |
---|
| 500 | vol_par_decl = 'void' |
---|
[f734e7d] | 501 | defines.append(('VOLUME_PARAMETER_DECLARATIONS', |
---|
[6137124] | 502 | vol_par_decl)) |
---|
[f734e7d] | 503 | fn = """\ |
---|
| 504 | double form_volume(VOLUME_PARAMETER_DECLARATIONS); |
---|
| 505 | double form_volume(VOLUME_PARAMETER_DECLARATIONS) { |
---|
| 506 | %(body)s |
---|
| 507 | } |
---|
[33e91b1] | 508 | """ % {'body':info['form_volume']} |
---|
[f734e7d] | 509 | source.append(fn) |
---|
| 510 | |
---|
| 511 | # Fill in definitions for Iq parameters |
---|
[33e91b1] | 512 | defines.append(('IQ_KERNEL_NAME', info['name'] + '_Iq')) |
---|
[f734e7d] | 513 | defines.append(('IQ_PARAMETERS', ', '.join(iq_parameters))) |
---|
| 514 | if fixed_1d: |
---|
| 515 | defines.append(('IQ_FIXED_PARAMETER_DECLARATIONS', |
---|
[33e91b1] | 516 | ', \\\n '.join('const double %s' % p for p in fixed_1d))) |
---|
[f734e7d] | 517 | if pd_1d: |
---|
| 518 | defines.append(('IQ_WEIGHT_PRODUCT', |
---|
[33e91b1] | 519 | '*'.join(p + '_w' for p in pd_1d))) |
---|
[f734e7d] | 520 | defines.append(('IQ_DISPERSION_LENGTH_DECLARATIONS', |
---|
[33e91b1] | 521 | ', \\\n '.join('const int N%s' % p for p in pd_1d))) |
---|
[f734e7d] | 522 | defines.append(('IQ_DISPERSION_LENGTH_SUM', |
---|
[33e91b1] | 523 | '+'.join('N' + p for p in pd_1d))) |
---|
[f734e7d] | 524 | open_loops, close_loops = build_polydispersity_loops(pd_1d) |
---|
| 525 | defines.append(('IQ_OPEN_LOOPS', |
---|
[33e91b1] | 526 | open_loops.replace('\n', ' \\\n'))) |
---|
[f734e7d] | 527 | defines.append(('IQ_CLOSE_LOOPS', |
---|
[33e91b1] | 528 | close_loops.replace('\n', ' \\\n'))) |
---|
[f734e7d] | 529 | if info['Iq'] is not None: |
---|
| 530 | defines.append(('IQ_PARAMETER_DECLARATIONS', |
---|
[33e91b1] | 531 | ', '.join('double ' + p for p in iq_parameters))) |
---|
[f734e7d] | 532 | fn = """\ |
---|
| 533 | double Iq(double q, IQ_PARAMETER_DECLARATIONS); |
---|
| 534 | double Iq(double q, IQ_PARAMETER_DECLARATIONS) { |
---|
| 535 | %(body)s |
---|
| 536 | } |
---|
[33e91b1] | 537 | """ % {'body':info['Iq']} |
---|
[f734e7d] | 538 | source.append(fn) |
---|
| 539 | |
---|
| 540 | # Fill in definitions for Iqxy parameters |
---|
[33e91b1] | 541 | defines.append(('IQXY_KERNEL_NAME', info['name'] + '_Iqxy')) |
---|
[f734e7d] | 542 | defines.append(('IQXY_PARAMETERS', ', '.join(iqxy_parameters))) |
---|
| 543 | if fixed_2d: |
---|
| 544 | defines.append(('IQXY_FIXED_PARAMETER_DECLARATIONS', |
---|
[33e91b1] | 545 | ', \\\n '.join('const double %s' % p for p in fixed_2d))) |
---|
[f734e7d] | 546 | if pd_2d: |
---|
| 547 | defines.append(('IQXY_WEIGHT_PRODUCT', |
---|
[33e91b1] | 548 | '*'.join(p + '_w' for p in pd_2d))) |
---|
[f734e7d] | 549 | defines.append(('IQXY_DISPERSION_LENGTH_DECLARATIONS', |
---|
[33e91b1] | 550 | ', \\\n '.join('const int N%s' % p for p in pd_2d))) |
---|
[f734e7d] | 551 | defines.append(('IQXY_DISPERSION_LENGTH_SUM', |
---|
[33e91b1] | 552 | '+'.join('N' + p for p in pd_2d))) |
---|
[f734e7d] | 553 | open_loops, close_loops = build_polydispersity_loops(pd_2d) |
---|
| 554 | defines.append(('IQXY_OPEN_LOOPS', |
---|
[33e91b1] | 555 | open_loops.replace('\n', ' \\\n'))) |
---|
[f734e7d] | 556 | defines.append(('IQXY_CLOSE_LOOPS', |
---|
[33e91b1] | 557 | close_loops.replace('\n', ' \\\n'))) |
---|
[f734e7d] | 558 | if info['Iqxy'] is not None: |
---|
| 559 | defines.append(('IQXY_PARAMETER_DECLARATIONS', |
---|
[33e91b1] | 560 | ', '.join('double ' + p for p in iqxy_parameters))) |
---|
[f734e7d] | 561 | fn = """\ |
---|
| 562 | double Iqxy(double qx, double qy, IQXY_PARAMETER_DECLARATIONS); |
---|
| 563 | double Iqxy(double qx, double qy, IQXY_PARAMETER_DECLARATIONS) { |
---|
| 564 | %(body)s |
---|
| 565 | } |
---|
[33e91b1] | 566 | """ % {'body':info['Iqxy']} |
---|
[f734e7d] | 567 | source.append(fn) |
---|
| 568 | |
---|
| 569 | # Need to know if we have a theta parameter for Iqxy; it is not there |
---|
| 570 | # for the magnetic sphere model, for example, which has a magnetic |
---|
| 571 | # orientation but no shape orientation. |
---|
| 572 | if 'theta' in pd_2d: |
---|
| 573 | defines.append(('IQXY_HAS_THETA', '1')) |
---|
| 574 | |
---|
[9404dd3] | 575 | #for d in defines: print(d) |
---|
[823e620] | 576 | defines = '\n'.join('#define %s %s' % (k, v) for k, v in defines) |
---|
| 577 | sources = '\n\n'.join(source) |
---|
[33e91b1] | 578 | return C_KERNEL_TEMPLATE % { |
---|
[823e620] | 579 | 'DEFINES': defines, |
---|
| 580 | 'SOURCES': sources, |
---|
[f734e7d] | 581 | } |
---|
| 582 | |
---|
[cd3dba0] | 583 | def make_info(kernel_module): |
---|
[14de349] | 584 | """ |
---|
[cd3dba0] | 585 | Interpret the model definition file, categorizing the parameters. |
---|
[14de349] | 586 | """ |
---|
[9404dd3] | 587 | #print(kernelfile) |
---|
[cd3dba0] | 588 | category = getattr(kernel_module, 'category', None) |
---|
| 589 | parameters = COMMON_PARAMETERS + kernel_module.parameters |
---|
| 590 | # Default the demo parameters to the starting values for the individual |
---|
| 591 | # parameters if an explicit demo parameter set has not been specified. |
---|
| 592 | demo_parameters = getattr(kernel_module, 'demo', None) |
---|
| 593 | if demo_parameters is None: |
---|
[823e620] | 594 | demo_parameters = dict((p[0], p[2]) for p in parameters) |
---|
[cd3dba0] | 595 | filename = abspath(kernel_module.__file__) |
---|
[d138d43] | 596 | kernel_id = splitext(basename(filename))[0] |
---|
[cd3dba0] | 597 | name = getattr(kernel_module, 'name', None) |
---|
| 598 | if name is None: |
---|
| 599 | name = " ".join(w.capitalize() for w in kernel_id.split('_')) |
---|
[32c160a] | 600 | info = dict( |
---|
[823e620] | 601 | id=kernel_id, # string used to load the kernel |
---|
[33e91b1] | 602 | filename=abspath(kernel_module.__file__), |
---|
[cd3dba0] | 603 | name=name, |
---|
[33e91b1] | 604 | title=kernel_module.title, |
---|
| 605 | description=kernel_module.description, |
---|
[cd3dba0] | 606 | category=category, |
---|
| 607 | parameters=parameters, |
---|
| 608 | demo=demo_parameters, |
---|
[33e91b1] | 609 | source=getattr(kernel_module, 'source', []), |
---|
| 610 | oldname=kernel_module.oldname, |
---|
| 611 | oldpars=kernel_module.oldpars, |
---|
[32c160a] | 612 | ) |
---|
[5d4777d] | 613 | # Fill in attributes which default to None |
---|
[33e91b1] | 614 | info.update((k, getattr(kernel_module, k, None)) |
---|
[5d4777d] | 615 | for k in ('ER', 'VR', 'form_volume', 'Iq', 'Iqxy')) |
---|
| 616 | # Fill in the derived attributes |
---|
[33e91b1] | 617 | info['limits'] = dict((p[0], p[3]) for p in info['parameters']) |
---|
[32c160a] | 618 | info['partype'] = categorize_parameters(info['parameters']) |
---|
[33e91b1] | 619 | info['defaults'] = dict((p[0], p[2]) for p in info['parameters']) |
---|
[cd3dba0] | 620 | return info |
---|
| 621 | |
---|
| 622 | def make(kernel_module): |
---|
| 623 | """ |
---|
| 624 | Build an OpenCL/ctypes function from the definition in *kernel_module*. |
---|
[32c160a] | 625 | |
---|
[cd3dba0] | 626 | The module can be loaded with a normal python import statement if you |
---|
| 627 | know which module you need, or with __import__('sasmodels.model.'+name) |
---|
| 628 | if the name is in a string. |
---|
| 629 | """ |
---|
| 630 | info = make_info(kernel_module) |
---|
[f734e7d] | 631 | # Assume if one part of the kernel is python then all parts are. |
---|
| 632 | source = make_model(info) if not callable(info['Iq']) else None |
---|
[32c160a] | 633 | return source, info |
---|
[14de349] | 634 | |
---|
[e88bb78] | 635 | section_marker = re.compile(r'\A(?P<first>[%s])(?P=first)*\Z' |
---|
| 636 | %re.escape(string.punctuation)) |
---|
| 637 | def _convert_section_titles_to_boldface(lines): |
---|
[190fc2b] | 638 | """ |
---|
| 639 | Do the actual work of identifying and converting section headings. |
---|
| 640 | """ |
---|
[e88bb78] | 641 | prior = None |
---|
| 642 | for line in lines: |
---|
| 643 | if prior is None: |
---|
| 644 | prior = line |
---|
| 645 | elif section_marker.match(line): |
---|
| 646 | if len(line) >= len(prior): |
---|
[823e620] | 647 | yield "".join(("**", prior, "**")) |
---|
[e88bb78] | 648 | prior = None |
---|
| 649 | else: |
---|
| 650 | yield prior |
---|
| 651 | prior = line |
---|
| 652 | else: |
---|
| 653 | yield prior |
---|
| 654 | prior = line |
---|
| 655 | if prior is not None: |
---|
| 656 | yield prior |
---|
| 657 | |
---|
[190fc2b] | 658 | def convert_section_titles_to_boldface(s): |
---|
| 659 | """ |
---|
| 660 | Use explicit bold-face rather than section headings so that the table of |
---|
| 661 | contents is not polluted with section names from the model documentation. |
---|
| 662 | |
---|
| 663 | Sections are identified as the title line followed by a line of punctuation |
---|
| 664 | at least as long as the title line. |
---|
| 665 | """ |
---|
| 666 | return "\n".join(_convert_section_titles_to_boldface(s.split('\n'))) |
---|
[e88bb78] | 667 | |
---|
[a7684e5] | 668 | def doc(kernel_module): |
---|
| 669 | """ |
---|
| 670 | Return the documentation for the model. |
---|
| 671 | """ |
---|
[eb69cce] | 672 | Iq_units = "The returned value is scaled to units of |cm^-1| |sr^-1|, absolute scale." |
---|
| 673 | Sq_units = "The returned value is a dimensionless structure factor, $S(q)$." |
---|
[cd3dba0] | 674 | info = make_info(kernel_module) |
---|
[eb69cce] | 675 | is_Sq = ("structure-factor" in info['category']) |
---|
[e88bb78] | 676 | #docs = kernel_module.__doc__ |
---|
| 677 | docs = convert_section_titles_to_boldface(kernel_module.__doc__) |
---|
[cd3dba0] | 678 | subst = dict(id=info['id'].replace('_', '-'), |
---|
| 679 | name=info['name'], |
---|
| 680 | title=info['title'], |
---|
| 681 | parameters=make_partable(info['parameters']), |
---|
[eb69cce] | 682 | returns=Sq_units if is_Sq else Iq_units, |
---|
[e88bb78] | 683 | docs=docs) |
---|
[33e91b1] | 684 | return DOC_HEADER % subst |
---|
[a7684e5] | 685 | |
---|
[ff7119b] | 686 | |
---|
[14de349] | 687 | |
---|
| 688 | def demo_time(): |
---|
[190fc2b] | 689 | """ |
---|
| 690 | Show how long it takes to process a model. |
---|
| 691 | """ |
---|
[b3f6bc3] | 692 | from .models import cylinder |
---|
[3c56da87] | 693 | import datetime |
---|
[b3f6bc3] | 694 | tic = datetime.datetime.now() |
---|
[33e91b1] | 695 | make(cylinder) |
---|
[3c56da87] | 696 | toc = (datetime.datetime.now() - tic).total_seconds() |
---|
[9404dd3] | 697 | print("time: %g"%toc) |
---|
[14de349] | 698 | |
---|
[ff58110] | 699 | def main(): |
---|
[190fc2b] | 700 | """ |
---|
| 701 | Program which prints the source produced by the model. |
---|
| 702 | """ |
---|
[ff58110] | 703 | if len(sys.argv) <= 1: |
---|
[9404dd3] | 704 | print("usage: python -m sasmodels.generate modelname") |
---|
[ff58110] | 705 | else: |
---|
| 706 | name = sys.argv[1] |
---|
| 707 | import sasmodels.models |
---|
[33e91b1] | 708 | __import__('sasmodels.models.' + name) |
---|
[ff58110] | 709 | model = getattr(sasmodels.models, name) |
---|
[33e91b1] | 710 | source, _ = make(model) |
---|
[9404dd3] | 711 | print(source) |
---|
[14de349] | 712 | |
---|
| 713 | if __name__ == "__main__": |
---|
[ff58110] | 714 | main() |
---|