source: sasmodels/sasmodels/generate.py @ a261a83

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

Merge branch 'ticket-786' into generic_integration_loop

  • Property mode set to 100644
File size: 34.8 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, 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
176# pylint: disable=unused-import
177try:
178    from typing import Tuple, Sequence, Iterator, Dict
179    from .modelinfo import ModelInfo
180except ImportError:
181    pass
182# pylint: enable=unused-import
183
184# jitter projection to use in the kernel code.  See explore/jitter.py
185# for details.  To change it from a program, set generate.PROJECTION.
186PROJECTION = 1
187
188def get_data_path(external_dir, target_file):
189    path = abspath(dirname(__file__))
190    if exists(joinpath(path, target_file)):
191        return path
192
193    # check next to exe/zip file
194    exepath = dirname(sys.executable)
195    path = joinpath(exepath, external_dir)
196    if exists(joinpath(path, target_file)):
197        return path
198
199    # check in py2app Contents/Resources
200    path = joinpath(exepath, '..', 'Resources', external_dir)
201    if exists(joinpath(path, target_file)):
202        return abspath(path)
203
204    raise RuntimeError('Could not find '+joinpath(external_dir, target_file))
205
206EXTERNAL_DIR = 'sasmodels-data'
207DATA_PATH = get_data_path(EXTERNAL_DIR, 'kernel_template.c')
208MODEL_PATH = joinpath(DATA_PATH, 'models')
209
210F16 = np.dtype('float16')
211F32 = np.dtype('float32')
212F64 = np.dtype('float64')
213try:  # CRUFT: older numpy does not support float128
214    F128 = np.dtype('float128')
215except TypeError:
216    F128 = None
217
218# Conversion from units defined in the parameter table for each model
219# to units displayed in the sphinx documentation.
220# This section associates the unit with the macro to use to produce the LaTex
221# code.  The macro itself needs to be defined in sasmodels/doc/rst_prolog.
222#
223# NOTE: there is an RST_PROLOG at the end of this file which is NOT
224# used for the bundled documentation. Still as long as we are defining the macros
225# in two places any new addition should define the macro in both places.
226RST_UNITS = {
227    "Ang": "|Ang|",
228    "1/Ang": "|Ang^-1|",
229    "1/Ang^2": "|Ang^-2|",
230    "Ang^3": "|Ang^3|",
231    "Ang^2": "|Ang^2|",
232    "1e15/cm^3": "|1e15cm^3|",
233    "Ang^3/mol": "|Ang^3|/mol",
234    "1e-6/Ang^2": "|1e-6Ang^-2|",
235    "degrees": "degree",
236    "1/cm": "|cm^-1|",
237    "Ang/cm": "|Ang*cm^-1|",
238    "g/cm^3": "|g/cm^3|",
239    "mg/m^2": "|mg/m^2|",
240    "": "None",
241    }
242
243# Headers for the parameters tables in th sphinx documentation
244PARTABLE_HEADERS = [
245    "Parameter",
246    "Description",
247    "Units",
248    "Default value",
249    ]
250
251# Minimum width for a default value (this is shorter than the column header
252# width, so will be ignored).
253PARTABLE_VALUE_WIDTH = 10
254
255# Documentation header for the module, giving the model name, its short
256# description and its parameter table.  The remainder of the doc comes
257# from the module docstring.
258DOC_HEADER = """.. _%(id)s:
259
260%(name)s
261=======================================================
262
263%(title)s
264
265%(parameters)s
266
267%(returns)s
268
269%(docs)s
270"""
271
272
273def set_integration_size(info, n):
274    # type: (ModelInfo, int) -> None
275    """
276    Update the model definition, replacing the gaussian integration with
277    a gaussian integration of a different size.
278
279    Note: this really ought to be a method in modelinfo, but that leads to
280    import loops.
281    """
282    if (info.source and any(lib.startswith('lib/gauss') for lib in info.source)):
283        import os.path
284        from .gengauss import gengauss
285        path = os.path.join(MODEL_PATH, "lib", "gauss%d.c"%n)
286        if not os.path.exists(path):
287            gengauss(n, path)
288        info.source = ["lib/gauss%d.c"%n if lib.startswith('lib/gauss')
289                        else lib for lib in info.source]
290
291def format_units(units):
292    # type: (str) -> str
293    """
294    Convert units into ReStructured Text format.
295    """
296    return "string" if isinstance(units, list) else RST_UNITS.get(units, units)
297
298
299def make_partable(pars):
300    # type: (List[Parameter]) -> str
301    """
302    Generate the parameter table to include in the sphinx documentation.
303    """
304    column_widths = [
305        max(len(p.name) for p in pars),
306        max(len(p.description) for p in pars),
307        max(len(format_units(p.units)) for p in pars),
308        PARTABLE_VALUE_WIDTH,
309        ]
310    column_widths = [max(w, len(h))
311                     for w, h in zip(column_widths, PARTABLE_HEADERS)]
312
313    sep = " ".join("="*w for w in column_widths)
314    lines = [
315        sep,
316        " ".join("%-*s" % (w, h)
317                 for w, h in zip(column_widths, PARTABLE_HEADERS)),
318        sep,
319        ]
320    for p in pars:
321        lines.append(" ".join([
322            "%-*s" % (column_widths[0], p.name),
323            "%-*s" % (column_widths[1], p.description),
324            "%-*s" % (column_widths[2], format_units(p.units)),
325            "%*g" % (column_widths[3], p.default),
326            ]))
327    lines.append(sep)
328    return "\n".join(lines)
329
330
331def _search(search_path, filename):
332    # type: (List[str], str) -> str
333    """
334    Find *filename* in *search_path*.
335
336    Raises ValueError if file does not exist.
337    """
338    for path in search_path:
339        target = joinpath(path, filename)
340        if exists(target):
341            return target
342    raise ValueError("%r not found in %s" % (filename, search_path))
343
344
345def model_sources(model_info):
346    # type: (ModelInfo) -> List[str]
347    """
348    Return a list of the sources file paths for the module.
349    """
350    search_path = [dirname(model_info.filename), MODEL_PATH]
351    return [_search(search_path, f) for f in model_info.source]
352
353
354def dll_timestamp(model_info):
355    # type: (ModelInfo) -> int
356    """
357    Return a timestamp for the model corresponding to the most recently
358    changed file or dependency.
359    """
360    # TODO: fails DRY; templates appear two places.
361    model_templates = [joinpath(DATA_PATH, filename)
362                       for filename in ('kernel_header.c', 'kernel_iq.c')]
363    source_files = (model_sources(model_info)
364                    + model_templates
365                    + [model_info.filename])
366    # Note: file may not exist when it is a standard model from library.zip
367    times = [getmtime(f) for f in source_files if exists(f)]
368    newest = max(times) if times else 0
369    return newest
370
371def ocl_timestamp(model_info):
372    # type: (ModelInfo) -> int
373    """
374    Return a timestamp for the model corresponding to the most recently
375    changed file or dependency.
376
377    Note that this does not look at the time stamps for the OpenCL header
378    information since that need not trigger a recompile of the DLL.
379    """
380    # TODO: fails DRY; templates appear two places.
381    model_templates = [joinpath(DATA_PATH, filename)
382                       for filename in ('kernel_header.c', 'kernel_iq.cl')]
383    source_files = (model_sources(model_info)
384                    + model_templates
385                    + [model_info.filename])
386    # Note: file may not exist when it is a standard model from library.zip
387    times = [getmtime(f) for f in source_files if exists(f)]
388    newest = max(times) if times else 0
389    return newest
390
391def tag_source(source):
392    # type: (str) -> str
393    """
394    Return a unique tag for the source code.
395    """
396    # Note: need 0xffffffff&val to force an unsigned 32-bit number
397    try:
398        source = source.encode('utf8')
399    except AttributeError: # bytes has no encode attribute in python 3
400        pass
401    return "%08X"%(0xffffffff&crc32(source))
402
403def convert_type(source, dtype):
404    # type: (str, np.dtype) -> str
405    """
406    Convert code from double precision to the desired type.
407
408    Floating point constants are tagged with 'f' for single precision or 'L'
409    for long double precision.
410    """
411    source = _fix_tgmath_int(source)
412    if dtype == F16:
413        fbytes = 2
414        source = _convert_type(source, "half", "f")
415    elif dtype == F32:
416        fbytes = 4
417        source = _convert_type(source, "float", "f")
418    elif dtype == F64:
419        fbytes = 8
420        # no need to convert if it is already double
421    elif dtype == F128:
422        fbytes = 16
423        source = _convert_type(source, "long double", "L")
424    else:
425        raise ValueError("Unexpected dtype in source conversion: %s" % dtype)
426    return ("#define FLOAT_SIZE %d\n" % fbytes)+source
427
428
429def _convert_type(source, type_name, constant_flag):
430    # type: (str, str, str) -> str
431    """
432    Replace 'double' with *type_name* in *source*, tagging floating point
433    constants with *constant_flag*.
434    """
435    # Convert double keyword to float/long double/half.
436    # Accept an 'n' # parameter for vector # values, where n is 2, 4, 8 or 16.
437    # Assume complex numbers are represented as cdouble which is typedef'd
438    # to double2.
439    source = re.sub(r'(^|[^a-zA-Z0-9_]c?)double(([248]|16)?($|[^a-zA-Z0-9_]))',
440                    r'\1%s\2'%type_name, source)
441    source = _tag_float(source, constant_flag)
442    return source
443
444TGMATH_INT_RE = re.compile(r"""
445(?: # Non-capturing match; not lookbehind since pattern length is variable
446  \b              # word boundary
447   # various math functions
448  (a?(sin|cos|tan)h? | atan2
449   | erfc? | tgamma
450   | exp(2|10|m1)? | log(2|10|1p)? | pow[nr]? | sqrt | rsqrt | rootn
451   | fabs | fmax | fmin
452   )
453  \s*[(]\s*       # open parenthesis
454)
455[+-]?(0|[1-9]\d*) # integer
456(?=               # lookahead match: don't want to move from end of int
457  \s*[,)]         # comma or close parenthesis for end of argument
458)                 # end lookahead
459""", re.VERBOSE)
460def _fix_tgmath_int(source):
461    # type: (str) -> str
462    """
463    Replace f(integer) with f(integer.) for sin, cos, pow, etc.
464
465    OS X OpenCL complains that it can't resolve the type generic calls to
466    the standard math functions when they are called with integer constants,
467    but this does not happen with the Windows Intel driver for example.
468    To avoid confusion on the matrix marketplace, automatically promote
469    integers to floats if we recognize them in the source.
470
471    The specific functions we look for are:
472
473        trigonometric: sin, asin, sinh, asinh, etc., and atan2
474        exponential:   exp, exp2, exp10, expm1, log, log2, log10, logp1
475        power:         pow, pown, powr, sqrt, rsqrt, rootn
476        special:       erf, erfc, tgamma
477        float:         fabs, fmin, fmax
478
479    Note that we don't convert the second argument of dual argument
480    functions: atan2, fmax, fmin, pow, powr.  This could potentially
481    be a problem for pow(x, 2), but that case seems to work without change.
482    """
483    out = TGMATH_INT_RE.sub(r'\g<0>.', source)
484    return out
485
486
487# Floating point regular expression
488#
489# Define parts:
490#
491#    E = [eE][+-]?\d+    : Exponent
492#    P = [.]             : Decimal separator
493#    N = [1-9]\d*        : Natural number, no leading zeros
494#    Z = 0               : Zero
495#    F = \d+             : Fractional number, maybe leading zeros
496#    F? = \d*            : Optional fractional number
497#
498# We want to reject bare natural numbers and bare decimal points, so we
499# need to tediously outline the cases where we have either a fraction or
500# an exponent:
501#
502#   ( ZP | ZPF | ZE | ZPE | ZPFE | NP | NPF | NE | NPE | NPFE | PF | PFE )
503#
504#
505# We can then join cases by making parts optional.  The following are
506# some ways to do this:
507#
508#   ( (Z|N)(P|PF|E|PE|PFE) | PFE? )                   # Split on lead
509#     => ( (Z|N)(PF?|(PF?)?E) | PFE? )
510#   ( ((Z|N)PF?|PF)E? | (Z|N)E)                       # Split on point
511#   ( (ZP|ZPF|NP|NPF|PF) | (Z|ZP|ZPF|N|NP|NPF|PF)E )  # Split on E
512#     => ( ((Z|N)PF?|PF) | ((Z|N)(PF?)? | PF) E )
513FLOAT_RE = re.compile(r"""
514    (?<!\w)  # use negative lookbehind since '.' confuses \b test
515    # use split on lead to match float ( (Z|N)(PF?|(PF?)?E) | PFE? )
516    ( ( 0 | [1-9]\d* )                     # ( ( Z | N )
517      ([.]\d* | ([.]\d*)? [eE][+-]?\d+ )   #   (PF? | (PF?)? E )
518    | [.]\d+ ([eE][+-]?\d+)?               # | PF (E)?
519    )                                      # )
520    (?!\w)  # use negative lookahead since '.' confuses \b test
521    """, re.VERBOSE)
522def _tag_float(source, constant_flag):
523    # Convert floating point constants to single by adding 'f' to the end,
524    # or long double with an 'L' suffix.  OS/X complains if you don't do this.
525    out = FLOAT_RE.sub(r'\g<0>%s'%constant_flag, source)
526    #print("in",repr(source),"out",repr(out), constant_flag)
527    return out
528
529def test_tag_float():
530    """check that floating point constants are properly identified and tagged with 'f'"""
531
532    cases = """
533ZP  : 0.
534ZPF : 0.0,0.01,0.1
535Z  E: 0e+001
536ZP E: 0.E0
537ZPFE: 0.13e-031
538NP  : 1., 12.
539NPF : 1.0001, 1.1, 1.0
540N  E: 1e0, 37E-080
541NP E: 1.e0, 37.E-080
542NPFE: 845.017e+22
543 PF : .1, .0, .0100
544 PFE: .6e+9, .82E-004
545# isolated cases
5460.
5471e0
5480.13e-013
549# untouched
550struct3.e3, 03.05.67, 37
551# expressions
5523.75+-1.6e-7-27+13.2
553a3.e2 - 0.
5544*atan(1)
5554.*atan(1.)
556"""
557
558    output = """
559ZP  : 0.f
560ZPF : 0.0f,0.01f,0.1f
561Z  E: 0e+001f
562ZP E: 0.E0f
563ZPFE: 0.13e-031f
564NP  : 1.f, 12.f
565NPF : 1.0001f, 1.1f, 1.0f
566N  E: 1e0f, 37E-080f
567NP E: 1.e0f, 37.E-080f
568NPFE: 845.017e+22f
569 PF : .1f, .0f, .0100f
570 PFE: .6e+9f, .82E-004f
571# isolated cases
5720.f
5731e0f
5740.13e-013f
575# untouched
576struct3.e3, 03.05.67, 37
577# expressions
5783.75f+-1.6e-7f-27+13.2f
579a3.e2 - 0.f
5804*atan(1)
5814.f*atan(1.f)
582"""
583
584    for case_in, case_out in zip(cases.split('\n'), output.split('\n')):
585        out = _tag_float(case_in, 'f')
586        assert case_out == out, "%r => %r"%(case_in, out)
587
588
589def kernel_name(model_info, variant):
590    # type: (ModelInfo, str) -> str
591    """
592    Name of the exported kernel symbol.
593
594    *variant* is "Iq", "Iqxy" or "Imagnetic".
595    """
596    return model_info.name + "_" + variant
597
598
599def indent(s, depth):
600    # type: (str, int) -> str
601    """
602    Indent a string of text with *depth* additional spaces on each line.
603    """
604    spaces = " "*depth
605    sep = "\n" + spaces
606    return spaces + sep.join(s.split("\n"))
607
608
609_template_cache = {}  # type: Dict[str, Tuple[int, str, str]]
610def load_template(filename):
611    # type: (str) -> str
612    path = joinpath(DATA_PATH, filename)
613    mtime = getmtime(path)
614    if filename not in _template_cache or mtime > _template_cache[filename][0]:
615        with open(path) as fid:
616            _template_cache[filename] = (mtime, fid.read(), path)
617    return _template_cache[filename][1], path
618
619
620_FN_TEMPLATE = """\
621double %(name)s(%(pars)s);
622double %(name)s(%(pars)s) {
623#line %(line)d "%(filename)s"
624    %(body)s
625}
626
627"""
628def _gen_fn(name, pars, body, filename, line):
629    # type: (str, List[Parameter], str, str, int) -> str
630    """
631    Generate a function given pars and body.
632
633    Returns the following string::
634
635         double fn(double a, double b, ...);
636         double fn(double a, double b, ...) {
637             ....
638         }
639    """
640    par_decl = ', '.join(p.as_function_argument() for p in pars) if pars else 'void'
641    return _FN_TEMPLATE % {
642        'name': name, 'pars': par_decl, 'body': body,
643        'filename': filename.replace('\\', '\\\\'), 'line': line,
644    }
645
646
647def _call_pars(prefix, pars):
648    # type: (str, List[Parameter]) -> List[str]
649    """
650    Return a list of *prefix+parameter* from parameter items.
651
652    *prefix* should be "v." if v is a struct.
653    """
654    return [p.as_call_reference(prefix) for p in pars]
655
656
657# type in IQXY pattern could be single, float, double, long double, ...
658_IQXY_PATTERN = re.compile("^((inline|static) )? *([a-z ]+ )? *Iqxy *([(]|$)",
659                           flags=re.MULTILINE)
660def _have_Iqxy(sources):
661    # type: (List[str]) -> bool
662    """
663    Return true if any file defines Iqxy.
664
665    Note this is not a C parser, and so can be easily confused by
666    non-standard syntax.  Also, it will incorrectly identify the following
667    as having Iqxy::
668
669        /*
670        double Iqxy(qx, qy, ...) { ... fill this in later ... }
671        */
672
673    If you want to comment out an Iqxy function, use // on the front of the
674    line instead.
675    """
676    for _path, code in sources:
677        if _IQXY_PATTERN.search(code):
678            return True
679    return False
680
681
682def _add_source(source, code, path):
683    """
684    Add a file to the list of source code chunks, tagged with path and line.
685    """
686    path = path.replace('\\', '\\\\')
687    source.append('#line 1 "%s"' % path)
688    source.append(code)
689
690def make_source(model_info):
691    # type: (ModelInfo) -> Dict[str, str]
692    """
693    Generate the OpenCL/ctypes kernel from the module info.
694
695    Uses source files found in the given search path.  Returns None if this
696    is a pure python model, with no C source components.
697    """
698    if callable(model_info.Iq):
699        raise ValueError("can't compile python model")
700        #return None
701
702    # TODO: need something other than volume to indicate dispersion parameters
703    # No volume normalization despite having a volume parameter.
704    # Thickness is labelled a volume in order to trigger polydispersity.
705    # May want a separate dispersion flag, or perhaps a separate category for
706    # disperse, but not volume.  Volume parameters also use relative values
707    # for the distribution rather than the absolute values used by angular
708    # dispersion.  Need to be careful that necessary parameters are available
709    # for computing volume even if we allow non-disperse volume parameters.
710
711    partable = model_info.parameters
712
713    # Load templates and user code
714    kernel_header = load_template('kernel_header.c')
715    kernel_code = load_template('kernel_iq.c')
716    user_code = [(f, open(f).read()) for f in model_sources(model_info)]
717
718    # What kind of 2D model do we need?
719    xy_mode = ('qa' if not _have_Iqxy(user_code) and not isinstance(model_info.Iqxy, str)
720               else 'qac' if not partable.is_asymmetric
721               else 'qabc')
722
723    # Build initial sources
724    source = []
725    _add_source(source, *kernel_header)
726    for path, code in user_code:
727        _add_source(source, code, path)
728
729    # Make parameters for q, qx, qy so that we can use them in declarations
730    q, qx, qy = [Parameter(name=v) for v in ('q', 'qx', 'qy')]
731    # Generate form_volume function, etc. from body only
732    if isinstance(model_info.form_volume, str):
733        pars = partable.form_volume_parameters
734        source.append(_gen_fn('form_volume', pars, model_info.form_volume,
735                              model_info.filename, model_info._form_volume_line))
736    if isinstance(model_info.Iq, str):
737        pars = [q] + partable.iq_parameters
738        source.append(_gen_fn('Iq', pars, model_info.Iq,
739                              model_info.filename, model_info._Iq_line))
740    if isinstance(model_info.Iqxy, str):
741        pars = [qx, qy] + partable.iqxy_parameters
742        source.append(_gen_fn('Iqxy', pars, model_info.Iqxy,
743                              model_info.filename, model_info._Iqxy_line))
744
745    # Define the parameter table
746    lineno = getframeinfo(currentframe()).lineno + 2
747    source.append('#line %d "sasmodels/generate.py"'%lineno)
748    #source.append('introduce breakage in generate to test lineno reporting')
749    source.append("#define PARAMETER_TABLE \\")
750    source.append("\\\n".join(p.as_definition()
751                              for p in partable.kernel_parameters))
752
753    # Define the function calls
754    if partable.form_volume_parameters:
755        refs = _call_pars("_v.", partable.form_volume_parameters)
756        call_volume = "#define CALL_VOLUME(_v) form_volume(%s)"%(",".join(refs))
757    else:
758        # Model doesn't have volume.  We could make the kernel run a little
759        # faster by not using/transferring the volume normalizations, but
760        # the ifdef's reduce readability more than is worthwhile.
761        call_volume = "#define CALL_VOLUME(v) 1.0"
762    source.append(call_volume)
763
764    model_refs = _call_pars("_v.", partable.iq_parameters)
765    pars = ",".join(["_q"] + model_refs)
766    call_iq = "#define CALL_IQ(_q, _v) Iq(%s)" % pars
767    if xy_mode == 'qabc':
768        pars = ",".join(["_qa", "_qb", "_qc"] + model_refs)
769        call_iqxy = "#define CALL_IQ_ABC(_qa,_qb,_qc,_v) Iqxy(%s)" % pars
770        clear_iqxy = "#undef CALL_IQ_ABC"
771    elif xy_mode == 'qac':
772        pars = ",".join(["_qa", "_qc"] + model_refs)
773        call_iqxy = "#define CALL_IQ_AC(_qa,_qc,_v) Iqxy(%s)" % pars
774        clear_iqxy = "#undef CALL_IQ_AC"
775    else:  # xy_mode == 'qa'
776        pars = ",".join(["_qa"] + model_refs)
777        call_iqxy = "#define CALL_IQ_A(_qa,_v) Iq(%s)" % pars
778        clear_iqxy = "#undef CALL_IQ_A"
779
780    magpars = [k-2 for k, p in enumerate(partable.call_parameters)
781               if p.type == 'sld']
782
783    # Fill in definitions for numbers of parameters
784    source.append("#define MAX_PD %s"%partable.max_pd)
785    source.append("#define NUM_PARS %d"%partable.npars)
786    source.append("#define NUM_VALUES %d" % partable.nvalues)
787    source.append("#define NUM_MAGNETIC %d" % partable.nmagnetic)
788    source.append("#define MAGNETIC_PARS %s"%",".join(str(k) for k in magpars))
789    source.append("#define PROJECTION %d"%PROJECTION)
790
791    # TODO: allow mixed python/opencl kernels?
792
793    ocl = _kernels(kernel_code, call_iq, call_iqxy, clear_iqxy, model_info.name)
794    dll = _kernels(kernel_code, call_iq, call_iqxy, clear_iqxy, model_info.name)
795    result = {
796        'dll': '\n'.join(source+dll[0]+dll[1]+dll[2]),
797        'opencl': '\n'.join(source+ocl[0]+ocl[1]+ocl[2]),
798    }
799
800    return result
801
802
803def _kernels(kernel, call_iq, call_iqxy, clear_iqxy, name):
804    # type: ([str,str], str, str, str) -> List[str]
805    code = kernel[0]
806    path = kernel[1].replace('\\', '\\\\')
807    iq = [
808        # define the Iq kernel
809        "#define KERNEL_NAME %s_Iq" % name,
810        call_iq,
811        '#line 1 "%s Iq"' % path,
812        code,
813        "#undef CALL_IQ",
814        "#undef KERNEL_NAME",
815        ]
816
817    iqxy = [
818        # define the Iqxy kernel from the same source with different #defines
819        "#define KERNEL_NAME %s_Iqxy" % name,
820        call_iqxy,
821        '#line 1 "%s Iqxy"' % path,
822        code,
823        clear_iqxy,
824        "#undef KERNEL_NAME",
825    ]
826
827    imagnetic = [
828        # define the Imagnetic kernel
829        "#define KERNEL_NAME %s_Imagnetic" % name,
830        "#define MAGNETIC 1",
831        call_iqxy,
832        '#line 1 "%s Imagnetic"' % path,
833        code,
834        clear_iqxy,
835        "#undef MAGNETIC",
836        "#undef KERNEL_NAME",
837    ]
838
839    return iq, iqxy, imagnetic
840
841
842def load_kernel_module(model_name):
843    # type: (str) -> module
844    """
845    Return the kernel module named in *model_name*.
846
847    If the name ends in *.py* then load it as a custom model using
848    :func:`sasmodels.custom.load_custom_kernel_module`, otherwise
849    load it from :mod:`sasmodels.models`.
850    """
851    if model_name.endswith('.py'):
852        kernel_module = load_custom_kernel_module(model_name)
853    else:
854        from sasmodels import models
855        __import__('sasmodels.models.'+model_name)
856        kernel_module = getattr(models, model_name, None)
857    return kernel_module
858
859
860section_marker = re.compile(r'\A(?P<first>[%s])(?P=first)*\Z'
861                            % re.escape(string.punctuation))
862def _convert_section_titles_to_boldface(lines):
863    # type: (Sequence[str]) -> Iterator[str]
864    """
865    Do the actual work of identifying and converting section headings.
866    """
867    prior = None
868    for line in lines:
869        if prior is None:
870            prior = line
871        elif section_marker.match(line):
872            if len(line) >= len(prior):
873                yield "".join(("**", prior, "**"))
874                prior = None
875            else:
876                yield prior
877                prior = line
878        else:
879            yield prior
880            prior = line
881    if prior is not None:
882        yield prior
883
884
885def convert_section_titles_to_boldface(s):
886    # type: (str) -> str
887    """
888    Use explicit bold-face rather than section headings so that the table of
889    contents is not polluted with section names from the model documentation.
890
891    Sections are identified as the title line followed by a line of punctuation
892    at least as long as the title line.
893    """
894    return "\n".join(_convert_section_titles_to_boldface(s.split('\n')))
895
896
897def make_doc(model_info):
898    # type: (ModelInfo) -> str
899    """
900    Return the documentation for the model.
901    """
902    Iq_units = "The returned value is scaled to units of |cm^-1| |sr^-1|, absolute scale."
903    Sq_units = "The returned value is a dimensionless structure factor, $S(q)$."
904    docs = model_info.docs if model_info.docs is not None else ""
905    docs = convert_section_titles_to_boldface(docs)
906    pars = make_partable(model_info.parameters.COMMON
907                         + model_info.parameters.kernel_parameters)
908    subst = dict(id=model_info.id.replace('_', '-'),
909                 name=model_info.name,
910                 title=model_info.title,
911                 parameters=pars,
912                 returns=Sq_units if model_info.structure_factor else Iq_units,
913                 docs=docs)
914    return DOC_HEADER % subst
915
916
917# TODO: need a single source for rst_prolog; it is also in doc/rst_prolog
918RST_PROLOG = r"""\
919.. |Ang| unicode:: U+212B
920.. |Ang^-1| replace:: |Ang|\ :sup:`-1`
921.. |Ang^2| replace:: |Ang|\ :sup:`2`
922.. |Ang^-2| replace:: |Ang|\ :sup:`-2`
923.. |1e-6Ang^-2| replace:: 10\ :sup:`-6`\ |Ang|\ :sup:`-2`
924.. |Ang^3| replace:: |Ang|\ :sup:`3`
925.. |Ang^-3| replace:: |Ang|\ :sup:`-3`
926.. |Ang^-4| replace:: |Ang|\ :sup:`-4`
927.. |cm^-1| replace:: cm\ :sup:`-1`
928.. |cm^2| replace:: cm\ :sup:`2`
929.. |cm^-2| replace:: cm\ :sup:`-2`
930.. |cm^3| replace:: cm\ :sup:`3`
931.. |1e15cm^3| replace:: 10\ :sup:`15`\ cm\ :sup:`3`
932.. |cm^-3| replace:: cm\ :sup:`-3`
933.. |sr^-1| replace:: sr\ :sup:`-1`
934
935.. |cdot| unicode:: U+00B7
936.. |deg| unicode:: U+00B0
937.. |g/cm^3| replace:: g\ |cdot|\ cm\ :sup:`-3`
938.. |mg/m^2| replace:: mg\ |cdot|\ m\ :sup:`-2`
939.. |fm^2| replace:: fm\ :sup:`2`
940.. |Ang*cm^-1| replace:: |Ang|\ |cdot|\ cm\ :sup:`-1`
941"""
942
943# TODO: make a better fake reference role
944RST_ROLES = """\
945.. role:: ref
946
947.. role:: numref
948
949"""
950
951def make_html(model_info):
952    # type: (ModelInfo) -> str
953    """
954    Convert model docs directly to html.
955    """
956    from . import rst2html
957
958    rst = make_doc(model_info)
959    return rst2html.rst2html("".join((RST_ROLES, RST_PROLOG, rst)))
960
961def view_html(model_name):
962    # type: (str) -> None
963    """
964    Load the model definition and view its help.
965    """
966    from . import modelinfo
967    kernel_module = load_kernel_module(model_name)
968    info = modelinfo.make_model_info(kernel_module)
969    view_html_from_info(info)
970
971def view_html_from_info(info):
972    # type: (ModelInfo) -> None
973    """
974    View the help for a loaded model definition.
975    """
976    from . import rst2html
977    url = "file://"+dirname(info.filename)+"/"
978    rst2html.view_html(make_html(info), url=url)
979
980def demo_time():
981    # type: () -> None
982    """
983    Show how long it takes to process a model.
984    """
985    import datetime
986    from .modelinfo import make_model_info
987    from .models import cylinder
988
989    tic = datetime.datetime.now()
990    make_source(make_model_info(cylinder))
991    toc = (datetime.datetime.now() - tic).total_seconds()
992    print("time: %g"%toc)
993
994
995def main():
996    # type: () -> None
997    """
998    Program which prints the source produced by the model.
999    """
1000    from .modelinfo import make_model_info
1001
1002    if len(sys.argv) <= 1:
1003        print("usage: python -m sasmodels.generate modelname")
1004    else:
1005        name = sys.argv[1]
1006        kernel_module = load_kernel_module(name)
1007        model_info = make_model_info(kernel_module)
1008        source = make_source(model_info)
1009        print(source['dll'])
1010
1011
1012if __name__ == "__main__":
1013    main()
Note: See TracBrowser for help on using the repository browser.