[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 | |
---|
| 9 | *Iqxy(qx, qy, p1, p2, ...)* returns the scattering at qx,qy for a form |
---|
| 10 | with particular dimensions for a single orientation. |
---|
| 11 | |
---|
| 12 | *Imagnetic(qx, qy, result[], p1, p2, ...)* returns the scattering for the |
---|
| 13 | polarized neutron spin states (up-up, up-down, down-up, down-down) for |
---|
| 14 | a form with particular dimensions for a single orientation. |
---|
| 15 | |
---|
| 16 | *form_volume(p1, p2, ...)* returns the volume of the form with particular |
---|
| 17 | dimension. |
---|
| 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 |
---|
| 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 | |
---|
| 101 | *name* is the model name |
---|
| 102 | |
---|
| 103 | *title* is a short description of the model, suitable for a tool tip, |
---|
| 104 | or a one line model summary in a table of models. |
---|
| 105 | |
---|
| 106 | *description* is an extended description of the model to be displayed |
---|
| 107 | while the model parameters are being edited. |
---|
| 108 | |
---|
[ff7119b] | 109 | *parameters* is the list of parameters. Parameters in the kernel |
---|
| 110 | functions must appear in the same order as they appear in the |
---|
| 111 | parameters list. Two additional parameters, *scale* and *background* |
---|
| 112 | are added to the beginning of the parameter list. They will show up |
---|
| 113 | in the documentation as model parameters, but they are never sent to |
---|
| 114 | the kernel functions. |
---|
[a7684e5] | 115 | |
---|
| 116 | *source* is the list of C-99 source files that must be joined to |
---|
| 117 | create the OpenCL kernel functions. The files defining the functions |
---|
| 118 | need to be listed before the files which use the functions. |
---|
| 119 | |
---|
| 120 | *ER* is a python function defining the effective radius. If it is |
---|
| 121 | not present, the effective radius is 0. |
---|
| 122 | |
---|
| 123 | *VR* is a python function defining the volume ratio. If it is not |
---|
| 124 | present, the volume ratio is 1. |
---|
| 125 | |
---|
[5d4777d] | 126 | *form_volume*, *Iq*, *Iqxy*, *Imagnetic* are strings containing the |
---|
| 127 | C source code for the body of the volume, Iq, and Iqxy functions |
---|
| 128 | respectively. These can also be defined in the last source file. |
---|
| 129 | |
---|
[ff7119b] | 130 | An *info* dictionary is constructed from the kernel meta data and |
---|
| 131 | returned to the caller. It includes the additional fields |
---|
| 132 | |
---|
| 133 | |
---|
| 134 | The model evaluator, function call sequence consists of q inputs and the return vector, |
---|
| 135 | followed by the loop value/weight vector, followed by the values for |
---|
| 136 | the non-polydisperse parameters, followed by the lengths of the |
---|
| 137 | polydispersity loops. To construct the call for 1D models, the |
---|
| 138 | categories *fixed-1d* and *pd-1d* list the names of the parameters |
---|
| 139 | of the non-polydisperse and the polydisperse parameters respectively. |
---|
| 140 | Similarly, *fixed-2d* and *pd-2d* provide parameter names for 2D models. |
---|
| 141 | The *pd-rel* category is a set of those parameters which give |
---|
| 142 | polydispersitiy as a portion of the value (so a 10% length dispersity |
---|
| 143 | would use a polydispersity value of 0.1) rather than absolute |
---|
| 144 | dispersity such as an angle plus or minus 15 degrees. |
---|
| 145 | |
---|
| 146 | The *volume* category lists the volume parameters in order for calls |
---|
| 147 | to volume within the kernel (used for volume normalization) and for |
---|
| 148 | calls to ER and VR for effective radius and volume ratio respectively. |
---|
| 149 | |
---|
| 150 | The *orientation* and *magnetic* categories list the orientation and |
---|
| 151 | magnetic parameters. These are used by the sasview interface. The |
---|
| 152 | blank category is for parameters such as scale which don't have any |
---|
| 153 | other marking. |
---|
| 154 | |
---|
[a7684e5] | 155 | The doc string at the start of the kernel module will be used to |
---|
| 156 | construct the model documentation web pages. Embedded figures should |
---|
| 157 | appear in the subdirectory "img" beside the model definition, and tagged |
---|
| 158 | with the kernel module name to avoid collision with other models. Some |
---|
| 159 | file systems are case-sensitive, so only use lower case characters for |
---|
| 160 | file names and extensions. |
---|
| 161 | |
---|
| 162 | |
---|
| 163 | The function :func:`make` loads the metadata from the module and returns |
---|
[ff7119b] | 164 | the kernel source. The function :func:`doc` extracts the doc string |
---|
| 165 | and adds the parameter table to the top. The function :func:`sources` |
---|
| 166 | returns a list of files required by the model. |
---|
[a7684e5] | 167 | """ |
---|
| 168 | |
---|
| 169 | # TODO: identify model files which have changed since loading and reload them. |
---|
| 170 | |
---|
[994d77f] | 171 | __all__ = ["make, doc", "sources", "use_single"] |
---|
[14de349] | 172 | |
---|
[5d4777d] | 173 | import sys |
---|
| 174 | import os |
---|
[14de349] | 175 | import os.path |
---|
[994d77f] | 176 | import re |
---|
[14de349] | 177 | |
---|
| 178 | import numpy as np |
---|
| 179 | |
---|
| 180 | F64 = np.dtype('float64') |
---|
| 181 | F32 = np.dtype('float32') |
---|
| 182 | |
---|
[ce27e21] | 183 | # Scale and background, which are parameters common to every form factor |
---|
| 184 | COMMON_PARAMETERS = [ |
---|
| 185 | [ "scale", "", 1, [0, np.inf], "", "Source intensity" ], |
---|
| 186 | [ "background", "1/cm", 0, [0, np.inf], "", "Source background" ], |
---|
| 187 | ] |
---|
| 188 | |
---|
| 189 | |
---|
[14de349] | 190 | # Conversion from units defined in the parameter table for each model |
---|
| 191 | # to units displayed in the sphinx documentation. |
---|
| 192 | RST_UNITS = { |
---|
| 193 | "Ang": "|Ang|", |
---|
| 194 | "1/Ang^2": "|Ang^-2|", |
---|
| 195 | "1e-6/Ang^2": "|1e-6Ang^-2|", |
---|
| 196 | "degrees": "degree", |
---|
| 197 | "1/cm": "|cm^-1|", |
---|
| 198 | "": "None", |
---|
| 199 | } |
---|
| 200 | |
---|
| 201 | # Headers for the parameters tables in th sphinx documentation |
---|
| 202 | PARTABLE_HEADERS = [ |
---|
[19dcb933] | 203 | "Parameter", |
---|
| 204 | "Description", |
---|
[14de349] | 205 | "Units", |
---|
| 206 | "Default value", |
---|
| 207 | ] |
---|
| 208 | |
---|
[ff7119b] | 209 | # Minimum width for a default value (this is shorter than the column header |
---|
| 210 | # width, so will be ignored). |
---|
[14de349] | 211 | PARTABLE_VALUE_WIDTH = 10 |
---|
| 212 | |
---|
| 213 | # Header included before every kernel. |
---|
[ff7119b] | 214 | # This makes sure that the appropriate math constants are defined, and does |
---|
| 215 | # whatever is required to make the kernel compile as pure C rather than |
---|
| 216 | # as an OpenCL kernel. |
---|
[14de349] | 217 | KERNEL_HEADER = """\ |
---|
| 218 | // GENERATED CODE --- DO NOT EDIT --- |
---|
| 219 | // Code is produced by sasmodels.gen from sasmodels/models/MODEL.c |
---|
| 220 | |
---|
| 221 | #ifdef __OPENCL_VERSION__ |
---|
| 222 | # define USE_OPENCL |
---|
| 223 | #endif |
---|
| 224 | |
---|
| 225 | // If opencl is not available, then we are compiling a C function |
---|
| 226 | // Note: if using a C++ compiler, then define kernel as extern "C" |
---|
| 227 | #ifndef USE_OPENCL |
---|
| 228 | # include <math.h> |
---|
| 229 | # define global |
---|
| 230 | # define local |
---|
| 231 | # define constant const |
---|
| 232 | # define kernel |
---|
| 233 | # define SINCOS(angle,svar,cvar) do {svar=sin(angle);cvar=cos(angle);} while (0) |
---|
[ce27e21] | 234 | # define powr(a,b) pow(a,b) |
---|
[14de349] | 235 | #else |
---|
| 236 | # ifdef USE_SINCOS |
---|
| 237 | # define SINCOS(angle,svar,cvar) svar=sincos(angle,&cvar) |
---|
| 238 | # else |
---|
| 239 | # define SINCOS(angle,svar,cvar) do {svar=sin(angle);cvar=cos(angle);} while (0) |
---|
| 240 | # endif |
---|
| 241 | #endif |
---|
| 242 | |
---|
[5d4777d] | 243 | // Standard mathematical constants: |
---|
| 244 | // M_E, M_LOG2E, M_LOG10E, M_LN2, M_LN10, M_PI, M_PI_2=pi/2, M_PI_4=pi/4, |
---|
| 245 | // M_1_PI=1/pi, M_2_PI=2/pi, M_2_SQRTPI=2/sqrt(pi), SQRT2, SQRT1_2=sqrt(1/2) |
---|
[14de349] | 246 | // OpenCL defines M_constant_F for float constants, and nothing if double |
---|
| 247 | // is not enabled on the card, which is why these constants may be missing |
---|
| 248 | #ifndef M_PI |
---|
[994d77f] | 249 | # define M_PI 3.141592653589793 |
---|
[14de349] | 250 | #endif |
---|
| 251 | #ifndef M_PI_2 |
---|
[994d77f] | 252 | # define M_PI_2 1.570796326794897 |
---|
[14de349] | 253 | #endif |
---|
| 254 | #ifndef M_PI_4 |
---|
[994d77f] | 255 | # define M_PI_4 0.7853981633974483 |
---|
[14de349] | 256 | #endif |
---|
| 257 | |
---|
| 258 | // Non-standard pi/180, used for converting between degrees and radians |
---|
| 259 | #ifndef M_PI_180 |
---|
[994d77f] | 260 | # define M_PI_180 0.017453292519943295 |
---|
[14de349] | 261 | #endif |
---|
| 262 | """ |
---|
| 263 | |
---|
| 264 | |
---|
| 265 | # The I(q) kernel and the I(qx, qy) kernel have one and two q parameters |
---|
| 266 | # respectively, so the template builder will need to do extra work to |
---|
| 267 | # declare, initialize and pass the q parameters. |
---|
[ce27e21] | 268 | KERNEL_1D = { |
---|
[14de349] | 269 | 'fn': "Iq", |
---|
[994d77f] | 270 | 'q_par_decl': "global const double *q,", |
---|
| 271 | 'qinit': "const double qi = q[i];", |
---|
[14de349] | 272 | 'qcall': "qi", |
---|
[5d4777d] | 273 | 'qwork': ["q"], |
---|
[14de349] | 274 | } |
---|
| 275 | |
---|
[ce27e21] | 276 | KERNEL_2D = { |
---|
[14de349] | 277 | 'fn': "Iqxy", |
---|
[994d77f] | 278 | 'q_par_decl': "global const double *qx,\n global const double *qy,", |
---|
| 279 | 'qinit': "const double qxi = qx[i];\n const double qyi = qy[i];", |
---|
[14de349] | 280 | 'qcall': "qxi, qyi", |
---|
[5d4777d] | 281 | 'qwork': ["qx", "qy"], |
---|
[14de349] | 282 | } |
---|
| 283 | |
---|
[ff7119b] | 284 | # Generic kernel template for the polydispersity loop. |
---|
[14de349] | 285 | # This defines the opencl kernel that is available to the host. The same |
---|
| 286 | # structure is used for Iq and Iqxy kernels, so extra flexibility is needed |
---|
| 287 | # for q parameters. The polydispersity loop is built elsewhere and |
---|
| 288 | # substituted into this template. |
---|
| 289 | KERNEL_TEMPLATE = """\ |
---|
| 290 | kernel void %(name)s( |
---|
| 291 | %(q_par_decl)s |
---|
[994d77f] | 292 | global double *result, |
---|
[14de349] | 293 | #ifdef USE_OPENCL |
---|
[994d77f] | 294 | global double *loops_g, |
---|
[14de349] | 295 | #else |
---|
| 296 | const int Nq, |
---|
| 297 | #endif |
---|
[994d77f] | 298 | local double *loops, |
---|
| 299 | const double cutoff, |
---|
[14de349] | 300 | %(par_decl)s |
---|
| 301 | ) |
---|
| 302 | { |
---|
| 303 | #ifdef USE_OPENCL |
---|
| 304 | // copy loops info to local memory |
---|
| 305 | event_t e = async_work_group_copy(loops, loops_g, (%(pd_length)s)*2, 0); |
---|
| 306 | wait_group_events(1, &e); |
---|
| 307 | |
---|
| 308 | int i = get_global_id(0); |
---|
| 309 | int Nq = get_global_size(0); |
---|
| 310 | #endif |
---|
| 311 | |
---|
| 312 | #ifdef USE_OPENCL |
---|
| 313 | if (i < Nq) |
---|
| 314 | #else |
---|
| 315 | #pragma omp parallel for |
---|
| 316 | for (int i=0; i < Nq; i++) |
---|
| 317 | #endif |
---|
| 318 | { |
---|
| 319 | %(qinit)s |
---|
[994d77f] | 320 | double ret=0.0, norm=0.0; |
---|
| 321 | double vol=0.0, norm_vol=0.0; |
---|
[14de349] | 322 | %(loops)s |
---|
[994d77f] | 323 | if (vol*norm_vol != 0.0) { |
---|
[14de349] | 324 | ret *= norm_vol/vol; |
---|
| 325 | } |
---|
| 326 | result[i] = scale*ret/norm+background; |
---|
| 327 | } |
---|
| 328 | } |
---|
| 329 | """ |
---|
| 330 | |
---|
| 331 | # Polydispersity loop level. |
---|
| 332 | # This pulls the parameter value and weight from the looping vector in order |
---|
| 333 | # in preperation for a nested loop. |
---|
| 334 | LOOP_OPEN="""\ |
---|
| 335 | for (int %(name)s_i=0; %(name)s_i < N%(name)s; %(name)s_i++) { |
---|
[994d77f] | 336 | const double %(name)s = loops[2*(%(name)s_i%(offset)s)]; |
---|
| 337 | const double %(name)s_w = loops[2*(%(name)s_i%(offset)s)+1];\ |
---|
[5d4777d] | 338 | """ |
---|
[14de349] | 339 | |
---|
| 340 | # Polydispersity loop body. |
---|
| 341 | # This computes the weight, and if it is sufficient, calls the scattering |
---|
| 342 | # function and adds it to the total. If there is a volume normalization, |
---|
| 343 | # it will also be added here. |
---|
| 344 | LOOP_BODY="""\ |
---|
[994d77f] | 345 | const double weight = %(weight_product)s; |
---|
[14de349] | 346 | if (weight > cutoff) { |
---|
[994d77f] | 347 | const double I = %(fn)s(%(qcall)s, %(pcall)s); |
---|
| 348 | if (I>=0.0) { // scattering cannot be negative |
---|
[f4cf580] | 349 | ret += weight*I%(sasview_spherical)s; |
---|
[5d4777d] | 350 | norm += weight; |
---|
| 351 | %(volume_norm)s |
---|
| 352 | } |
---|
| 353 | //else { printf("exclude qx,qy,I:%%g,%%g,%%g\\n",%(qcall)s,I); } |
---|
| 354 | } |
---|
| 355 | //else { printf("exclude weight:%%g\\n",weight); }\ |
---|
| 356 | """ |
---|
| 357 | |
---|
| 358 | # Use this when integrating over orientation |
---|
| 359 | SPHERICAL_CORRECTION="""\ |
---|
| 360 | // Correction factor for spherical integration p(theta) I(q) sin(theta) dtheta |
---|
[994d77f] | 361 | double spherical_correction = (Ntheta>1 ? fabs(sin(M_PI_180*theta)) : 1.0);\ |
---|
[f4cf580] | 362 | """ |
---|
| 363 | # Use this to reproduce sasview behaviour |
---|
| 364 | SASVIEW_SPHERICAL_CORRECTION="""\ |
---|
| 365 | // Correction factor for spherical integration p(theta) I(q) sin(theta) dtheta |
---|
[994d77f] | 366 | double spherical_correction = (Ntheta>1 ? fabs(cos(M_PI_180*theta))*M_PI_2 : 1.0);\ |
---|
[5d4777d] | 367 | """ |
---|
[14de349] | 368 | |
---|
| 369 | # Volume normalization. |
---|
| 370 | # If there are "volume" polydispersity parameters, then these will be used |
---|
[ce27e21] | 371 | # to call the form_volume function from the user supplied kernel, and accumulate |
---|
[14de349] | 372 | # a normalized weight. |
---|
[994d77f] | 373 | VOLUME_NORM="""const double vol_weight = %(weight)s; |
---|
[5d4777d] | 374 | vol += vol_weight*form_volume(%(pars)s); |
---|
| 375 | norm_vol += vol_weight;\ |
---|
| 376 | """ |
---|
| 377 | |
---|
| 378 | # functions defined as strings in the .py module |
---|
| 379 | WORK_FUNCTION="""\ |
---|
[994d77f] | 380 | double %(name)s(%(pars)s); |
---|
| 381 | double %(name)s(%(pars)s) |
---|
[5d4777d] | 382 | { |
---|
| 383 | %(body)s |
---|
| 384 | }\ |
---|
| 385 | """ |
---|
[14de349] | 386 | |
---|
[a7684e5] | 387 | # Documentation header for the module, giving the model name, its short |
---|
| 388 | # description and its parameter table. The remainder of the doc comes |
---|
| 389 | # from the module docstring. |
---|
| 390 | DOC_HEADER=""".. _%(name)s: |
---|
| 391 | |
---|
[19dcb933] | 392 | %(label)s |
---|
[a7684e5] | 393 | ======================================================= |
---|
| 394 | |
---|
| 395 | %(title)s |
---|
| 396 | |
---|
| 397 | %(parameters)s |
---|
| 398 | |
---|
| 399 | The returned value is scaled to units of |cm^-1|. |
---|
| 400 | |
---|
| 401 | %(docs)s |
---|
| 402 | """ |
---|
[ce27e21] | 403 | |
---|
[14de349] | 404 | def indent(s, depth): |
---|
| 405 | """ |
---|
| 406 | Indent a string of text with *depth* additional spaces on each line. |
---|
| 407 | """ |
---|
| 408 | spaces = " "*depth |
---|
| 409 | sep = "\n"+spaces |
---|
| 410 | return spaces + sep.join(s.split("\n")) |
---|
| 411 | |
---|
| 412 | |
---|
[ce27e21] | 413 | def kernel_name(info, is_2D): |
---|
[ff7119b] | 414 | """ |
---|
| 415 | Name of the exported kernel symbol. |
---|
| 416 | """ |
---|
[ce27e21] | 417 | return info['name'] + "_" + ("Iqxy" if is_2D else "Iq") |
---|
| 418 | |
---|
| 419 | |
---|
[994d77f] | 420 | def use_single(source): |
---|
| 421 | """ |
---|
| 422 | Convert code from double precision to single precision. |
---|
| 423 | """ |
---|
| 424 | source = re.sub(r'(^|[^a-zA-Z0-9_])double($|[^a-zA-Z0-9_])', |
---|
| 425 | r'\1float\2', source) |
---|
| 426 | source = re.sub(r'[^a-zA-Z_](\d*[.]\d+|\d+[.]\d*)([eE][+-]?\d+)?', |
---|
| 427 | r'\g<0>f', source) |
---|
| 428 | return source |
---|
| 429 | |
---|
| 430 | |
---|
[ce27e21] | 431 | def make_kernel(info, is_2D): |
---|
[14de349] | 432 | """ |
---|
| 433 | Build a kernel call from metadata supplied by the user. |
---|
| 434 | |
---|
[ce27e21] | 435 | *info* is the json object defined in the kernel file. |
---|
[14de349] | 436 | |
---|
| 437 | *form* is either "Iq" or "Iqxy". |
---|
| 438 | |
---|
| 439 | This does not create a complete OpenCL kernel source, only the top |
---|
| 440 | level kernel call with polydispersity and a call to the appropriate |
---|
| 441 | Iq or Iqxy function. |
---|
| 442 | """ |
---|
| 443 | |
---|
| 444 | # If we are building the Iqxy kernel, we need to propagate qx,qy |
---|
| 445 | # parameters, otherwise we can |
---|
[ce27e21] | 446 | dim = "2d" if is_2D else "1d" |
---|
| 447 | fixed_pars = info['partype']['fixed-'+dim] |
---|
| 448 | pd_pars = info['partype']['pd-'+dim] |
---|
| 449 | vol_pars = info['partype']['volume'] |
---|
| 450 | q_pars = KERNEL_2D if is_2D else KERNEL_1D |
---|
[5d4777d] | 451 | fn = q_pars['fn'] |
---|
[14de349] | 452 | |
---|
[ce27e21] | 453 | # Build polydispersity loops |
---|
[14de349] | 454 | depth = 4 |
---|
| 455 | offset = "" |
---|
| 456 | loop_head = [] |
---|
| 457 | loop_end = [] |
---|
[ce27e21] | 458 | for name in pd_pars: |
---|
[14de349] | 459 | subst = { 'name': name, 'offset': offset } |
---|
| 460 | loop_head.append(indent(LOOP_OPEN%subst, depth)) |
---|
| 461 | loop_end.insert(0, (" "*depth) + "}") |
---|
| 462 | offset += '+N'+name |
---|
| 463 | depth += 2 |
---|
| 464 | |
---|
| 465 | # The volume parameters in the inner loop are used to call the volume() |
---|
| 466 | # function in the kernel, with the parameters defined in vol_pars and the |
---|
| 467 | # weight product defined in weight. If there are no volume parameters, |
---|
| 468 | # then there will be no volume normalization. |
---|
| 469 | if vol_pars: |
---|
| 470 | subst = { |
---|
| 471 | 'weight': "*".join(p+"_w" for p in vol_pars), |
---|
| 472 | 'pars': ", ".join(vol_pars), |
---|
| 473 | } |
---|
| 474 | volume_norm = VOLUME_NORM%subst |
---|
| 475 | else: |
---|
| 476 | volume_norm = "" |
---|
| 477 | |
---|
| 478 | # Define the inner loop function call |
---|
[ce27e21] | 479 | # The parameters to the f(q,p1,p2...) call should occur in the same |
---|
| 480 | # order as given in the parameter info structure. This may be different |
---|
| 481 | # from the parameter order in the call to the kernel since the kernel |
---|
| 482 | # call places all fixed parameters before all polydisperse parameters. |
---|
| 483 | fq_pars = [p[0] for p in info['parameters'][len(COMMON_PARAMETERS):] |
---|
| 484 | if p[0] in set(fixed_pars+pd_pars)] |
---|
[f4cf580] | 485 | if False and "theta" in pd_pars: |
---|
[5d4777d] | 486 | spherical_correction = [indent(SPHERICAL_CORRECTION, depth)] |
---|
| 487 | weights = [p+"_w" for p in pd_pars]+['spherical_correction'] |
---|
[f4cf580] | 488 | sasview_spherical = "" |
---|
[78356b31] | 489 | elif True and "theta" in pd_pars: |
---|
[f4cf580] | 490 | spherical_correction = [indent(SASVIEW_SPHERICAL_CORRECTION,depth)] |
---|
| 491 | weights = [p+"_w" for p in pd_pars] |
---|
| 492 | sasview_spherical = "*spherical_correction" |
---|
[5d4777d] | 493 | else: |
---|
| 494 | spherical_correction = [] |
---|
| 495 | weights = [p+"_w" for p in pd_pars] |
---|
[f4cf580] | 496 | sasview_spherical = "" |
---|
[14de349] | 497 | subst = { |
---|
[5d4777d] | 498 | 'weight_product': "*".join(weights), |
---|
[14de349] | 499 | 'volume_norm': volume_norm, |
---|
[5d4777d] | 500 | 'fn': fn, |
---|
[ce27e21] | 501 | 'qcall': q_pars['qcall'], |
---|
| 502 | 'pcall': ", ".join(fq_pars), # skip scale and background |
---|
[f4cf580] | 503 | 'sasview_spherical': sasview_spherical, |
---|
[14de349] | 504 | } |
---|
| 505 | loop_body = [indent(LOOP_BODY%subst, depth)] |
---|
[5d4777d] | 506 | loops = "\n".join(loop_head+spherical_correction+loop_body+loop_end) |
---|
[14de349] | 507 | |
---|
| 508 | # declarations for non-pd followed by pd pars |
---|
| 509 | # e.g., |
---|
[994d77f] | 510 | # const double sld, |
---|
[14de349] | 511 | # const int Nradius |
---|
[994d77f] | 512 | fixed_par_decl = ",\n ".join("const double %s"%p for p in fixed_pars) |
---|
[14de349] | 513 | pd_par_decl = ",\n ".join("const int N%s"%p for p in pd_pars) |
---|
| 514 | if fixed_par_decl and pd_par_decl: |
---|
| 515 | par_decl = ",\n ".join((fixed_par_decl, pd_par_decl)) |
---|
| 516 | elif fixed_par_decl: |
---|
| 517 | par_decl = fixed_par_decl |
---|
| 518 | else: |
---|
| 519 | par_decl = pd_par_decl |
---|
| 520 | |
---|
| 521 | # Finally, put the pieces together in the kernel. |
---|
| 522 | subst = { |
---|
| 523 | # kernel name is, e.g., cylinder_Iq |
---|
[ce27e21] | 524 | 'name': kernel_name(info, is_2D), |
---|
[994d77f] | 525 | # to declare, e.g., global double q[], |
---|
[ce27e21] | 526 | 'q_par_decl': q_pars['q_par_decl'], |
---|
[994d77f] | 527 | # to declare, e.g., double sld, int Nradius, int Nlength |
---|
[14de349] | 528 | 'par_decl': par_decl, |
---|
| 529 | # to copy global to local pd pars we need, e.g., Nradius+Nlength |
---|
| 530 | 'pd_length': "+".join('N'+p for p in pd_pars), |
---|
[994d77f] | 531 | # the q initializers, e.g., double qi = q[i]; |
---|
[ce27e21] | 532 | 'qinit': q_pars['qinit'], |
---|
[14de349] | 533 | # the actual polydispersity loop |
---|
| 534 | 'loops': loops, |
---|
| 535 | } |
---|
| 536 | kernel = KERNEL_TEMPLATE%subst |
---|
[5d4777d] | 537 | |
---|
| 538 | # If the working function is defined in the kernel metadata as a |
---|
| 539 | # string, translate the string to an actual function definition |
---|
| 540 | # and put it before the kernel. |
---|
| 541 | if info[fn]: |
---|
| 542 | subst = { |
---|
| 543 | 'name': fn, |
---|
[994d77f] | 544 | 'pars': ", ".join("double "+p for p in q_pars['qwork']+fq_pars), |
---|
[5d4777d] | 545 | 'body': info[fn], |
---|
| 546 | } |
---|
| 547 | kernel = "\n".join((WORK_FUNCTION%subst, kernel)) |
---|
[14de349] | 548 | return kernel |
---|
| 549 | |
---|
[19dcb933] | 550 | def make_partable(pars): |
---|
[ff7119b] | 551 | """ |
---|
| 552 | Generate the parameter table to include in the sphinx documentation. |
---|
| 553 | """ |
---|
[19dcb933] | 554 | pars = COMMON_PARAMETERS + pars |
---|
[14de349] | 555 | column_widths = [ |
---|
| 556 | max(len(p[0]) for p in pars), |
---|
[19dcb933] | 557 | max(len(p[-1]) for p in pars), |
---|
[14de349] | 558 | max(len(RST_UNITS[p[1]]) for p in pars), |
---|
| 559 | PARTABLE_VALUE_WIDTH, |
---|
| 560 | ] |
---|
| 561 | column_widths = [max(w, len(h)) |
---|
| 562 | for w,h in zip(column_widths, PARTABLE_HEADERS)] |
---|
| 563 | |
---|
| 564 | sep = " ".join("="*w for w in column_widths) |
---|
| 565 | lines = [ |
---|
| 566 | sep, |
---|
| 567 | " ".join("%-*s"%(w,h) for w,h in zip(column_widths, PARTABLE_HEADERS)), |
---|
| 568 | sep, |
---|
| 569 | ] |
---|
| 570 | for p in pars: |
---|
| 571 | lines.append(" ".join([ |
---|
| 572 | "%-*s"%(column_widths[0],p[0]), |
---|
[19dcb933] | 573 | "%-*s"%(column_widths[1],p[-1]), |
---|
| 574 | "%-*s"%(column_widths[2],RST_UNITS[p[1]]), |
---|
| 575 | "%*g"%(column_widths[3],p[2]), |
---|
[14de349] | 576 | ])) |
---|
| 577 | lines.append(sep) |
---|
| 578 | return "\n".join(lines) |
---|
| 579 | |
---|
[32c160a] | 580 | def _search(search_path, filename): |
---|
| 581 | """ |
---|
| 582 | Find *filename* in *search_path*. |
---|
| 583 | |
---|
| 584 | Raises ValueError if file does not exist. |
---|
| 585 | """ |
---|
| 586 | for path in search_path: |
---|
| 587 | target = os.path.join(path, filename) |
---|
| 588 | if os.path.exists(target): |
---|
| 589 | return target |
---|
| 590 | raise ValueError("%r not found in %s"%(filename, search_path)) |
---|
[14de349] | 591 | |
---|
[ff7119b] | 592 | def sources(info): |
---|
| 593 | """ |
---|
| 594 | Return a list of the sources file paths for the module. |
---|
| 595 | """ |
---|
| 596 | from os.path import abspath, dirname, join as joinpath |
---|
| 597 | search_path = [ dirname(info['filename']), |
---|
| 598 | abspath(joinpath(dirname(__file__),'models')) ] |
---|
[5d4777d] | 599 | return [_search(search_path, f) for f in info['source']] |
---|
[ff7119b] | 600 | |
---|
| 601 | def make_model(info): |
---|
| 602 | """ |
---|
| 603 | Generate the code for the kernel defined by info, using source files |
---|
| 604 | found in the given search path. |
---|
| 605 | """ |
---|
[5d4777d] | 606 | source = [open(f).read() for f in sources(info)] |
---|
| 607 | # If the form volume is defined as a string, then wrap it in a |
---|
| 608 | # function definition and place it after the external sources but |
---|
| 609 | # before the kernel functions. If the kernel functions are strings, |
---|
| 610 | # they will be translated in the make_kernel call. |
---|
| 611 | if info['form_volume']: |
---|
| 612 | subst = { |
---|
| 613 | 'name': "form_volume", |
---|
[994d77f] | 614 | 'pars': ", ".join("double "+p for p in info['partype']['volume']), |
---|
[5d4777d] | 615 | 'body': info['form_volume'], |
---|
| 616 | } |
---|
| 617 | source.append(WORK_FUNCTION%subst) |
---|
[ce27e21] | 618 | kernel_Iq = make_kernel(info, is_2D=False) |
---|
| 619 | kernel_Iqxy = make_kernel(info, is_2D=True) |
---|
[32c160a] | 620 | kernel = "\n\n".join([KERNEL_HEADER]+source+[kernel_Iq, kernel_Iqxy]) |
---|
[14de349] | 621 | return kernel |
---|
| 622 | |
---|
[ce27e21] | 623 | def categorize_parameters(pars): |
---|
[14de349] | 624 | """ |
---|
[ce27e21] | 625 | Build parameter categories out of the the parameter definitions. |
---|
| 626 | |
---|
| 627 | Returns a dictionary of categories. |
---|
[14de349] | 628 | """ |
---|
[ce27e21] | 629 | partype = { |
---|
| 630 | 'volume': [], 'orientation': [], 'magnetic': [], '': [], |
---|
| 631 | 'fixed-1d': [], 'fixed-2d': [], 'pd-1d': [], 'pd-2d': [], |
---|
| 632 | 'pd-rel': set(), |
---|
[14de349] | 633 | } |
---|
| 634 | |
---|
[ce27e21] | 635 | for p in pars: |
---|
| 636 | name,ptype = p[0],p[4] |
---|
| 637 | if ptype == 'volume': |
---|
| 638 | partype['pd-1d'].append(name) |
---|
| 639 | partype['pd-2d'].append(name) |
---|
| 640 | partype['pd-rel'].add(name) |
---|
| 641 | elif ptype == 'magnetic': |
---|
| 642 | partype['fixed-2d'].append(name) |
---|
| 643 | elif ptype == 'orientation': |
---|
| 644 | partype['pd-2d'].append(name) |
---|
| 645 | elif ptype == '': |
---|
| 646 | partype['fixed-1d'].append(name) |
---|
| 647 | partype['fixed-2d'].append(name) |
---|
| 648 | else: |
---|
| 649 | raise ValueError("unknown parameter type %r"%ptype) |
---|
| 650 | partype[ptype].append(name) |
---|
[14de349] | 651 | |
---|
[ce27e21] | 652 | return partype |
---|
[14de349] | 653 | |
---|
[32c160a] | 654 | def make(kernel_module): |
---|
[14de349] | 655 | """ |
---|
[a7684e5] | 656 | Build an OpenCL/ctypes function from the definition in *kernel_module*. |
---|
[14de349] | 657 | |
---|
[a7684e5] | 658 | The module can be loaded with a normal python import statement if you |
---|
| 659 | know which module you need, or with __import__('sasmodels.model.'+name) |
---|
| 660 | if the name is in a string. |
---|
[14de349] | 661 | """ |
---|
[32c160a] | 662 | # TODO: allow Iq and Iqxy to be defined in python |
---|
[ff7119b] | 663 | from os.path import abspath |
---|
[ce27e21] | 664 | #print kernelfile |
---|
[32c160a] | 665 | info = dict( |
---|
| 666 | filename = abspath(kernel_module.__file__), |
---|
| 667 | name = kernel_module.name, |
---|
| 668 | title = kernel_module.title, |
---|
| 669 | description = kernel_module.description, |
---|
| 670 | parameters = COMMON_PARAMETERS + kernel_module.parameters, |
---|
[5d4777d] | 671 | source = getattr(kernel_module, 'source', []), |
---|
[32c160a] | 672 | ) |
---|
[5d4777d] | 673 | # Fill in attributes which default to None |
---|
| 674 | info.update((k,getattr(kernel_module, k, None)) |
---|
| 675 | for k in ('ER', 'VR', 'form_volume', 'Iq', 'Iqxy')) |
---|
| 676 | # Fill in the derived attributes |
---|
[ce27e21] | 677 | info['limits'] = dict((p[0],p[3]) for p in info['parameters']) |
---|
[32c160a] | 678 | info['partype'] = categorize_parameters(info['parameters']) |
---|
| 679 | |
---|
[ff7119b] | 680 | source = make_model(info) |
---|
[32c160a] | 681 | |
---|
| 682 | return source, info |
---|
[14de349] | 683 | |
---|
[a7684e5] | 684 | def doc(kernel_module): |
---|
| 685 | """ |
---|
| 686 | Return the documentation for the model. |
---|
| 687 | """ |
---|
[19dcb933] | 688 | subst = dict(name=kernel_module.name.replace('_','-'), |
---|
| 689 | label=" ".join(kernel_module.name.split('_')).capitalize(), |
---|
[a7684e5] | 690 | title=kernel_module.title, |
---|
| 691 | parameters=make_partable(kernel_module.parameters), |
---|
[19dcb933] | 692 | docs=kernel_module.__doc__) |
---|
[a7684e5] | 693 | return DOC_HEADER%subst |
---|
| 694 | |
---|
[ff7119b] | 695 | |
---|
[14de349] | 696 | |
---|
| 697 | def demo_time(): |
---|
| 698 | import datetime |
---|
| 699 | tic = datetime.datetime.now() |
---|
| 700 | toc = lambda: (datetime.datetime.now()-tic).total_seconds() |
---|
| 701 | path = os.path.dirname("__file__") |
---|
| 702 | doc, c = make_model(os.path.join(path, "models", "cylinder.c")) |
---|
| 703 | print "time:",toc() |
---|
| 704 | |
---|
| 705 | def demo(): |
---|
| 706 | from os.path import join as joinpath, dirname |
---|
[ce27e21] | 707 | c, info, doc = make_model(joinpath(dirname(__file__), "models", "cylinder.c")) |
---|
[14de349] | 708 | #print doc |
---|
| 709 | #print c |
---|
| 710 | |
---|
| 711 | if __name__ == "__main__": |
---|
| 712 | demo() |
---|