source: sasmodels/sasmodels/generate.py @ 785cbec

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

doc fixes

  • Property mode set to 100644
File size: 26.4 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    sinc(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
168
169import numpy as np  # type: ignore
170
171from .modelinfo import Parameter
172from .custom import load_custom_kernel_module
173
174try:
175    from typing import Tuple, Sequence, Iterator, Dict
176    from .modelinfo import ModelInfo
177except ImportError:
178    pass
179
180def get_data_path(external_dir, target_file):
181    path = abspath(dirname(__file__))
182    if exists(joinpath(path, target_file)):
183        return path
184
185    # check next to exe/zip file
186    exepath = dirname(sys.executable)
187    path = joinpath(exepath, external_dir)
188    if exists(joinpath(path, target_file)):
189        return path
190
191    # check in py2app Contents/Resources
192    path = joinpath(exepath, '..', 'Resources', external_dir)
193    if exists(joinpath(path, target_file)):
194        return abspath(path)
195
196    raise RuntimeError('Could not find '+joinpath(external_dir, target_file))
197
198EXTERNAL_DIR = 'sasmodels-data'
199DATA_PATH = get_data_path(EXTERNAL_DIR, 'kernel_template.c')
200MODEL_PATH = joinpath(DATA_PATH, 'models')
201
202F16 = np.dtype('float16')
203F32 = np.dtype('float32')
204F64 = np.dtype('float64')
205try:  # CRUFT: older numpy does not support float128
206    F128 = np.dtype('float128')
207except TypeError:
208    F128 = None
209
210# Conversion from units defined in the parameter table for each model
211# to units displayed in the sphinx documentation.
212RST_UNITS = {
213    "Ang": "|Ang|",
214    "1/Ang": "|Ang^-1|",
215    "1/Ang^2": "|Ang^-2|",
216    "1e-6/Ang^2": "|1e-6Ang^-2|",
217    "degrees": "degree",
218    "1/cm": "|cm^-1|",
219    "Ang/cm": "|Ang*cm^-1|",
220    "g/cm3": "|g/cm^3|",
221    "mg/m2": "|mg/m^2|",
222    "": "None",
223    }
224
225# Headers for the parameters tables in th sphinx documentation
226PARTABLE_HEADERS = [
227    "Parameter",
228    "Description",
229    "Units",
230    "Default value",
231    ]
232
233# Minimum width for a default value (this is shorter than the column header
234# width, so will be ignored).
235PARTABLE_VALUE_WIDTH = 10
236
237# Documentation header for the module, giving the model name, its short
238# description and its parameter table.  The remainder of the doc comes
239# from the module docstring.
240DOC_HEADER = """.. _%(id)s:
241
242%(name)s
243=======================================================
244
245%(title)s
246
247%(parameters)s
248
249%(returns)s
250
251%(docs)s
252"""
253
254
255def format_units(units):
256    # type: (str) -> str
257    """
258    Convert units into ReStructured Text format.
259    """
260    return "string" if isinstance(units, list) else RST_UNITS.get(units, units)
261
262
263def make_partable(pars):
264    # type: (List[Parameter]) -> str
265    """
266    Generate the parameter table to include in the sphinx documentation.
267    """
268    column_widths = [
269        max(len(p.name) for p in pars),
270        max(len(p.description) for p in pars),
271        max(len(format_units(p.units)) for p in pars),
272        PARTABLE_VALUE_WIDTH,
273        ]
274    column_widths = [max(w, len(h))
275                     for w, h in zip(column_widths, PARTABLE_HEADERS)]
276
277    sep = " ".join("="*w for w in column_widths)
278    lines = [
279        sep,
280        " ".join("%-*s" % (w, h)
281                 for w, h in zip(column_widths, PARTABLE_HEADERS)),
282        sep,
283        ]
284    for p in pars:
285        lines.append(" ".join([
286            "%-*s" % (column_widths[0], p.name),
287            "%-*s" % (column_widths[1], p.description),
288            "%-*s" % (column_widths[2], format_units(p.units)),
289            "%*g" % (column_widths[3], p.default),
290            ]))
291    lines.append(sep)
292    return "\n".join(lines)
293
294
295def _search(search_path, filename):
296    # type: (List[str], str) -> str
297    """
298    Find *filename* in *search_path*.
299
300    Raises ValueError if file does not exist.
301    """
302    for path in search_path:
303        target = joinpath(path, filename)
304        if exists(target):
305            return target
306    raise ValueError("%r not found in %s" % (filename, search_path))
307
308
309def model_sources(model_info):
310    # type: (ModelInfo) -> List[str]
311    """
312    Return a list of the sources file paths for the module.
313    """
314    search_path = [dirname(model_info.filename), MODEL_PATH]
315    return [_search(search_path, f) for f in model_info.source]
316
317
318def timestamp(model_info):
319    # type: (ModelInfo) -> int
320    """
321    Return a timestamp for the model corresponding to the most recently
322    changed file or dependency.
323
324    Note that this does not look at the time stamps for the OpenCL header
325    information since that need not trigger a recompile of the DLL.
326    """
327    source_files = (model_sources(model_info)
328                    + model_templates()
329                    + [model_info.filename])
330    newest = max(getmtime(f) for f in source_files)
331    return newest
332
333
334def model_templates():
335    # type: () -> List[str]
336    # TODO: fails DRY; templates appear two places.
337    # should instead have model_info contain a list of paths
338    # Note: kernel_iq.cl is not on this list because changing it need not
339    # trigger a recompile of the dll.
340    return [joinpath(DATA_PATH, filename)
341            for filename in ('kernel_header.c', 'kernel_iq.c')]
342
343
344def convert_type(source, dtype):
345    # type: (str, np.dtype) -> str
346    """
347    Convert code from double precision to the desired type.
348
349    Floating point constants are tagged with 'f' for single precision or 'L'
350    for long double precision.
351    """
352    if dtype == F16:
353        fbytes = 2
354        source = _convert_type(source, "half", "f")
355    elif dtype == F32:
356        fbytes = 4
357        source = _convert_type(source, "float", "f")
358    elif dtype == F64:
359        fbytes = 8
360        # no need to convert if it is already double
361    elif dtype == F128:
362        fbytes = 16
363        source = _convert_type(source, "long double", "L")
364    else:
365        raise ValueError("Unexpected dtype in source conversion: %s" % dtype)
366    return ("#define FLOAT_SIZE %d\n" % fbytes)+source
367
368
369def _convert_type(source, type_name, constant_flag):
370    # type: (str, str, str) -> str
371    """
372    Replace 'double' with *type_name* in *source*, tagging floating point
373    constants with *constant_flag*.
374    """
375    # Convert double keyword to float/long double/half.
376    # Accept an 'n' # parameter for vector # values, where n is 2, 4, 8 or 16.
377    # Assume complex numbers are represented as cdouble which is typedef'd
378    # to double2.
379    source = re.sub(r'(^|[^a-zA-Z0-9_]c?)double(([248]|16)?($|[^a-zA-Z0-9_]))',
380                    r'\1%s\2'%type_name, source)
381    # Convert floating point constants to single by adding 'f' to the end,
382    # or long double with an 'L' suffix.  OS/X complains if you don't do this.
383    source = re.sub(r'[^a-zA-Z_](\d*[.]\d+|\d+[.]\d*)([eE][+-]?\d+)?',
384                    r'\g<0>%s'%constant_flag, source)
385    return source
386
387
388def kernel_name(model_info, variant):
389    # type: (ModelInfo, str) -> str
390    """
391    Name of the exported kernel symbol.
392
393    *variant* is "Iq", "Iqxy" or "Imagnetic".
394    """
395    return model_info.name + "_" + variant
396
397
398def indent(s, depth):
399    # type: (str, int) -> str
400    """
401    Indent a string of text with *depth* additional spaces on each line.
402    """
403    spaces = " "*depth
404    sep = "\n" + spaces
405    return spaces + sep.join(s.split("\n"))
406
407
408_template_cache = {}  # type: Dict[str, Tuple[int, str, str]]
409def load_template(filename):
410    # type: (str) -> str
411    path = joinpath(DATA_PATH, filename)
412    mtime = getmtime(path)
413    if filename not in _template_cache or mtime > _template_cache[filename][0]:
414        with open(path) as fid:
415            _template_cache[filename] = (mtime, fid.read(), path)
416    return _template_cache[filename][1], path
417
418
419_FN_TEMPLATE = """\
420double %(name)s(%(pars)s);
421double %(name)s(%(pars)s) {
422#line %(line)d "%(filename)s"
423    %(body)s
424}
425
426"""
427def _gen_fn(name, pars, body, filename, line):
428    # type: (str, List[Parameter], str, str, int) -> str
429    """
430    Generate a function given pars and body.
431
432    Returns the following string::
433
434         double fn(double a, double b, ...);
435         double fn(double a, double b, ...) {
436             ....
437         }
438    """
439    par_decl = ', '.join(p.as_function_argument() for p in pars) if pars else 'void'
440    return _FN_TEMPLATE % {
441        'name': name, 'pars': par_decl, 'body': body,
442        'filename': filename.replace('\\', '\\\\'), 'line': line,
443    }
444
445
446def _call_pars(prefix, pars):
447    # type: (str, List[Parameter]) -> List[str]
448    """
449    Return a list of *prefix.parameter* from parameter items.
450    """
451    return [p.as_call_reference(prefix) for p in pars]
452
453
454# type in IQXY pattern could be single, float, double, long double, ...
455_IQXY_PATTERN = re.compile("^((inline|static) )? *([a-z ]+ )? *Iqxy *([(]|$)",
456                           flags=re.MULTILINE)
457def _have_Iqxy(sources):
458    # type: (List[str]) -> bool
459    """
460    Return true if any file defines Iqxy.
461
462    Note this is not a C parser, and so can be easily confused by
463    non-standard syntax.  Also, it will incorrectly identify the following
464    as having Iqxy::
465
466        /*
467        double Iqxy(qx, qy, ...) { ... fill this in later ... }
468        */
469
470    If you want to comment out an Iqxy function, use // on the front of the
471    line instead.
472    """
473    for path, code in sources:
474        if _IQXY_PATTERN.search(code):
475            return True
476    else:
477        return False
478
479
480def _add_source(source, code, path):
481    """
482    Add a file to the list of source code chunks, tagged with path and line.
483    """
484    path = path.replace('\\', '\\\\')
485    source.append('#line 1 "%s"' % path)
486    source.append(code)
487
488def make_source(model_info):
489    # type: (ModelInfo) -> Dict[str, str]
490    """
491    Generate the OpenCL/ctypes kernel from the module info.
492
493    Uses source files found in the given search path.  Returns None if this
494    is a pure python model, with no C source components.
495    """
496    if callable(model_info.Iq):
497        raise ValueError("can't compile python model")
498        #return None
499
500    # TODO: need something other than volume to indicate dispersion parameters
501    # No volume normalization despite having a volume parameter.
502    # Thickness is labelled a volume in order to trigger polydispersity.
503    # May want a separate dispersion flag, or perhaps a separate category for
504    # disperse, but not volume.  Volume parameters also use relative values
505    # for the distribution rather than the absolute values used by angular
506    # dispersion.  Need to be careful that necessary parameters are available
507    # for computing volume even if we allow non-disperse volume parameters.
508
509    partable = model_info.parameters
510
511    # Load templates and user code
512    kernel_header = load_template('kernel_header.c')
513    dll_code = load_template('kernel_iq.c')
514    ocl_code = load_template('kernel_iq.cl')
515    #ocl_code = load_template('kernel_iq_local.cl')
516    user_code = [(f, open(f).read()) for f in model_sources(model_info)]
517
518    # Build initial sources
519    source = []
520    _add_source(source, *kernel_header)
521    for path, code in user_code:
522        _add_source(source, code, path)
523
524    # Make parameters for q, qx, qy so that we can use them in declarations
525    q, qx, qy = [Parameter(name=v) for v in ('q', 'qx', 'qy')]
526    # Generate form_volume function, etc. from body only
527    if isinstance(model_info.form_volume, str):
528        pars = partable.form_volume_parameters
529        source.append(_gen_fn('form_volume', pars, model_info.form_volume,
530                              model_info.filename, model_info._form_volume_line))
531    if isinstance(model_info.Iq, str):
532        pars = [q] + partable.iq_parameters
533        source.append(_gen_fn('Iq', pars, model_info.Iq,
534                              model_info.filename, model_info._Iq_line))
535    if isinstance(model_info.Iqxy, str):
536        pars = [qx, qy] + partable.iqxy_parameters
537        source.append(_gen_fn('Iqxy', pars, model_info.Iqxy,
538                              model_info.filename, model_info._Iqxy_line))
539
540    # Define the parameter table
541    # TODO: plug in current line number
542    source.append('#line 542 "sasmodels/generate.py"')
543    source.append("#define PARAMETER_TABLE \\")
544    source.append("\\\n".join(p.as_definition()
545                              for p in partable.kernel_parameters))
546
547    # Define the function calls
548    if partable.form_volume_parameters:
549        refs = _call_pars("_v.", partable.form_volume_parameters)
550        call_volume = "#define CALL_VOLUME(_v) form_volume(%s)"%(",".join(refs))
551    else:
552        # Model doesn't have volume.  We could make the kernel run a little
553        # faster by not using/transferring the volume normalizations, but
554        # the ifdef's reduce readability more than is worthwhile.
555        call_volume = "#define CALL_VOLUME(v) 1.0"
556    source.append(call_volume)
557
558    refs = ["_q[_i]"] + _call_pars("_v.", partable.iq_parameters)
559    call_iq = "#define CALL_IQ(_q,_i,_v) Iq(%s)" % (",".join(refs))
560    if _have_Iqxy(user_code) or isinstance(model_info.Iqxy, str):
561        # Call 2D model
562        refs = ["_q[2*_i]", "_q[2*_i+1]"] + _call_pars("_v.", partable.iqxy_parameters)
563        call_iqxy = "#define CALL_IQ(_q,_i,_v) Iqxy(%s)" % (",".join(refs))
564    else:
565        # Call 1D model with sqrt(qx^2 + qy^2)
566        #warnings.warn("Creating Iqxy = Iq(sqrt(qx^2 + qy^2))")
567        # still defined:: refs = ["q[i]"] + _call_pars("v", iq_parameters)
568        pars_sqrt = ["sqrt(_q[2*_i]*_q[2*_i]+_q[2*_i+1]*_q[2*_i+1])"] + refs[1:]
569        call_iqxy = "#define CALL_IQ(_q,_i,_v) Iq(%s)" % (",".join(pars_sqrt))
570
571    magpars = [k-2 for k,p in enumerate(partable.call_parameters)
572               if p.type == 'sld']
573
574    # Fill in definitions for numbers of parameters
575    source.append("#define MAX_PD %s"%partable.max_pd)
576    source.append("#define NUM_PARS %d"%partable.npars)
577    source.append("#define NUM_VALUES %d" % partable.nvalues)
578    source.append("#define NUM_MAGNETIC %d" % partable.nmagnetic)
579    source.append("#define MAGNETIC_PARS %s"%",".join(str(k) for k in magpars))
580    for k,v in enumerate(magpars[:3]):
581        source.append("#define MAGNETIC_PAR%d %d"%(k+1, v))
582
583    # TODO: allow mixed python/opencl kernels?
584
585    ocl = kernels(ocl_code, call_iq, call_iqxy, model_info.name)
586    dll = kernels(dll_code, call_iq, call_iqxy, model_info.name)
587    result = {
588        'dll': '\n'.join(source+dll[0]+dll[1]+dll[2]),
589        'opencl': '\n'.join(source+ocl[0]+ocl[1]+ocl[2]),
590    }
591
592    return result
593
594
595def kernels(kernel, call_iq, call_iqxy, name):
596    # type: ([str,str], str, str, str) -> List[str]
597    code = kernel[0]
598    path = kernel[1].replace('\\', '\\\\')
599    iq = [
600        # define the Iq kernel
601        "#define KERNEL_NAME %s_Iq" % name,
602        call_iq,
603        '#line 1 "%s Iq"' % path,
604        code,
605        "#undef CALL_IQ",
606        "#undef KERNEL_NAME",
607        ]
608
609    iqxy = [
610        # define the Iqxy kernel from the same source with different #defines
611        "#define KERNEL_NAME %s_Iqxy" % name,
612        call_iqxy,
613        '#line 1 "%s Iqxy"' % path,
614        code,
615        "#undef CALL_IQ",
616        "#undef KERNEL_NAME",
617         ]
618
619    imagnetic = [
620        # define the Imagnetic kernel
621        "#define KERNEL_NAME %s_Imagnetic" % name,
622        "#define MAGNETIC 1",
623        call_iqxy,
624        '#line 1 "%s Imagnetic"' % path,
625        code,
626        "#undef MAGNETIC",
627        "#undef CALL_IQ",
628        "#undef KERNEL_NAME",
629    ]
630
631    return iq, iqxy, imagnetic
632
633
634def load_kernel_module(model_name):
635    # type: (str) -> module
636    """
637    Return the kernel module named in *model_name*.
638
639    If the name ends in *.py* then load it as a custom model using
640    :func:`sasmodels.custom.load_custom_kernel_module`, otherwise
641    load it from :mod:`sasmodels.models`.
642    """
643    if model_name.endswith('.py'):
644        kernel_module = load_custom_kernel_module(model_name)
645    else:
646        from sasmodels import models
647        __import__('sasmodels.models.'+model_name)
648        kernel_module = getattr(models, model_name, None)
649    return kernel_module
650
651
652section_marker = re.compile(r'\A(?P<first>[%s])(?P=first)*\Z'
653                            % re.escape(string.punctuation))
654def _convert_section_titles_to_boldface(lines):
655    # type: (Sequence[str]) -> Iterator[str]
656    """
657    Do the actual work of identifying and converting section headings.
658    """
659    prior = None
660    for line in lines:
661        if prior is None:
662            prior = line
663        elif section_marker.match(line):
664            if len(line) >= len(prior):
665                yield "".join(("**", prior, "**"))
666                prior = None
667            else:
668                yield prior
669                prior = line
670        else:
671            yield prior
672            prior = line
673    if prior is not None:
674        yield prior
675
676
677def convert_section_titles_to_boldface(s):
678    # type: (str) -> str
679    """
680    Use explicit bold-face rather than section headings so that the table of
681    contents is not polluted with section names from the model documentation.
682
683    Sections are identified as the title line followed by a line of punctuation
684    at least as long as the title line.
685    """
686    return "\n".join(_convert_section_titles_to_boldface(s.split('\n')))
687
688
689def make_doc(model_info):
690    # type: (ModelInfo) -> str
691    """
692    Return the documentation for the model.
693    """
694    Iq_units = "The returned value is scaled to units of |cm^-1| |sr^-1|, absolute scale."
695    Sq_units = "The returned value is a dimensionless structure factor, $S(q)$."
696    docs = convert_section_titles_to_boldface(model_info.docs)
697    pars = make_partable(model_info.parameters.COMMON
698                         + model_info.parameters.kernel_parameters)
699    subst = dict(id=model_info.id.replace('_', '-'),
700                 name=model_info.name,
701                 title=model_info.title,
702                 parameters=pars,
703                 returns=Sq_units if model_info.structure_factor else Iq_units,
704                 docs=docs)
705    return DOC_HEADER % subst
706
707
708def make_html(model_info):
709    """
710    Convert model docs directly to html.
711    """
712    from . import rst2html
713    return rst2html.convert(make_doc(model_info), title=model_info['name'])
714
715def demo_time():
716    # type: () -> None
717    """
718    Show how long it takes to process a model.
719    """
720    import datetime
721    from .modelinfo import make_model_info
722    from .models import cylinder
723
724    tic = datetime.datetime.now()
725    make_source(make_model_info(cylinder))
726    toc = (datetime.datetime.now() - tic).total_seconds()
727    print("time: %g"%toc)
728
729
730def main():
731    # type: () -> None
732    """
733    Program which prints the source produced by the model.
734    """
735    import sys
736    from .modelinfo import make_model_info
737
738    if len(sys.argv) <= 1:
739        print("usage: python -m sasmodels.generate modelname")
740    else:
741        name = sys.argv[1]
742        kernel_module = load_kernel_module(name)
743        model_info = make_model_info(kernel_module)
744        source = make_source(model_info)
745        print(source['dll'])
746
747
748if __name__ == "__main__":
749    main()
Note: See TracBrowser for help on using the repository browser.