source: sasmodels/sasmodels/generate.py @ 5edfe12

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

support long double kernels for precision limited models

  • Property mode set to 100644
File size: 24.6 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
199__all__ = ["make", "doc", "sources", "use_single", "use_long_double"]
200
201import sys
202from os.path import abspath, dirname, join as joinpath, exists, basename
203import re
204
205import numpy as np
206C_KERNEL_TEMPLATE_PATH = joinpath(dirname(__file__), 'kernel_template.c')
207
208F128 = np.dtype('float128')
209F64 = np.dtype('float64')
210F32 = np.dtype('float32')
211
212# Scale and background, which are parameters common to every form factor
213COMMON_PARAMETERS = [
214    ["scale", "", 1, [0, np.inf], "", "Source intensity"],
215    ["background", "1/cm", 0, [0, np.inf], "", "Source background"],
216    ]
217
218
219# Conversion from units defined in the parameter table for each model
220# to units displayed in the sphinx documentation.
221RST_UNITS = {
222    "Ang": "|Ang|",
223    "1/Ang": "|Ang^-1|",
224    "1/Ang^2": "|Ang^-2|",
225    "1e-6/Ang^2": "|1e-6Ang^-2|",
226    "degrees": "degree",
227    "1/cm": "|cm^-1|",
228    "": "None",
229    }
230
231# Headers for the parameters tables in th sphinx documentation
232PARTABLE_HEADERS = [
233    "Parameter",
234    "Description",
235    "Units",
236    "Default value",
237    ]
238
239# Minimum width for a default value (this is shorter than the column header
240# width, so will be ignored).
241PARTABLE_VALUE_WIDTH = 10
242
243# Documentation header for the module, giving the model name, its short
244# description and its parameter table.  The remainder of the doc comes
245# from the module docstring.
246DOC_HEADER = """.. _%(id)s:
247
248%(name)s
249=======================================================
250
251%(title)s
252
253%(parameters)s
254
255The returned value is scaled to units of |cm^-1|.
256
257%(docs)s
258"""
259
260def format_units(par):
261    return RST_UNITS.get(par, par)
262
263def make_partable(pars):
264    """
265    Generate the parameter table to include in the sphinx documentation.
266    """
267    column_widths = [
268        max(len(p[0]) for p in pars),
269        max(len(p[-1]) for p in pars),
270        max(len(format_units(p[1])) for p in pars),
271        PARTABLE_VALUE_WIDTH,
272        ]
273    column_widths = [max(w, len(h))
274                     for w, h in zip(column_widths, PARTABLE_HEADERS)]
275
276    sep = " ".join("="*w for w in column_widths)
277    lines = [
278        sep,
279        " ".join("%-*s" % (w, h) for w, h in zip(column_widths, PARTABLE_HEADERS)),
280        sep,
281        ]
282    for p in pars:
283        lines.append(" ".join([
284            "%-*s" % (column_widths[0], p[0]),
285            "%-*s" % (column_widths[1], p[-1]),
286            "%-*s" % (column_widths[2], format_units(p[1])),
287            "%*g" % (column_widths[3], p[2]),
288            ]))
289    lines.append(sep)
290    return "\n".join(lines)
291
292def _search(search_path, filename):
293    """
294    Find *filename* in *search_path*.
295
296    Raises ValueError if file does not exist.
297    """
298    for path in search_path:
299        target = joinpath(path, filename)
300        if exists(target):
301            return target
302    raise ValueError("%r not found in %s" % (filename, search_path))
303
304def sources(info):
305    """
306    Return a list of the sources file paths for the module.
307    """
308    search_path = [dirname(info['filename']),
309                   abspath(joinpath(dirname(__file__), 'models'))]
310    return [_search(search_path, f) for f in info['source']]
311
312def use_single(source):
313    """
314    Convert code from double precision to single precision.
315    """
316    # Convert double keyword to float.  Accept an 'n' parameter for vector
317    # values, where n is 2, 4, 8 or 16. Assume complex numbers are represented
318    # as cdouble which is typedef'd to double2.
319    source = re.sub(r'(^|[^a-zA-Z0-9_]c?)double(([248]|16)?($|[^a-zA-Z0-9_]))',
320                    r'\1float\2', source)
321    # Convert floating point constants to single by adding 'f' to the end.
322    # OS/X driver complains if you don't do this.
323    source = re.sub(r'[^a-zA-Z_](\d*[.]\d+|\d+[.]\d*)([eE][+-]?\d+)?',
324                    r'\g<0>f', source)
325    return source
326
327def use_long_double(source):
328    """
329    Convert code from double precision to long double precision.
330    """
331    # Convert double keyword to float.  Accept an 'n' parameter for vector
332    # values, where n is 2, 4, 8 or 16. Assume complex numbers are represented
333    # as cdouble which is typedef'd to double2.
334    source = re.sub(r'(^|[^a-zA-Z0-9_]c?)double(([248]|16)?($|[^a-zA-Z0-9_]))',
335                    r'\1long double\2', source)
336    # Convert floating point constants to single by adding 'f' to the end.
337    # OS/X driver complains if you don't do this.
338    source = re.sub(r'[^a-zA-Z_](\d*[.]\d+|\d+[.]\d*)([eE][+-]?\d+)?',
339                    r'\g<0>L', source)
340    return source
341
342
343def kernel_name(info, is_2D):
344    """
345    Name of the exported kernel symbol.
346    """
347    return info['name'] + "_" + ("Iqxy" if is_2D else "Iq")
348
349
350def categorize_parameters(pars):
351    """
352    Build parameter categories out of the the parameter definitions.
353
354    Returns a dictionary of categories.
355    """
356    partype = {
357        'volume': [], 'orientation': [], 'magnetic': [], '': [],
358        'fixed-1d': [], 'fixed-2d': [], 'pd-1d': [], 'pd-2d': [],
359        'pd-rel': set(),
360    }
361
362    for p in pars:
363        name, ptype = p[0], p[4]
364        if ptype == 'volume':
365            partype['pd-1d'].append(name)
366            partype['pd-2d'].append(name)
367            partype['pd-rel'].add(name)
368        elif ptype == 'magnetic':
369            partype['fixed-2d'].append(name)
370        elif ptype == 'orientation':
371            partype['pd-2d'].append(name)
372        elif ptype == '':
373            partype['fixed-1d'].append(name)
374            partype['fixed-2d'].append(name)
375        else:
376            raise ValueError("unknown parameter type %r" % ptype)
377        partype[ptype].append(name)
378
379    return partype
380
381def indent(s, depth):
382    """
383    Indent a string of text with *depth* additional spaces on each line.
384    """
385    spaces = " "*depth
386    sep = "\n" + spaces
387    return spaces + sep.join(s.split("\n"))
388
389
390def build_polydispersity_loops(pd_pars):
391    """
392    Build polydispersity loops
393
394    Returns loop opening and loop closing
395    """
396    LOOP_OPEN = """\
397for (int %(name)s_i=0; %(name)s_i < N%(name)s; %(name)s_i++) {
398  const double %(name)s = loops[2*(%(name)s_i%(offset)s)];
399  const double %(name)s_w = loops[2*(%(name)s_i%(offset)s)+1];\
400"""
401    depth = 4
402    offset = ""
403    loop_head = []
404    loop_end = []
405    for name in pd_pars:
406        subst = {'name': name, 'offset': offset}
407        loop_head.append(indent(LOOP_OPEN % subst, depth))
408        loop_end.insert(0, (" "*depth) + "}")
409        offset += '+N' + name
410        depth += 2
411    return "\n".join(loop_head), "\n".join(loop_end)
412
413C_KERNEL_TEMPLATE = None
414def make_model(info):
415    """
416    Generate the code for the kernel defined by info, using source files
417    found in the given search path.
418    """
419    # TODO: need something other than volume to indicate dispersion parameters
420    # No volume normalization despite having a volume parameter.
421    # Thickness is labelled a volume in order to trigger polydispersity.
422    # May want a separate dispersion flag, or perhaps a separate category for
423    # disperse, but not volume.  Volume parameters also use relative values
424    # for the distribution rather than the absolute values used by angular
425    # dispersion.  Need to be careful that necessary parameters are available
426    # for computing volume even if we allow non-disperse volume parameters.
427
428    # Load template
429    global C_KERNEL_TEMPLATE
430    if C_KERNEL_TEMPLATE is None:
431        with open(C_KERNEL_TEMPLATE_PATH) as fid:
432            C_KERNEL_TEMPLATE = fid.read()
433
434    # Load additional sources
435    source = [open(f).read() for f in sources(info)]
436
437    # Prepare defines
438    defines = []
439    partype = info['partype']
440    pd_1d = partype['pd-1d']
441    pd_2d = partype['pd-2d']
442    fixed_1d = partype['fixed-1d']
443    fixed_2d = partype['fixed-1d']
444
445    iq_parameters = [p[0]
446                     for p in info['parameters'][2:] # skip scale, background
447                     if p[0] in set(fixed_1d + pd_1d)]
448    iqxy_parameters = [p[0]
449                       for p in info['parameters'][2:] # skip scale, background
450                       if p[0] in set(fixed_2d + pd_2d)]
451    volume_parameters = [p[0]
452                         for p in info['parameters']
453                         if p[4] == 'volume']
454
455    # Fill in defintions for volume parameters
456    if volume_parameters:
457        defines.append(('VOLUME_PARAMETERS',
458                        ','.join(volume_parameters)))
459        defines.append(('VOLUME_WEIGHT_PRODUCT',
460                        '*'.join(p + '_w' for p in volume_parameters)))
461
462    # Generate form_volume function from body only
463    if info['form_volume'] is not None:
464        if volume_parameters:
465            vol_par_decl = ', '.join('double ' + p for p in volume_parameters)
466        else:
467            vol_par_decl = 'void'
468        defines.append(('VOLUME_PARAMETER_DECLARATIONS',
469                        vol_par_decl))
470        fn = """\
471double form_volume(VOLUME_PARAMETER_DECLARATIONS);
472double form_volume(VOLUME_PARAMETER_DECLARATIONS) {
473    %(body)s
474}
475""" % {'body':info['form_volume']}
476        source.append(fn)
477
478    # Fill in definitions for Iq parameters
479    defines.append(('IQ_KERNEL_NAME', info['name'] + '_Iq'))
480    defines.append(('IQ_PARAMETERS', ', '.join(iq_parameters)))
481    if fixed_1d:
482        defines.append(('IQ_FIXED_PARAMETER_DECLARATIONS',
483                        ', \\\n    '.join('const double %s' % p for p in fixed_1d)))
484    if pd_1d:
485        defines.append(('IQ_WEIGHT_PRODUCT',
486                        '*'.join(p + '_w' for p in pd_1d)))
487        defines.append(('IQ_DISPERSION_LENGTH_DECLARATIONS',
488                        ', \\\n    '.join('const int N%s' % p for p in pd_1d)))
489        defines.append(('IQ_DISPERSION_LENGTH_SUM',
490                        '+'.join('N' + p for p in pd_1d)))
491        open_loops, close_loops = build_polydispersity_loops(pd_1d)
492        defines.append(('IQ_OPEN_LOOPS',
493                        open_loops.replace('\n', ' \\\n')))
494        defines.append(('IQ_CLOSE_LOOPS',
495                        close_loops.replace('\n', ' \\\n')))
496    if info['Iq'] is not None:
497        defines.append(('IQ_PARAMETER_DECLARATIONS',
498                        ', '.join('double ' + p for p in iq_parameters)))
499        fn = """\
500double Iq(double q, IQ_PARAMETER_DECLARATIONS);
501double Iq(double q, IQ_PARAMETER_DECLARATIONS) {
502    %(body)s
503}
504""" % {'body':info['Iq']}
505        source.append(fn)
506
507    # Fill in definitions for Iqxy parameters
508    defines.append(('IQXY_KERNEL_NAME', info['name'] + '_Iqxy'))
509    defines.append(('IQXY_PARAMETERS', ', '.join(iqxy_parameters)))
510    if fixed_2d:
511        defines.append(('IQXY_FIXED_PARAMETER_DECLARATIONS',
512                        ', \\\n    '.join('const double %s' % p for p in fixed_2d)))
513    if pd_2d:
514        defines.append(('IQXY_WEIGHT_PRODUCT',
515                        '*'.join(p + '_w' for p in pd_2d)))
516        defines.append(('IQXY_DISPERSION_LENGTH_DECLARATIONS',
517                        ', \\\n    '.join('const int N%s' % p for p in pd_2d)))
518        defines.append(('IQXY_DISPERSION_LENGTH_SUM',
519                        '+'.join('N' + p for p in pd_2d)))
520        open_loops, close_loops = build_polydispersity_loops(pd_2d)
521        defines.append(('IQXY_OPEN_LOOPS',
522                        open_loops.replace('\n', ' \\\n')))
523        defines.append(('IQXY_CLOSE_LOOPS',
524                        close_loops.replace('\n', ' \\\n')))
525    if info['Iqxy'] is not None:
526        defines.append(('IQXY_PARAMETER_DECLARATIONS',
527                        ', '.join('double ' + p for p in iqxy_parameters)))
528        fn = """\
529double Iqxy(double qx, double qy, IQXY_PARAMETER_DECLARATIONS);
530double Iqxy(double qx, double qy, IQXY_PARAMETER_DECLARATIONS) {
531    %(body)s
532}
533""" % {'body':info['Iqxy']}
534        source.append(fn)
535
536    # Need to know if we have a theta parameter for Iqxy; it is not there
537    # for the magnetic sphere model, for example, which has a magnetic
538    # orientation but no shape orientation.
539    if 'theta' in pd_2d:
540        defines.append(('IQXY_HAS_THETA', '1'))
541
542    #for d in defines: print d
543    DEFINES = '\n'.join('#define %s %s' % (k, v) for k, v in defines)
544    SOURCES = '\n\n'.join(source)
545    return C_KERNEL_TEMPLATE % {
546        'DEFINES':DEFINES,
547        'SOURCES':SOURCES,
548        }
549
550def make_info(kernel_module):
551    """
552    Interpret the model definition file, categorizing the parameters.
553    """
554    #print kernelfile
555    category = getattr(kernel_module, 'category', None)
556    parameters = COMMON_PARAMETERS + kernel_module.parameters
557    # Default the demo parameters to the starting values for the individual
558    # parameters if an explicit demo parameter set has not been specified.
559    demo_parameters = getattr(kernel_module, 'demo', None)
560    if demo_parameters is None:
561        demo_parameters = dict((p[0],p[2]) for p in parameters)
562    filename = abspath(kernel_module.__file__)
563    kernel_id = basename(filename)[:-3]
564    name = getattr(kernel_module, 'name', None)
565    if name is None:
566        name = " ".join(w.capitalize() for w in kernel_id.split('_'))
567    info = dict(
568        id = kernel_id,  # string used to load the kernel
569        filename=abspath(kernel_module.__file__),
570        name=name,
571        title=kernel_module.title,
572        description=kernel_module.description,
573        category=category,
574        parameters=parameters,
575        demo=demo_parameters,
576        source=getattr(kernel_module, 'source', []),
577        oldname=kernel_module.oldname,
578        oldpars=kernel_module.oldpars,
579        )
580    # Fill in attributes which default to None
581    info.update((k, getattr(kernel_module, k, None))
582                for k in ('ER', 'VR', 'form_volume', 'Iq', 'Iqxy'))
583    # Fill in the derived attributes
584    info['limits'] = dict((p[0], p[3]) for p in info['parameters'])
585    info['partype'] = categorize_parameters(info['parameters'])
586    info['defaults'] = dict((p[0], p[2]) for p in info['parameters'])
587    return info
588
589def make(kernel_module):
590    """
591    Build an OpenCL/ctypes function from the definition in *kernel_module*.
592
593    The module can be loaded with a normal python import statement if you
594    know which module you need, or with __import__('sasmodels.model.'+name)
595    if the name is in a string.
596    """
597    info = make_info(kernel_module)
598    # Assume if one part of the kernel is python then all parts are.
599    source = make_model(info) if not callable(info['Iq']) else None
600    return source, info
601
602def doc(kernel_module):
603    """
604    Return the documentation for the model.
605    """
606    info = make_info(kernel_module)
607    subst = dict(id=info['id'].replace('_', '-'),
608                 name=info['name'],
609                 title=info['title'],
610                 parameters=make_partable(info['parameters']),
611                 docs=kernel_module.__doc__)
612    return DOC_HEADER % subst
613
614
615
616def demo_time():
617    from .models import cylinder
618    import datetime
619    tic = datetime.datetime.now()
620    make(cylinder)
621    toc = (datetime.datetime.now() - tic).total_seconds()
622    print "time:", toc
623
624def main():
625    if len(sys.argv) <= 1:
626        print "usage: python -m sasmodels.generate modelname"
627    else:
628        name = sys.argv[1]
629        import sasmodels.models
630        __import__('sasmodels.models.' + name)
631        model = getattr(sasmodels.models, name)
632        source, _ = make(model)
633        print source
634
635if __name__ == "__main__":
636    main()
Note: See TracBrowser for help on using the repository browser.