source: sasmodels/sasmodels/gen.py @ f4cf580

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

resolve remaining differences between sasview and sasmodels

  • Property mode set to 100644
File size: 24.7 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%(sasview_spherical)s;
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(sin(M_PI_180*theta)) : REAL(1.0));\
367"""
368# Use this to reproduce sasview behaviour
369SASVIEW_SPHERICAL_CORRECTION="""\
370// Correction factor for spherical integration p(theta) I(q) sin(theta) dtheta
371real spherical_correction = (Ntheta>1 ? fabs(cos(M_PI_180*theta))*M_PI_2 : REAL(1.0));\
372"""
373
374# Volume normalization.
375# If there are "volume" polydispersity parameters, then these will be used
376# to call the form_volume function from the user supplied kernel, and accumulate
377# a normalized weight.
378VOLUME_NORM="""const real vol_weight = %(weight)s;
379    vol += vol_weight*form_volume(%(pars)s);
380    norm_vol += vol_weight;\
381"""
382
383# functions defined as strings in the .py module
384WORK_FUNCTION="""\
385real %(name)s(%(pars)s);
386real %(name)s(%(pars)s)
387{
388%(body)s
389}\
390"""
391
392# Documentation header for the module, giving the model name, its short
393# description and its parameter table.  The remainder of the doc comes
394# from the module docstring.
395DOC_HEADER=""".. _%(name)s:
396
397%(name)s
398=======================================================
399
400%(title)s
401
402%(parameters)s
403
404The returned value is scaled to units of |cm^-1|.
405
406%(docs)s
407"""
408
409def indent(s, depth):
410    """
411    Indent a string of text with *depth* additional spaces on each line.
412    """
413    spaces = " "*depth
414    sep = "\n"+spaces
415    return spaces + sep.join(s.split("\n"))
416
417
418def kernel_name(info, is_2D):
419    """
420    Name of the exported kernel symbol.
421    """
422    return info['name'] + "_" + ("Iqxy" if is_2D else "Iq")
423
424
425def make_kernel(info, is_2D):
426    """
427    Build a kernel call from metadata supplied by the user.
428
429    *info* is the json object defined in the kernel file.
430
431    *form* is either "Iq" or "Iqxy".
432
433    This does not create a complete OpenCL kernel source, only the top
434    level kernel call with polydispersity and a call to the appropriate
435    Iq or Iqxy function.
436    """
437
438    # If we are building the Iqxy kernel, we need to propagate qx,qy
439    # parameters, otherwise we can
440    dim = "2d" if is_2D else "1d"
441    fixed_pars = info['partype']['fixed-'+dim]
442    pd_pars = info['partype']['pd-'+dim]
443    vol_pars = info['partype']['volume']
444    q_pars = KERNEL_2D if is_2D else KERNEL_1D
445    fn = q_pars['fn']
446
447    # Build polydispersity loops
448    depth = 4
449    offset = ""
450    loop_head = []
451    loop_end = []
452    for name in pd_pars:
453        subst = { 'name': name, 'offset': offset }
454        loop_head.append(indent(LOOP_OPEN%subst, depth))
455        loop_end.insert(0, (" "*depth) + "}")
456        offset += '+N'+name
457        depth += 2
458
459    # The volume parameters in the inner loop are used to call the volume()
460    # function in the kernel, with the parameters defined in vol_pars and the
461    # weight product defined in weight.  If there are no volume parameters,
462    # then there will be no volume normalization.
463    if vol_pars:
464        subst = {
465            'weight': "*".join(p+"_w" for p in vol_pars),
466            'pars': ", ".join(vol_pars),
467            }
468        volume_norm = VOLUME_NORM%subst
469    else:
470        volume_norm = ""
471
472    # Define the inner loop function call
473    # The parameters to the f(q,p1,p2...) call should occur in the same
474    # order as given in the parameter info structure.  This may be different
475    # from the parameter order in the call to the kernel since the kernel
476    # call places all fixed parameters before all polydisperse parameters.
477    fq_pars = [p[0] for p in info['parameters'][len(COMMON_PARAMETERS):]
478               if p[0] in set(fixed_pars+pd_pars)]
479    if False and "theta" in pd_pars:
480        spherical_correction = [indent(SPHERICAL_CORRECTION, depth)]
481        weights = [p+"_w" for p in pd_pars]+['spherical_correction']
482        sasview_spherical = ""
483    elif "theta" in pd_pars:
484        spherical_correction = [indent(SASVIEW_SPHERICAL_CORRECTION,depth)]
485        weights = [p+"_w" for p in pd_pars]
486        sasview_spherical = "*spherical_correction"
487    else:
488        spherical_correction = []
489        weights = [p+"_w" for p in pd_pars]
490        sasview_spherical = ""
491    subst = {
492        'weight_product': "*".join(weights),
493        'volume_norm': volume_norm,
494        'fn': fn,
495        'qcall': q_pars['qcall'],
496        'pcall': ", ".join(fq_pars), # skip scale and background
497        'sasview_spherical': sasview_spherical,
498        }
499    loop_body = [indent(LOOP_BODY%subst, depth)]
500    loops = "\n".join(loop_head+spherical_correction+loop_body+loop_end)
501
502    # declarations for non-pd followed by pd pars
503    # e.g.,
504    #     const real sld,
505    #     const int Nradius
506    fixed_par_decl = ",\n    ".join("const real %s"%p for p in fixed_pars)
507    pd_par_decl = ",\n    ".join("const int N%s"%p for p in pd_pars)
508    if fixed_par_decl and pd_par_decl:
509        par_decl = ",\n    ".join((fixed_par_decl, pd_par_decl))
510    elif fixed_par_decl:
511        par_decl = fixed_par_decl
512    else:
513        par_decl = pd_par_decl
514
515    # Finally, put the pieces together in the kernel.
516    subst = {
517        # kernel name is, e.g., cylinder_Iq
518        'name': kernel_name(info, is_2D),
519        # to declare, e.g., global real q[],
520        'q_par_decl': q_pars['q_par_decl'],
521        # to declare, e.g., real sld, int Nradius, int Nlength
522        'par_decl': par_decl,
523        # to copy global to local pd pars we need, e.g., Nradius+Nlength
524        'pd_length': "+".join('N'+p for p in pd_pars),
525        # the q initializers, e.g., real qi = q[i];
526        'qinit': q_pars['qinit'],
527        # the actual polydispersity loop
528        'loops': loops,
529        }
530    kernel = KERNEL_TEMPLATE%subst
531
532    # If the working function is defined in the kernel metadata as a
533    # string, translate the string to an actual function definition
534    # and put it before the kernel.
535    if info[fn]:
536        subst = {
537            'name': fn,
538            'pars': ", ".join("real "+p for p in q_pars['qwork']+fq_pars),
539            'body': info[fn],
540            }
541        kernel = "\n".join((WORK_FUNCTION%subst, kernel))
542    return kernel
543
544def make_partable(info):
545    """
546    Generate the parameter table to include in the sphinx documentation.
547    """
548    pars = info['parameters']
549    column_widths = [
550        max(len(p[0]) for p in pars),
551        max(len(RST_UNITS[p[1]]) for p in pars),
552        PARTABLE_VALUE_WIDTH,
553        ]
554    column_widths = [max(w, len(h))
555                     for w,h in zip(column_widths, PARTABLE_HEADERS)]
556
557    sep = " ".join("="*w for w in column_widths)
558    lines = [
559        sep,
560        " ".join("%-*s"%(w,h) for w,h in zip(column_widths, PARTABLE_HEADERS)),
561        sep,
562        ]
563    for p in pars:
564        lines.append(" ".join([
565            "%-*s"%(column_widths[0],p[0]),
566            "%-*s"%(column_widths[1],RST_UNITS[p[1]]),
567            "%*g"%(column_widths[2],p[2]),
568            ]))
569    lines.append(sep)
570    return "\n".join(lines)
571
572def _search(search_path, filename):
573    """
574    Find *filename* in *search_path*.
575
576    Raises ValueError if file does not exist.
577    """
578    for path in search_path:
579        target = os.path.join(path, filename)
580        if os.path.exists(target):
581            return target
582    raise ValueError("%r not found in %s"%(filename, search_path))
583
584def sources(info):
585    """
586    Return a list of the sources file paths for the module.
587    """
588    from os.path import abspath, dirname, join as joinpath
589    search_path = [ dirname(info['filename']),
590                    abspath(joinpath(dirname(__file__),'models')) ]
591    return [_search(search_path, f) for f in info['source']]
592
593def make_model(info):
594    """
595    Generate the code for the kernel defined by info, using source files
596    found in the given search path.
597    """
598    source = [open(f).read() for f in sources(info)]
599    # If the form volume is defined as a string, then wrap it in a
600    # function definition and place it after the external sources but
601    # before the kernel functions.  If the kernel functions are strings,
602    # they will be translated in the make_kernel call.
603    if info['form_volume']:
604        subst = {
605            'name': "form_volume",
606            'pars': ", ".join("real "+p for p in info['partype']['volume']),
607            'body': info['form_volume'],
608            }
609        source.append(WORK_FUNCTION%subst)
610    kernel_Iq = make_kernel(info, is_2D=False)
611    kernel_Iqxy = make_kernel(info, is_2D=True)
612    kernel = "\n\n".join([KERNEL_HEADER]+source+[kernel_Iq, kernel_Iqxy])
613    return kernel
614
615def categorize_parameters(pars):
616    """
617    Build parameter categories out of the the parameter definitions.
618
619    Returns a dictionary of categories.
620    """
621    partype = {
622        'volume': [], 'orientation': [], 'magnetic': [], '': [],
623        'fixed-1d': [], 'fixed-2d': [], 'pd-1d': [], 'pd-2d': [],
624        'pd-rel': set(),
625    }
626
627    for p in pars:
628        name,ptype = p[0],p[4]
629        if ptype == 'volume':
630            partype['pd-1d'].append(name)
631            partype['pd-2d'].append(name)
632            partype['pd-rel'].add(name)
633        elif ptype == 'magnetic':
634            partype['fixed-2d'].append(name)
635        elif ptype == 'orientation':
636            partype['pd-2d'].append(name)
637        elif ptype == '':
638            partype['fixed-1d'].append(name)
639            partype['fixed-2d'].append(name)
640        else:
641            raise ValueError("unknown parameter type %r"%ptype)
642        partype[ptype].append(name)
643
644    return partype
645
646def make(kernel_module):
647    """
648    Build an OpenCL/ctypes function from the definition in *kernel_module*.
649
650    The module can be loaded with a normal python import statement if you
651    know which module you need, or with __import__('sasmodels.model.'+name)
652    if the name is in a string.
653    """
654    # TODO: allow Iq and Iqxy to be defined in python
655    from os.path import abspath
656    #print kernelfile
657    info = dict(
658        filename = abspath(kernel_module.__file__),
659        name = kernel_module.name,
660        title = kernel_module.title,
661        description = kernel_module.description,
662        parameters = COMMON_PARAMETERS + kernel_module.parameters,
663        source = getattr(kernel_module, 'source', []),
664        )
665    # Fill in attributes which default to None
666    info.update((k,getattr(kernel_module, k, None))
667                for k in ('ER', 'VR', 'form_volume', 'Iq', 'Iqxy'))
668    # Fill in the derived attributes
669    info['limits'] = dict((p[0],p[3]) for p in info['parameters'])
670    info['partype'] = categorize_parameters(info['parameters'])
671
672    source = make_model(info)
673
674    return source, info
675
676def doc(kernel_module):
677    """
678    Return the documentation for the model.
679    """
680    subst = dict(name=kernel_module.name,
681                 title=kernel_module.title,
682                 parameters=make_partable(kernel_module.parameters),
683                 doc=kernel_module.__doc__)
684    return DOC_HEADER%subst
685
686
687
688def demo_time():
689    import datetime
690    tic = datetime.datetime.now()
691    toc = lambda: (datetime.datetime.now()-tic).total_seconds()
692    path = os.path.dirname("__file__")
693    doc, c = make_model(os.path.join(path, "models", "cylinder.c"))
694    print "time:",toc()
695
696def demo():
697    from os.path import join as joinpath, dirname
698    c, info, doc = make_model(joinpath(dirname(__file__), "models", "cylinder.c"))
699    #print doc
700    #print c
701
702if __name__ == "__main__":
703    demo()
Note: See TracBrowser for help on using the repository browser.