source: sasview/src/sas/sasgui/perspectives/fitting/media/plugin.rst @ 7f23423

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 7f23423 was 7f23423, checked in by smk78, 8 years ago

Under review. More minor changes.

  • Property mode set to 100644
File size: 29.5 KB
RevLine 
[05829fb]1.. _Writing_a_Plugin:
2
[7f23423]3Writing a Plugin Model
4======================
[05829fb]5
[7f23423]6Overview
7^^^^^^^^
8
9You can write your own model and save it to the the SasView
[05829fb]10*plugin_models* folder
11
[7f23423]12  *C:\\Users\\[username]\\.sasview\\plugin_models* (on Windows)
[05829fb]13
14The next time SasView is started it will compile the plugin and add
[7f23423]15it to the list of *Customized Models* in a FitPage.  It is recommended that an
[05829fb]16existing model be used as a template.
17
18SasView has three ways of writing models:
19
20- As a pure python model : Example -
21  `broadpeak.py <https://github.com/SasView/sasmodels/blob/master/sasmodels/models/broad_peak.py>`_
22- As a python model with embedded C : Example -
23  `sphere.py <https://github.com/SasView/sasmodels/blob/master/sasmodels/models/sphere.py>`_
24- As a python wrapper with separate C code : Example -
25  `cylinder.py <https://github.com/SasView/sasmodels/blob/master/sasmodels/models/cylinder.py>`_,
26  `cylinder.c <https://github.com/SasView/sasmodels/blob/master/sasmodels/models/cylinder.c>`_
27
[3d164b9]28The built-in modules are available in the *sasmodels-data\\models* subdirectory
[7f23423]29of your SasView installation folder.  On Windows, this will be something like
30*C:\\Program Files (x86)\\SasView\\sasmodels-data\\models*.  On Mac OSX, these will be within
[05829fb]31the application bundle as
32*/Applications/SasView 4.0.app/Contents/Resources/sasmodels-data/models*.
33
[7f23423]34Other models are available for download from our
35`Model Marketplace <http://marketplace.sasview.org/>`_. You can contribute your own models to the
36Marketplace aswell.
37
[05829fb]38Create New Model Files
39^^^^^^^^^^^^^^^^^^^^^^
40
[3d164b9]41In the *~\\.sasview\\plugin_models* directory, copy the appropriate files
[05829fb]42(using the examples above as templates) to mymodel.py (and mymodel.c, etc)
43as required, where "mymodel" is the name for the model you are creating.
44
45*Please follow these naming rules:*
46
[7f23423]47- No capitalization and thus no CamelCase
[3d164b9]48- If necessary use underscore to separate words (i.e. barbell not BarBell or
[05829fb]49  broad_peak not BroadPeak)
[3d164b9]50- Do not include “model” in the name (i.e. barbell not BarBellModel)
[05829fb]51
52
53Edit New Model Files
54^^^^^^^^^^^^^^^^^^^^
55
[7f23423]56Model Contents
57..............
58
[05829fb]59The model interface definition is in the .py file.  This file contains:
60
61- a **model name**:
62   - this is the **name** string in the *.py* file
63   - titles should be:
64
65    - all in *lower* case
66    - without spaces (use underscores to separate words instead)
67    - without any capitalization or CamelCase
[7f23423]68    - without incorporating the word "model"
[05829fb]69    - examples: *barbell* **not** *BarBell*; *broad_peak* **not** *BroadPeak*;
70      *barbell* **not** *BarBellModel*
71
72- a **model title**:
73   - this is the **title** string in the *.py* file
74   - this is a one or two line description of the model, which will appear
[7f23423]75     at the start of the model documentation and as a tooltip in the SasView GUI
[05829fb]76
77- a **short discription**:
78   - this is the **description** string in the *.py* file
79   - this is a medium length description which appears when you click
[7f23423]80     *Description* on the model FitPage
[05829fb]81
82- a **parameter table**:
83   - this will be auto-generated from the *parameters* in the *.py* file
84
85- a **long description**:
86   - this is ReStructuredText enclosed between the r""" and """ delimiters
87     at the top of the *.py* file
[7f23423]88   - what you write here is abstracted into the SasView help documentation
89   - this is what other users will refer to when they want to know what your model does;
90     so please be helpful!
[05829fb]91
92- a **definition** of the model:
93   - as part of the **long description**
94
95- a **formula** defining the function the model calculates:
96   - as part of the **long description**
97
98- an **explanation of the parameters**:
99   - as part of the **long description**
100   - explaining how the symbols in the formula map to the model parameters
101
102- a **plot** of the function, with a **figure caption**:
[7f23423]103   - this is automatically generated from your default parameters
[05829fb]104
105- at least one **reference**:
106   - as part of the **long description**
107   - specifying where the reader can obtain more information about the model
108
109- the **name of the author**
110   - as part of the **long description**
111   - the *.py* file should also contain a comment identifying *who*
112     converted/created the model file
113
[3d164b9]114Models that do not conform to these requirements will *never* be incorporated
115into the built-in library.
116
[05829fb]117More complete documentation for the sasmodels package can be found at
118`<http://www.sasview.org/sasmodels>`_. In particular,
119`<http://www.sasview.org/sasmodels/api/generate.html#module-sasmodels.generate>`_
120describes the structure of a model.
121
122
123Model Documentation
124...................
125
126The *.py* file starts with an r (for raw) and three sets of quotes
127to start the doc string and ends with a second set of three quotes.
128For example::
129
130    r"""
131    Definition
132    ----------
133
134    The 1D scattering intensity of the sphere is calculated in the following
135    way (Guinier, 1955)
136
137    .. math::
138
139        I(q) = \frac{\text{scale}}{V} \cdot \left[
140            3V(\Delta\rho) \cdot \frac{\sin(qr) - qr\cos(qr))}{(qr)^3}
141            \right]^2 + \text{background}
142
143    where *scale* is a volume fraction, $V$ is the volume of the scatterer,
144    $r$ is the radius of the sphere and *background* is the background level.
145    *sld* and *sld_solvent* are the scattering length densities (SLDs) of the
146    scatterer and the solvent respectively, whose difference is $\Delta\rho$.
147
148    You can included figures in your documentation, as in the following
149    figure for the cylinder model.
150
151    .. figure:: img/cylinder_angle_definition.jpg
152
153        Definition of the angles for oriented cylinders.
154
155    References
156    ----------
157
158    A Guinier, G Fournet, *Small-Angle Scattering of X-Rays*,
159    John Wiley and Sons, New York, (1955)
160    """
161
162This is where the FULL documentation for the model goes (to be picked up by
163the automatic documentation system).  Although it feels odd, you
164should start the documentation immediately with the **definition**---the model
165name, a brief description and the parameter table are automatically inserted
166above the definition, and the a plot of the model is automatically inserted
167before the **reference**.
168
169Figures can be included using the *figure* command, with the name
170of the *.png* file containing the figure and a caption to appear below the
171figure.  Figure numbers will be added automatically.
172
173See this `Sphinx cheat sheet <http://matplotlib.org/sampledoc/cheatsheet.html>`_
174for a quick guide to the documentation layout commands, or the
175`Sphinx Documentation <http://www.sphinx-doc.org/en/stable/>`_ for
176complete details.
177
178The model should include a **formula** written using LaTeX markup.
[7f23423]179The example above uses the *math* command to make a displayed equation.  You
[05829fb]180can also use *\$formula\$* for an inline formula. This is handy for defining
181the relationship between the model parameters and formula variables, such
182as the phrase "\$r\$ is the radius" used above.  The live demo MathJax
183page `<http://www.mathjax.org/>`_ is handy for checking that the equations
[7f23423]184will look like you intend.
[05829fb]185
186Math layout uses the `amsmath <http://www.ams.org/publications/authors/tex/amslatex>`_
187package for aligning equations (see amsldoc.pdf on that page for complete documentation).
188You will automatically be in an aligned environment, with blank lines separating
189the lines of the equation.  Place an ampersand before the operator on which to
190align.  For example::
191
192    .. math::
193
194      x + y &= 1 \\
195      y &= x - 1
196
197produces
198
199.. math::
200
201      x + y &= 1 \\
202      y &= x - 1
203
204If you need more control, use::
205
206    .. math::
207        :nowrap:
208
209
210Model Definition
211................
212
213Following the documentation string, there are a series of definitions::
214
215    name = "sphere"  # optional: defaults to the filename without .py
[7f23423]216
[05829fb]217    title = "Spheres with uniform scattering length density"
[7f23423]218
[05829fb]219    description = """\
220    P(q)=(scale/V)*[3V(sld-sld_solvent)*(sin(qr)-qr cos(qr))
221                    /(qr)^3]^2 + background
222        r: radius of sphere
223        V: The volume of the scatter
224        sld: the SLD of the sphere
225        sld_solvent: the SLD of the solvent
226    """
[7f23423]227
[05829fb]228    category = "shape:sphere"
[7f23423]229
[05829fb]230    single = True   # optional: defaults to True
[7f23423]231
[05829fb]232    opencl = False  # optional: defaults to False
[7f23423]233
[05829fb]234    structure_factor = False  # optional: defaults to False
235
236**name = "mymodel"** defines the name of the model that is shown to the user.
237If it is not provided, it will use the name of the model file, with '_'
238replaced by spaces and the parts capitalized.  So *adsorbed_layer.py* will
239become *Adsorbed Layer*.  The predefined models all use the name of the
240model file as the name of the model, so the default may be changed.
241
242**title = "short description"** is short description of the model which
243is included after the model name in the automatically generated documentation.
[7f23423]244The title can also be used for a tooltip.
[05829fb]245
246**description = """doc string"""** is a longer description of the model. It
[7f23423]247shows up when you press the "Description" button of the SasView FitPage.
[05829fb]248It should give a brief description of the equation and the parameters
249without the need to read the entire model documentation. The triple quotes
250allow you to write the description over multiple lines. Keep the lines
251short since the GUI will wrap each one separately if they are too long.
[7f23423]252**Make sure the parameter names in the description match the model definition!**
[05829fb]253
254**category = "shape:sphere"** defines where the model will appear in the
255model documentation.  In this example, the model will appear alphabetically
[7f23423]256in the list of spheroid models in the *Shape* category.
[05829fb]257
258**single = True** indicates that the model can be run using single
259precision floating point values.  Set it to False if the numerical
260calculation for the model is unstable, which is the case for about 20 of
261the built in models.  It is worthwhile modifying the calculation to support
262single precision, allowing models to run up to 10 times faster.  The
263section `Test_Your_New_Model`_  describes how to compare model values for
264single vs. double precision so you can decide if you need to set
265single to False.
266
267**opencl = False** indicates that the model should not be run using OpenCL.
268This may be because the model definition includes code that cannot be
269compiled for the GPU (for example, goto statements).  It can also be used
270for large models which can't run on most GPUs.  This flag has not been
271used on any of the built in models; models which were failing were
272streamlined so this flag was not necessary.
273
274**structure_factor = True** indicates that the model can be used as a
275structure factor to account for interactions between particles.  See
276`Form_Factors`_ for more details.
277
278Model Parameters
279................
280
281Next comes the parameter table.  For example::
282
283    # pylint: disable=bad-whitespace, line-too-long
284    #   ["name",        "units", default, [min, max], "type",    "description"],
285    parameters = [
286        ["sld",         "1e-6/Ang^2",  1, [-inf, inf], "sld",    "Layer scattering length density"],
287        ["sld_solvent", "1e-6/Ang^2",  6, [-inf, inf], "sld",    "Solvent scattering length density"],
288        ["radius",      "Ang",        50, [0, inf],    "volume", "Sphere radius"],
289    ]
290
291**parameters = [["name", "units", default, [min,max], "type", "tooltip"],...]**
[7f23423]292defines the parameters that form the model.
[05829fb]293
[7f23423]294**Note: The order of the parameters in the definition will be the order of the
295parameters in the user interface and the order of the parameters in Iq(),
296Iqxy() and form_volume(). And** *scale* **and** *background* **parameters are
297implicit to all models, so they do not need to be included in the parameter table.**
[05829fb]298
[7f23423]299- **"name"** is the name of the parameter shown on the FitPage.
[05829fb]300
301  - parameter names should follow the mathematical convention; e.g.,
[7f23423]302    *radius_core* not *core_radius*, or *sld_solvent* not *solvent_sld*.
303
[05829fb]304  - model parameter names should be consistent between different models,
305    so *sld_solvent*, for example, should have exactly the same name
[7f23423]306    in every model.
307
[05829fb]308  - to see all the parameter names currently in use, type the following in the
309    python shell/editor under the Tools menu::
310
311       import sasmodels.list_pars
312       sasmodels.list_pars.list_pars()
313
314    *re-use* as many as possible!!!
[7f23423]315
[05829fb]316  - use "name[n]" for multiplicity parameters, where *n* is the name of
317    the parameter defining the number of shells/layers/segments, etc.
318
319- **"units"** are displayed along with the parameter name
320
[7f23423]321  - every parameter should have units; use "None" if there are no units.
322
[05829fb]323  - **sld's should be given in units of 1e-6/Ang^2, and not simply
324    1/Ang^2 to be consistent with the builtin models.  Adjust your formulas
325    appropriately.**
[7f23423]326
[05829fb]327  - fancy units markup is available for some units, including::
328
329        Ang, 1/Ang, 1/Ang^2, 1e-6/Ang^2, degrees, 1/cm, Ang/cm, g/cm^3, mg/m^2
330
331  - the list of units is defined in the variable *RST_UNITS* within
332    `sasmodels/generate.py <https://github.com/SasView/sasmodels/tree/master/sasmodels/generate.py>`_
333
334    - new units can be added using the macros defined in *doc/rst_prolog*
335      in the sasmodels source.
336    - units should be properly formatted using sub-/super-scripts
337      and using negative exponents instead of the / operator, though
338      the unit name should use the / operator for consistency.
[7f23423]339    - please post a message to the SasView developers mailing list with your changes.
[05829fb]340
[7f23423]341- **default** is the initial value for the parameter.
[05829fb]342
343  - **the parameter default values are used to auto-generate a plot of
344    the model function in the documentation.**
345
[7f23423]346- **[min, max]** are the lower and upper limits on the parameter.
347
348  - lower and upper limits can be any number, or *-inf* or *inf*.
[05829fb]349
350  - the limits will show up as the default limits for the fit making it easy,
351    for example, to force the radius to always be greater than zero.
352
[7f23423]353- **"type"** can be one of: "", "sld", "volume", or "orientation".
[05829fb]354
355  - "sld" parameters can have magnetic moments when fitting magnetic models;
356    depending on the spin polarization of the beam and the $q$ value being
357    examined, the effective sld for that material will be used to compute the
[7f23423]358    scattered intensity.
359
[05829fb]360  - "volume" parameters are passed to Iq(), Iqxy(), and form_volume(), and
361    have polydispersity loops generated automatically.
[7f23423]362
[05829fb]363  - "orientation" parameters are only passed to Iqxy(), and have angular
364    dispersion.
365
366
367Model Computation
368.................
369
370Models can be defined as pure python models, or they can be a mixture of
371python and C models.  C models are run on the GPU if it is available,
372otherwise they are compiled and run on the CPU.
373
374Models are defined by the scattering kernel, which takes a set of parameter
375values defining the shape, orientation and material, and returns the
376expected scattering. Polydispersity and angular dispersion are defined
377by the computational infrastructure.  Any parameters defined as "volume"
378parameters are polydisperse, with polydispersity defined in proportion
379to their value.  "orientation" parameters use angular dispersion defined
380in degrees, and are not relative to the current angle.
381
382Based on a weighting function $G(x)$ and a number of points $n$, the
383computed value is
384
385.. math::
386
387     \hat I(q)
388     = \frac{\int G(x) I(q, x)\,dx}{\int G(x) V(x)\,dx}
389     \approx \frac{\sum_{i=1}^n G(x_i) I(q,x_i)}{\sum_{i=1}^n G(x_i) V(x_i)}
390
391That is, the indivdual models do not need to include polydispersity
392calculations, but instead rely on numerical integration to compute the
393appropriately smeared pattern.   Angular dispersion values over polar angle
394$\theta$ requires an additional $\cos \theta$ weighting due to decreased
395arc length for the equatorial angle $\phi$ with increasing latitude.
396
397Python Models
398.............
399
[7f23423]400For pure python models, define the *Iq* function::
[05829fb]401
402      import numpy as np
403      from numpy import cos, sin, ...
404
405      def Iq(q, par1, par2, ...):
406          return I(q, par1, par2, ...)
407      Iq.vectorized = True
408
409The parameters *par1, par2, ...* are the list of non-orientation parameters
410to the model in the order that they appear in the parameter table.
[7f23423]411**Note that the autogenerated model file uses** *x* **rather than** *q*.
[05829fb]412
413The *.py* file should import trigonometric and exponential functions from
[7f23423]414numpy rather than from math.  This lets us evaluate the model for the whole
[05829fb]415range of $q$ values at once rather than looping over each $q$ separately in
416python.  With $q$ as a vector, you cannot use if statements, but must instead
417do tricks like
418
419::
420
421     a = x*q*(q>0) + y*q*(q<=0)
422
423or
424
425::
426
427     a = np.empty_like(q)
428     index = q>0
429     a[index] = x*q[index]
430     a[~index] = y*q[~index]
431
432which sets $a$ to $q \cdot x$ if $q$ is positive or $q \cdot y$ if $q$
433is zero or negative. If you have not converted your function to use $q$
434vectors, you can set the following and it will only receive one $q$
435value at a time::
436
437    Iq.vectorized = False
438
439Return np.NaN if the parameters are not valid (e.g., cap_radius < radius in
440barbell).  If I(q; pars) is NaN for any $q$, then those parameters will be
441ignored, and not included in the calculation of the weighted polydispersity.
442
443Similar to *Iq*, you can define *Iqxy(qx, qy, par1, par2, ...)* where the
444parameter list includes any orientation parameters.  If *Iqxy* is not defined,
445then it will default to *Iqxy = Iq(sqrt(qx**2+qy**2), par1, par2, ...)*.
446
447Models should define *form_volume(par1, par2, ...)* where the parameter
448list includes the *volume* parameters in order.  This is used for a weighted
449volume normalization so that scattering is on an absolute scale.  If
[7f23423]450*form_volume* is not defined, then the default *form_volume = 1.0* will be
[05829fb]451used.
452
453Embedded C Models
454.................
455
[7f23423]456Like pure python models, inline C models need to define an *Iq* function::
[05829fb]457
458    Iq = """
459        return I(q, par1, par2, ...);
460    """
461
462This expands into the equivalent C code::
463
464    #include <math.h>
465    double Iq(double q, double par1, double par2, ...);
466    double Iq(double q, double par1, double par2, ...)
467    {
468        return I(q, par1, par2, ...);
469    }
470
471The C model operates on a single $q$ value at a time.  The code will be
472run in parallel across different $q$ values, either on the graphics card
473or the processor.
474
475Rather than returning NAN from Iq, you must define the *INVALID(v)*.  The
476*v* parameter lets you access all the parameters in the model using
477*v.par1*, *v.par2*, etc. For example::
478
479    #define INVALID(v) (v.bell_radius < v.radius)
480
481*Iqxy* is similar to *Iq*, except it uses parameters *qx, qy* instead of *q*,
482and it includes orientation parameters. As in python models, *form_volume*
483includes only the volume parameters.  *Iqxy* will default to
484*Iq(sqrt(qx**2 + qy**2), par1, ...)* and *form_volume* will default to 1.0.
485
486The C code follows the C99 standard, including the usual math functions,
487as defined in
488`OpenCL <https://www.khronos.org/registry/cl/sdk/1.1/docs/man/xhtml/mathFunctions.html>`_.
489
490The standard constants and functions include the following::
491
492    M_PI = pi
493    M_PI_2 = pi/2
494    M_PI_4 = pi/4
495    M_E = e
496    M_SQRT1_2 = 1/sqrt(2)
497    NAN = NaN
498    INFINITY = 1/0
499    erf(x) = error function
500    erfc(x) = 1-erf(x)
501    expm1(x) = exp(x) - 1
502    tgamma(x) = gamma function
503
504Some non-standard constants and functions are also provided::
505
506    M_PI_180 = pi/180
507    M_4PI_3 = 4pi/3
508    square(x) = x*x
509    cube(x) = x*x*x
510    sinc(x) = sin(x)/x, with sin(0)/0 -> 1
511    SINCOS(x, s, c) sets s=sin(angle) and c=cos(angle)
512    powr(x, y) = x^y for x >= 0
513    pown(x, n) = x^n for n integer
514
515**source=['lib/fn.c', ...]** includes the listed C source files in the
516program before *Iq* and *Iqxy* are defined. This allows you to extend the
517library of available C functions. Additional special functions and
518scattering calculations are defined in
519`sasmodels/models/lib <https://github.com/SasView/sasmodels/tree/master/sasmodels/models/lib>`_,
520including::
521
522    sph_j1c(x) = 3 j1(x)/x = 3 (sin(x) - x cos(x))/x^3  [spherical bessel function]
523    sas_J1c(x) = 2 J1(x)/x  [bessel function of the first kind]
524    sas_gamma(x) = gamma function  [tgamma is unstable below 1]
525    sas_erf(x) = error function [erf is broken on some Intel OpenCL drivers]
526    sas_erfc(x) = 1-erf(x)
527    sas_J0(x) = J0(x)
528    sas_J1(x) = J1(x)
529    sas_JN(x) = JN(x)
530    Si(x) = integral sin(z)/z from 0 to x
531    Gauss76Wt = gaussian quadrature weights for 76 point integral
532    Gauss76Z = gaussian quadrature values for 76 point integral
533
534These functions have been tuned to be fast and numerically stable down
535to $q=0$ even in single precision.  In some cases they work around bugs
[7f23423]536which appear on some platforms but not others. So use them where needed!!!
[05829fb]537
538Models are defined using double precision declarations for the
539parameters and return values.  Declarations and constants will be converted
540to float or long double depending on the precision requested.
[7f23423]541
[05829fb]542**Floating point constants must include the decimal point.**  This allows us
543to convert values such as 1.0 (double precision) to 1.0f (single precision)
544so that expressions that use these values are not promoted to double precision
545expressions.  Some graphics card drivers are confused when functions
546that expect floating point values are passed integers, such as 4*atan(1); it
547is safest to not use integers in floating point expressions.  Even better,
548use the builtin constant M_PI rather than 4*atan(1); it is faster and smaller!
549
550FLOAT_SIZE is the number of bytes in the converted variables. If your
551algorithm depends on precision (which is not uncommon for numerical
552algorithms), use the following::
553
554    #if FLOAT_SIZE>4
555    ... code for double precision ...
556    #else
557    ... code for single precision ...
558    #endif
559
560A value defined as SAS_DOUBLE will stay double precision; this should
[7f23423]561not be used since some graphics cards do not support double precision.
[05829fb]562
563
564External C Models
565.................
566
567External C models are very much like embedded C models, except that
568*Iq*, *Iqxy* and *form_volume* are defined in an external source file
569loaded using the *source=[...]*  method. You need to supply the function
570declarations for each of these that you need instead of building them
571automatically from the parameter table.
572
573
574.. _Form_Factors:
575
576Form Factors
577............
578
579::
580
581    def ER(radius, thickness):
582        """Effective radius of a core-shell sphere."""
583        return radius + thickness
584
585Away from the dilute limit you can estimate scattering including
586particle-particle interactions using $I(q) = P(q)*S(q)$ where $P(q)$
587is the form factor and $S(q)$ is the structure factor.  The simplest
588structure factor is the *hardsphere* interaction, which
589uses the effective radius of the form factor as an input to the structure
590factor model.  The effective radius is the average radius of the
591form averaged over all the polydispersity values.
592
593Consider the *core_shell_sphere*, which has a simple effective radius
594equal to the radius of the core plus the thickness of the shell, as
595shown above. Given polydispersity over *(r1, r2, ..., rm)* in radius and
596*(t1, t2, ..., tn)* in thickness, *ER* is called with a mesh
597grid covering all possible combinations of radius and thickness.
598That is, *radius* is *(r1, r2, ..., rm, r1, r2, ..., rm, ...)*
599and *thickness* is *(t1, t1, ... t1, t2, t2, ..., t2, ...)*.
600The *ER* function returns one effective radius for each combination.
601The effective radius calculator weights each of these according to
602the polydispersity distributions and calls the structure factor
603with the average *ER*.
604
605::
606
607    def VR(radius, thickness):
608        """Sphere and shell volumes for a core-shell sphere."""
609        whole = 4.0/3.0 * pi * (radius + thickness)**3
610        core = 4.0/3.0 * pi * radius**3
611        return whole, whole - core
612
613Core-shell type models have an additional volume ratio which scales
614the structure factor.  The *VR* function returns the volume of
615the whole sphere and the volume of the shell. Like *ER*, there is
616one return value for each point in the mesh grid.
617
618*NOTE: we may be removing or modifying this feature soon.*  As of this
619writing, core-shell sphere returns (1., 1.) for *VR*, giving a volume
620ratio of 1.0.
621
622Unit Tests
623..........
624
625THESE ARE VERY IMPORTANT. Include at least one test for each model and
626PLEASE make sure that the answer value is correct (i.e. not a random number).
627
628::
629
630    tests = [
631        [{}, 0.2, 0.726362],
632        [{"scale": 1., "background": 0., "sld": 6., "sld_solvent": 1.,
633          "radius": 120., "radius_pd": 0.2, "radius_pd_n":45},
634         0.2, 0.228843],
635        [{"radius": 120., "radius_pd": 0.2, "radius_pd_n":45}, "ER", 120.],
636        [{"radius": 120., "radius_pd": 0.2, "radius_pd_n":45}, "VR", 1.],
637    ]
638
639
640**tests=[[{parameters}, q, result], ...]** is a list of lists.
641Each list is one test and contains, in order:
642
643- a dictionary of parameter values. This can be {} using the default
644  parameters, or filled with some parameters that will be different
645  from the default, such as {‘radius’:10.0, ‘sld’:4}. Unlisted parameters
646  will be given the default values.
647- the input $q$ value or tuple of $(q_x, q_y)$ values.
648- the output $I(q)$ or $I(q_x,q_y)$ expected of the model for the parameters
649  and input value given.
650- input and output values can themselves be lists if you have several
651  $q$ values to test for the same model parameters.
652- for testing *ER* and *VR*, give the inputs as "ER" and "VR" respectively;
653  the output for *VR* should be the sphere/shell ratio, not the individual
654  sphere and shell values.
655
656.. _Test_Your_New_Model:
657
658Test Your New Model
659^^^^^^^^^^^^^^^^^^^
660
661If you are editing your model from the SasView GUI, you can test it
662by selecting *Run -> Compile* from the *Model Editor* menu bar. An
663*Info* box will appear with the results of the compilation and a
664check that the model runs.
665
666If the model compiles and runs, you can next run the unit tests that
667you have added using the **test=** values. Switch to the *Shell* tab
668and type the following::
669
670    from sasmodels.model_test import run_one
671    run_one("~/.sasview/plugin_models/model.py")
672
673This should print::
674
675    test_model_python (sasmodels.model_test.ModelTestCase) ... ok
676
677To check whether single precision is good enough, type the following::
678
679    from sasmodels.compare import main
680    main("~/.sasview/plugin_models/model.py")
681
682This will pop up a plot showing the difference between single precision
683and double precision on a range of $q$ values.
684
685::
686
687  demo = dict(scale=1, background=0,
688              sld=6, sld_solvent=1,
689              radius=120,
690              radius_pd=.2, radius_pd_n=45)
691
692**demo={'par': value, ...}** in the model file sets the default values for
693the comparison. You can include polydispersity parameters such as
694*radius_pd=0.2, radius_pd_n=45* which would otherwise be zero.
695
696The options to compare are quite extensive; type the following for help::
697
698    main()
699
700Options will need to be passed as separate strings.
701For example to run your model with a random set of parameters::
702
703    main("-random", "-pars", "~/.sasview/plugin_models/model.py")
704
705For the random models,
706
707- sld will be in(-0.5,10.5),
708- angles (theta, phi, psi) will be in (-180,180),
709- angular dispersion will be in (0,45),
710- polydispersity will be in (0,1)
711- other values will be in (0, 2*v) where v is the value of the parameter in demo.
712
713Dispersion parameters n, sigma and type will be unchanged from demo so that
714run times are predictable.
715
716If your model has 2D orientational calculation, then you should also
717test with::
718
719    main("-2d", "~/.sasview/plugin_models/model.py")
720
721
722Clean Lint
723^^^^^^^^^^
724
725**NB: For now we are not providing pylint with SasView; unless you have a
726SasView development environment available, you can ignore this section.**
727
728Run the lint check with::
729
730    python -m pylint --rcfile=extra/pylint.rc ~/.sasview/plugin_models/model.py
731
732We are not aiming for zero lint just yet, only keeping it to a minimum.
733For now, don't worry too much about *invalid-name*. If you really want a
734variable name *Rg* for example because $R_g$ is the right name for the model
735parameter then ignore the lint errors.  Also, ignore *missing-docstring*
736for standard model functions *Iq*, *Iqxy*, etc.
737
738We will have delinting sessions at the SasView code camps, where we can
739decide on standards for model files, parameter names, etc.
740
741For now, you can tell pylint to ignore things.  For example, to align you
742parameters in blocks::
743
744    # pylint: disable=bad-whitespace,line-too-long
745    #   ["name",                  "units", default, [lower, upper], "type", "description"],
746    parameters = [
747        ["contrast_factor",       "barns",    10.0,  [-inf, inf], "", "Contrast factor of the polymer"],
748        ["bjerrum_length",        "Ang",       7.1,  [0, inf],    "", "Bjerrum length"],
749        ["virial_param",          "1/Ang^2",  12.0,  [-inf, inf], "", "Virial parameter"],
750        ["monomer_length",        "Ang",      10.0,  [0, inf],    "", "Monomer length"],
751        ["salt_concentration",    "mol/L",     0.0,  [-inf, inf], "", "Concentration of monovalent salt"],
752        ["ionization_degree",     "",          0.05, [0, inf],    "", "Degree of ionization"],
753        ["polymer_concentration", "mol/L",     0.7,  [0, inf],    "", "Polymer molar concentration"],
754        ]
755    # pylint: enable=bad-whitespace,line-too-long
756
757Don't put in too many pylint statements, though, since they make the code ugly.
758
759Check The Docs
760^^^^^^^^^^^^^^
761
762You can get a rough idea of how the documentation will look using the
763following::
764
765    from sasmodels.generate import view_html
766    view_html('~/.sasview/plugin_models/model.py')
767
768This does not use the same styling as the SasView docs, but it will allow
769you to check that your ReStructuredText and LaTeX formatting.  Here are
770some tools to help with the inevitable syntax errors:
771
772- `Sphinx cheat sheet <http://matplotlib.org/sampledoc/cheatsheet.html>`_
773- `Sphinx Documentation <http://www.sphinx-doc.org/en/stable/>`_
774- `MathJax <http://www.mathjax.org/>`_
775- `amsmath <http://www.ams.org/publications/authors/tex/amslatex>`_
776
777Finally
778^^^^^^^
779
780Once compare and the unit test(s) pass properly and everything is done,
781consider adding your model to the
782`model marketplace <http://marketplace.sasview.org/>`_.
Note: See TracBrowser for help on using the repository browser.