source: sasmodels/sasmodels/generate.py @ 6d6508e

core_shell_microgelscostrafo411magnetic_modelrelease_v0.94release_v0.95ticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since 6d6508e was 6d6508e, checked in by Paul Kienzle <pkienzle@…>, 8 years ago

refactor model_info from dictionary to class

  • Property mode set to 100644
File size: 21.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
125An *model_info* dictionary is constructed from the kernel meta data and
126returned 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
135
136The function :func:`make` loads the metadata from the module and returns
137the kernel source.  The function :func:`make_doc` extracts the doc string
138and adds the parameter table to the top.  The function :func:`model_sources`
139returns a list of files required by the model.
140
141Code follows the C99 standard with the following extensions and conditions::
142
143    M_PI_180 = pi/180
144    M_4PI_3 = 4pi/3
145    square(x) = x*x
146    cube(x) = x*x*x
147    sinc(x) = sin(x)/x, with sin(0)/0 -> 1
148    all double precision constants must include the decimal point
149    all double declarations may be converted to half, float, or long double
150    FLOAT_SIZE is the number of bytes in the converted variables
151"""
152from __future__ import print_function
153
154#TODO: determine which functions are useful outside of generate
155#__all__ = ["model_info", "make_doc", "make_source", "convert_type"]
156
157from os.path import abspath, dirname, join as joinpath, exists, getmtime
158import re
159import string
160import warnings
161
162import numpy as np
163
164from .modelinfo import Parameter
165from .custom import load_custom_kernel_module
166
167TEMPLATE_ROOT = dirname(__file__)
168
169F16 = np.dtype('float16')
170F32 = np.dtype('float32')
171F64 = np.dtype('float64')
172try:  # CRUFT: older numpy does not support float128
173    F128 = np.dtype('float128')
174except TypeError:
175    F128 = None
176
177# Conversion from units defined in the parameter table for each model
178# to units displayed in the sphinx documentation.
179RST_UNITS = {
180    "Ang": "|Ang|",
181    "1/Ang": "|Ang^-1|",
182    "1/Ang^2": "|Ang^-2|",
183    "1e-6/Ang^2": "|1e-6Ang^-2|",
184    "degrees": "degree",
185    "1/cm": "|cm^-1|",
186    "Ang/cm": "|Ang*cm^-1|",
187    "g/cm3": "|g/cm^3|",
188    "mg/m2": "|mg/m^2|",
189    "": "None",
190    }
191
192# Headers for the parameters tables in th sphinx documentation
193PARTABLE_HEADERS = [
194    "Parameter",
195    "Description",
196    "Units",
197    "Default value",
198    ]
199
200# Minimum width for a default value (this is shorter than the column header
201# width, so will be ignored).
202PARTABLE_VALUE_WIDTH = 10
203
204# Documentation header for the module, giving the model name, its short
205# description and its parameter table.  The remainder of the doc comes
206# from the module docstring.
207DOC_HEADER = """.. _%(id)s:
208
209%(name)s
210=======================================================
211
212%(title)s
213
214%(parameters)s
215
216%(returns)s
217
218%(docs)s
219"""
220
221def format_units(units):
222    """
223    Convert units into ReStructured Text format.
224    """
225    return "string" if isinstance(units, list) else RST_UNITS.get(units, units)
226
227def make_partable(pars):
228    """
229    Generate the parameter table to include in the sphinx documentation.
230    """
231    column_widths = [
232        max(len(p.name) for p in pars),
233        max(len(p.description) for p in pars),
234        max(len(format_units(p.units)) for p in pars),
235        PARTABLE_VALUE_WIDTH,
236        ]
237    column_widths = [max(w, len(h))
238                     for w, h in zip(column_widths, PARTABLE_HEADERS)]
239
240    sep = " ".join("="*w for w in column_widths)
241    lines = [
242        sep,
243        " ".join("%-*s" % (w, h)
244                 for w, h in zip(column_widths, PARTABLE_HEADERS)),
245        sep,
246        ]
247    for p in pars:
248        lines.append(" ".join([
249            "%-*s" % (column_widths[0], p.name),
250            "%-*s" % (column_widths[1], p.description),
251            "%-*s" % (column_widths[2], format_units(p.units)),
252            "%*g" % (column_widths[3], p.default),
253            ]))
254    lines.append(sep)
255    return "\n".join(lines)
256
257def _search(search_path, filename):
258    """
259    Find *filename* in *search_path*.
260
261    Raises ValueError if file does not exist.
262    """
263    for path in search_path:
264        target = joinpath(path, filename)
265        if exists(target):
266            return target
267    raise ValueError("%r not found in %s" % (filename, search_path))
268
269
270def model_sources(model_info):
271    """
272    Return a list of the sources file paths for the module.
273    """
274    search_path = [dirname(model_info.filename),
275                   abspath(joinpath(dirname(__file__), 'models'))]
276    return [_search(search_path, f) for f in model_info.source]
277
278def timestamp(model_info):
279    """
280    Return a timestamp for the model corresponding to the most recently
281    changed file or dependency.
282    """
283    source_files = (model_sources(model_info)
284                    + model_templates()
285                    + [model_info.filename])
286    newest = max(getmtime(f) for f in source_files)
287    return newest
288
289def convert_type(source, dtype):
290    """
291    Convert code from double precision to the desired type.
292
293    Floating point constants are tagged with 'f' for single precision or 'L'
294    for long double precision.
295    """
296    if dtype == F16:
297        fbytes = 2
298        source = _convert_type(source, "half", "f")
299    elif dtype == F32:
300        fbytes = 4
301        source = _convert_type(source, "float", "f")
302    elif dtype == F64:
303        fbytes = 8
304        # no need to convert if it is already double
305    elif dtype == F128:
306        fbytes = 16
307        source = _convert_type(source, "long double", "L")
308    else:
309        raise ValueError("Unexpected dtype in source conversion: %s"%dtype)
310    return ("#define FLOAT_SIZE %d\n"%fbytes)+source
311
312
313def _convert_type(source, type_name, constant_flag):
314    """
315    Replace 'double' with *type_name* in *source*, tagging floating point
316    constants with *constant_flag*.
317    """
318    # Convert double keyword to float/long double/half.
319    # Accept an 'n' # parameter for vector # values, where n is 2, 4, 8 or 16.
320    # Assume complex numbers are represented as cdouble which is typedef'd
321    # to double2.
322    source = re.sub(r'(^|[^a-zA-Z0-9_]c?)double(([248]|16)?($|[^a-zA-Z0-9_]))',
323                    r'\1%s\2'%type_name, source)
324    # Convert floating point constants to single by adding 'f' to the end,
325    # or long double with an 'L' suffix.  OS/X complains if you don't do this.
326    source = re.sub(r'[^a-zA-Z_](\d*[.]\d+|\d+[.]\d*)([eE][+-]?\d+)?',
327                    r'\g<0>%s'%constant_flag, source)
328    return source
329
330
331def kernel_name(model_info, is_2d):
332    """
333    Name of the exported kernel symbol.
334    """
335    return model_info.name + "_" + ("Iqxy" if is_2d else "Iq")
336
337
338def indent(s, depth):
339    """
340    Indent a string of text with *depth* additional spaces on each line.
341    """
342    spaces = " "*depth
343    sep = "\n" + spaces
344    return spaces + sep.join(s.split("\n"))
345
346
347_template_cache = {}
348def load_template(filename):
349    path = joinpath(TEMPLATE_ROOT, filename)
350    mtime = getmtime(path)
351    if filename not in _template_cache or mtime > _template_cache[filename][0]:
352        with open(path) as fid:
353            _template_cache[filename] = (mtime, fid.read(), path)
354    return _template_cache[filename][1]
355
356def model_templates():
357    # TODO: fails DRY; templates are listed in two places.
358    # should instead have model_info contain a list of paths
359    return [joinpath(TEMPLATE_ROOT, filename)
360            for filename in ('kernel_header.c', 'kernel_iq.c')]
361
362
363_FN_TEMPLATE = """\
364double %(name)s(%(pars)s);
365double %(name)s(%(pars)s) {
366    %(body)s
367}
368
369
370"""
371
372def _gen_fn(name, pars, body):
373    """
374    Generate a function given pars and body.
375
376    Returns the following string::
377
378         double fn(double a, double b, ...);
379         double fn(double a, double b, ...) {
380             ....
381         }
382    """
383    par_decl = ', '.join(p.as_function_argument() for p in pars) if pars else 'void'
384    return _FN_TEMPLATE % {'name': name, 'body': body, 'pars': par_decl}
385
386def _call_pars(prefix, pars):
387    """
388    Return a list of *prefix.parameter* from parameter items.
389    """
390    return [p.as_call_reference(prefix) for p in pars]
391
392_IQXY_PATTERN = re.compile("^((inline|static) )? *(double )? *Iqxy *([(]|$)",
393                           flags=re.MULTILINE)
394def _have_Iqxy(sources):
395    """
396    Return true if any file defines Iqxy.
397
398    Note this is not a C parser, and so can be easily confused by
399    non-standard syntax.  Also, it will incorrectly identify the following
400    as having Iqxy::
401
402        /*
403        double Iqxy(qx, qy, ...) { ... fill this in later ... }
404        */
405
406    If you want to comment out an Iqxy function, use // on the front of the
407    line instead.
408    """
409    for code in sources:
410        if _IQXY_PATTERN.search(code):
411            return True
412    else:
413        return False
414
415def make_source(model_info):
416    """
417    Generate the OpenCL/ctypes kernel from the module info.
418
419    Uses source files found in the given search path.
420    """
421    if callable(model_info.Iq):
422        return None
423
424    # TODO: need something other than volume to indicate dispersion parameters
425    # No volume normalization despite having a volume parameter.
426    # Thickness is labelled a volume in order to trigger polydispersity.
427    # May want a separate dispersion flag, or perhaps a separate category for
428    # disperse, but not volume.  Volume parameters also use relative values
429    # for the distribution rather than the absolute values used by angular
430    # dispersion.  Need to be careful that necessary parameters are available
431    # for computing volume even if we allow non-disperse volume parameters.
432
433    partable = model_info.parameters
434
435    # Identify parameters for Iq, Iqxy, Iq_magnetic and form_volume.
436    # Note that scale and volume are not possible types.
437
438    # Load templates and user code
439    kernel_header = load_template('kernel_header.c')
440    kernel_code = load_template('kernel_iq.c')
441    user_code = [open(f).read() for f in model_sources(model_info)]
442
443    # Build initial sources
444    source = [kernel_header] + user_code
445
446    # Make parameters for q, qx, qy so that we can use them in declarations
447    q, qx, qy = [Parameter(name=v) for v in ('q', 'qx', 'qy')]
448    # Generate form_volume function, etc. from body only
449    if model_info.form_volume is not None:
450        pars = partable.form_volume_parameters
451        source.append(_gen_fn('form_volume', pars, model_info.form_volume))
452    if model_info.Iq is not None:
453        pars = [q] + partable.iq_parameters
454        source.append(_gen_fn('Iq', pars, model_info.Iq))
455    if model_info.Iqxy is not None:
456        pars = [qx, qy] + partable.iqxy_parameters
457        source.append(_gen_fn('Iqxy', pars, model_info.Iqxy))
458
459    # Define the parameter table
460    source.append("#define PARAMETER_TABLE \\")
461    source.append("\\\n".join(p.as_definition()
462                              for p in partable.kernel_parameters))
463
464    # Define the function calls
465    if partable.form_volume_parameters:
466        refs = _call_pars("_v.", partable.form_volume_parameters)
467        call_volume = "#define CALL_VOLUME(_v) form_volume(%s)" % (",".join(refs))
468    else:
469        # Model doesn't have volume.  We could make the kernel run a little
470        # faster by not using/transferring the volume normalizations, but
471        # the ifdef's reduce readability more than is worthwhile.
472        call_volume = "#define CALL_VOLUME(v) 1.0"
473    source.append(call_volume)
474
475    refs = ["_q[_i]"] + _call_pars("_v.", partable.iq_parameters)
476    call_iq = "#define CALL_IQ(_q,_i,_v) Iq(%s)" % (",".join(refs))
477    if _have_Iqxy(user_code):
478        # Call 2D model
479        refs = ["q[2*i]", "q[2*i+1]"] + _call_pars("_v.", partable.iqxy_parameters)
480        call_iqxy = "#define CALL_IQ(_q,_i,_v) Iqxy(%s)" % (",".join(refs))
481    else:
482        # Call 1D model with sqrt(qx^2 + qy^2)
483        warnings.warn("Creating Iqxy = Iq(sqrt(qx^2 + qy^2))")
484        # still defined:: refs = ["q[i]"] + _call_pars("v", iq_parameters)
485        pars_sqrt = ["sqrt(_q[2*_i]*_q[2*_i]+_q[2*_i+1]*_q[2*_i+1])"] + refs[1:]
486        call_iqxy = "#define CALL_IQ(_q,_i,_v) Iq(%s)" % (",".join(pars_sqrt))
487
488    # Fill in definitions for numbers of parameters
489    source.append("#define MAX_PD %s"%partable.max_pd)
490    source.append("#define NPARS %d"%partable.npars)
491
492    # TODO: allow mixed python/opencl kernels?
493
494    # define the Iq kernel
495    source.append("#define KERNEL_NAME %s_Iq"%model_info.name)
496    source.append(call_iq)
497    source.append(kernel_code)
498    source.append("#undef CALL_IQ")
499    source.append("#undef KERNEL_NAME")
500
501    # define the Iqxy kernel from the same source with different #defines
502    source.append("#define KERNEL_NAME %s_Iqxy"%model_info.name)
503    source.append(call_iqxy)
504    source.append(kernel_code)
505    source.append("#undef CALL_IQ")
506    source.append("#undef KERNEL_NAME")
507
508    return '\n'.join(source)
509
510def load_kernel_module(model_name):
511    if model_name.endswith('.py'):
512        kernel_module = load_custom_kernel_module(model_name)
513    else:
514        from sasmodels import models
515        __import__('sasmodels.models.'+model_name)
516        kernel_module = getattr(models, model_name, None)
517    return kernel_module
518
519
520
521section_marker = re.compile(r'\A(?P<first>[%s])(?P=first)*\Z'
522                            %re.escape(string.punctuation))
523def _convert_section_titles_to_boldface(lines):
524    """
525    Do the actual work of identifying and converting section headings.
526    """
527    prior = None
528    for line in lines:
529        if prior is None:
530            prior = line
531        elif section_marker.match(line):
532            if len(line) >= len(prior):
533                yield "".join(("**", prior, "**"))
534                prior = None
535            else:
536                yield prior
537                prior = line
538        else:
539            yield prior
540            prior = line
541    if prior is not None:
542        yield prior
543
544def convert_section_titles_to_boldface(s):
545    """
546    Use explicit bold-face rather than section headings so that the table of
547    contents is not polluted with section names from the model documentation.
548
549    Sections are identified as the title line followed by a line of punctuation
550    at least as long as the title line.
551    """
552    return "\n".join(_convert_section_titles_to_boldface(s.split('\n')))
553
554def make_doc(model_info):
555    """
556    Return the documentation for the model.
557    """
558    Iq_units = "The returned value is scaled to units of |cm^-1| |sr^-1|, absolute scale."
559    Sq_units = "The returned value is a dimensionless structure factor, $S(q)$."
560    docs = convert_section_titles_to_boldface(model_info.docs)
561    subst = dict(id=model_info.id.replace('_', '-'),
562                 name=model_info.name,
563                 title=model_info.title,
564                 parameters=make_partable(model_info.parameters),
565                 returns=Sq_units if model_info.structure_factor else Iq_units,
566                 docs=docs)
567    return DOC_HEADER % subst
568
569
570def demo_time():
571    """
572    Show how long it takes to process a model.
573    """
574    import datetime
575    from .modelinfo import make_model_info
576    from .models import cylinder
577
578    tic = datetime.datetime.now()
579    make_source(make_model_info(cylinder))
580    toc = (datetime.datetime.now() - tic).total_seconds()
581    print("time: %g"%toc)
582
583def main():
584    """
585    Program which prints the source produced by the model.
586    """
587    import sys
588    from .modelinfo import make_model_info
589
590    if len(sys.argv) <= 1:
591        print("usage: python -m sasmodels.generate modelname")
592    else:
593        name = sys.argv[1]
594        kernel_module = load_kernel_module(name)
595        model_info = make_model_info(kernel_module)
596        source = make_source(model_info)
597        print(source)
598
599if __name__ == "__main__":
600    main()
Note: See TracBrowser for help on using the repository browser.