source: sasmodels/sasmodels/gen.py @ 5d4777d

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

reorganize, check and update models

  • Property mode set to 100644
File size: 24.1 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 *real*.  Depending on how the
40function is called, a macro will replace *real* with *float* or *double*.
41Unfortunately, MacOSX is picky about floating point constants, which
42should be defined with value + 'f' if they are of type *float* or just
43a bare value if they are of type *double*.  The solution is a macro
44*REAL(value)* which adds the 'f' if compiling for single precision
45floating point.  [Note: we could write a clever regular expression
46which automatically detects real-valued constants.  If we wanted to
47make our code more C-like, we could define variables with double but
48replace them with float before compiling for single precision.]
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 *real* values.  *value* may be an expression.  When
55compiled for systems without OpenCL, *SINCOS* will be replaced by
56*sin* and *cos* calls.
57
58If the input parameters are invalid, the scattering calculator should
59return a negative number. Particularly with polydispersity, there are
60some sets of shape parameters which lead to nonsensical forms, such
61as a capped cylinder where the cap radius is smaller than the
62cylinder radius.  The polydispersity calculation will ignore these points,
63effectively chopping the parameter weight distributions at the boundary
64of the infeasible region.  The resulting scattering will be set to
65background.  This will work correctly even when polydispersity is off.
66
67*ER* and *VR* are python functions which operate on parameter vectors.
68The constructor code will generate the necessary vectors for computing
69them with the desired polydispersity.
70
71The available kernel parameters are defined as a list, with each parameter
72defined as a sublist with the following elements:
73
74    *name* is the name that will be used in the call to the kernel
75    function and the name that will be displayed to the user.  Names
76    should be lower case, with words separated by underscore.  If
77    acronyms are used, the whole acronym should be upper case.
78
79    *units* should be one of *degrees* for angles, *Ang* for lengths,
80    *1e-6/Ang^2* for SLDs.
81
82    *default value* will be the initial value for  the model when it
83    is selected, or when an initial value is not otherwise specified.
84
85    [*lb*, *ub*] are the hard limits on the parameter value, used to limit
86    the polydispersity density function.  In the fit, the parameter limits
87    given to the fit are the limits  on the central value of the parameter.
88    If there is polydispersity, it will evaluate parameter values outside
89    the fit limits, but not outside the hard limits specified in the model.
90    If there are no limits, use +/-inf imported from numpy.
91
92    *type* indicates how the parameter will be used.  "volume" parameters
93    will be used in all functions.  "orientation" parameters will be used
94    in *Iqxy* and *Imagnetic*.  "magnetic* parameters will be used in
95    *Imagnetic* only.  If *type* is the empty string, the parameter will
96    be used in all of *Iq*, *Iqxy* and *Imagnetic*.
97
98    *description* is a short description of the parameter.  This will
99    be displayed in the parameter table and used as a tool tip for the
100    parameter value in the user interface.
101
102The kernel module must set variables defining the kernel meta data:
103
104    *name* is the model name
105
106    *title* is a short description of the model, suitable for a tool tip,
107    or a one line model summary in a table of models.
108
109    *description* is an extended description of the model to be displayed
110    while the model parameters are being edited.
111
112    *parameters* is the list of parameters.  Parameters in the kernel
113    functions must appear in the same order as they appear in the
114    parameters list.  Two additional parameters, *scale* and *background*
115    are added to the beginning of the parameter list.  They will show up
116    in the documentation as model parameters, but they are never sent to
117    the kernel functions.
118
119    *source* is the list of C-99 source files that must be joined to
120    create the OpenCL kernel functions.  The files defining the functions
121    need to be listed before the files which use the functions.
122
123    *ER* is a python function defining the effective radius.  If it is
124    not present, the effective radius is 0.
125
126    *VR* is a python function defining the volume ratio.  If it is not
127    present, the volume ratio is 1.
128
129    *form_volume*, *Iq*, *Iqxy*, *Imagnetic* are strings containing the
130    C source code for the body of the volume, Iq, and Iqxy functions
131    respectively.  These can also be defined in the last source file.
132
133An *info* dictionary is constructed from the kernel meta data and
134returned to the caller.  It includes the additional fields
135
136
137The model evaluator, function call sequence consists of q inputs and the return vector,
138followed by the loop value/weight vector, followed by the values for
139the non-polydisperse parameters, followed by the lengths of the
140polydispersity loops.  To construct the call for 1D models, the
141categories *fixed-1d* and *pd-1d* list the names of the parameters
142of the non-polydisperse and the polydisperse parameters respectively.
143Similarly, *fixed-2d* and *pd-2d* provide parameter names for 2D models.
144The *pd-rel* category is a set of those parameters which give
145polydispersitiy as a portion of the value (so a 10% length dispersity
146would use a polydispersity value of 0.1) rather than absolute
147dispersity such as an angle plus or minus 15 degrees.
148
149The *volume* category lists the volume parameters in order for calls
150to volume within the kernel (used for volume normalization) and for
151calls to ER and VR for effective radius and volume ratio respectively.
152
153The *orientation* and *magnetic* categories list the orientation and
154magnetic parameters.  These are used by the sasview interface.  The
155blank category is for parameters such as scale which don't have any
156other marking.
157
158The doc string at the start of the kernel module will be used to
159construct the model documentation web pages.  Embedded figures should
160appear in the subdirectory "img" beside the model definition, and tagged
161with the kernel module name to avoid collision with other models.  Some
162file systems are case-sensitive, so only use lower case characters for
163file names and extensions.
164
165
166The function :func:`make` loads the metadata from the module and returns
167the kernel source.  The function :func:`doc` extracts the doc string
168and adds the parameter table to the top.  The function :func:`sources`
169returns a list of files required by the model.
170"""
171
172# TODO: identify model files which have changed since loading and reload them.
173
174__all__ = ["make, doc", "sources"]
175
176import sys
177import os
178import os.path
179
180import numpy as np
181
182F64 = np.dtype('float64')
183F32 = np.dtype('float32')
184
185# Scale and background, which are parameters common to every form factor
186COMMON_PARAMETERS = [
187    [ "scale", "", 1, [0, np.inf], "", "Source intensity" ],
188    [ "background", "1/cm", 0, [0, np.inf], "", "Source background" ],
189    ]
190
191
192# Conversion from units defined in the parameter table for each model
193# to units displayed in the sphinx documentation.
194RST_UNITS = {
195    "Ang": "|Ang|",
196    "1/Ang^2": "|Ang^-2|",
197    "1e-6/Ang^2": "|1e-6Ang^-2|",
198    "degrees": "degree",
199    "1/cm": "|cm^-1|",
200    "": "None",
201    }
202
203# Headers for the parameters tables in th sphinx documentation
204PARTABLE_HEADERS = [
205    "Parameter name",
206    "Units",
207    "Default value",
208    ]
209
210# Minimum width for a default value (this is shorter than the column header
211# width, so will be ignored).
212PARTABLE_VALUE_WIDTH = 10
213
214# Header included before every kernel.
215# This makes sure that the appropriate math constants are defined, and does
216# whatever is required to make the kernel compile as pure C rather than
217# as an OpenCL kernel.
218KERNEL_HEADER = """\
219// GENERATED CODE --- DO NOT EDIT ---
220// Code is produced by sasmodels.gen from sasmodels/models/MODEL.c
221
222#ifdef __OPENCL_VERSION__
223# define USE_OPENCL
224#endif
225
226// If opencl is not available, then we are compiling a C function
227// Note: if using a C++ compiler, then define kernel as extern "C"
228#ifndef USE_OPENCL
229#  include <math.h>
230#  define REAL(x) (x)
231#  ifndef real
232#      define real double
233#  endif
234#  define global
235#  define local
236#  define constant const
237#  define kernel
238#  define SINCOS(angle,svar,cvar) do {svar=sin(angle);cvar=cos(angle);} while (0)
239#  define powr(a,b) pow(a,b)
240#else
241#  ifdef USE_SINCOS
242#    define SINCOS(angle,svar,cvar) svar=sincos(angle,&cvar)
243#  else
244#    define SINCOS(angle,svar,cvar) do {svar=sin(angle);cvar=cos(angle);} while (0)
245#  endif
246#endif
247
248// Standard mathematical constants:
249//   M_E, M_LOG2E, M_LOG10E, M_LN2, M_LN10, M_PI, M_PI_2=pi/2, M_PI_4=pi/4,
250//   M_1_PI=1/pi, M_2_PI=2/pi, M_2_SQRTPI=2/sqrt(pi), SQRT2, SQRT1_2=sqrt(1/2)
251// OpenCL defines M_constant_F for float constants, and nothing if double
252// is not enabled on the card, which is why these constants may be missing
253#ifndef M_PI
254#  define M_PI REAL(3.141592653589793)
255#endif
256#ifndef M_PI_2
257#  define M_PI_2 REAL(1.570796326794897)
258#endif
259#ifndef M_PI_4
260#  define M_PI_4 REAL(0.7853981633974483)
261#endif
262
263// Non-standard pi/180, used for converting between degrees and radians
264#ifndef M_PI_180
265#  define M_PI_180 REAL(0.017453292519943295)
266#endif
267"""
268
269
270# The I(q) kernel and the I(qx, qy) kernel have one and two q parameters
271# respectively, so the template builder will need to do extra work to
272# declare, initialize and pass the q parameters.
273KERNEL_1D = {
274    'fn': "Iq",
275    'q_par_decl': "global const real *q,",
276    'qinit': "const real qi = q[i];",
277    'qcall': "qi",
278    'qwork': ["q"],
279    }
280
281KERNEL_2D = {
282    'fn': "Iqxy",
283    'q_par_decl': "global const real *qx,\n    global const real *qy,",
284    'qinit': "const real qxi = qx[i];\n    const real qyi = qy[i];",
285    'qcall': "qxi, qyi",
286    'qwork': ["qx", "qy"],
287    }
288
289# Generic kernel template for the polydispersity loop.
290# This defines the opencl kernel that is available to the host.  The same
291# structure is used for Iq and Iqxy kernels, so extra flexibility is needed
292# for q parameters.  The polydispersity loop is built elsewhere and
293# substituted into this template.
294KERNEL_TEMPLATE = """\
295kernel void %(name)s(
296    %(q_par_decl)s
297    global real *result,
298#ifdef USE_OPENCL
299    global real *loops_g,
300#else
301    const int Nq,
302#endif
303    local real *loops,
304    const real cutoff,
305    %(par_decl)s
306    )
307{
308#ifdef USE_OPENCL
309  // copy loops info to local memory
310  event_t e = async_work_group_copy(loops, loops_g, (%(pd_length)s)*2, 0);
311  wait_group_events(1, &e);
312
313  int i = get_global_id(0);
314  int Nq = get_global_size(0);
315#endif
316
317#ifdef USE_OPENCL
318  if (i < Nq)
319#else
320  #pragma omp parallel for
321  for (int i=0; i < Nq; i++)
322#endif
323  {
324    %(qinit)s
325    real ret=REAL(0.0), norm=REAL(0.0);
326    real vol=REAL(0.0), norm_vol=REAL(0.0);
327%(loops)s
328    if (vol*norm_vol != REAL(0.0)) {
329      ret *= norm_vol/vol;
330    }
331    result[i] = scale*ret/norm+background;
332  }
333}
334"""
335
336# Polydispersity loop level.
337# This pulls the parameter value and weight from the looping vector in order
338# in preperation for a nested loop.
339LOOP_OPEN="""\
340for (int %(name)s_i=0; %(name)s_i < N%(name)s; %(name)s_i++) {
341  const real %(name)s = loops[2*(%(name)s_i%(offset)s)];
342  const real %(name)s_w = loops[2*(%(name)s_i%(offset)s)+1];\
343"""
344
345# Polydispersity loop body.
346# This computes the weight, and if it is sufficient, calls the scattering
347# function and adds it to the total.  If there is a volume normalization,
348# it will also be added here.
349LOOP_BODY="""\
350const real weight = %(weight_product)s;
351if (weight > cutoff) {
352  const real I = %(fn)s(%(qcall)s, %(pcall)s);
353  if (I>=REAL(0.0)) { // scattering cannot be negative
354    ret += weight*I;
355    norm += weight;
356    %(volume_norm)s
357  }
358  //else { printf("exclude qx,qy,I:%%g,%%g,%%g\\n",%(qcall)s,I); }
359}
360//else { printf("exclude weight:%%g\\n",weight); }\
361"""
362
363# Use this when integrating over orientation
364SPHERICAL_CORRECTION="""\
365// Correction factor for spherical integration p(theta) I(q) sin(theta) dtheta
366real spherical_correction = (Ntheta>1 ? fabs(cos(M_PI_180*phi)) : REAL(1.0));\
367"""
368
369# Volume normalization.
370# If there are "volume" polydispersity parameters, then these will be used
371# to call the form_volume function from the user supplied kernel, and accumulate
372# a normalized weight.
373VOLUME_NORM="""const real vol_weight = %(weight)s;
374    vol += vol_weight*form_volume(%(pars)s);
375    norm_vol += vol_weight;\
376"""
377
378# functions defined as strings in the .py module
379WORK_FUNCTION="""\
380real %(name)s(%(pars)s);
381real %(name)s(%(pars)s)
382{
383%(body)s
384}\
385"""
386
387# Documentation header for the module, giving the model name, its short
388# description and its parameter table.  The remainder of the doc comes
389# from the module docstring.
390DOC_HEADER=""".. _%(name)s:
391
392%(name)s
393=======================================================
394
395%(title)s
396
397%(parameters)s
398
399The returned value is scaled to units of |cm^-1|.
400
401%(docs)s
402"""
403
404def indent(s, depth):
405    """
406    Indent a string of text with *depth* additional spaces on each line.
407    """
408    spaces = " "*depth
409    sep = "\n"+spaces
410    return spaces + sep.join(s.split("\n"))
411
412
413def kernel_name(info, is_2D):
414    """
415    Name of the exported kernel symbol.
416    """
417    return info['name'] + "_" + ("Iqxy" if is_2D else "Iq")
418
419
420def make_kernel(info, is_2D):
421    """
422    Build a kernel call from metadata supplied by the user.
423
424    *info* is the json object defined in the kernel file.
425
426    *form* is either "Iq" or "Iqxy".
427
428    This does not create a complete OpenCL kernel source, only the top
429    level kernel call with polydispersity and a call to the appropriate
430    Iq or Iqxy function.
431    """
432
433    # If we are building the Iqxy kernel, we need to propagate qx,qy
434    # parameters, otherwise we can
435    dim = "2d" if is_2D else "1d"
436    fixed_pars = info['partype']['fixed-'+dim]
437    pd_pars = info['partype']['pd-'+dim]
438    vol_pars = info['partype']['volume']
439    q_pars = KERNEL_2D if is_2D else KERNEL_1D
440    fn = q_pars['fn']
441
442    # Build polydispersity loops
443    depth = 4
444    offset = ""
445    loop_head = []
446    loop_end = []
447    for name in pd_pars:
448        subst = { 'name': name, 'offset': offset }
449        loop_head.append(indent(LOOP_OPEN%subst, depth))
450        loop_end.insert(0, (" "*depth) + "}")
451        offset += '+N'+name
452        depth += 2
453
454    # The volume parameters in the inner loop are used to call the volume()
455    # function in the kernel, with the parameters defined in vol_pars and the
456    # weight product defined in weight.  If there are no volume parameters,
457    # then there will be no volume normalization.
458    if vol_pars:
459        subst = {
460            'weight': "*".join(p+"_w" for p in vol_pars),
461            'pars': ", ".join(vol_pars),
462            }
463        volume_norm = VOLUME_NORM%subst
464    else:
465        volume_norm = ""
466
467    # Define the inner loop function call
468    # The parameters to the f(q,p1,p2...) call should occur in the same
469    # order as given in the parameter info structure.  This may be different
470    # from the parameter order in the call to the kernel since the kernel
471    # call places all fixed parameters before all polydisperse parameters.
472    fq_pars = [p[0] for p in info['parameters'][len(COMMON_PARAMETERS):]
473               if p[0] in set(fixed_pars+pd_pars)]
474    if False and "phi" in pd_pars:
475        spherical_correction = [indent(SPHERICAL_CORRECTION, depth)]
476        weights = [p+"_w" for p in pd_pars]+['spherical_correction']
477    else:
478        spherical_correction = []
479        weights = [p+"_w" for p in pd_pars]
480    subst = {
481        'weight_product': "*".join(weights),
482        'volume_norm': volume_norm,
483        'fn': fn,
484        'qcall': q_pars['qcall'],
485        'pcall': ", ".join(fq_pars), # skip scale and background
486        }
487    loop_body = [indent(LOOP_BODY%subst, depth)]
488    loops = "\n".join(loop_head+spherical_correction+loop_body+loop_end)
489
490    # declarations for non-pd followed by pd pars
491    # e.g.,
492    #     const real sld,
493    #     const int Nradius
494    fixed_par_decl = ",\n    ".join("const real %s"%p for p in fixed_pars)
495    pd_par_decl = ",\n    ".join("const int N%s"%p for p in pd_pars)
496    if fixed_par_decl and pd_par_decl:
497        par_decl = ",\n    ".join((fixed_par_decl, pd_par_decl))
498    elif fixed_par_decl:
499        par_decl = fixed_par_decl
500    else:
501        par_decl = pd_par_decl
502
503    # Finally, put the pieces together in the kernel.
504    subst = {
505        # kernel name is, e.g., cylinder_Iq
506        'name': kernel_name(info, is_2D),
507        # to declare, e.g., global real q[],
508        'q_par_decl': q_pars['q_par_decl'],
509        # to declare, e.g., real sld, int Nradius, int Nlength
510        'par_decl': par_decl,
511        # to copy global to local pd pars we need, e.g., Nradius+Nlength
512        'pd_length': "+".join('N'+p for p in pd_pars),
513        # the q initializers, e.g., real qi = q[i];
514        'qinit': q_pars['qinit'],
515        # the actual polydispersity loop
516        'loops': loops,
517        }
518    kernel = KERNEL_TEMPLATE%subst
519
520    # If the working function is defined in the kernel metadata as a
521    # string, translate the string to an actual function definition
522    # and put it before the kernel.
523    if info[fn]:
524        subst = {
525            'name': fn,
526            'pars': ", ".join("real "+p for p in q_pars['qwork']+fq_pars),
527            'body': info[fn],
528            }
529        kernel = "\n".join((WORK_FUNCTION%subst, kernel))
530    return kernel
531
532def make_partable(info):
533    """
534    Generate the parameter table to include in the sphinx documentation.
535    """
536    pars = info['parameters']
537    column_widths = [
538        max(len(p[0]) for p in pars),
539        max(len(RST_UNITS[p[1]]) for p in pars),
540        PARTABLE_VALUE_WIDTH,
541        ]
542    column_widths = [max(w, len(h))
543                     for w,h in zip(column_widths, PARTABLE_HEADERS)]
544
545    sep = " ".join("="*w for w in column_widths)
546    lines = [
547        sep,
548        " ".join("%-*s"%(w,h) for w,h in zip(column_widths, PARTABLE_HEADERS)),
549        sep,
550        ]
551    for p in pars:
552        lines.append(" ".join([
553            "%-*s"%(column_widths[0],p[0]),
554            "%-*s"%(column_widths[1],RST_UNITS[p[1]]),
555            "%*g"%(column_widths[2],p[2]),
556            ]))
557    lines.append(sep)
558    return "\n".join(lines)
559
560def _search(search_path, filename):
561    """
562    Find *filename* in *search_path*.
563
564    Raises ValueError if file does not exist.
565    """
566    for path in search_path:
567        target = os.path.join(path, filename)
568        if os.path.exists(target):
569            return target
570    raise ValueError("%r not found in %s"%(filename, search_path))
571
572def sources(info):
573    """
574    Return a list of the sources file paths for the module.
575    """
576    from os.path import abspath, dirname, join as joinpath
577    search_path = [ dirname(info['filename']),
578                    abspath(joinpath(dirname(__file__),'models')) ]
579    return [_search(search_path, f) for f in info['source']]
580
581def make_model(info):
582    """
583    Generate the code for the kernel defined by info, using source files
584    found in the given search path.
585    """
586    source = [open(f).read() for f in sources(info)]
587    # If the form volume is defined as a string, then wrap it in a
588    # function definition and place it after the external sources but
589    # before the kernel functions.  If the kernel functions are strings,
590    # they will be translated in the make_kernel call.
591    if info['form_volume']:
592        subst = {
593            'name': "form_volume",
594            'pars': ", ".join("real "+p for p in info['partype']['volume']),
595            'body': info['form_volume'],
596            }
597        source.append(WORK_FUNCTION%subst)
598    kernel_Iq = make_kernel(info, is_2D=False)
599    kernel_Iqxy = make_kernel(info, is_2D=True)
600    kernel = "\n\n".join([KERNEL_HEADER]+source+[kernel_Iq, kernel_Iqxy])
601    return kernel
602
603def categorize_parameters(pars):
604    """
605    Build parameter categories out of the the parameter definitions.
606
607    Returns a dictionary of categories.
608    """
609    partype = {
610        'volume': [], 'orientation': [], 'magnetic': [], '': [],
611        'fixed-1d': [], 'fixed-2d': [], 'pd-1d': [], 'pd-2d': [],
612        'pd-rel': set(),
613    }
614
615    for p in pars:
616        name,ptype = p[0],p[4]
617        if ptype == 'volume':
618            partype['pd-1d'].append(name)
619            partype['pd-2d'].append(name)
620            partype['pd-rel'].add(name)
621        elif ptype == 'magnetic':
622            partype['fixed-2d'].append(name)
623        elif ptype == 'orientation':
624            partype['pd-2d'].append(name)
625        elif ptype == '':
626            partype['fixed-1d'].append(name)
627            partype['fixed-2d'].append(name)
628        else:
629            raise ValueError("unknown parameter type %r"%ptype)
630        partype[ptype].append(name)
631
632    return partype
633
634def make(kernel_module):
635    """
636    Build an OpenCL/ctypes function from the definition in *kernel_module*.
637
638    The module can be loaded with a normal python import statement if you
639    know which module you need, or with __import__('sasmodels.model.'+name)
640    if the name is in a string.
641    """
642    # TODO: allow Iq and Iqxy to be defined in python
643    from os.path import abspath
644    #print kernelfile
645    info = dict(
646        filename = abspath(kernel_module.__file__),
647        name = kernel_module.name,
648        title = kernel_module.title,
649        description = kernel_module.description,
650        parameters = COMMON_PARAMETERS + kernel_module.parameters,
651        source = getattr(kernel_module, 'source', []),
652        )
653    # Fill in attributes which default to None
654    info.update((k,getattr(kernel_module, k, None))
655                for k in ('ER', 'VR', 'form_volume', 'Iq', 'Iqxy'))
656    # Fill in the derived attributes
657    info['limits'] = dict((p[0],p[3]) for p in info['parameters'])
658    info['partype'] = categorize_parameters(info['parameters'])
659
660    source = make_model(info)
661
662    return source, info
663
664def doc(kernel_module):
665    """
666    Return the documentation for the model.
667    """
668    subst = dict(name=kernel_module.name,
669                 title=kernel_module.title,
670                 parameters=make_partable(kernel_module.parameters),
671                 doc=kernel_module.__doc__)
672    return DOC_HEADER%subst
673
674
675
676def demo_time():
677    import datetime
678    tic = datetime.datetime.now()
679    toc = lambda: (datetime.datetime.now()-tic).total_seconds()
680    path = os.path.dirname("__file__")
681    doc, c = make_model(os.path.join(path, "models", "cylinder.c"))
682    print "time:",toc()
683
684def demo():
685    from os.path import join as joinpath, dirname
686    c, info, doc = make_model(joinpath(dirname(__file__), "models", "cylinder.c"))
687    #print doc
688    #print c
689
690if __name__ == "__main__":
691    demo()
Note: See TracBrowser for help on using the repository browser.