source: sasmodels/sasmodels/generate.py @ 190fc2b

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

delint

  • Property mode set to 100644
File size: 26.9 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.
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
24These functions are defined in a kernel module .py script and an associated
25set of .c files.  The model constructor will use them to create models with
26polydispersity across volume and orientation parameters, and provide
27scale and background parameters for each model.
28
29*Iq*, *Iqxy*, *Imagnetic* and *form_volume* should be stylized C-99
30functions written for OpenCL.  All functions need prototype declarations
31even if the are defined before they are used.  OpenCL does not support
32*#include* preprocessor directives, so instead the list of includes needs
33to be given as part of the metadata in the kernel module definition.
34The included files should be listed using a path relative to the kernel
35module, or if using "lib/file.c" if it is one of the standard includes
36provided with the sasmodels source.  The includes need to be listed in
37order so that functions are defined before they are used.
38
39Floating point values should be declared as *double*.  For single precision
40calculations, *double* will be replaced by *float*.  The single precision
41conversion will also tag floating point constants with "f" to make them
42single precision constants.  When using integral values in floating point
43expressions, they should be expressed as floating point values by including
44a decimal point.  This includes 0., 1. and 2.
45
46OpenCL has a *sincos* function which can improve performance when both
47the *sin* and *cos* values are needed for a particular argument.  Since
48this function does not exist in C99, all use of *sincos* should be
49replaced by the macro *SINCOS(value,sn,cn)* where *sn* and *cn* are
50previously declared *double* variables.  When compiled for systems without
51OpenCL, *SINCOS* will be replaced by *sin* and *cos* calls.   If *value* is
52an expression, it will appear twice in this case; whether or not it will be
53evaluated twice depends on the quality of the compiler.
54
55If the input parameters are invalid, the scattering calculator should
56return a negative number. Particularly with polydispersity, there are
57some sets of shape parameters which lead to nonsensical forms, such
58as a capped cylinder where the cap radius is smaller than the
59cylinder radius.  The polydispersity calculation will ignore these points,
60effectively chopping the parameter weight distributions at the boundary
61of the infeasible region.  The resulting scattering will be set to
62background.  This will work correctly even when polydispersity is off.
63
64*ER* and *VR* are python functions which operate on parameter vectors.
65The constructor code will generate the necessary vectors for computing
66them with the desired polydispersity.
67
68The available kernel parameters are defined as a list, with each parameter
69defined as a sublist with the following elements:
70
71    *name* is the name that will be used in the call to the kernel
72    function and the name that will be displayed to the user.  Names
73    should be lower case, with words separated by underscore.  If
74    acronyms are used, the whole acronym should be upper case.
75
76    *units* should be one of *degrees* for angles, *Ang* for lengths,
77    *1e-6/Ang^2* for SLDs.
78
79    *default value* will be the initial value for  the model when it
80    is selected, or when an initial value is not otherwise specified.
81
82    [*lb*, *ub*] are the hard limits on the parameter value, used to limit
83    the polydispersity density function.  In the fit, the parameter limits
84    given to the fit are the limits  on the central value of the parameter.
85    If there is polydispersity, it will evaluate parameter values outside
86    the fit limits, but not outside the hard limits specified in the model.
87    If there are no limits, use +/-inf imported from numpy.
88
89    *type* indicates how the parameter will be used.  "volume" parameters
90    will be used in all functions.  "orientation" parameters will be used
91    in *Iqxy* and *Imagnetic*.  "magnetic* parameters will be used in
92    *Imagnetic* only.  If *type* is the empty string, the parameter will
93    be used in all of *Iq*, *Iqxy* and *Imagnetic*.
94
95    *description* is a short description of the parameter.  This will
96    be displayed in the parameter table and used as a tool tip for the
97    parameter value in the user interface.
98
99The kernel module must set variables defining the kernel meta data:
100
101    *id* is an implicit variable formed from the filename.  It will be
102    a valid python identifier, and will be used as the reference into
103    the html documentation, with '_' replaced by '-'.
104
105    *name* is the model name as displayed to the user.  If it is missing,
106    it will be constructed from the id.
107
108    *title* is a short description of the model, suitable for a tool tip,
109    or a one line model summary in a table of models.
110
111    *description* is an extended description of the model to be displayed
112    while the model parameters are being edited.
113
114    *parameters* is the list of parameters.  Parameters in the kernel
115    functions must appear in the same order as they appear in the
116    parameters list.  Two additional parameters, *scale* and *background*
117    are added to the beginning of the parameter list.  They will show up
118    in the documentation as model parameters, but they are never sent to
119    the kernel functions.
120
121    *category* is the default category for the model.  Models in the
122    *structure-factor* category do not have *scale* and *background*
123    added.
124
125    *source* is the list of C-99 source files that must be joined to
126    create the OpenCL kernel functions.  The files defining the functions
127    need to be listed before the files which use the functions.
128
129    *ER* is a python function defining the effective radius.  If it is
130    not present, the effective radius is 0.
131
132    *VR* is a python function defining the volume ratio.  If it is not
133    present, the volume ratio is 1.
134
135    *form_volume*, *Iq*, *Iqxy*, *Imagnetic* are strings containing the
136    C source code for the body of the volume, Iq, and Iqxy functions
137    respectively.  These can also be defined in the last source file.
138
139    *Iq* and *Iqxy* also be instead be python functions defining the
140    kernel.  If they are marked as *Iq.vectorized = True* then the
141    kernel is passed the entire *q* vector at once, otherwise it is
142    passed values one *q* at a time.  The performance improvement of
143    this step is significant.
144
145    *demo* is a dictionary of parameter=value defining a set of
146    parameters to use by default when *compare* is called.  Any
147    parameter not set in *demo* gets the initial value from the
148    parameter list.  *demo* is mostly needed to set the default
149    polydispersity values for tests.
150
151    *oldname* is the name of the model in sasview before sasmodels
152    was split into its own package, and *oldpars* is a dictionary
153    of *parameter: old_parameter* pairs defining the new names for
154    the parameters.  This is used by *compare* to check the values
155    of the new model against the values of the old model before
156    you are ready to add the new model to sasmodels.
157
158
159An *info* dictionary is constructed from the kernel meta data and
160returned to the caller.
161
162The model evaluator, function call sequence consists of q inputs and the return vector,
163followed by the loop value/weight vector, followed by the values for
164the non-polydisperse parameters, followed by the lengths of the
165polydispersity loops.  To construct the call for 1D models, the
166categories *fixed-1d* and *pd-1d* list the names of the parameters
167of the non-polydisperse and the polydisperse parameters respectively.
168Similarly, *fixed-2d* and *pd-2d* provide parameter names for 2D models.
169The *pd-rel* category is a set of those parameters which give
170polydispersitiy as a portion of the value (so a 10% length dispersity
171would use a polydispersity value of 0.1) rather than absolute
172dispersity such as an angle plus or minus 15 degrees.
173
174The *volume* category lists the volume parameters in order for calls
175to volume within the kernel (used for volume normalization) and for
176calls to ER and VR for effective radius and volume ratio respectively.
177
178The *orientation* and *magnetic* categories list the orientation and
179magnetic parameters.  These are used by the sasview interface.  The
180blank category is for parameters such as scale which don't have any
181other marking.
182
183The doc string at the start of the kernel module will be used to
184construct the model documentation web pages.  Embedded figures should
185appear in the subdirectory "img" beside the model definition, and tagged
186with the kernel module name to avoid collision with other models.  Some
187file systems are case-sensitive, so only use lower case characters for
188file names and extensions.
189
190
191The function :func:`make` loads the metadata from the module and returns
192the kernel source.  The function :func:`doc` extracts the doc string
193and adds the parameter table to the top.  The function :func:`sources`
194returns a list of files required by the model.
195"""
196
197# TODO: identify model files which have changed since loading and reload them.
198
199import sys
200from os.path import abspath, dirname, join as joinpath, exists, basename, \
201    splitext
202import re
203import string
204
205import numpy as np
206
207__all__ = ["make", "doc", "sources", "convert_type"]
208
209C_KERNEL_TEMPLATE_PATH = joinpath(dirname(__file__), 'kernel_template.c')
210
211F16 = np.dtype('float16')
212F32 = np.dtype('float32')
213F64 = np.dtype('float64')
214try:  # CRUFT: older numpy does not support float128
215    F128 = np.dtype('float128')
216except TypeError:
217    F128 = None
218
219# Scale and background, which are parameters common to every form factor
220COMMON_PARAMETERS = [
221    ["scale", "", 1, [0, np.inf], "", "Source intensity"],
222    ["background", "1/cm", 0, [0, np.inf], "", "Source background"],
223    ]
224
225# Conversion from units defined in the parameter table for each model
226# to units displayed in the sphinx documentation.
227RST_UNITS = {
228    "Ang": "|Ang|",
229    "1/Ang": "|Ang^-1|",
230    "1/Ang^2": "|Ang^-2|",
231    "1e-6/Ang^2": "|1e-6Ang^-2|",
232    "degrees": "degree",
233    "1/cm": "|cm^-1|",
234    "": "None",
235    }
236
237# Headers for the parameters tables in th sphinx documentation
238PARTABLE_HEADERS = [
239    "Parameter",
240    "Description",
241    "Units",
242    "Default value",
243    ]
244
245# Minimum width for a default value (this is shorter than the column header
246# width, so will be ignored).
247PARTABLE_VALUE_WIDTH = 10
248
249# Documentation header for the module, giving the model name, its short
250# description and its parameter table.  The remainder of the doc comes
251# from the module docstring.
252DOC_HEADER = """.. _%(id)s:
253
254%(name)s
255=======================================================
256
257%(title)s
258
259%(parameters)s
260
261%(returns)s
262
263%(docs)s
264"""
265
266def format_units(units):
267    """
268    Convert units into ReStructured Text format.
269    """
270    return "string" if isinstance(units, list) else RST_UNITS.get(units, units)
271
272def make_partable(pars):
273    """
274    Generate the parameter table to include in the sphinx documentation.
275    """
276    column_widths = [
277        max(len(p[0]) for p in pars),
278        max(len(p[-1]) for p in pars),
279        max(len(format_units(p[1])) for p in pars),
280        PARTABLE_VALUE_WIDTH,
281        ]
282    column_widths = [max(w, len(h))
283                     for w, h in zip(column_widths, PARTABLE_HEADERS)]
284
285    sep = " ".join("="*w for w in column_widths)
286    lines = [
287        sep,
288        " ".join("%-*s" % (w, h)
289                 for w, h in zip(column_widths, PARTABLE_HEADERS)),
290        sep,
291        ]
292    for p in pars:
293        lines.append(" ".join([
294            "%-*s" % (column_widths[0], p[0]),
295            "%-*s" % (column_widths[1], p[-1]),
296            "%-*s" % (column_widths[2], format_units(p[1])),
297            "%*g" % (column_widths[3], p[2]),
298            ]))
299    lines.append(sep)
300    return "\n".join(lines)
301
302def _search(search_path, filename):
303    """
304    Find *filename* in *search_path*.
305
306    Raises ValueError if file does not exist.
307    """
308    for path in search_path:
309        target = joinpath(path, filename)
310        if exists(target):
311            return target
312    raise ValueError("%r not found in %s" % (filename, search_path))
313
314def sources(info):
315    """
316    Return a list of the sources file paths for the module.
317    """
318    search_path = [dirname(info['filename']),
319                   abspath(joinpath(dirname(__file__), 'models'))]
320    return [_search(search_path, f) for f in info['source']]
321
322# Pragmas for enable OpenCL features.  Be sure to protect them so that they
323# still compile even if OpenCL is not present.
324_F16_PRAGMA = """\
325#if defined(__OPENCL_VERSION__) && !defined(cl_khr_fp16)
326#  pragma OPENCL EXTENSION cl_khr_fp16: enable
327#endif
328"""
329
330_F64_PRAGMA = """\
331#if defined(__OPENCL_VERSION__) && !defined(cl_khr_fp64)
332#  pragma OPENCL EXTENSION cl_khr_fp64: enable
333#endif
334"""
335
336def convert_type(source, dtype):
337    """
338    Convert code from double precision to the desired type.
339
340    Floating point constants are tagged with 'f' for single precision or 'L'
341    for long double precision.
342    """
343    if dtype == F16:
344        source = _F16_PRAGMA + _convert_type(source, "half", "f")
345    elif dtype == F32:
346        source = _convert_type(source, "float", "f")
347    elif dtype == F64:
348        source = _F64_PRAGMA + source  # Source is already double
349    elif dtype == F128:
350        source = _convert_type(source, "long double", "L")
351    else:
352        raise ValueError("Unexpected dtype in source conversion: %s"%dtype)
353    return source
354
355
356def _convert_type(source, type_name, constant_flag):
357    """
358    Replace 'double' with *type_name* in *source*, tagging floating point
359    constants with *constant_flag*.
360    """
361    # Convert double keyword to float/long double/half.
362    # Accept an 'n' # parameter for vector # values, where n is 2, 4, 8 or 16.
363    # Assume complex numbers are represented as cdouble which is typedef'd
364    # to double2.
365    source = re.sub(r'(^|[^a-zA-Z0-9_]c?)double(([248]|16)?($|[^a-zA-Z0-9_]))',
366                    r'\1%s\2'%type_name, source)
367    # Convert floating point constants to single by adding 'f' to the end,
368    # or long double with an 'L' suffix.  OS/X complains if you don't do this.
369    source = re.sub(r'[^a-zA-Z_](\d*[.]\d+|\d+[.]\d*)([eE][+-]?\d+)?',
370                    r'\g<0>%s'%constant_flag, source)
371    return source
372
373
374def kernel_name(info, is_2D):
375    """
376    Name of the exported kernel symbol.
377    """
378    return info['name'] + "_" + ("Iqxy" if is_2D else "Iq")
379
380
381def categorize_parameters(pars):
382    """
383    Build parameter categories out of the the parameter definitions.
384
385    Returns a dictionary of categories.
386    """
387    partype = {
388        'volume': [], 'orientation': [], 'magnetic': [], '': [],
389        'fixed-1d': [], 'fixed-2d': [], 'pd-1d': [], 'pd-2d': [],
390        'pd-rel': set(),
391    }
392
393    for p in pars:
394        name, ptype = p[0], p[4]
395        if ptype == 'volume':
396            partype['pd-1d'].append(name)
397            partype['pd-2d'].append(name)
398            partype['pd-rel'].add(name)
399        elif ptype == 'magnetic':
400            partype['fixed-2d'].append(name)
401        elif ptype == 'orientation':
402            partype['pd-2d'].append(name)
403        elif ptype == '':
404            partype['fixed-1d'].append(name)
405            partype['fixed-2d'].append(name)
406        else:
407            raise ValueError("unknown parameter type %r" % ptype)
408        partype[ptype].append(name)
409
410    return partype
411
412def indent(s, depth):
413    """
414    Indent a string of text with *depth* additional spaces on each line.
415    """
416    spaces = " "*depth
417    sep = "\n" + spaces
418    return spaces + sep.join(s.split("\n"))
419
420
421def build_polydispersity_loops(pd_pars):
422    """
423    Build polydispersity loops
424
425    Returns loop opening and loop closing
426    """
427    LOOP_OPEN = """\
428for (int %(name)s_i=0; %(name)s_i < N%(name)s; %(name)s_i++) {
429  const double %(name)s = loops[2*(%(name)s_i%(offset)s)];
430  const double %(name)s_w = loops[2*(%(name)s_i%(offset)s)+1];\
431"""
432    depth = 4
433    offset = ""
434    loop_head = []
435    loop_end = []
436    for name in pd_pars:
437        subst = {'name': name, 'offset': offset}
438        loop_head.append(indent(LOOP_OPEN % subst, depth))
439        loop_end.insert(0, (" "*depth) + "}")
440        offset += '+N' + name
441        depth += 2
442    return "\n".join(loop_head), "\n".join(loop_end)
443
444C_KERNEL_TEMPLATE = None
445def make_model(info):
446    """
447    Generate the code for the kernel defined by info, using source files
448    found in the given search path.
449    """
450    # TODO: need something other than volume to indicate dispersion parameters
451    # No volume normalization despite having a volume parameter.
452    # Thickness is labelled a volume in order to trigger polydispersity.
453    # May want a separate dispersion flag, or perhaps a separate category for
454    # disperse, but not volume.  Volume parameters also use relative values
455    # for the distribution rather than the absolute values used by angular
456    # dispersion.  Need to be careful that necessary parameters are available
457    # for computing volume even if we allow non-disperse volume parameters.
458
459    # Load template
460    global C_KERNEL_TEMPLATE
461    if C_KERNEL_TEMPLATE is None:
462        with open(C_KERNEL_TEMPLATE_PATH) as fid:
463            C_KERNEL_TEMPLATE = fid.read()
464
465    # Load additional sources
466    source = [open(f).read() for f in sources(info)]
467
468    # Prepare defines
469    defines = []
470    partype = info['partype']
471    pd_1d = partype['pd-1d']
472    pd_2d = partype['pd-2d']
473    fixed_1d = partype['fixed-1d']
474    fixed_2d = partype['fixed-1d']
475
476    iq_parameters = [p[0]
477                     for p in info['parameters'][2:] # skip scale, background
478                     if p[0] in set(fixed_1d + pd_1d)]
479    iqxy_parameters = [p[0]
480                       for p in info['parameters'][2:] # skip scale, background
481                       if p[0] in set(fixed_2d + pd_2d)]
482    volume_parameters = [p[0]
483                         for p in info['parameters']
484                         if p[4] == 'volume']
485
486    # Fill in defintions for volume parameters
487    if volume_parameters:
488        defines.append(('VOLUME_PARAMETERS',
489                        ','.join(volume_parameters)))
490        defines.append(('VOLUME_WEIGHT_PRODUCT',
491                        '*'.join(p + '_w' for p in volume_parameters)))
492
493    # Generate form_volume function from body only
494    if info['form_volume'] is not None:
495        if volume_parameters:
496            vol_par_decl = ', '.join('double ' + p for p in volume_parameters)
497        else:
498            vol_par_decl = 'void'
499        defines.append(('VOLUME_PARAMETER_DECLARATIONS',
500                        vol_par_decl))
501        fn = """\
502double form_volume(VOLUME_PARAMETER_DECLARATIONS);
503double form_volume(VOLUME_PARAMETER_DECLARATIONS) {
504    %(body)s
505}
506""" % {'body':info['form_volume']}
507        source.append(fn)
508
509    # Fill in definitions for Iq parameters
510    defines.append(('IQ_KERNEL_NAME', info['name'] + '_Iq'))
511    defines.append(('IQ_PARAMETERS', ', '.join(iq_parameters)))
512    if fixed_1d:
513        defines.append(('IQ_FIXED_PARAMETER_DECLARATIONS',
514                        ', \\\n    '.join('const double %s' % p for p in fixed_1d)))
515    if pd_1d:
516        defines.append(('IQ_WEIGHT_PRODUCT',
517                        '*'.join(p + '_w' for p in pd_1d)))
518        defines.append(('IQ_DISPERSION_LENGTH_DECLARATIONS',
519                        ', \\\n    '.join('const int N%s' % p for p in pd_1d)))
520        defines.append(('IQ_DISPERSION_LENGTH_SUM',
521                        '+'.join('N' + p for p in pd_1d)))
522        open_loops, close_loops = build_polydispersity_loops(pd_1d)
523        defines.append(('IQ_OPEN_LOOPS',
524                        open_loops.replace('\n', ' \\\n')))
525        defines.append(('IQ_CLOSE_LOOPS',
526                        close_loops.replace('\n', ' \\\n')))
527    if info['Iq'] is not None:
528        defines.append(('IQ_PARAMETER_DECLARATIONS',
529                        ', '.join('double ' + p for p in iq_parameters)))
530        fn = """\
531double Iq(double q, IQ_PARAMETER_DECLARATIONS);
532double Iq(double q, IQ_PARAMETER_DECLARATIONS) {
533    %(body)s
534}
535""" % {'body':info['Iq']}
536        source.append(fn)
537
538    # Fill in definitions for Iqxy parameters
539    defines.append(('IQXY_KERNEL_NAME', info['name'] + '_Iqxy'))
540    defines.append(('IQXY_PARAMETERS', ', '.join(iqxy_parameters)))
541    if fixed_2d:
542        defines.append(('IQXY_FIXED_PARAMETER_DECLARATIONS',
543                        ', \\\n    '.join('const double %s' % p for p in fixed_2d)))
544    if pd_2d:
545        defines.append(('IQXY_WEIGHT_PRODUCT',
546                        '*'.join(p + '_w' for p in pd_2d)))
547        defines.append(('IQXY_DISPERSION_LENGTH_DECLARATIONS',
548                        ', \\\n    '.join('const int N%s' % p for p in pd_2d)))
549        defines.append(('IQXY_DISPERSION_LENGTH_SUM',
550                        '+'.join('N' + p for p in pd_2d)))
551        open_loops, close_loops = build_polydispersity_loops(pd_2d)
552        defines.append(('IQXY_OPEN_LOOPS',
553                        open_loops.replace('\n', ' \\\n')))
554        defines.append(('IQXY_CLOSE_LOOPS',
555                        close_loops.replace('\n', ' \\\n')))
556    if info['Iqxy'] is not None:
557        defines.append(('IQXY_PARAMETER_DECLARATIONS',
558                        ', '.join('double ' + p for p in iqxy_parameters)))
559        fn = """\
560double Iqxy(double qx, double qy, IQXY_PARAMETER_DECLARATIONS);
561double Iqxy(double qx, double qy, IQXY_PARAMETER_DECLARATIONS) {
562    %(body)s
563}
564""" % {'body':info['Iqxy']}
565        source.append(fn)
566
567    # Need to know if we have a theta parameter for Iqxy; it is not there
568    # for the magnetic sphere model, for example, which has a magnetic
569    # orientation but no shape orientation.
570    if 'theta' in pd_2d:
571        defines.append(('IQXY_HAS_THETA', '1'))
572
573    #for d in defines: print(d)
574    DEFINES = '\n'.join('#define %s %s' % (k, v) for k, v in defines)
575    SOURCES = '\n\n'.join(source)
576    return C_KERNEL_TEMPLATE % {
577        'DEFINES':DEFINES,
578        'SOURCES':SOURCES,
579        }
580
581def make_info(kernel_module):
582    """
583    Interpret the model definition file, categorizing the parameters.
584    """
585    #print(kernelfile)
586    category = getattr(kernel_module, 'category', None)
587    parameters = COMMON_PARAMETERS + kernel_module.parameters
588    # Default the demo parameters to the starting values for the individual
589    # parameters if an explicit demo parameter set has not been specified.
590    demo_parameters = getattr(kernel_module, 'demo', None)
591    if demo_parameters is None:
592        demo_parameters = dict((p[0],p[2]) for p in parameters)
593    filename = abspath(kernel_module.__file__)
594    kernel_id = splitext(basename(filename))[0]
595    name = getattr(kernel_module, 'name', None)
596    if name is None:
597        name = " ".join(w.capitalize() for w in kernel_id.split('_'))
598    info = dict(
599        id = kernel_id,  # string used to load the kernel
600        filename=abspath(kernel_module.__file__),
601        name=name,
602        title=kernel_module.title,
603        description=kernel_module.description,
604        category=category,
605        parameters=parameters,
606        demo=demo_parameters,
607        source=getattr(kernel_module, 'source', []),
608        oldname=kernel_module.oldname,
609        oldpars=kernel_module.oldpars,
610        )
611    # Fill in attributes which default to None
612    info.update((k, getattr(kernel_module, k, None))
613                for k in ('ER', 'VR', 'form_volume', 'Iq', 'Iqxy'))
614    # Fill in the derived attributes
615    info['limits'] = dict((p[0], p[3]) for p in info['parameters'])
616    info['partype'] = categorize_parameters(info['parameters'])
617    info['defaults'] = dict((p[0], p[2]) for p in info['parameters'])
618    return info
619
620def make(kernel_module):
621    """
622    Build an OpenCL/ctypes function from the definition in *kernel_module*.
623
624    The module can be loaded with a normal python import statement if you
625    know which module you need, or with __import__('sasmodels.model.'+name)
626    if the name is in a string.
627    """
628    info = make_info(kernel_module)
629    # Assume if one part of the kernel is python then all parts are.
630    source = make_model(info) if not callable(info['Iq']) else None
631    return source, info
632
633section_marker = re.compile(r'\A(?P<first>[%s])(?P=first)*\Z'
634                            %re.escape(string.punctuation))
635def _convert_section_titles_to_boldface(lines):
636    """
637    Do the actual work of identifying and converting section headings.
638    """
639    prior = None
640    for line in lines:
641        if prior is None:
642            prior = line
643        elif section_marker.match(line):
644            if len(line) >= len(prior):
645                yield "".join( ("**",prior,"**") )
646                prior = None
647            else:
648                yield prior
649                prior = line
650        else:
651            yield prior
652            prior = line
653    if prior is not None:
654        yield prior
655
656def convert_section_titles_to_boldface(s):
657    """
658    Use explicit bold-face rather than section headings so that the table of
659    contents is not polluted with section names from the model documentation.
660
661    Sections are identified as the title line followed by a line of punctuation
662    at least as long as the title line.
663    """
664    return "\n".join(_convert_section_titles_to_boldface(s.split('\n')))
665
666def doc(kernel_module):
667    """
668    Return the documentation for the model.
669    """
670    Iq_units = "The returned value is scaled to units of |cm^-1| |sr^-1|, absolute scale."
671    Sq_units = "The returned value is a dimensionless structure factor, $S(q)$."
672    info = make_info(kernel_module)
673    is_Sq = ("structure-factor" in info['category'])
674    #docs = kernel_module.__doc__
675    docs = convert_section_titles_to_boldface(kernel_module.__doc__)
676    subst = dict(id=info['id'].replace('_', '-'),
677                 name=info['name'],
678                 title=info['title'],
679                 parameters=make_partable(info['parameters']),
680                 returns=Sq_units if is_Sq else Iq_units,
681                 docs=docs)
682    return DOC_HEADER % subst
683
684
685
686def demo_time():
687    """
688    Show how long it takes to process a model.
689    """
690    from .models import cylinder
691    import datetime
692    tic = datetime.datetime.now()
693    make(cylinder)
694    toc = (datetime.datetime.now() - tic).total_seconds()
695    print("time: %g"%toc)
696
697def main():
698    """
699    Program which prints the source produced by the model.
700    """
701    if len(sys.argv) <= 1:
702        print("usage: python -m sasmodels.generate modelname")
703    else:
704        name = sys.argv[1]
705        import sasmodels.models
706        __import__('sasmodels.models.' + name)
707        model = getattr(sasmodels.models, name)
708        source, _ = make(model)
709        print(source)
710
711if __name__ == "__main__":
712    main()
Note: See TracBrowser for help on using the repository browser.