source: sasmodels/sasmodels/generate.py @ 6773b02

core_shell_microgelsmagnetic_modelticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since 6773b02 was 6773b02, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

fix py3 support for opencl kernels

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