source: sasmodels/sasmodels/generate.py @ ff31782

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

add -ngauss option to compare in order to set the number of integration points

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