source: sasmodels/sasmodels/generate.py @ e65c3ba

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

lint

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