Changeset b297ba9 in sasmodels


Ignore:
Timestamp:
Mar 20, 2019 7:03:50 PM (2 months ago)
Author:
Paul Kienzle <pkienzle@…>
Branches:
master, core_shell_microgels, magnetic_model, ticket-1257-vesicle-product, ticket_1156, ticket_1265_superball, ticket_822_more_unit_tests
Children:
4e28511
Parents:
0d362b7
Message:

lint

Files:
104 edited

Legend:

Unmodified
Added
Removed
  • extra/pylint.rc

    r6e68289 rb297ba9  
    6767    locally-enabled, 
    6868    locally-disabled, 
     69    #no-else-return, 
     70    #invalid-name, 
     71    #fixme, 
     72    #too-many-lines, 
     73    #too-many-locals, 
     74    #too-many-branches, 
     75    #too-many-statements, 
     76    #too-many-instance-attributes, 
     77    #too-many-return-statements, 
     78    #no-self-use, 
    6979 
    7080[REPORTS] 
     
    109119good-names=_, 
    110120    input, id, 
    111     h, i, j, k, n, p, v, w, x, y, z, 
     121    h, i, j, k, n, p, u, v, w, x, y, z, 
    112122    q, qx, qy, qz, Q, Qx, Qy, Qz, 
    113123    dt, dx, dy, dz, dq, 
  • sasmodels/bumps_model.py

    r2c4a190 rb297ba9  
    2626    from .kernel import KernelModel 
    2727    from .modelinfo import ModelInfo 
     28    from .resolution import Resolution 
    2829    Data = Union[Data1D, Data2D] 
    2930except ImportError: 
     
    180181    @property 
    181182    def resolution(self): 
     183        # type: () -> Union[None, Resolution] 
     184        """ 
     185        :class:`sasmodels.Resolution` applied to the data, if any. 
     186        """ 
    182187        return self._resolution 
    183188 
    184189    @resolution.setter 
    185190    def resolution(self, value): 
     191        # type: (Resolution) -> None 
     192        """ 
     193        :class:`sasmodels.Resolution` applied to the data, if any. 
     194        """ 
    186195        self._resolution = value 
    187196 
     
    270279        Save the model parameters and data into a file. 
    271280 
    272         Not Implemented. 
     281        Not Implemented except for sesans fits. 
    273282        """ 
    274283        if self.data_type == "sesans": 
  • sasmodels/compare.py

    rc1799d3 rb297ba9  
    725725        set_integration_size(model_info, ngauss) 
    726726 
    727     if (dtype != "default" and not dtype.endswith('!')  
     727    if (dtype != "default" and not dtype.endswith('!') 
    728728            and not (kernelcl.use_opencl() or kernelcuda.use_cuda())): 
    729729        raise RuntimeError("OpenCL not available " + kernelcl.OPENCL_ERROR) 
     
    772772        opts['pars'] = parse_pars(opts, maxdim=maxdim) 
    773773        if opts['pars'] is None: 
    774             return 
     774            return limits 
    775775        result = run_models(opts, verbose=True) 
    776776        if opts['plot']: 
     
    822822    args = dict((k, v) for k, v in args.items() 
    823823                if "_pd" not in k 
    824                    and ":" not in k 
    825                    and k not in ("background", "scale", "theta", "phi", "psi")) 
     824                and ":" not in k 
     825                and k not in ("background", "scale", "theta", "phi", "psi")) 
    826826    args = args.copy() 
    827827 
     
    896896    # work with trimmed data, not the full set 
    897897    sorted_err = np.sort(abs(err.compressed())) 
    898     if len(sorted_err) == 0: 
     898    if sorted_err.size == 0: 
    899899        print(label + "  no valid values") 
    900900        return 
  • sasmodels/convert.py

    r21c93c3 rb297ba9  
    384384 
    385385def revert_name(model_info): 
     386    """Translate model name back to the name used in SasView 3.x""" 
    386387    oldname, _ = CONVERSION_TABLE.get(model_info.id, [None, {}]) 
    387388    return oldname 
     
    653654 
    654655def test_backward_forward(): 
     656    """ 
     657    Test conversion of model parameters from 4.x to 3.x and back. 
     658    """ 
    655659    from .core import list_models 
    656660    L = lambda name: _check_one(name, seed=1) 
  • sasmodels/core.py

    rd92182f rb297ba9  
    323323 
    324324def test_composite_order(): 
     325    """ 
     326    Check that mixture models produce the same result independent of ordder. 
     327    """ 
    325328    def test_models(fst, snd): 
    326329        """Confirm that two models produce the same parameters""" 
     
    337340 
    338341    def build_test(first, second): 
     342        """Construct pair model test""" 
    339343        test = lambda description: test_models(first, second) 
    340344        description = first + " vs. " + second 
     
    382386 
    383387def list_models_main(): 
    384     # type: () -> None 
     388    # type: () -> int 
    385389    """ 
    386390    Run list_models as a main program.  See :func:`list_models` for the 
     
    391395    try: 
    392396        models = list_models(kind) 
    393     except Exception as exc: 
     397        print("\n".join(models)) 
     398    except Exception: 
    394399        print(list_models.__doc__) 
    395400        return 1 
    396  
    397     print("\n".join(list_models(kind))) 
     401    return 0 
    398402 
    399403if __name__ == "__main__": 
  • sasmodels/data.py

    rc88f983 rb297ba9  
    500500            mdata = masked_array(data.y, data.mask.copy()) 
    501501            mdata[~np.isfinite(mdata)] = masked 
    502             if view is 'log': 
     502            if view == 'log': 
    503503                mdata[mdata <= 0] = masked 
    504504            plt.errorbar(data.x, scale*mdata, yerr=data.dy, fmt='.') 
     
    514514            mtheory = masked_array(theory) 
    515515            mtheory[~np.isfinite(mtheory)] = masked 
    516             if view is 'log': 
     516            if view == 'log': 
    517517                mtheory[mtheory <= 0] = masked 
    518518            plt.plot(theory_x, scale*mtheory, '-') 
  • sasmodels/details.py

    r885753a rb297ba9  
    236236    npars = kernel.info.parameters.npars 
    237237    nvalues = kernel.info.parameters.nvalues 
    238     scalars = [value for value, _dispersity, _weight in mesh] 
     238    scalars = [value for value, dispersity, weight in mesh] 
    239239    # skipping scale and background when building values and weights 
    240     _values, dispersity, weights = zip(*mesh[2:npars+2]) if npars else ((), (), ()) 
    241     #weights = correct_theta_weights(kernel.info.parameters, dispersity, weights) 
    242     length = np.array([len(w) for w in weights]) 
     240    value, dispersity, weight = zip(*mesh[2:npars+2]) if npars else ((), (), ()) 
     241    #weight = correct_theta_weights(kernel.info.parameters, dispersity, weight) 
     242    length = np.array([len(w) for w in weight]) 
    243243    offset = np.cumsum(np.hstack((0, length))) 
    244244    call_details = make_details(kernel.info, length, offset[:-1], offset[-1]) 
     
    246246    data_len = nvalues + 2*sum(len(v) for v in dispersity) 
    247247    extra = (32 - data_len%32)%32 
    248     data = np.hstack((scalars,) + dispersity + weights + ZEROS[:extra]) 
     248    data = np.hstack((scalars,) + dispersity + weight + ZEROS[:extra]) 
    249249    data = data.astype(kernel.dtype) 
    250250    is_magnetic = convert_magnetism(kernel.info.parameters, data) 
  • sasmodels/direct_model.py

    r9150036 rb297ba9  
    3131from . import resolution2d 
    3232from .details import make_kernel_args, dispersion_mesh 
    33 from .modelinfo import DEFAULT_BACKGROUND 
    3433from .product import RADIUS_MODE_ID 
    3534 
  • sasmodels/generate.py

    ra8a1d48 rb297ba9  
    190190 
    191191def get_data_path(external_dir, target_file): 
     192    """ 
     193    Search for the target file relative in the installed application. 
     194 
     195    Search first in the location of the generate module in case we are 
     196    running directly from the distribution.  Search next to the python 
     197    executable for windows installs.  Search in the ../Resources directory 
     198    next to the executable for Mac OS/X installs. 
     199    """ 
    192200    path = abspath(dirname(__file__)) 
    193201    if exists(joinpath(path, target_file)): 
     
    225233# 
    226234# NOTE: there is an RST_PROLOG at the end of this file which is NOT 
    227 # used for the bundled documentation. Still as long as we are defining the macros 
    228 # in two places any new addition should define the macro in both places. 
     235# used for the bundled documentation. Still as long as we are defining the 
     236# macros in two places any new addition should define the macro in both places. 
    229237RST_UNITS = { 
    230238    "Ang": "|Ang|", 
     
    530538 
    531539def test_tag_float(): 
    532     """check that floating point constants are properly identified and tagged with 'f'""" 
     540    """Check that floating point constants are identified and tagged with 'f'""" 
    533541 
    534542    cases = """ 
     
    707715    return False 
    708716 
    709 _SHELL_VOLUME_PATTERN = re.compile(r"(^|\s)double\s+shell_volume[(]", flags=re.MULTILINE) 
     717_SHELL_VOLUME_PATTERN = re.compile(r"(^|\s)double\s+shell_volume[(]", 
     718                                   flags=re.MULTILINE) 
    710719def contains_shell_volume(source): 
    711720    # type: (List[str]) -> bool 
     
    801810            logger.warn("oriented shapes should define Iqac or Iqabc") 
    802811        else: 
    803             raise ValueError("Expected function Iqac or Iqabc for oriented shape") 
     812            raise ValueError("Expected Iqac or Iqabc for oriented shape") 
    804813 
    805814    # Define the parameter table 
     
    815824        refs = _call_pars("_v.", partable.form_volume_parameters) 
    816825        if is_hollow: 
    817             call_volume = "#define CALL_VOLUME(_form, _shell, _v) do { _form = form_volume(%s); _shell = shell_volume(%s); } while (0)"%((",".join(refs),)*2) 
     826            call_volume = ( 
     827                "#define CALL_VOLUME(_form, _shell, _v) " 
     828                "do { _form = form_volume(%s); _shell = shell_volume(%s); } " 
     829                "while (0)") % ((",".join(refs),)*2) 
    818830        else: 
    819             call_volume = "#define CALL_VOLUME(_form, _shell, _v) do { _form = _shell = form_volume(%s); } while (0)"%(",".join(refs)) 
     831            call_volume = ( 
     832                "#define CALL_VOLUME(_form, _shell, _v) " 
     833                "do { _form = _shell = form_volume(%s); } " 
     834                "while (0)") % (",".join(refs)) 
    820835        if model_info.effective_radius_type: 
    821             call_effective_radius = "#define CALL_EFFECTIVE_RADIUS(_mode, _v) effective_radius(_mode, %s)"%(",".join(refs)) 
     836            call_effective_radius = ( 
     837                "#define CALL_EFFECTIVE_RADIUS(_mode, _v) " 
     838                "effective_radius(_mode, %s)") % (",".join(refs)) 
    822839    else: 
    823840        # Model doesn't have volume.  We could make the kernel run a little 
    824841        # faster by not using/transferring the volume normalizations, but 
    825842        # the ifdef's reduce readability more than is worthwhile. 
    826         call_volume = "#define CALL_VOLUME(_form, _shell, _v) do { _form = _shell = 1.0; } while (0)" 
     843        call_volume = ( 
     844            "#define CALL_VOLUME(_form, _shell, _v) " 
     845            "do { _form = _shell = 1.0; } while (0)") 
    827846    source.append(call_volume) 
    828847    source.append(call_effective_radius) 
     
    879898    source.append("#define MAGNETIC_PARS %s"%",".join(str(k) for k in magpars)) 
    880899    source.append("#define PROJECTION %d"%PROJECTION) 
    881     # TODO: allow mixed python/opencl kernels? 
    882     ocl = _kernels(kernel_code, call_iq, clear_iq, call_iqxy, clear_iqxy, model_info.name) 
    883     dll = _kernels(kernel_code, call_iq, clear_iq, call_iqxy, clear_iqxy, model_info.name) 
    884  
    885     result = { 
    886         'dll': '\n'.join(source+dll[0]+dll[1]+dll[2]), 
    887         'opencl': '\n'.join(source+ocl[0]+ocl[1]+ocl[2]), 
    888     } 
     900    wrappers = _kernels(kernel_code, call_iq, clear_iq, 
     901                        call_iqxy, clear_iqxy, model_info.name) 
     902    code = '\n'.join(source + wrappers[0] + wrappers[1] + wrappers[2]) 
     903 
     904    # Note: Identical code for dll and opencl.  This may not always be the case 
     905    # so leave them as separate entries in the returned value. 
     906    result = {'dll': code, 'opencl': code} 
    889907    return result 
    890908 
  • sasmodels/gengauss.py

    rff31782 rb297ba9  
    11#!/usr/bin/env python 
     2""" 
     3Generate the Gauss-Legendre integration points and save them as a C file. 
     4""" 
    25from __future__ import division, print_function 
    3  
    4 import sys 
    56 
    67import numpy as np 
     
    89 
    910def gengauss(n, path): 
     11    """ 
     12    Save the Gauss-Legendre integration points for length *n* into file *path*. 
     13    """ 
    1014    z, w = leggauss(n) 
    1115 
  • sasmodels/guyou.py

    rb3703f5 rb297ba9  
    6868 
    6969def ellipticJi(u, v, m): 
     70    """Returns [sn, cn, dn](u + iv|m).""" 
    7071    scalar = np.isscalar(u) and np.isscalar(v) and np.isscalar(m) 
    7172    u, v, m = np.broadcast_arrays(u, v, m) 
     
    100101    ] 
    101102 
    102 # calculate F(phi+ipsi|m). 
    103 # see Abramowitz and Stegun, 17.4.11. 
    104103def ellipticFi(phi, psi, m): 
     104    """Returns F(phi+ipsi|m). See Abramowitz and Stegun, 17.4.11.""" 
    105105    if np.any(phi == 0): 
    106106        scalar = np.isscalar(phi) and np.isscalar(psi) and np.isscalar(m) 
     
    207207        plt.plot(x, y, 'g') 
    208208 
    209     for long in range(-limit, limit+1, step): 
    210         x, y = guyou_invert(scale*long, scale*long_line) 
     209    for longitude in range(-limit, limit+1, step): 
     210        x, y = guyou_invert(scale*longitude, scale*long_line) 
    211211        plt.plot(x, y, 'b') 
    212212    plt.xlabel('longitude') 
  • sasmodels/jitter.py

    rcff2939 rb297ba9  
    5151 
    5252import numpy as np 
    53 from numpy import pi, cos, sin, sqrt, exp, degrees, radians 
     53from numpy import pi, cos, sin, sqrt, exp, log, degrees, radians, arccos, arctan2 
     54 
     55# Too many complaints about variable names from pylint: 
     56#    a, b, c, u, v, x, y, z, dx, dy, dz, px, py, pz, R, Rx, Ry, Rz, ... 
     57# pylint: disable=invalid-name 
    5458 
    5559def draw_beam(axes, view=(0, 0), alpha=0.5, steps=25): 
     
    6064    #axes.scatter([0]*100,[0]*100,np.linspace(1, -1, 100), alpha=alpha) 
    6165 
    62     u = np.linspace(0, 2 * np.pi, steps) 
     66    u = np.linspace(0, 2 * pi, steps) 
    6367    v = np.linspace(-1, 1, 2) 
    6468 
    6569    r = 0.02 
    66     x = r*np.outer(np.cos(u), np.ones_like(v)) 
    67     y = r*np.outer(np.sin(u), np.ones_like(v)) 
     70    x = r*np.outer(cos(u), np.ones_like(v)) 
     71    y = r*np.outer(sin(u), np.ones_like(v)) 
    6872    z = 1.3*np.outer(np.ones_like(u), v) 
    6973 
     
    9094    """Draw an ellipsoid.""" 
    9195    a, b, c = size 
    92     u = np.linspace(0, 2 * np.pi, steps) 
    93     v = np.linspace(0, np.pi, steps) 
    94     x = a*np.outer(np.cos(u), np.sin(v)) 
    95     y = b*np.outer(np.sin(u), np.sin(v)) 
    96     z = c*np.outer(np.ones_like(u), np.cos(v)) 
     96    u = np.linspace(0, 2 * pi, steps) 
     97    v = np.linspace(0, pi, steps) 
     98    x = a*np.outer(cos(u), sin(v)) 
     99    y = b*np.outer(sin(u), sin(v)) 
     100    z = c*np.outer(np.ones_like(u), cos(v)) 
    97101    x, y, z = transform_xyz(view, jitter, x, y, z) 
    98102 
     
    167171 
    168172def draw_box(axes, size, view): 
     173    """Draw a wireframe box at a particular view.""" 
    169174    a, b, c = size 
    170175    x = a*np.array([+1, -1, +1, -1, +1, -1, +1, -1]) 
     
    172177    z = c*np.array([+1, +1, +1, +1, -1, -1, -1, -1]) 
    173178    x, y, z = transform_xyz(view, None, x, y, z) 
    174     def draw(i, j): 
    175         axes.plot([x[i],x[j]], [y[i], y[j]], [z[i], z[j]], color='black') 
    176     draw(0, 1) 
    177     draw(0, 2) 
    178     draw(0, 3) 
    179     draw(7, 4) 
    180     draw(7, 5) 
    181     draw(7, 6) 
     179    def _draw(i, j): 
     180        axes.plot([x[i], x[j]], [y[i], y[j]], [z[i], z[j]], color='black') 
     181    _draw(0, 1) 
     182    _draw(0, 2) 
     183    _draw(0, 3) 
     184    _draw(7, 4) 
     185    _draw(7, 5) 
     186    _draw(7, 6) 
    182187 
    183188def draw_parallelepiped(axes, size, view, jitter, steps=None, 
    184189                        color=(0.6, 1.0, 0.6), alpha=1): 
    185     """Draw a parallelepiped.""" 
     190    """Draw a parallelepiped surface, with view and jitter.""" 
    186191    a, b, c = size 
    187192    x = a*np.array([+1, -1, +1, -1, +1, -1, +1, -1]) 
     
    224229    ]) 
    225230 
    226 def draw_sphere(axes, radius=0.5, steps=25, center=(0,0,0), color='w', alpha=1.): 
     231def draw_sphere(axes, radius=0.5, steps=25, 
     232                center=(0, 0, 0), color='w', alpha=1.): 
    227233    """Draw a sphere""" 
    228     u = np.linspace(0, 2 * np.pi, steps) 
    229     v = np.linspace(0, np.pi, steps) 
    230  
    231     x = radius * np.outer(np.cos(u), np.sin(v)) + center[0] 
    232     y = radius * np.outer(np.sin(u), np.sin(v)) + center[1] 
    233     z = radius * np.outer(np.ones(np.size(u)), np.cos(v)) + center[2] 
     234    u = np.linspace(0, 2 * pi, steps) 
     235    v = np.linspace(0, pi, steps) 
     236 
     237    x = radius * np.outer(cos(u), sin(v)) + center[0] 
     238    y = radius * np.outer(sin(u), sin(v)) + center[1] 
     239    z = radius * np.outer(np.ones(np.size(u)), cos(v)) + center[2] 
    234240    axes.plot_surface(x, y, z, color=color, alpha=alpha) 
    235241    #axes.plot_wireframe(x, y, z) 
    236242 
    237243def draw_axes(axes, origin=(-1, -1, -1), length=(2, 2, 2)): 
     244    """Draw wireframe axes lines, with given origin and length""" 
    238245    x, y, z = origin 
    239246    dx, dy, dz = length 
     
    243250 
    244251def draw_person_on_sphere(axes, view, height=0.5, radius=0.5): 
     252    """ 
     253    Draw a person on the surface of a sphere. 
     254 
     255    *view* indicates (latitude, longitude, orientation) 
     256    """ 
    245257    limb_offset = height * 0.05 
    246258    head_radius = height * 0.10 
     
    259271 
    260272    # circle for head 
    261     u = np.linspace(0, 2 * np.pi, 40) 
    262     x = head_radius * np.cos(u) 
    263     z = head_radius * np.sin(u) + head_height 
     273    u = np.linspace(0, 2 * pi, 40) 
     274    x = head_radius * cos(u) 
     275    z = head_radius * sin(u) + head_height 
    264276    _draw_part(x, z) 
    265277 
     
    304316    dtheta, dphi, dpsi = jitter 
    305317    base = {'gaussian':3, 'rectangle':sqrt(3), 'uniform':1}[dist] 
    306     def steps(delta): 
     318    def _steps(delta): 
    307319        if views is None: 
    308320            n = max(3, min(25, 2*int(base*delta/5))) 
     
    310322            n = views 
    311323        return base*delta*np.linspace(-1, 1, n) if delta > 0 else [0.] 
    312     for theta in steps(dtheta): 
    313         for phi in steps(dphi): 
    314             for psi in steps(dpsi): 
     324    for theta in _steps(dtheta): 
     325        for phi in _steps(dphi): 
     326            for psi in _steps(dpsi): 
    315327                w = project_weight(theta, phi, 1.0, 1.0) 
    316328                if w > 0: 
     
    319331    for v in 'xyz': 
    320332        a, b, c = size 
    321         lim = np.sqrt(a**2 + b**2 + c**2) 
     333        lim = sqrt(a**2 + b**2 + c**2) 
    322334        getattr(axes, 'set_'+v+'lim')([-lim, lim]) 
    323335        #getattr(axes, v+'axis').label.set_text(v) 
     
    390402        def _project(theta_i, phi_j, psi): 
    391403            latitude, longitude = theta_i, phi_j 
    392             return latitude, longitude, psi 
     404            return latitude, longitude, psi, 'xyz' 
    393405            #return Rx(phi_j)*Ry(theta_i) 
    394406        def _weight(theta_i, phi_j, w_i, w_j): 
     
    400412            longitude = phi_j/scale if abs(phi_j) < abs(scale)*180 else 0 
    401413            #print("(%+7.2f, %+7.2f) => (%+7.2f, %+7.2f)"%(theta_i, phi_j, latitude, longitude)) 
    402             return latitude, longitude, psi 
     414            return latitude, longitude, psi, 'xyz' 
    403415            #return Rx(longitude)*Ry(latitude) 
    404416        def _project(theta_i, phi_j, w_i, w_j): 
     
    412424            #latitude, longitude = guyou_invert([theta_i], [phi_j]) 
    413425            longitude, latitude = guyou_invert([phi_j], [theta_i]) 
    414             return latitude, longitude, psi 
     426            return latitude, longitude, psi, 'xyz' 
    415427            #return Rx(longitude[0])*Ry(latitude[0]) 
    416428        def _weight(theta_i, phi_j, w_i, w_j): 
     
    420432        def _project(theta_i, phi_j, psi): 
    421433            latitude = sqrt(theta_i**2 + phi_j**2) 
    422             longitude = degrees(np.arctan2(phi_j, theta_i)) 
     434            longitude = degrees(arctan2(phi_j, theta_i)) 
    423435            #print("(%+7.2f, %+7.2f) => (%+7.2f, %+7.2f)"%(theta_i, phi_j, latitude, longitude)) 
    424436            return latitude, longitude, psi-longitude, 'zyz' 
     
    462474        def _project(theta_i, phi_j, psi): 
    463475            radius = min(1, sqrt(theta_i**2 + phi_j**2)/180) 
    464             latitude = 180-degrees(2*np.arccos(radius)) 
    465             longitude = degrees(np.arctan2(phi_j, theta_i)) 
     476            latitude = 180-degrees(2*arccos(radius)) 
     477            longitude = degrees(arctan2(phi_j, theta_i)) 
    466478            #print("(%+7.2f, %+7.2f) => (%+7.2f, %+7.2f)"%(theta_i, phi_j, latitude, longitude)) 
    467             return latitude, longitude, psi, "zyz" 
     479            return latitude, longitude, psi, 'zyz' 
    468480            #R = Rz(longitude)*Ry(latitude)*Rz(psi) 
    469481            #return R_to_xyz(R) 
     
    487499    Based on: Shoemake’s "Euler Angle Conversion", Graphics Gems IV, pp.  222-229 
    488500    """ 
    489     phi = np.arctan2(R[1, 2], R[2, 2]) 
    490     theta = np.arctan2(-R[0, 2], np.sqrt(R[0, 0]**2 + R[0, 1]**2)) 
    491     psi = np.arctan2(R[0, 1], R[0, 0]) 
    492     return np.degrees(phi), np.degrees(theta), np.degrees(psi) 
     501    phi = arctan2(R[1, 2], R[2, 2]) 
     502    theta = arctan2(-R[0, 2], sqrt(R[0, 0]**2 + R[0, 1]**2)) 
     503    psi = arctan2(R[0, 1], R[0, 0]) 
     504    return degrees(phi), degrees(theta), degrees(psi) 
    493505 
    494506def draw_mesh(axes, view, jitter, radius=1.2, n=11, dist='gaussian', 
     
    502514    def _rotate(theta, phi, z): 
    503515        dview = _project(theta, phi, 0.) 
    504         if len(dview) == 4: # hack for zyz coords 
     516        if dview[3] == 'zyz': 
    505517            return Rz(dview[1])*Ry(dview[0])*z 
    506         else: 
     518        else:  # dview[3] == 'xyz': 
    507519            return Rx(dview[1])*Ry(dview[0])*z 
    508520 
     
    657669#orient_relative_to_beam = orient_relative_to_beam_quaternion 
    658670 
     671# === Quaterion class definition === BEGIN 
    659672# Simple stand-alone quaternion class 
    660 import numpy as np 
    661 from copy import copy 
     673 
     674# Note: this code works but isn't unused since quaternions didn't solve the 
     675# representation problem.  Leave it here in case we want to revisit this later. 
     676 
     677#import numpy as np 
    662678class Quaternion(object): 
     679    r""" 
     680    Quaternion(w, r) = w + ir[0] + jr[1] + kr[2] 
     681 
     682    Quaternion.from_angle_axis(theta, r) for a rotation of angle theta about 
     683    an axis oriented toward the direction r.  This defines a unit quaternion, 
     684    normalizing $r$ to the unit vector $\hat r$, and setting quaternion 
     685    $Q = \cos \theta + \sin \theta \hat r$ 
     686 
     687    Quaternion objects can be multiplied, which applies a rotation about the 
     688    given axis, allowing composition of rotations without risk of gimbal lock. 
     689    The resulting quaternion is applied to a set of points using *Q.rot(v)*. 
     690    """ 
    663691    def __init__(self, w, r): 
    664          self.w = w 
    665          self.r = np.asarray(r, dtype='d') 
     692        self.w = w 
     693        self.r = np.asarray(r, dtype='d') 
     694 
    666695    @staticmethod 
    667696    def from_angle_axis(theta, r): 
    668          theta = np.radians(theta)/2 
    669          r = np.asarray(r) 
    670          w = np.cos(theta) 
    671          r = np.sin(theta)*r/np.dot(r,r) 
    672          return Quaternion(w, r) 
     697        """Build quaternion as rotation theta about axis r""" 
     698        theta = np.radians(theta)/2 
     699        r = np.asarray(r) 
     700        w = np.cos(theta) 
     701        r = np.sin(theta)*r/np.dot(r, r) 
     702        return Quaternion(w, r) 
     703 
    673704    def __mul__(self, other): 
     705        """Multiply quaterions""" 
    674706        if isinstance(other, Quaternion): 
    675707            w = self.w*other.w - np.dot(self.r, other.r) 
    676708            r = self.w*other.r + other.w*self.r + np.cross(self.r, other.r) 
    677709            return Quaternion(w, r) 
     710        raise NotImplementedError("Quaternion * non-quaternion not implemented") 
     711 
    678712    def rot(self, v): 
     713        """Transform point *v* by quaternion""" 
    679714        v = np.asarray(v).T 
    680715        use_transpose = (v.shape[-1] != 3) 
    681         if use_transpose: v = v.T 
     716        if use_transpose: 
     717            v = v.T 
    682718        v = v + np.cross(2*self.r, np.cross(self.r, v) + self.w*v) 
    683719        #v = v + 2*self.w*np.cross(self.r, v) + np.cross(2*self.r, np.cross(self.r, v)) 
    684         if use_transpose: v = v.T 
     720        if use_transpose: 
     721            v = v.T 
    685722        return v.T 
     723 
    686724    def conj(self): 
     725        """Conjugate quaternion""" 
    687726        return Quaternion(self.w, -self.r) 
     727 
    688728    def inv(self): 
     729        """Inverse quaternion""" 
    689730        return self.conj()/self.norm()**2 
     731 
    690732    def norm(self): 
     733        """Quaternion length""" 
    691734        return np.sqrt(self.w**2 + np.sum(self.r**2)) 
     735 
    692736    def __str__(self): 
    693737        return "%g%+gi%+gj%+gk"%(self.w, self.r[0], self.r[1], self.r[2]) 
     738 
    694739def test_qrot(): 
    695     # Define rotation of 60 degrees around an axis in y-z that is 60 degrees from y. 
    696     # The rotation axis is determined by rotating the point [0, 1, 0] about x. 
     740    """Quaternion checks""" 
     741    # Define rotation of 60 degrees around an axis in y-z that is 60 degrees 
     742    # from y.  The rotation axis is determined by rotating the point [0, 1, 0] 
     743    # about x. 
    697744    ax = Quaternion.from_angle_axis(60, [1, 0, 0]).rot([0, 1, 0]) 
    698745    q = Quaternion.from_angle_axis(60, ax) 
     
    704751#test_qrot() 
    705752#import sys; sys.exit() 
     753# === Quaterion class definition === END 
    706754 
    707755# translate between number of dimension of dispersity and the number of 
     
    725773    or the top of the range, depending on whether *mode* is 'central' or 'top'. 
    726774    """ 
    727     if portion == 1.0: 
    728         return data.min(), data.max() 
    729     elif mode == 'central': 
    730         data = np.sort(data.flatten()) 
    731         offset = int(portion*len(data)/2 + 0.5) 
    732         return data[offset], data[-offset] 
    733     elif mode == 'top': 
    734         data = np.sort(data.flatten()) 
    735         offset = int(portion*len(data) + 0.5) 
    736         return data[offset], data[-1] 
     775    if portion < 1.0: 
     776        if mode == 'central': 
     777            data = np.sort(data.flatten()) 
     778            offset = int(portion*len(data)/2 + 0.5) 
     779            return data[offset], data[-offset] 
     780        if mode == 'top': 
     781            data = np.sort(data.flatten()) 
     782            offset = int(portion*len(data) + 0.5) 
     783            return data[offset], data[-1] 
     784    # Default: full range 
     785    return data.min(), data.max() 
    737786 
    738787def draw_scattering(calculator, axes, view, jitter, dist='gaussian'): 
     
    765814 
    766815    # compute the pattern 
    767     qx, qy = calculator._data.x_bins, calculator._data.y_bins 
     816    qx, qy = calculator.qxqy 
    768817    Iqxy = calculator(**pars).reshape(len(qx), len(qy)) 
    769818 
    770819    # scale it and draw it 
    771     Iqxy = np.log(Iqxy) 
     820    Iqxy = log(Iqxy) 
    772821    if calculator.limits: 
    773822        # use limits from orientation (0,0,0) 
     
    781830    #qx, qy = np.meshgrid(qx, qy) 
    782831    if 0: 
    783         from matplotlib import cm 
    784832        level = np.asarray(255*(Iqxy - vmin)/(vmax - vmin), 'i') 
    785833        level[level < 0] = 0 
     834        from matplotlib import pylab as plt 
    786835        colors = plt.get_cmap()(level) 
     836        #from matplotlib import cm 
    787837        #colors = cm.coolwarm(level) 
    788838        #colors = cm.gist_yarg(level) 
    789839        #colors = cm.Wistia(level) 
    790         colors[level<=0, 3] = 0.  # set floor to transparent 
     840        colors[level <= 0, 3] = 0.  # set floor to transparent 
    791841        x, y = np.meshgrid(qx/qx.max(), qy/qy.max()) 
    792842        axes.plot_surface(x, y, -1.1*np.ones_like(x), facecolors=colors) 
     
    822872    calculator = DirectModel(data, model) 
    823873 
     874    # Remember the data axes so we can plot the results 
     875    calculator.qxqy = (q, q) 
     876 
    824877    # stuff the values for non-orientation parameters into the calculator 
    825878    calculator.pars = pars.copy() 
     
    829882    # under rotation or angular dispersion 
    830883    Iqxy = calculator(theta=0, phi=0, psi=0, **calculator.pars) 
    831     Iqxy = np.log(Iqxy) 
     884    Iqxy = log(Iqxy) 
    832885    vmin, vmax = clipped_range(Iqxy, 0.95, mode='top') 
    833886    calculator.limits = vmin, vmax+1 
     
    9631016    PLOT_ENGINE(calculator, draw_shape, size, view, jitter, dist, mesh, projection) 
    9641017 
    965 def mpl_plot(calculator, draw_shape, size, view, jitter, dist, mesh, projection): 
     1018def _mpl_plot(calculator, draw_shape, size, view, jitter, dist, mesh, projection): 
    9661019    # Note: travis-ci does not support mpl_toolkits.mplot3d, but this shouldn't be 
    9671020    # an issue since we are lazy-loading the package on a path that isn't tested. 
     
    10201073 
    10211074    ## callback to draw the new view 
    1022     def update(val, axis=None): 
     1075    def _update(val, axis=None): 
    10231076        view = stheta.val, sphi.val, spsi.val 
    10241077        jitter = sdtheta.val, sdphi.val, sdpsi.val 
     
    10471100 
    10481101    ## bind control widgets to view updater 
    1049     stheta.on_changed(lambda v: update(v, 'theta')) 
    1050     sphi.on_changed(lambda v: update(v, 'phi')) 
    1051     spsi.on_changed(lambda v: update(v, 'psi')) 
    1052     sdtheta.on_changed(lambda v: update(v, 'dtheta')) 
    1053     sdphi.on_changed(lambda v: update(v, 'dphi')) 
    1054     sdpsi.on_changed(lambda v: update(v, 'dpsi')) 
     1102    stheta.on_changed(lambda v: _update(v, 'theta')) 
     1103    sphi.on_changed(lambda v: _update(v, 'phi')) 
     1104    spsi.on_changed(lambda v: _update(v, 'psi')) 
     1105    sdtheta.on_changed(lambda v: _update(v, 'dtheta')) 
     1106    sdphi.on_changed(lambda v: _update(v, 'dphi')) 
     1107    sdpsi.on_changed(lambda v: _update(v, 'dpsi')) 
    10551108 
    10561109    ## initialize view 
    1057     update(None, 'phi') 
     1110    _update(None, 'phi') 
    10581111 
    10591112    ## go interactive 
     
    10621115 
    10631116def map_colors(z, kw): 
     1117    """ 
     1118    Process matplotlib-style colour arguments. 
     1119 
     1120    Pulls 'cmap', 'alpha', 'vmin', and 'vmax' from th *kw* dictionary, setting 
     1121    the *kw['color']* to an RGB array.  These are ignored if 'c' or 'color' are 
     1122    set inside *kw*. 
     1123    """ 
    10641124    from matplotlib import cm 
    10651125 
     
    10831143 
    10841144def make_vec(*args): 
     1145    """Turn all elements of *args* into numpy arrays""" 
    10851146    #return [np.asarray(v, 'd').flatten() for v in args] 
    10861147    return [np.asarray(v, 'd') for v in args] 
    10871148 
    10881149def make_image(z, kw): 
     1150    """Convert numpy array *z* into a *PIL* RGB image.""" 
    10891151    import PIL.Image 
    10901152    from matplotlib import cm 
     
    11131175    'b': 'blue', 
    11141176} 
    1115 def ipv_fix_color(kw): 
     1177def _ipv_fix_color(kw): 
    11161178    alpha = kw.pop('alpha', None) 
    11171179    color = kw.get('color', None) 
     
    11321194            kw['color'] = color 
    11331195 
    1134 def ipv_set_transparency(kw, obj): 
     1196def _ipv_set_transparency(kw, obj): 
    11351197    color = kw.get('color', None) 
    11361198    if (isinstance(color, np.ndarray) 
     
    11411203 
    11421204def ipv_axes(): 
     1205    """ 
     1206    Build a matplotlib style Axes interface for ipyvolume 
     1207    """ 
    11431208    import ipyvolume as ipv 
    11441209 
    1145     class Plotter: 
     1210    class Axes: 
     1211        """ 
     1212        Matplotlib Axes3D style interface to ipyvolume renderer. 
     1213        """ 
    11461214        # transparency can be achieved by setting the following: 
    11471215        #    mesh.color = [r, g, b, alpha] 
     
    11561224        # maybe need to synchronize update of x/y/z to avoid shimmy when moving 
    11571225        def plot(self, x, y, z, **kw): 
    1158             ipv_fix_color(kw) 
     1226            """mpl style plot interface for ipyvolume""" 
     1227            _ipv_fix_color(kw) 
    11591228            x, y, z = make_vec(x, y, z) 
    11601229            ipv.plot(x, y, z, **kw) 
    11611230        def plot_surface(self, x, y, z, **kw): 
     1231            """mpl style plot_surface interface for ipyvolume""" 
    11621232            facecolors = kw.pop('facecolors', None) 
    11631233            if facecolors is not None: 
    11641234                kw['color'] = facecolors 
    1165             ipv_fix_color(kw) 
     1235            _ipv_fix_color(kw) 
    11661236            x, y, z = make_vec(x, y, z) 
    11671237            h = ipv.plot_surface(x, y, z, **kw) 
    1168             ipv_set_transparency(kw, h) 
     1238            _ipv_set_transparency(kw, h) 
    11691239            #h.material.side = "DoubleSide" 
    11701240            return h 
    11711241        def plot_trisurf(self, x, y, triangles=None, Z=None, **kw): 
     1242            """mpl style plot_trisurf interface for ipyvolume""" 
    11721243            kw.pop('linewidth', None) 
    1173             ipv_fix_color(kw) 
     1244            _ipv_fix_color(kw) 
    11741245            x, y, z = make_vec(x, y, Z) 
    11751246            if triangles is not None: 
    11761247                triangles = np.asarray(triangles) 
    11771248            h = ipv.plot_trisurf(x, y, z, triangles=triangles, **kw) 
    1178             ipv_set_transparency(kw, h) 
     1249            _ipv_set_transparency(kw, h) 
    11791250            return h 
    11801251        def scatter(self, x, y, z, **kw): 
     1252            """mpl style scatter interface for ipyvolume""" 
    11811253            x, y, z = make_vec(x, y, z) 
    11821254            map_colors(z, kw) 
     
    11841256            kw['marker'] = _IPV_MARKERS.get(marker, marker) 
    11851257            h = ipv.scatter(x, y, z, **kw) 
    1186             ipv_set_transparency(kw, h) 
     1258            _ipv_set_transparency(kw, h) 
    11871259            return h 
    11881260        def contourf(self, x, y, v, zdir='z', offset=0, levels=None, **kw): 
     1261            """mpl style contourf interface for ipyvolume""" 
    11891262            # Don't use contour for now (although we might want to later) 
    11901263            self.pcolor(x, y, v, zdir='z', offset=offset, **kw) 
    11911264        def pcolor(self, x, y, v, zdir='z', offset=0, **kw): 
     1265            """mpl style pcolor interface for ipyvolume""" 
    11921266            x, y, v = make_vec(x, y, v) 
    11931267            image = make_image(v, kw) 
     
    12001274            v = np.array([[0., 0], [1, 1]]) 
    12011275            h = ipv.plot_mesh(x, y, z, u=u, v=v, texture=image, wireframe=False) 
    1202             ipv_set_transparency(kw, h) 
     1276            _ipv_set_transparency(kw, h) 
    12031277            h.material.side = "DoubleSide" 
    12041278            return h 
    12051279        def text(self, *args, **kw): 
     1280            """mpl style text interface for ipyvolume""" 
    12061281            pass 
    12071282        def set_xlim(self, limits): 
     1283            """mpl style set_xlim interface for ipyvolume""" 
    12081284            ipv.xlim(*limits) 
    12091285        def set_ylim(self, limits): 
     1286            """mpl style set_ylim interface for ipyvolume""" 
    12101287            ipv.ylim(*limits) 
    12111288        def set_zlim(self, limits): 
     1289            """mpl style set_zlim interface for ipyvolume""" 
    12121290            ipv.zlim(*limits) 
    12131291        def set_axes_on(self): 
     1292            """mpl style set_axes_on interface for ipyvolume""" 
    12141293            ipv.style.axis_on() 
    12151294        def set_axis_off(self): 
     1295            """mpl style set_axes_off interface for ipyvolume""" 
    12161296            ipv.style.axes_off() 
    1217     return Plotter() 
    1218  
    1219 def ipv_plot(calculator, draw_shape, size, view, jitter, dist, mesh, projection): 
     1297    return Axes() 
     1298 
     1299def _ipv_plot(calculator, draw_shape, size, view, jitter, dist, mesh, projection): 
     1300    from IPython.display import display 
    12201301    import ipywidgets as widgets 
    12211302    import ipyvolume as ipv 
     
    12231304    axes = ipv_axes() 
    12241305 
    1225     def draw(view, jitter): 
     1306    def _draw(view, jitter): 
    12261307        camera = ipv.gcf().camera 
    12271308        #print(ipv.gcf().__dict__.keys()) 
     
    12711352    #widgets.interact(update, Ξ=trange, φ=prange, ψ=prange, Δξ=dtrange, Δφ=dprange, Δψ=dprange) 
    12721353 
    1273     def update(theta, phi, psi, dtheta, dphi, dpsi): 
    1274         draw(view=(theta, phi, psi), jitter=(dtheta, dphi, dpsi)) 
    1275  
    1276     def slider(name, slice, init=0.): 
     1354    def _update(theta, phi, psi, dtheta, dphi, dpsi): 
     1355        _draw(view=(theta, phi, psi), jitter=(dtheta, dphi, dpsi)) 
     1356 
     1357    def _slider(name, slice, init=0.): 
    12771358        return widgets.FloatSlider( 
    12781359            value=init, 
     
    12881369            readout_format='.1f', 
    12891370            ) 
    1290     theta = slider(u'Ξ', trange, view[0]) 
    1291     phi = slider(u'φ', prange, view[1]) 
    1292     psi = slider(u'ψ', prange, view[2]) 
    1293     dtheta = slider(u'Δξ', dtrange, jitter[0]) 
    1294     dphi = slider(u'Δφ', dprange, jitter[1]) 
    1295     dpsi = slider(u'Δψ', dprange, jitter[2]) 
     1371    theta = _slider(u'Ξ', trange, view[0]) 
     1372    phi = _slider(u'φ', prange, view[1]) 
     1373    psi = _slider(u'ψ', prange, view[2]) 
     1374    dtheta = _slider(u'Δξ', dtrange, jitter[0]) 
     1375    dphi = _slider(u'Δφ', dprange, jitter[1]) 
     1376    dpsi = _slider(u'Δψ', dprange, jitter[2]) 
    12961377    fields = { 
    12971378        'theta': theta, 'phi': phi, 'psi': psi, 
     
    13031384    ]) 
    13041385 
    1305     out = widgets.interactive_output(update, fields) 
     1386    out = widgets.interactive_output(_update, fields) 
    13061387    display(ui, out) 
    13071388 
    13081389 
    13091390_ENGINES = { 
    1310     "matplotlib": mpl_plot, 
    1311     "mpl": mpl_plot, 
    1312     #"plotly": plotly_plot, 
    1313     "ipvolume": ipv_plot, 
    1314     "ipv": ipv_plot, 
     1391    "matplotlib": _mpl_plot, 
     1392    "mpl": _mpl_plot, 
     1393    #"plotly": _plotly_plot, 
     1394    "ipvolume": _ipv_plot, 
     1395    "ipv": _ipv_plot, 
    13151396} 
    13161397PLOT_ENGINE = _ENGINES["matplotlib"] 
    13171398def set_plotter(name): 
     1399    """ 
     1400    Setting the plotting engine to matplotlib/ipyvolume or equivalently mpl/ipv. 
     1401    """ 
    13181402    global PLOT_ENGINE 
    13191403    PLOT_ENGINE = _ENGINES[name] 
    13201404 
    13211405def main(): 
     1406    """ 
     1407    Command line interface to the jitter viewer. 
     1408    """ 
    13221409    parser = argparse.ArgumentParser( 
    13231410        description="Display jitter", 
  • sasmodels/kernel.py

    r36a2418 rb297ba9  
    2525 
    2626class KernelModel(object): 
     27    """ 
     28    Model definition for the compute engine. 
     29    """ 
    2730    info = None  # type: ModelInfo 
    2831    dtype = None # type: np.dtype 
    2932    def make_kernel(self, q_vectors): 
    3033        # type: (List[np.ndarray]) -> "Kernel" 
     34        """ 
     35        Instantiate a kernel for evaluating the model at *q_vectors*. 
     36        """ 
    3137        raise NotImplementedError("need to implement make_kernel") 
    3238 
    3339    def release(self): 
    3440        # type: () -> None 
     41        """ 
     42        Free resources associated with the kernel. 
     43        """ 
    3544        pass 
    3645 
    3746 
    3847class Kernel(object): 
    39     #: kernel dimension, either "1d" or "2d" 
     48    """ 
     49    Instantiated model for the compute engine, applied to a particular *q*. 
     50 
     51    Subclasses should define :meth:`_call_kernel` to evaluate the kernel over 
     52    its inputs. 
     53    """ 
     54    #: Kernel dimension, either "1d" or "2d". 
    4055    dim = None  # type: str 
     56    #: Model info. 
    4157    info = None  # type: ModelInfo 
    42     results = None # type: List[np.ndarray] 
     58    #: Numerical precision for the computation. 
    4359    dtype = None  # type: np.dtype 
     60    #: q values at which the kernel is to be evaluated 
     61    q_input = None  # type: Any 
     62    #: Place to hold result of :meth:`_call_kernel` for subclass. 
     63    result = None # type: np.ndarray 
    4464 
    4565    def Iq(self, call_details, values, cutoff, magnetic): 
     
    5777        built into the model, and do not need an additional scale. 
    5878        """ 
    59         _, F2, _, shell_volume, _ = self.Fq(call_details, values, cutoff, magnetic, 
    60                               effective_radius_type=0) 
     79        _, F2, _, shell_volume, _ = self.Fq(call_details, values, cutoff, 
     80                                            magnetic, effective_radius_type=0) 
    6181        combined_scale = values[0]/shell_volume 
    6282        background = values[1] 
     
    6484    __call__ = Iq 
    6585 
    66     def Fq(self, call_details, values, cutoff, magnetic, effective_radius_type=0): 
     86    def Fq(self, call_details, values, cutoff, magnetic, 
     87           effective_radius_type=0): 
    6788        # type: (CallDetails, np.ndarray, np.ndarray, float, bool, int) -> np.ndarray 
    6889        r""" 
     
    81102        .. math:: 
    82103 
    83             I(q) = \text{scale} * P (1 + <F>^2/<F^2> (S - 1)) + \text{background} 
     104            I(q) = \text{scale} P (1 + <F>^2/<F^2> (S - 1)) + \text{background} 
    84105                 = \text{scale}/<V> (<F^2> + <F>^2 (S - 1)) + \text{background} 
    85106 
     
    90111        .. math:: 
    91112 
    92             P(q) = \frac{\sum w_k F^2(q, x_k) / \sum w_k}{\sum w_k V_k / \sum w_k} 
     113            P(q)=\frac{\sum w_k F^2(q, x_k) / \sum w_k}{\sum w_k V_k / \sum w_k} 
    93114 
    94115        The form factor itself is scaled by volume and contrast to compute the 
     
    131152        hollow and solid shapes. 
    132153        """ 
    133         self._call_kernel(call_details, values, cutoff, magnetic, effective_radius_type) 
     154        self._call_kernel(call_details, values, cutoff, magnetic, 
     155                          effective_radius_type) 
    134156        #print("returned",self.q_input.q, self.result) 
    135157        nout = 2 if self.info.have_Fq and self.dim == '1d' else 1 
     
    146168        if shell_volume == 0.: 
    147169            shell_volume = 1. 
    148         F1 = self.result[1:nout*self.q_input.nq:nout]/total_weight if nout == 2 else None 
     170        F1 = (self.result[1:nout*self.q_input.nq:nout]/total_weight 
     171              if nout == 2 else None) 
    149172        F2 = self.result[0:nout*self.q_input.nq:nout]/total_weight 
    150173        return F1, F2, effective_radius, shell_volume, form_volume/shell_volume 
     
    152175    def release(self): 
    153176        # type: () -> None 
     177        """ 
     178        Free resources associated with the kernel instance. 
     179        """ 
    154180        pass 
    155181 
    156     def _call_kernel(self, call_details, values, cutoff, magnetic, effective_radius_type): 
     182    def _call_kernel(self, call_details, values, cutoff, magnetic, 
     183                     effective_radius_type): 
    157184        # type: (CallDetails, np.ndarray, np.ndarray, float, bool, int) -> np.ndarray 
    158185        """ 
  • sasmodels/kernelcl.py

    r0d26e91 rb297ba9  
    5353from __future__ import print_function 
    5454 
     55import sys 
    5556import os 
    5657import warnings 
     
    6162    from time import perf_counter as clock 
    6263except ImportError: # CRUFT: python < 3.3 
    63     import sys 
    6464    if sys.platform.count("darwin") > 0: 
    6565        from time import time as clock 
     
    9999# CRUFT: pyopencl < 2017.1 (as of June 2016 needs quotes around include path). 
    100100def quote_path(v): 
     101    # type: (str) -> str 
    101102    """ 
    102103    Quote the path if it is not already quoted. 
     
    110111 
    111112def fix_pyopencl_include(): 
     113    # type: (None) -> None 
    112114    """ 
    113115    Monkey patch pyopencl to allow spaces in include file path. 
    114116    """ 
    115     import pyopencl as cl 
    116     if hasattr(cl, '_DEFAULT_INCLUDE_OPTIONS'): 
    117         cl._DEFAULT_INCLUDE_OPTIONS = [ 
    118             quote_path(v) for v in cl._DEFAULT_INCLUDE_OPTIONS 
     117    import pyopencl 
     118    if hasattr(pyopencl, '_DEFAULT_INCLUDE_OPTIONS'): 
     119        pyopencl._DEFAULT_INCLUDE_OPTIONS = [ 
     120            quote_path(v) for v in pyopencl._DEFAULT_INCLUDE_OPTIONS 
    119121            ] 
    120122 
     
    147149 
    148150def use_opencl(): 
     151    # type: () -> bool 
     152    """Return True if OpenCL is the default computational engine""" 
    149153    sas_opencl = os.environ.get("SAS_OPENCL", "OpenCL").lower() 
    150154    return HAVE_OPENCL and sas_opencl != "none" and not sas_opencl.startswith("cuda") 
     
    153157ENV = None 
    154158def reset_environment(): 
     159    # type: () -> None 
    155160    """ 
    156161    Call to create a new OpenCL context, such as after a change to SAS_OPENCL. 
     
    323328            return [cl.create_some_context(interactive=False)] 
    324329        except Exception as exc: 
     330            # TODO: Should warnings instead by put into logging.warn? 
    325331            warnings.warn(str(exc)) 
    326             warnings.warn("pyopencl.create_some_context() failed.  The " 
    327                 "environment variable 'SAS_OPENCL' or 'PYOPENCL_CTX' might " 
    328                 "not be set correctly") 
     332            warnings.warn( 
     333                "pyopencl.create_some_context() failed.  The environment " 
     334                "variable 'SAS_OPENCL' or 'PYOPENCL_CTX' might not be set " 
     335                "correctly") 
    329336 
    330337    return _get_default_context() 
  • sasmodels/kernelcuda.py

    rfa26e78 rb297ba9  
    5959 
    6060import os 
    61 import warnings 
    6261import logging 
    6362import time 
     
    110109 
    111110def use_cuda(): 
     111    # type: None -> bool 
     112    """Returns True if CUDA is the default compute engine.""" 
    112113    sas_opencl = os.environ.get("SAS_OPENCL", "CUDA").lower() 
    113114    return HAVE_CUDA and sas_opencl.startswith("cuda") 
     
    136137        if not HAVE_CUDA: 
    137138            raise RuntimeError("CUDA startup failed with ***" 
    138                             + CUDA_ERROR + "***; using C compiler instead") 
     139                               + CUDA_ERROR + "***; using C compiler instead") 
    139140        reset_environment() 
    140141        if ENV is None: 
     
    198199    """ 
    199200    for match in FUNCTION_PATTERN.finditer(source): 
    200         print(match.group('qualifiers').replace('\n',r'\n'), match.group('function'), '(') 
     201        print(match.group('qualifiers').replace('\n', r'\n'), 
     202              match.group('function'), '(') 
    201203    return source 
    202204 
     
    260262 
    261263    def release(self): 
     264        """Free the CUDA device associated with this context.""" 
    262265        if self.context is not None: 
    263266            self.context.pop() 
  • sasmodels/kerneldll.py

    r3199b17 rb297ba9  
    174174 
    175175 
    176 def compile(source, output): 
     176def compile_model(source, output): 
    177177    # type: (str, str) -> None 
    178178    """ 
     
    265265        with os.fdopen(system_fd, "w") as file_handle: 
    266266            file_handle.write(source) 
    267         compile(source=filename, output=dll) 
     267        compile_model(source=filename, output=dll) 
    268268        # Comment the following to keep the generated C file. 
    269269        # Note: If there is a syntax error then compile raises an error 
  • sasmodels/kernelpy.py

    r3199b17 rb297ba9  
    1616    from numpy import cbrt 
    1717except ImportError: 
    18     def cbrt(x): return x ** (1.0/3.0) 
     18    def cbrt(x): 
     19        """Return cubed root of x.""" 
     20        return x ** (1.0/3.0) 
    1921 
    2022from .generate import F64 
     
    4345        self.info = model_info 
    4446        self.dtype = np.dtype('d') 
    45         logger.info("make python model " + self.info.name) 
     47        logger.info("make python model %s", self.info.name) 
    4648 
    4749    def make_kernel(self, q_vectors): 
     50        """Instantiate the python kernel with input *q_vectors*""" 
    4851        q_input = PyInput(q_vectors, dtype=F64) 
    4952        return PyKernel(self.info, q_input) 
  • sasmodels/list_pars.py

    r2d81cfe rb297ba9  
    1616from .compare import columnize 
    1717 
    18 def find_pars(type=None): 
     18def find_pars(kind=None): 
    1919    """ 
    2020    Find all parameters in all models. 
     
    2626        model_info = load_model_info(name) 
    2727        for p in model_info.parameters.kernel_parameters: 
    28             if type is None or p.type == type: 
     28            if kind is None or p.type == kind: 
    2929                partable.setdefault(p.name, []) 
    3030                partable[p.name].append(name) 
    3131    return partable 
    3232 
    33 def list_pars(names_only=True, type=None): 
     33def list_pars(names_only=True, kind=None): 
    3434    """ 
    3535    Print all parameters in all models. 
     
    3838    occurs in. 
    3939    """ 
    40     partable = find_pars(type) 
     40    partable = find_pars(kind) 
    4141    if names_only: 
    4242        print(columnize(list(sorted(partable.keys())))) 
     
    5757        help="list models which use this argument") 
    5858    parser.add_argument( 
    59         'type', default="any", nargs='?', 
     59        'kind', default="any", nargs='?', 
    6060        metavar="volume|orientation|sld|none|any", 
    6161        choices=['volume', 'orientation', 'sld', None, 'any'], 
    62         type=lambda v: None if v == 'any' else '' if v == 'none' else v, 
    63         help="only list arguments of the given type") 
     62        type=lambda v: None if v == 'any' else None if v == 'none' else v, 
     63        help="only list arguments of the given kind") 
    6464    args = parser.parse_args() 
    6565 
    66     list_pars(names_only=not args.verbose, type=args.type) 
     66    list_pars(names_only=not args.verbose, kind=args.kind) 
    6767 
    6868if __name__ == "__main__": 
  • sasmodels/mixture.py

    r39a06c9 rb297ba9  
    120120 
    121121    def random(): 
     122        """Random set of model parameters for mixture model""" 
    122123        combined_pars = {} 
    123124        for k, part in enumerate(parts): 
     
    149150 
    150151class MixtureModel(KernelModel): 
     152    """ 
     153    Model definition for mixture of models. 
     154    """ 
    151155    def __init__(self, model_info, parts): 
    152156        # type: (ModelInfo, List[KernelModel]) -> None 
     
    165169        kernels = [part.make_kernel(q_vectors) for part in self.parts] 
    166170        return MixtureKernel(self.info, kernels) 
     171    make_kernel.__doc__ = KernelModel.make_kernel.__doc__ 
    167172 
    168173    def release(self): 
    169174        # type: () -> None 
    170         """ 
    171         Free resources associated with the model. 
    172         """ 
     175        """Free resources associated with the model.""" 
    173176        for part in self.parts: 
    174177            part.release() 
     178    release.__doc__ = KernelModel.release.__doc__ 
    175179 
    176180 
    177181class MixtureKernel(Kernel): 
     182    """ 
     183    Instantiated kernel for mixture of models. 
     184    """ 
    178185    def __init__(self, model_info, kernels): 
    179186        # type: (ModelInfo, List[Kernel]) -> None 
     
    185192        self.results = []  # type: List[np.ndarray] 
    186193 
    187     def __call__(self, call_details, values, cutoff, magnetic): 
     194    def Iq(self, call_details, values, cutoff, magnetic): 
    188195        # type: (CallDetails, np.ndarray, np.ndarry, float, bool) -> np.ndarray 
    189196        scale, background = values[0:2] 
     
    191198        # remember the parts for plotting later 
    192199        self.results = []  # type: List[np.ndarray] 
    193         parts = MixtureParts(self.info, self.kernels, call_details, values) 
     200        parts = _MixtureParts(self.info, self.kernels, call_details, values) 
    194201        for kernel, kernel_details, kernel_values in parts: 
    195202            #print("calling kernel", kernel.info.name) 
     
    208215        return scale*total + background 
    209216 
     217    Iq.__doc__ = Kernel.Iq.__doc__ 
     218    __call__ = Iq 
     219 
    210220    def release(self): 
    211221        # type: () -> None 
     222        """Free resources associated with the kernel.""" 
    212223        for k in self.kernels: 
    213224            k.release() 
    214225 
    215226 
    216 class MixtureParts(object): 
     227# Note: _MixtureParts doesn't implement iteration correctly, and only allows 
     228# a single iterator to be active at once.  It doesn't matter in this case 
     229# since _MixtureParts is only used in one place, but it is not clean style. 
     230class _MixtureParts(object): 
     231    """ 
     232    Mixture component iterator. 
     233    """ 
    217234    def __init__(self, model_info, kernels, call_details, values): 
    218235        # type: (ModelInfo, List[Kernel], CallDetails, np.ndarray) -> None 
     
    223240        self.values = values 
    224241        self.spin_index = model_info.parameters.npars + 2 
     242        # The following are redefined by __iter__, but set them here so that 
     243        # lint complains a little less. 
     244        self.part_num = -1 
     245        self.par_index = -1 
     246        self.mag_index = -1 
    225247        #call_details.show(values) 
    226248 
  • sasmodels/model_test.py

    rd92182f rb297ba9  
    6161import numpy as np  # type: ignore 
    6262 
    63 from . import core 
    6463from .core import list_models, load_model_info, build_model 
    6564from .direct_model import call_kernel, call_Fq 
     
    137136        test_method_name = "test_%s_python" % model_info.id 
    138137        test = ModelTestCase(test_name, model_info, 
    139                                 test_method_name, 
    140                                 platform="dll",  # so that 
    141                                 dtype="double", 
    142                                 stash=stash) 
     138                             test_method_name, 
     139                             platform="dll",  # so that 
     140                             dtype="double", 
     141                             stash=stash) 
    143142        suite.addTest(test) 
    144143    else:   # kernel implemented in C 
     
    149148            test_method_name = "test_%s_dll" % model_info.id 
    150149            test = ModelTestCase(test_name, model_info, 
    151                                     test_method_name, 
    152                                     platform="dll", 
    153                                     dtype="double", 
    154                                     stash=stash) 
     150                                 test_method_name, 
     151                                 platform="dll", 
     152                                 dtype="double", 
     153                                 stash=stash) 
    155154            suite.addTest(test) 
    156155 
     
    164163            # presence of *single=False* in the model file. 
    165164            test = ModelTestCase(test_name, model_info, 
    166                                     test_method_name, 
    167                                     platform="ocl", dtype=None, 
    168                                     stash=stash) 
     165                                 test_method_name, 
     166                                 platform="ocl", dtype=None, 
     167                                 stash=stash) 
    169168            #print("defining", test_name) 
    170169            suite.addTest(test) 
     
    179178            # presence of *single=False* in the model file. 
    180179            test = ModelTestCase(test_name, model_info, 
    181                                     test_method_name, 
    182                                     platform="cuda", dtype=None, 
    183                                     stash=stash) 
     180                                 test_method_name, 
     181                                 platform="cuda", dtype=None, 
     182                                 stash=stash) 
    184183            #print("defining", test_name) 
    185184            suite.addTest(test) 
     
    413412# CRUFT: old interface; should be deprecated and removed 
    414413def run_one(model_name): 
     414    # type: (str) -> str 
     415    """ 
     416    [Deprecated] Run the tests associated with *model_name*. 
     417 
     418    Use the following instead:: 
     419 
     420        succss, output = check_model(load_model_info(model_name)) 
     421    """ 
    415422    # msg = "use check_model(model_info) rather than run_one(model_name)" 
    416423    # warnings.warn(msg, category=DeprecationWarning, stacklevel=2) 
     
    421428        return output 
    422429 
    423     success, output = check_model(model_info) 
     430    _, output = check_model(model_info) 
    424431    return output 
    425432 
    426433def check_model(model_info): 
    427     # type: (ModelInfo) -> str 
     434    # type: (ModelInfo) -> Tuple[bool, str] 
    428435    """ 
    429436    Run the tests for a single model, capturing the output. 
     
    492499        loaders.append('cuda') 
    493500    tests = make_suite(loaders, ['all']) 
    494     def build_test(test): 
     501    def _build_test(test): 
    495502        # In order for nosetest to show the test name, wrap the test.run_all 
    496503        # instance in function that takes the test name as a parameter which 
     
    510517 
    511518    for test in tests: 
    512         yield build_test(test) 
     519        yield _build_test(test) 
    513520 
    514521 
     
    539546                        "models will be tested.  See core.list_models() for " 
    540547                        "names of other groups, such as 'py' or 'single'.") 
    541     args, models = parser.parse_known_args() 
    542  
    543     if args.engine == "opencl": 
     548    opts = parser.parse_args() 
     549 
     550    if opts.engine == "opencl": 
    544551        if not use_opencl(): 
    545552            print("opencl is not available") 
    546553            return 1 
    547554        loaders = ['opencl'] 
    548     elif args.engine == "dll": 
     555    elif opts.engine == "dll": 
    549556        loaders = ["dll"] 
    550     elif args.engine == "cuda": 
     557    elif opts.engine == "cuda": 
    551558        if not use_cuda(): 
    552559            print("cuda is not available") 
    553560            return 1 
    554561        loaders = ['cuda'] 
    555     elif args.engine == "all": 
     562    elif opts.engine == "all": 
    556563        loaders = ['dll'] 
    557564        if use_opencl(): 
     
    560567            loaders.append('cuda') 
    561568    else: 
    562         print("unknown engine " + args.engine) 
     569        print("unknown engine " + opts.engine) 
    563570        return 1 
    564571 
    565     runner = TestRunner(verbosity=args.verbose, **test_args) 
    566     result = runner.run(make_suite(loaders, args.models)) 
     572    runner = TestRunner(verbosity=opts.verbose, **test_args) 
     573    result = runner.run(make_suite(loaders, opts.models)) 
    567574    return 1 if result.failures or result.errors else 0 
    568575 
  • sasmodels/modelinfo.py

    rd8eaa3d rb297ba9  
    10041004    #: *have_Fq* is True, then Iq should return an interleaved array of 
    10051005    #: $[\sum F(q_1), \sum F^2(q_1), \ldots, \sum F(q_n), \sum F^2(q_n)]$. 
    1006     Iq = None               # type: Union[None, str, Callable[[np.ndarray], np.ndarray]] 
     1006    Iq = None               # type: Union[None, str, Callable[[...], np.ndarray]] 
     1007    #: Returns *I(qx, qy, a, b, ...)*.  The interface follows :attr:`Iq`. 
     1008    Iqxy = None             # type: Union[None, str, Callable[[...], np.ndarray]] 
    10071009    #: Returns *I(qab, qc, a, b, ...)*.  The interface follows :attr:`Iq`. 
    1008     Iqac = None             # type: Union[None, str, Callable[[np.ndarray], np.ndarray]] 
     1010    Iqac = None             # type: Union[None, str, Callable[[...], np.ndarray]] 
    10091011    #: Returns *I(qa, qb, qc, a, b, ...)*.  The interface follows :attr:`Iq`. 
    1010     Iqabc = None            # type: Union[None, str, Callable[[np.ndarray], np.ndarray]] 
     1012    Iqabc = None            # type: Union[None, str, Callable[[...], np.ndarray]] 
    10111013    #: Returns *I(qx, qy, a, b, ...)*.  The interface follows :attr:`Iq`. 
    1012     Imagnetic = None        # type: Union[None, str, Callable[[np.ndarray], np.ndarray]] 
     1014    Imagnetic = None        # type: Union[None, str, Callable[[...], np.ndarray]] 
    10131015    #: Returns a model profile curve *x, y*.  If *profile* is defined, this 
    10141016    #: curve will appear in response to the *Show* button in SasView.  Use 
  • sasmodels/models/_spherepy.py

    r304c775 rb297ba9  
    6969 
    7070def form_volume(radius): 
     71    """Calculate volume for sphere""" 
    7172    return 1.333333333333333 * pi * radius ** 3 
    7273 
    7374def effective_radius(mode, radius): 
     75    """Calculate R_eff for sphere""" 
    7476    return radius 
    7577 
    7678def Iq(q, sld, sld_solvent, radius): 
     79    """Calculate I(q) for sphere""" 
    7780    #print "q",q 
    7881    #print "sld,r",sld,sld_solvent,radius 
  • sasmodels/models/adsorbed_layer.py

    r2d81cfe rb297ba9  
    8787def Iq(q, second_moment, adsorbed_amount, density_shell, radius, 
    8888       volfraction, sld_shell, sld_solvent): 
     89    """Return I(q) for adsorbed layer model.""" 
    8990    with errstate(divide='ignore'): 
    9091        aa = ((sld_shell - sld_solvent)/density_shell * adsorbed_amount) / q 
     
    9697 
    9798def random(): 
     99    """Return a random parameter set for the model.""" 
    98100    # only care about the value of second_moment: 
    99101    #    curve = scale * e**(-second_moment^2 q^2)/q^2 
  • sasmodels/models/barbell.py

    r99658f6 rb297ba9  
    7979.. [#] H Kaya and N R deSouza, *J. Appl. Cryst.*, 37 (2004) 508-509 (addenda 
    8080   and errata) 
    81 L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949).  
     81L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949). 
    8282 
    8383Authorship and Verification 
     
    117117 
    118118source = ["lib/polevl.c", "lib/sas_J1.c", "lib/gauss76.c", "barbell.c"] 
    119 have_Fq = True  
     119have_Fq = True 
    120120effective_radius_type = [ 
    121     "equivalent cylinder excluded volume","equivalent volume sphere", "radius", "half length", "half total length", 
     121    "equivalent cylinder excluded volume", "equivalent volume sphere", 
     122    "radius", "half length", "half total length", 
    122123    ] 
    123124 
    124125def random(): 
     126    """Return a random parameter set for the model.""" 
    125127    # TODO: increase volume range once problem with bell radius is fixed 
    126128    # The issue is that bell radii of more than about 200 fail at high q 
  • sasmodels/models/bcc_paracrystal.py

    rda7b26b rb297ba9  
    11r""" 
    2 .. warning:: This model and this model description are under review following  
    3              concerns raised by SasView users. If you need to use this model,  
    4              please email help@sasview.org for the latest situation. *The  
     2.. warning:: This model and this model description are under review following 
     3             concerns raised by SasView users. If you need to use this model, 
     4             please email help@sasview.org for the latest situation. *The 
    55             SasView Developers. September 2018.* 
    66 
     
    141141 
    142142def random(): 
     143    """Return a random parameter set for the model.""" 
    143144    # Define lattice spacing as a multiple of the particle radius 
    144145    # using the formulat a = 4 r/sqrt(3).  Systems which are ordered 
  • sasmodels/models/be_polyelectrolyte.py

    rca77fc1 rb297ba9  
    3636  constituting the polymer monomer and the solvent molecules, respectively. 
    3737 
    38 - $v_p$ and $v_s$ are the partial molar volume of the polymer and the  
     38- $v_p$ and $v_s$ are the partial molar volume of the polymer and the 
    3939  solvent, respectively. 
    4040 
     
    5050- $C_s$ is the concentration of monovalent salt(1/|Ang^3| - internally converted from mol/L). 
    5151 
    52 - $\alpha$ is the degree of ionization (the ratio of charged monomers to the total  
     52- $\alpha$ is the degree of ionization (the ratio of charged monomers to the total 
    5353  number of monomers) 
    5454 
     
    7474dimensionally useful units of 1/|Ang^3|, only the converted version of the 
    7575polymer concentration was actually being used in the calculation while the 
    76 unconverted salt concentration (still in apparent units of mol/L) was being  
    77 used.  This was carried through to Sasmodels as used for SasView 4.1 (though  
    78 the line of code converting the salt concentration to the new units was removed  
    79 somewhere along the line). Simple dimensional analysis of the calculation shows  
    80 that the converted salt concentration should be used, which the original code  
    81 suggests was the intention, so this has now been corrected (for SasView 4.2).  
     76unconverted salt concentration (still in apparent units of mol/L) was being 
     77used.  This was carried through to Sasmodels as used for SasView 4.1 (though 
     78the line of code converting the salt concentration to the new units was removed 
     79somewhere along the line). Simple dimensional analysis of the calculation shows 
     80that the converted salt concentration should be used, which the original code 
     81suggests was the intention, so this has now been corrected (for SasView 4.2). 
    8282Once better validation has been performed this note will be removed. 
    8383 
     
    141141    :params: see parameter table 
    142142    :return: 1-D form factor for polyelectrolytes in low salt 
    143      
     143 
    144144    parameter names, units, default values, and behavior (volume, sld etc) are 
    145145    defined in the parameter table.  The concentrations are converted from 
     
    167167 
    168168def random(): 
     169    """Return a random parameter set for the model.""" 
    169170    # TODO: review random be_polyelectrolyte model generation 
    170171    pars = dict( 
  • sasmodels/models/binary_hard_sphere.py

    r2d81cfe rb297ba9  
    112112 
    113113def random(): 
     114    """Return a random parameter set for the model.""" 
    114115    # TODO: binary_hard_sphere fails at low qr 
    115116    radius_lg = 10**np.random.uniform(2, 4.7) 
  • sasmodels/models/broad_peak.py

    r2d81cfe rb297ba9  
    9696 
    9797def random(): 
     98    """Return a random parameter set for the model.""" 
    9899    pars = dict( 
    99100        scale=1, 
  • sasmodels/models/capped_cylinder.py

    r99658f6 rb297ba9  
    8282.. [#] H Kaya and N-R deSouza, *J. Appl. Cryst.*, 37 (2004) 508-509 (addenda 
    8383   and errata) 
    84 L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949).  
     84L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949). 
    8585 
    8686Authorship and Verification 
     
    139139have_Fq = True 
    140140effective_radius_type = [ 
    141     "equivalent cylinder excluded volume", "equivalent volume sphere", "radius", "half length", "half total length", 
     141    "equivalent cylinder excluded volume", "equivalent volume sphere", 
     142    "radius", "half length", "half total length", 
    142143    ] 
    143144 
    144145def random(): 
     146    """Return a random parameter set for the model.""" 
    145147    # TODO: increase volume range once problem with bell radius is fixed 
    146148    # The issue is that bell radii of more than about 200 fail at high q 
  • sasmodels/models/core_multi_shell.py

    ree60aa7 rb297ba9  
    103103 
    104104def random(): 
     105    """Return a random parameter set for the model.""" 
    105106    num_shells = np.minimum(np.random.poisson(3)+1, 10) 
    106107    total_radius = 10**np.random.uniform(1.7, 4) 
  • sasmodels/models/core_shell_bicelle.py

    r99658f6 rb297ba9  
    8989   from Proquest <http://search.proquest.com/docview/304915826?accountid 
    9090   =26379>`_ 
    91     
    92    L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949).  
     91 
     92   L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949). 
    9393 
    9494Authorship and Verification 
     
    158158have_Fq = True 
    159159effective_radius_type = [ 
    160     "excluded volume","equivalent volume sphere", "outer rim radius", 
     160    "excluded volume", "equivalent volume sphere", "outer rim radius", 
    161161    "half outer thickness", "half diagonal", 
    162162    ] 
    163163 
    164164def random(): 
     165    """Return a random parameter set for the model.""" 
    165166    pars = dict( 
    166167        radius=10**np.random.uniform(1.3, 3), 
  • sasmodels/models/core_shell_bicelle_elliptical.py

    r99658f6 rb297ba9  
    100100 
    101101.. [#] 
    102 L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949).  
     102L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949). 
    103103 
    104104Authorship and Verification 
     
    149149have_Fq = True 
    150150effective_radius_type = [ 
    151     "equivalent cylinder excluded volume", "equivalent volume sphere", "outer rim average radius", "outer rim min radius", 
     151    "equivalent cylinder excluded volume", "equivalent volume sphere", 
     152    "outer rim average radius", "outer rim min radius", 
    152153    "outer max radius", "half outer thickness", "half diagonal", 
    153154    ] 
    154155 
    155156def random(): 
     157    """Return a random parameter set for the model.""" 
    156158    outer_major = 10**np.random.uniform(1, 4.7) 
    157159    outer_minor = 10**np.random.uniform(1, 4.7) 
  • sasmodels/models/core_shell_bicelle_elliptical_belt_rough.py

    r99658f6 rb297ba9  
    112112 
    113113.. [#] 
    114 L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949).  
     114L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949). 
    115115 
    116116Authorship and Verification 
     
    162162have_Fq = True 
    163163effective_radius_type = [ 
    164     "equivalent cylinder excluded volume", "equivalent volume sphere", "outer rim average radius", "outer rim min radius", 
     164    "equivalent cylinder excluded volume", "equivalent volume sphere", 
     165    "outer rim average radius", "outer rim min radius", 
    165166    "outer max radius", "half outer thickness", "half diagonal", 
    166167    ] 
     168 
     169# TODO: No random() for core-shell bicelle elliptical belt rough 
    167170 
    168171demo = dict(scale=1, background=0, 
     
    190193    #[{'radius': 30.0, 'x_core': 3.0, 'thick_rim':8.0, 'thick_face':14.0, 'length':50.0}, 'VR', 1], 
    191194 
    192     [{'radius': 30.0, 'x_core': 3.0, 'thick_rim':8.0, 'thick_face':14.0, 'length':50.0, 
    193       'sld_core':4.0, 'sld_face':7.0, 'sld_rim':1.0, 'sld_solvent':6.0, 'background':0.0}, 
     195    [{'radius': 30.0, 'x_core': 3.0, 'thick_rim': 8.0, 'thick_face': 14.0, 
     196      'length': 50.0, 'sld_core': 4.0, 'sld_face': 7.0, 'sld_rim': 1.0, 
     197      'sld_solvent': 6.0, 'background': 0.0}, 
    194198     0.015, 189.328], 
    195199    #[{'theta':80., 'phi':10.}, (qx, qy), 7.88866563001 ], 
  • sasmodels/models/core_shell_cylinder.py

    r99658f6 rb297ba9  
    7070   1445-1452 
    7171.. [#kline] S R Kline, *J Appl. Cryst.*, 39 (2006) 895 
    72 L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949).  
     72L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949). 
    7373 
    7474Authorship and Verification 
     
    139139 
    140140def random(): 
     141    """Return a random parameter set for the model.""" 
    141142    outer_radius = 10**np.random.uniform(1, 4.7) 
    142143    # Use a distribution with a preference for thin shell or thin core 
  • sasmodels/models/core_shell_ellipsoid.py

    r99658f6 rb297ba9  
    147147have_Fq = True 
    148148effective_radius_type = [ 
    149     "average outer curvature", "equivalent volume sphere",      
     149    "average outer curvature", "equivalent volume sphere", 
    150150    "min outer radius", "max outer radius", 
    151151    ] 
    152152 
    153153def random(): 
     154    """Return a random parameter set for the model.""" 
    154155    volume = 10**np.random.uniform(5, 12) 
    155156    outer_polar = 10**np.random.uniform(1.3, 4) 
  • sasmodels/models/core_shell_parallelepiped.py

    r99658f6 rb297ba9  
    173173   from Proquest <http://search.proquest.com/docview/304915826?accountid 
    174174   =26379>`_ 
    175 L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949).  
     175L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949). 
    176176 
    177177Authorship and Verification 
     
    186186 
    187187import numpy as np 
    188 from numpy import pi, inf, sqrt, cos, sin 
     188from numpy import inf 
    189189 
    190190name = "core_shell_parallelepiped" 
     
    229229have_Fq = True 
    230230effective_radius_type = [ 
    231     "equivalent cylinder excluded volume",  
     231    "equivalent cylinder excluded volume", 
    232232    "equivalent volume sphere", 
    233233    "half outer length_a", "half outer length_b", "half outer length_c", 
     
    237237 
    238238def random(): 
     239    """Return a random parameter set for the model.""" 
    239240    outer = 10**np.random.uniform(1, 4.7, size=3) 
    240241    thick = np.random.beta(0.5, 0.5, size=3)*(outer-2) + 1 
     
    269270# 2d values not tested against other codes or models 
    270271if 0:  # pak: model rewrite; need to update tests 
    271     qx, qy = 0.2 * cos(pi/6.), 0.2 * sin(pi/6.) 
     272    qx, qy = 0.2 * np.cos(np.pi/6.), 0.2 * np.sin(np.pi/6.) 
    272273    tests = [[{}, 0.2, 0.533149288477], 
    273274             [{}, [0.2], [0.533149288477]], 
  • sasmodels/models/core_shell_sphere.py

    r304c775 rb297ba9  
    8484 
    8585def random(): 
     86    """Return a random parameter set for the model.""" 
    8687    outer_radius = 10**np.random.uniform(1.3, 4.3) 
    8788    # Use a distribution with a preference for thin shell or thin core 
  • sasmodels/models/cylinder.py

    r99658f6 rb297ba9  
    9898J. S. Pedersen, Adv. Colloid Interface Sci. 70, 171-210 (1997). 
    9999G. Fournet, Bull. Soc. Fr. Mineral. Cristallogr. 74, 39-113 (1951). 
    100 L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949).  
     100L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949). 
    101101""" 
    102102 
     
    146146 
    147147def random(): 
     148    """Return a random parameter set for the model.""" 
    148149    volume = 10**np.random.uniform(5, 12) 
    149150    length = 10**np.random.uniform(-2, 2)*volume**0.333 
     
    184185 
    185186# Default radius and length 
    186 radius, length = parameters[2][2], parameters[3][2] 
     187def calc_volume(radius, length): 
     188    """Return form volume for cylinder.""" 
     189    return pi*radius**2*length 
     190def calc_r_effs(radius, length): 
     191    """Return effective radii for modes 0-7 of cylinder.""" 
     192    return [ 
     193        0., 
     194        0.5*(0.75*radius*(2.0*radius*length 
     195                          + (radius + length)*(pi*radius + length)))**(1./3.), 
     196        (0.75*radius**2*length)**(1./3.), 
     197        radius, 
     198        length/2., 
     199        min(radius, length/2.), 
     200        max(radius, length/2.), 
     201        np.sqrt(4*radius**2 + length**2)/2., 
     202    ] 
     203r_effs = calc_r_effs(parameters[2][2], parameters[3][2]) 
     204cyl_vol = calc_volume(parameters[2][2], parameters[3][2]) 
    187205tests.extend([ 
    188     ({'radius_effective_mode': 0}, 0.1, None, None, 0., pi*radius**2*length, 1.0),    
    189     ({'radius_effective_mode': 1}, 0.1, None, None, 0.5*(0.75*radius*(2.0*radius*length + (radius + length)*(pi*radius + length)))**(1./3.), None, None),     
    190     ({'radius_effective_mode': 2}, 0.1, None, None, (0.75*radius**2*length)**(1./3.), None, None), 
    191     ({'radius_effective_mode': 3}, 0.1, None, None, radius, None, None), 
    192     ({'radius_effective_mode': 4}, 0.1, None, None, length/2., None, None), 
    193     ({'radius_effective_mode': 5}, 0.1, None, None, min(radius, length/2.), None, None), 
    194     ({'radius_effective_mode': 6}, 0.1, None, None, max(radius, length/2.), None, None), 
    195     ({'radius_effective_mode': 7}, 0.1, None, None, np.sqrt(4*radius**2 + length**2)/2., None, None), 
     206    ({'radius_effective_mode': 0}, 0.1, None, None, r_effs[0], cyl_vol, 1.0), 
     207    ({'radius_effective_mode': 1}, 0.1, None, None, r_effs[1], None, None), 
     208    ({'radius_effective_mode': 2}, 0.1, None, None, r_effs[2], None, None), 
     209    ({'radius_effective_mode': 3}, 0.1, None, None, r_effs[3], None, None), 
     210    ({'radius_effective_mode': 4}, 0.1, None, None, r_effs[4], None, None), 
     211    ({'radius_effective_mode': 5}, 0.1, None, None, r_effs[5], None, None), 
     212    ({'radius_effective_mode': 6}, 0.1, None, None, r_effs[6], None, None), 
     213    ({'radius_effective_mode': 7}, 0.1, None, None, r_effs[7], None, None), 
    196214]) 
    197 del radius, length 
     215del r_effs, cyl_vol 
    198216# pylint: enable=bad-whitespace, line-too-long 
    199217 
  • sasmodels/models/dab.py

    r304c775 rb297ba9  
    6666 
    6767def random(): 
     68    """Return a random parameter set for the model.""" 
    6869    pars = dict( 
    6970        scale=10**np.random.uniform(1, 4), 
  • sasmodels/models/ellipsoid.py

    r99658f6 rb297ba9  
    126126from numpy import inf, sin, cos, pi 
    127127 
    128 try: 
    129     from numpy import cbrt 
    130 except ImportError: 
    131     def cbrt(x): return x ** (1.0/3.0) 
    132  
    133128name = "ellipsoid" 
    134129title = "Ellipsoid of revolution with uniform scattering length density." 
     
    174169 
    175170def random(): 
     171    """Return a random parameter set for the model.""" 
    176172    volume = 10**np.random.uniform(5, 12) 
    177173    radius_polar = 10**np.random.uniform(1.3, 4) 
  • sasmodels/models/elliptical_cylinder.py

    r99658f6 rb297ba9  
    8888L A Feigin and D I Svergun, *Structure Analysis by Small-Angle X-Ray and 
    8989Neutron Scattering*, Plenum, New York, (1987) [see table 3.4] 
    90 L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949).  
     90L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949). 
    9191 
    9292Authorship and Verification 
     
    125125have_Fq = True 
    126126effective_radius_type = [ 
    127     "equivalent cylinder excluded volume", "equivalent volume sphere", "average radius", "min radius", "max radius", 
     127    "equivalent cylinder excluded volume", 
     128    "equivalent volume sphere", "average radius", "min radius", "max radius", 
    128129    "equivalent circular cross-section", 
    129130    "half length", "half min dimension", "half max dimension", "half diagonal", 
     
    135136 
    136137def random(): 
     138    """Return a random parameter set for the model.""" 
    137139    # V = pi * radius_major * radius_minor * length; 
    138140    volume = 10**np.random.uniform(3, 9) 
    139141    length = 10**np.random.uniform(1, 3) 
    140142    axis_ratio = 10**np.random.uniform(0, 2) 
    141     radius_minor = np.sqrt(volume/length/axis_ratio) 
     143    radius_minor = sqrt(volume/length/axis_ratio) 
    142144    volfrac = 10**np.random.uniform(-4, -2) 
    143145    pars = dict( 
     
    156158 
    157159tests = [ 
    158 #    [{'radius_minor': 20.0, 'axis_ratio': 1.5, 'length':400.0}, 'ER', 79.89245454155024], 
    159 #    [{'radius_minor': 20.0, 'axis_ratio': 1.2, 'length':300.0}, 'VR', 1], 
     160    #[{'radius_minor': 20.0, 'axis_ratio': 1.5, 'length':400.0}, 'ER', 79.89245454155024], 
     161    #[{'radius_minor': 20.0, 'axis_ratio': 1.2, 'length':300.0}, 'VR', 1], 
    160162 
    161163    # The SasView test result was 0.00169, with a background of 0.001 
  • sasmodels/models/fcc_paracrystal.py

    rda7b26b rb297ba9  
    33#note - calculation requires double precision 
    44r""" 
    5 .. warning:: This model and this model description are under review following  
    6              concerns raised by SasView users. If you need to use this model,  
    7              please email help@sasview.org for the latest situation. *The  
     5.. warning:: This model and this model description are under review following 
     6             concerns raised by SasView users. If you need to use this model, 
     7             please email help@sasview.org for the latest situation. *The 
    88             SasView Developers. September 2018.* 
    99 
     
    137137 
    138138def random(): 
     139    """Return a random parameter set for the model.""" 
    139140    # copied from bcc_paracrystal 
    140141    radius = 10**np.random.uniform(1.3, 4) 
  • sasmodels/models/flexible_cylinder.py

    r2d81cfe rb297ba9  
    8989 
    9090def random(): 
     91    """Return a random parameter set for the model.""" 
    9192    length = 10**np.random.uniform(2, 6) 
    9293    radius = 10**np.random.uniform(1, 3) 
  • sasmodels/models/flexible_cylinder_elliptical.py

    r2d81cfe rb297ba9  
    115115 
    116116def random(): 
     117    """Return a random parameter set for the model.""" 
    117118    length = 10**np.random.uniform(2, 6) 
    118119    radius = 10**np.random.uniform(1, 3) 
  • sasmodels/models/fractal.py

    r2d81cfe rb297ba9  
    100100 
    101101def random(): 
     102    """Return a random parameter set for the model.""" 
    102103    radius = 10**np.random.uniform(0.7, 4) 
    103104    #radius = 5 
  • sasmodels/models/fractal_core_shell.py

    r2cc8aa2 rb297ba9  
    6060 
    6161import numpy as np 
    62 from numpy import pi, inf 
     62from numpy import inf 
    6363 
    6464name = "fractal_core_shell" 
     
    9898 
    9999def random(): 
     100    """Return a random parameter set for the model.""" 
    100101    outer_radius = 10**np.random.uniform(0.7, 4) 
    101102    # Use a distribution with a preference for thin shell or thin core 
     
    126127            cor_length=100.0) 
    127128 
     129# TODO: why is there an ER function here? 
    128130def ER(radius, thickness): 
    129131    """ 
     
    136138#tests = [[{'radius': 20.0, 'thickness': 10.0}, 'ER', 30.0], 
    137139tests = [ 
    138 #         # At some point the SasView 3.x test result was deemed incorrect. The 
    139           #following tests were verified against NIST IGOR macros ver 7.850. 
    140           #NOTE: NIST macros do only provide for a polydispers core (no option 
    141           #for a poly shell or for a monodisperse core.  The results seemed 
    142           #extremely sensitive to the core PD, varying non monotonically all 
    143           #the way to a PD of 1e-6. From 1e-6 to 1e-9 no changes in the 
    144           #results were observed and the values below were taken using PD=1e-9. 
    145           #Non-monotonically = I(0.001)=188 to 140 to 177 back to 160 etc. 
    146          [{'radius': 20.0, 
    147            'thickness': 5.0, 
    148            'sld_core': 3.5, 
    149            'sld_shell': 1.0, 
    150            'sld_solvent': 6.35, 
    151            'volfraction': 0.05, 
    152            'background': 0.0}, 
    153            [0.001,0.00291,0.0107944,0.029923,0.100726,0.476304], 
    154            [177.146,165.151,84.1596,20.1466,1.40906,0.00622666]]] 
     140    # At some point the SasView 3.x test result was deemed incorrect.  The 
     141    # following tests were verified against NIST IGOR macros ver 7.850. 
     142    # NOTE: NIST macros do only provide for a polydispers core (no option 
     143    # for a poly shell or for a monodisperse core.  The results seemed 
     144    # extremely sensitive to the core PD, varying non monotonically all 
     145    # the way to a PD of 1e-6. From 1e-6 to 1e-9 no changes in the 
     146    # results were observed and the values below were taken using PD=1e-9. 
     147    # Non-monotonically = I(0.001)=188 to 140 to 177 back to 160 etc. 
     148    [{'radius': 20.0, 
     149      'thickness': 5.0, 
     150      'sld_core': 3.5, 
     151      'sld_shell': 1.0, 
     152      'sld_solvent': 6.35, 
     153      'volfraction': 0.05, 
     154      'background': 0.0}, 
     155     [0.001, 0.00291, 0.0107944, 0.029923, 0.100726, 0.476304], 
     156     [177.146, 165.151, 84.1596, 20.1466, 1.40906, 0.00622666] 
     157    ] 
     158] 
  • sasmodels/models/fuzzy_sphere.py

    ree60aa7 rb297ba9  
    8282# pylint: enable=bad-whitespace,line-too-long 
    8383 
    84 source = ["lib/sas_3j1x_x.c","fuzzy_sphere.c"] 
     84source = ["lib/sas_3j1x_x.c", "fuzzy_sphere.c"] 
    8585have_Fq = True 
    8686effective_radius_type = ["radius", "radius + fuzziness"] 
    8787 
    8888def random(): 
     89    """Return a random parameter set for the model.""" 
    8990    radius = 10**np.random.uniform(1, 4.7) 
    9091    fuzziness = 10**np.random.uniform(-2, -0.5)*radius  # 1% to 31% fuzziness 
  • sasmodels/models/gauss_lorentz_gel.py

    r2d81cfe rb297ba9  
    8989 
    9090def random(): 
     91    """Return a random parameter set for the model.""" 
    9192    gauss_scale = 10**np.random.uniform(1, 3) 
    9293    lorentz_scale = 10**np.random.uniform(1, 3) 
  • sasmodels/models/gaussian_peak.py

    r304c775 rb297ba9  
    5151 
    5252def random(): 
     53    """Return a random parameter set for the model.""" 
    5354    peak_pos = 10**np.random.uniform(-3, -1) 
    5455    sigma = 10**np.random.uniform(-1.3, -0.3)*peak_pos 
  • sasmodels/models/gel_fit.py

    r2d81cfe rb297ba9  
    7272 
    7373def random(): 
     74    """Return a random parameter set for the model.""" 
    7475    guinier_scale = 10**np.random.uniform(1, 3) 
    7576    lorentz_scale = 10**np.random.uniform(1, 3) 
  • sasmodels/models/guinier.py

    rc9fc873 rb297ba9  
    3838 
    3939To specify a negative value of $R_g^2$ in SasView, simply give $R_g$ a negative 
    40 value ($R_g^2$ will be evaluated as $R_g |R_g|$). Note that the physical radius  
    41 of gyration, of the exterior of the particle, will still be large and positive.  
    42 It is only the apparent size from the small $Q$ data that will give a small or  
     40value ($R_g^2$ will be evaluated as $R_g |R_g|$). Note that the physical radius 
     41of gyration, of the exterior of the particle, will still be large and positive. 
     42It is only the apparent size from the small $Q$ data that will give a small or 
    4343negative value of $R_g^2$. 
    4444 
     
    7474 
    7575def random(): 
     76    """Return a random parameter set for the model.""" 
    7677    scale = 10**np.random.uniform(1, 4) 
    7778    # Note: compare.py has Rg cutoff of 1e-30 at q=1 for guinier, so use that 
     
    8990 
    9091# parameters for demo 
    91 demo = dict(scale=1.0,  background=0.001, rg=60.0 ) 
     92demo = dict(scale=1.0, background=0.001, rg=60.0) 
    9293 
    9394# parameters for unit tests 
  • sasmodels/models/guinier_porod.py

    r2d81cfe rb297ba9  
    115115 
    116116def random(): 
     117    """Return a random parameter set for the model.""" 
    117118    rg = 10**np.random.uniform(1, 5) 
    118119    s = np.random.uniform(0, 3) 
  • sasmodels/models/hardsphere.py

    rc1799d3 rb297ba9  
    155155 
    156156def random(): 
     157    """Return a random parameter set for the model.""" 
    157158    pars = dict( 
    158159        scale=1, background=0, 
  • sasmodels/models/hayter_msa.py

    r304c775 rb297ba9  
    9191 
    9292def random(): 
     93    """Return a random parameter set for the model.""" 
    9394    # TODO: too many failures for random hayter_msa parameters 
    9495    pars = dict( 
  • sasmodels/models/hollow_cylinder.py

    r99658f6 rb297ba9  
    6060.. [#] L A Feigin and D I Svergun, *Structure Analysis by Small-Angle X-Ray and 
    6161   Neutron Scattering*, Plenum Press, New York, (1987) 
    62 L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949).  
     62L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949). 
    6363 
    6464Authorship and Verification 
     
    103103have_Fq = True 
    104104effective_radius_type = [ 
    105     "excluded volume", "equivalent outer volume sphere", "outer radius", "half length", 
     105    "excluded volume", "equivalent outer volume sphere", 
     106    "outer radius", "half length", 
    106107    "half outer min dimension", "half outer max dimension", 
    107108    "half outer diagonal", 
     
    109110 
    110111def random(): 
     112    """Return a random parameter set for the model.""" 
    111113    length = 10**np.random.uniform(1, 4.7) 
    112114    outer_radius = 10**np.random.uniform(1, 4.7) 
     
    130132            theta_pd=10, theta_pd_n=5, 
    131133           ) 
     134 
     135def r_eff(radius, thickness, length): 
     136    """R_eff from excluded volume""" 
     137    radius += thickness 
     138    return (0.5*(0.75*radius*(2.0*radius*length 
     139                              + (radius + length)*(pi*radius + length)) 
     140                )**(1./3.)) 
     141 
     142def shell_volume(radius, thickness, length): 
     143    """shell volume for parameter set""" 
     144    return pi*((radius+thickness)**2-radius**2)*length 
     145 
     146def form_shell_ratio(radius, thickness, length): 
     147    """form:shell ratio""" 
     148    return (radius+thickness)**2/((radius+thickness)**2 - radius**2) 
     149 
    132150q = 0.1 
    133151# april 6 2017, rkh added a 2d unit test, assume correct! 
    134152qx = q*cos(pi/6.0) 
    135153qy = q*sin(pi/6.0) 
    136 radius = parameters[0][2] 
    137 thickness = parameters[1][2] 
    138 length = parameters[2][2] 
     154test_pars = [ 
     155    parameters[0][2], # radius 
     156    parameters[1][2], # thickness 
     157    parameters[2][2], # length 
     158] 
    139159# Parameters for unit tests 
    140160tests = [ 
    141161    [{}, 0.00005, 1764.926], 
    142162    [{}, 0.1, None, None, 
    143      0.5*(0.75*(radius+thickness)*(2.0*(radius+thickness)*length + ((radius+thickness) + length)*(pi*(radius+thickness) + length)))**(1./3.),  # R_eff from excluded volume 
    144      pi*((radius+thickness)**2-radius**2)*length,  # shell volume 
    145      (radius+thickness)**2/((radius+thickness)**2 - radius**2), # form:shell ratio 
     163     r_eff(*test_pars), shell_volume(*test_pars), form_shell_ratio(*test_pars), 
    146164    ], 
    147165    [{}, 0.001, 1756.76], 
    148166    [{}, (qx, qy), 2.36885476192], 
    149167] 
    150 del qx, qy  # not necessary to delete, but cleaner 
     168del qx, qy, test_pars  # not necessary to delete, but cleaner 
  • sasmodels/models/hollow_rectangular_prism.py

    r99658f6 rb297ba9  
    9898 
    9999.. [#Nayuk2012] R Nayuk and K Huber, *Z. Phys. Chem.*, 226 (2012) 837-854 
    100 L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949).  
     100L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949). 
    101101 
    102102 
     
    110110 
    111111import numpy as np 
    112 from numpy import pi, inf, sqrt 
     112from numpy import inf 
    113113 
    114114name = "hollow_rectangular_prism" 
     
    151151have_Fq = True 
    152152effective_radius_type = [ 
    153     "equivalent cylinder excluded volume", "equivalent outer volume sphere",  
     153    "equivalent cylinder excluded volume", "equivalent outer volume sphere", 
    154154    "half length_a", "half length_b", "half length_c", 
    155155    "equivalent outer circular cross-section", 
     
    158158 
    159159def random(): 
     160    """Return a random parameter set for the model.""" 
    160161    a, b, c = 10**np.random.uniform(1, 4.7, size=3) 
    161162    # Thickness is limited to 1/2 the smallest dimension 
  • sasmodels/models/hollow_rectangular_prism_thin_walls.py

    r99658f6 rb297ba9  
    7272 
    7373.. [#Nayuk2012] R Nayuk and K Huber, *Z. Phys. Chem.*, 226 (2012) 837-854 
    74 L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949).  
     74L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949). 
    7575 
    7676 
     
    8484 
    8585import numpy as np 
    86 from numpy import pi, inf, sqrt 
     86from numpy import inf 
    8787 
    8888name = "hollow_rectangular_prism_thin_walls" 
     
    111111have_Fq = True 
    112112effective_radius_type = [ 
    113     "equivalent cylinder excluded volume", "equivalent outer volume sphere",  
     113    "equivalent cylinder excluded volume", "equivalent outer volume sphere", 
    114114    "half length_a", "half length_b", "half length_c", 
    115115    "equivalent outer circular cross-section", 
     
    119119 
    120120def random(): 
     121    """Return a random parameter set for the model.""" 
    121122    a, b, c = 10**np.random.uniform(1, 4.7, size=3) 
    122123    pars = dict( 
  • sasmodels/models/lamellar.py

    r304c775 rb297ba9  
    8989 
    9090def random(): 
     91    """Return a random parameter set for the model.""" 
    9192    thickness = 10**np.random.uniform(1, 4) 
    9293    pars = dict( 
  • sasmodels/models/lamellar_hg.py

    r304c775 rb297ba9  
    100100 
    101101def random(): 
     102    """Return a random parameter set for the model.""" 
    102103    thickness = 10**np.random.uniform(1, 4) 
    103104    length_head = thickness * np.random.uniform(0, 1) 
  • sasmodels/models/lamellar_hg_stack_caille.py

    r304c775 rb297ba9  
    123123 
    124124def random(): 
     125    """Return a random parameter set for the model.""" 
    125126    total_thickness = 10**np.random.uniform(2, 4.7) 
    126127    Nlayers = np.random.randint(2, 200) 
  • sasmodels/models/lamellar_stack_caille.py

    r304c775 rb297ba9  
    101101 
    102102def random(): 
     103    """Return a random parameter set for the model.""" 
    103104    total_thickness = 10**np.random.uniform(2, 4.7) 
    104105    Nlayers = np.random.randint(2, 200) 
  • sasmodels/models/lamellar_stack_paracrystal.py

    r304c775 rb297ba9  
    133133 
    134134def random(): 
     135    """Return a random parameter set for the model.""" 
    135136    total_thickness = 10**np.random.uniform(2, 4.7) 
    136137    Nlayers = np.random.randint(2, 200) 
  • sasmodels/models/line.py

    r108e70e rb297ba9  
    5858 
    5959 
    60 def Iqxy(qx, qy, *args): 
     60def Iqxy(qx, qy, intercept, slope): 
    6161    """ 
    6262    :param qx:   Input q_x-value 
    6363    :param qy:   Input q_y-value 
    64     :param args: Remaining arguments 
     64    :param intercept:   Intrecept in linear model 
     65    :param slope:       Slope in linear model 
    6566    :return:     2D-Intensity 
    6667    """ 
    6768    # TODO: SasView documents 2D intensity as Iq(qx)*Iq(qy), but returns Iq(qy) 
    6869    # Note: SasView.run([r, theta]) does return Iq(qx)*Iq(qy) 
    69     return Iq(qx, *args)*Iq(qy, *args) 
     70    return Iq(qx, intercept, slope)*Iq(qy, intercept, slope) 
    7071 
    7172Iqxy.vectorized = True  # Iqxy accepts an array of qx qy values 
     
    8081 
    8182def random(): 
     83    """Return a random parameter set for the model.""" 
    8284    scale = 10**np.random.uniform(0, 3) 
    8385    slope = np.random.uniform(-1, 1)*1e2 
  • sasmodels/models/linear_pearls.py

    r2d81cfe rb297ba9  
    6666 
    6767def random(): 
     68    """Return a random parameter set for the model.""" 
    6869    radius = 10**np.random.uniform(1, 3) # 1 - 1000 
    6970    edge_sep = 10**np.random.uniform(0, 3)  # 1 - 1000 
     
    7677    return pars 
    7778 
    78 """ 
     79_ = """ 
    7980Tests temporarily disabled, until single-double precision accuracy issue solved. 
    8081 
  • sasmodels/models/lorentz.py

    r2d81cfe rb297ba9  
    5050 
    5151def random(): 
     52    """Return a random parameter set for the model.""" 
    5253    pars = dict( 
    5354        #background=0, 
  • sasmodels/models/mass_fractal.py

    r2d81cfe rb297ba9  
    8888 
    8989def random(): 
     90    """Return a random parameter set for the model.""" 
    9091    radius = 10**np.random.uniform(0.7, 4) 
    9192    cutoff_length = 10**np.random.uniform(0.7, 2)*radius 
  • sasmodels/models/mass_surface_fractal.py

    r71b751d rb297ba9  
    9696 
    9797def random(): 
     98    """Return a random parameter set for the model.""" 
    9899    fractal_dim = np.random.uniform(0, 6) 
    99100    surface_portion = np.random.uniform(0, 1) 
     
    122123tests = [ 
    123124 
    124     # Accuracy tests based on content in test/utest_other_models.py  All except first, changed so rg_cluster is the larger, RKH 30 May 2018 
     125    # Accuracy tests based on content in test/utest_other_models.py  All 
     126    # except first, changed so rg_cluster is the larger, RKH 30 May 2018 
    125127    [{'fractal_dim_mass':   1.8, 
    126128      'fractal_dim_surf':   2.3, 
  • sasmodels/models/mono_gauss_coil.py

    rc5f7aa9 rb297ba9  
    7979 
    8080def random(): 
     81    """Return a random parameter set for the model.""" 
    8182    rg = 10**np.random.uniform(0, 4) 
    8283    #rg = 1e3 
  • sasmodels/models/multilayer_vesicle.py

    ree60aa7 rb297ba9  
    149149 
    150150def random(): 
     151    """Return a random parameter set for the model.""" 
    151152    volfraction = 10**np.random.uniform(-3, -0.5)  # scale from 0.1% to 30% 
    152153    radius = 10**np.random.uniform(0, 2.5) # core less than 300 A 
  • sasmodels/models/onion.py

    ree60aa7 rb297ba9  
    367367    return np.asarray(z), np.asarray(rho) 
    368368 
     369# TODO: no random parameter function for onion model 
     370 
    369371demo = { 
    370372    "sld_solvent": 2.2, 
  • sasmodels/models/parallelepiped.py

    r99658f6 rb297ba9  
    180180   14 (1961) 185-211 
    181181.. [#] R Nayuk and K Huber, *Z. Phys. Chem.*, 226 (2012) 837-854 
    182 L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949).  
     182L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949). 
    183183 
    184184Authorship and Verification 
     
    192192 
    193193import numpy as np 
    194 from numpy import pi, inf, sqrt, sin, cos 
     194from numpy import inf 
    195195 
    196196name = "parallelepiped" 
     
    233233have_Fq = True 
    234234effective_radius_type = [ 
    235     "equivalent cylinder excluded volume", "equivalent volume sphere",  
     235    "equivalent cylinder excluded volume", "equivalent volume sphere", 
    236236    "half length_a", "half length_b", "half length_c", 
    237237    "equivalent circular cross-section", "half ab diagonal", "half diagonal", 
     
    239239 
    240240def random(): 
     241    """Return a random parameter set for the model.""" 
    241242    length = 10**np.random.uniform(1, 4.7, size=3) 
    242243    pars = dict( 
     
    261262# rkh 7/4/17 add random unit test for 2d, note make all params different, 
    262263# 2d values not tested against other codes or models 
    263 qx, qy = 0.2 * cos(pi/6.), 0.2 * sin(pi/6.) 
     264qx, qy = 0.2 * np.cos(np.pi/6.), 0.2 * np.sin(np.pi/6.) 
    264265tests = [[{}, 0.2, 0.17758004974], 
    265266         [{}, [0.2], [0.17758004974]], 
  • sasmodels/models/peak_lorentz.py

    r2d81cfe rb297ba9  
    6060 
    6161def random(): 
     62    """Return a random parameter set for the model.""" 
    6263    peak_pos = 10**np.random.uniform(-3, -1) 
    6364    peak_hwhm = peak_pos * 10**np.random.uniform(-3, 0) 
  • sasmodels/models/pearl_necklace.py

    rcf3d0ce rb297ba9  
    5353R Schweins and K Huber, *Particle Scattering Factor of Pearl Necklace Chains*, 
    5454*Macromol. Symp.* 211 (2004) 25-42 2004 
    55 L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949).  
     55L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949). 
    5656""" 
    5757 
    5858import numpy as np 
    59 from numpy import inf, pi 
     59from numpy import inf 
    6060 
    6161name = "pearl_necklace" 
     
    9696source = ["lib/sas_Si.c", "lib/sas_3j1x_x.c", "pearl_necklace.c"] 
    9797single = False  # use double precision unless told otherwise 
    98 effective_radius_type = [ 
    99     "equivalent volume sphere",  
    100     ] 
    101      
     98effective_radius_type = ["equivalent volume sphere"] 
     99 
    102100def random(): 
     101    """Return a random parameter set for the model.""" 
    103102    radius = 10**np.random.uniform(1, 3) # 1 - 1000 
    104103    thick_string = 10**np.random.uniform(0, np.log10(radius)-1) # 1 - radius/10 
     
    122121            thick_string_pd=0.2, thick_string_pd_n=5, 
    123122           ) 
    124 # ER function is not being used here, not that it is likely very sensible to  
    125 # include an S(Q) with this model, the default in sasview 5.0 would be to the  
     123# ER function is not being used here, not that it is likely very sensible to 
     124# include an S(Q) with this model, the default in sasview 5.0 would be to the 
    126125# "unconstrained" radius_effective. 
    127126#tests = [[{}, 0.001, 17380.245], [{}, 'ER', 115.39502]] 
  • sasmodels/models/poly_gauss_coil.py

    r2d81cfe rb297ba9  
    106106 
    107107def random(): 
     108    """Return a random parameter set for the model.""" 
    108109    rg = 10**np.random.uniform(0, 4) 
    109110    #rg = 1e3 
  • sasmodels/models/polymer_excl_volume.py

    raa90015 rb297ba9  
    163163 
    164164def random(): 
     165    """Return a random parameter set for the model.""" 
    165166    rg = 10**np.random.uniform(0, 4) 
    166167    porod_exp = np.random.uniform(1e-3, 6) 
  • sasmodels/models/polymer_micelle.py

    r791281c rb297ba9  
    113113 
    114114def random(): 
     115    """Return a random parameter set for the model.""" 
    115116    radius_core = 10**np.random.uniform(1, 3) 
    116117    rg = radius_core * 10**np.random.uniform(-2, -0.3) 
  • sasmodels/models/porod.py

    r2d81cfe rb297ba9  
    4747 
    4848def random(): 
     49    """Return a random parameter set for the model.""" 
    4950    sld, solvent = np.random.uniform(-0.5, 12, size=2) 
    5051    radius = 10**np.random.uniform(1, 4.7) 
  • sasmodels/models/power_law.py

    r2d81cfe rb297ba9  
    5252 
    5353def random(): 
     54    """Return a random parameter set for the model.""" 
    5455    power = np.random.uniform(1, 6) 
    5556    pars = dict( 
  • sasmodels/models/pringle.py

    r99658f6 rb297ba9  
    5050 
    5151import numpy as np 
    52 from numpy import inf, pi 
     52from numpy import inf 
    5353 
    5454name = "pringle" 
     
    7575source = ["lib/polevl.c", "lib/sas_J0.c", "lib/sas_J1.c", 
    7676          "lib/sas_JN.c", "lib/gauss76.c", "pringle.c"] 
    77 effective_radius_type = ["equivalent cylinder excluded volume", "equivalent volume sphere", "radius"] 
     77effective_radius_type = [ 
     78    "equivalent cylinder excluded volume", 
     79    "equivalent volume sphere", 
     80    "radius"] 
    7881 
    7982def random(): 
     83    """Return a random parameter set for the model.""" 
    8084    alpha, beta = 10**np.random.uniform(-1, 1, size=2) 
    8185    radius = 10**np.random.uniform(1, 3) 
  • sasmodels/models/raspberry.py

    ree60aa7 rb297ba9  
    155155 
    156156def random(): 
     157    """Return a random parameter set for the model.""" 
    157158    # Limit volume fraction to 20% each 
    158159    volfraction_lg = 10**np.random.uniform(-3, -0.3) 
  • sasmodels/models/rectangular_prism.py

    r99658f6 rb297ba9  
    3232.. math:: 
    3333 
    34   A_P\,(q) = 
     34    A_P\,(q) = 
    3535      \frac{\sin \left( \tfrac{1}{2}qC \cos\theta \right) }{\tfrac{1}{2} qC \cos\theta} 
    3636      \,\times\, 
     
    4848 
    4949.. math:: 
    50   P(q) =  \frac{2}{\pi} \int_0^{\frac{\pi}{2}} \, 
    51   \int_0^{\frac{\pi}{2}} A_P^2(q) \, \sin\theta \, d\theta \, d\phi 
     50    P(q) =  \frac{2}{\pi} \int_0^{\frac{\pi}{2}} \, 
     51    \int_0^{\frac{\pi}{2}} A_P^2(q) \, \sin\theta \, d\theta \, d\phi 
    5252 
    5353And the 1D scattering intensity is calculated as 
    5454 
    5555.. math:: 
    56   I(q) = \text{scale} \times V \times (\rho_\text{p} - 
    57   \rho_\text{solvent})^2 \times P(q) 
     56    I(q) = \text{scale} \times V \times (\rho_\text{p} - 
     57    \rho_\text{solvent})^2 \times P(q) 
    5858 
    5959where $V$ is the volume of the rectangular prism, $\rho_\text{p}$ 
     
    100100R Nayuk and K Huber, *Z. Phys. Chem.*, 226 (2012) 837-854 
    101101 
    102 L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949).  
     102L. Onsager, Ann. New York Acad. Sci. 51, 627-659 (1949). 
    103103 
    104104""" 
    105105 
    106106import numpy as np 
    107 from numpy import pi, inf, sqrt 
     107from numpy import inf 
    108108 
    109109name = "rectangular_prism" 
     
    140140have_Fq = True 
    141141effective_radius_type = [ 
    142     "equivalent cylinder excluded volume", "equivalent volume sphere",  
     142    "equivalent cylinder excluded volume", "equivalent volume sphere", 
    143143    "half length_a", "half length_b", "half length_c", 
    144144    "equivalent circular cross-section", "half ab diagonal", "half diagonal", 
     
    146146 
    147147def random(): 
     148    """Return a random parameter set for the model.""" 
    148149    a, b, c = 10**np.random.uniform(1, 4.7, size=3) 
    149150    pars = dict( 
  • sasmodels/models/rpa.py

    r2d81cfe rb297ba9  
    150150    else: 
    151151        return HIDE_ALL 
     152 
     153# TODO: no random parameters generated for RPA 
  • sasmodels/models/sc_paracrystal.py

    rda7b26b rb297ba9  
    11r""" 
    2 .. warning:: This model and this model description are under review following  
    3              concerns raised by SasView users. If you need to use this model,  
    4              please email help@sasview.org for the latest situation. *The  
     2.. warning:: This model and this model description are under review following 
     3             concerns raised by SasView users. If you need to use this model, 
     4             please email help@sasview.org for the latest situation. *The 
    55             SasView Developers. September 2018.* 
    6               
     6 
    77Definition 
    88---------- 
     
    153153 
    154154def random(): 
     155    """Return a random parameter set for the model.""" 
    155156    # copied from bcc_paracrystal 
    156157    radius = 10**np.random.uniform(1.3, 4) 
  • sasmodels/models/sphere.py

    r81751c2 rb297ba9  
    6767             ] 
    6868 
    69 source = ["lib/sas_3j1x_x.c","sphere.c"] 
     69source = ["lib/sas_3j1x_x.c", "sphere.c"] 
    7070have_Fq = True 
    7171effective_radius_type = ["radius"] 
    7272 
    7373def random(): 
     74    """Return a random parameter set for the model.""" 
    7475    radius = 10**np.random.uniform(1.3, 4) 
    7576    pars = dict( 
  • sasmodels/models/spherical_sld.py

    ree60aa7 rb297ba9  
    269269    return np.asarray(z), np.asarray(rho) 
    270270 
     271# TODO: no random parameter generator for spherical SLD. 
    271272 
    272273demo = { 
  • sasmodels/models/spinodal.py

    r07646b6 rb297ba9  
    33---------- 
    44 
    5 This model calculates the SAS signal of a phase separating system  
    6 undergoing spinodal decomposition. The scattering intensity $I(q)$ is calculated  
    7 as  
     5This model calculates the SAS signal of a phase separating system 
     6undergoing spinodal decomposition. The scattering intensity $I(q)$ is calculated 
     7as 
    88 
    99.. math:: 
    1010    I(q) = I_{max}\frac{(1+\gamma/2)x^2}{\gamma/2+x^{2+\gamma}}+B 
    1111 
    12 where $x=q/q_0$, $q_0$ is the peak position, $I_{max}$ is the intensity  
    13 at $q_0$ (parameterised as the $scale$ parameter), and $B$ is a flat  
    14 background. The spinodal wavelength, $\Lambda$, is given by $2\pi/q_0$.  
     12where $x=q/q_0$, $q_0$ is the peak position, $I_{max}$ is the intensity 
     13at $q_0$ (parameterised as the $scale$ parameter), and $B$ is a flat 
     14background. The spinodal wavelength, $\Lambda$, is given by $2\pi/q_0$. 
    1515 
    16 The definition of $I_{max}$ in the literature varies. Hashimoto *et al* (1991)  
    17 define it as  
     16The definition of $I_{max}$ in the literature varies. Hashimoto *et al* (1991) 
     17define it as 
    1818 
    1919.. math:: 
    2020    I_{max} = \Lambda^3\Delta\rho^2 
    21      
    22 whereas Meier & Strobl (1987) give  
     21 
     22whereas Meier & Strobl (1987) give 
    2323 
    2424.. math:: 
    2525    I_{max} = V_z\Delta\rho^2 
    26      
     26 
    2727where $V_z$ is the volume per monomer unit. 
    2828 
    29 The exponent $\gamma$ is equal to $d+1$ for off-critical concentration  
    30 mixtures (smooth interfaces) and $2d$ for critical concentration mixtures  
    31 (entangled interfaces), where $d$ is the dimensionality (ie, 1, 2, 3) of the  
    32 system. Thus 2 <= $\gamma$ <= 6. A transition from $\gamma=d+1$ to $\gamma=2d$  
    33 is expected near the percolation threshold.  
     29The exponent $\gamma$ is equal to $d+1$ for off-critical concentration 
     30mixtures (smooth interfaces) and $2d$ for critical concentration mixtures 
     31(entangled interfaces), where $d$ is the dimensionality (ie, 1, 2, 3) of the 
     32system. Thus 2 <= $\gamma$ <= 6. A transition from $\gamma=d+1$ to $\gamma=2d$ 
     33is expected near the percolation threshold. 
    3434 
    35 As this function tends to zero as $q$ tends to zero, in practice it may be  
    36 necessary to combine it with another function describing the low-angle  
     35As this function tends to zero as $q$ tends to zero, in practice it may be 
     36necessary to combine it with another function describing the low-angle 
    3737scattering, or to simply omit the low-angle scattering from the fit. 
    3838 
     
    4141 
    4242H. Furukawa. Dynamics-scaling theory for phase-separating unmixing mixtures: 
    43 Growth rates of droplets and scaling properties of autocorrelation functions.  
     43Growth rates of droplets and scaling properties of autocorrelation functions. 
    4444Physica A 123, 497 (1984). 
    4545 
    46 H. Meier & G. Strobl. Small-Angle X-ray Scattering Study of Spinodal  
    47 Decomposition in Polystyrene/Poly(styrene-co-bromostyrene) Blends.  
     46H. Meier & G. Strobl. Small-Angle X-ray Scattering Study of Spinodal 
     47Decomposition in Polystyrene/Poly(styrene-co-bromostyrene) Blends. 
    4848Macromolecules 20, 649-654 (1987). 
    4949 
    50 T. Hashimoto, M. Takenaka & H. Jinnai. Scattering Studies of Self-Assembling  
    51 Processes of Polymer Blends in Spinodal Decomposition.  
     50T. Hashimoto, M. Takenaka & H. Jinnai. Scattering Studies of Self-Assembling 
     51Processes of Polymer Blends in Spinodal Decomposition. 
    5252J. Appl. Cryst. 24, 457-466 (1991). 
    5353 
     
    6868 
    6969      List of default parameters: 
    70        
     70 
    7171      Imax = correlation peak intensity at q_0 
    7272      background = incoherent background 
     
    7474      q_0 = correlation peak position [1/A] 
    7575      x = q/q_0""" 
    76        
     76 
    7777category = "shape-independent" 
    7878 
     
    100100 
    101101def random(): 
     102    """Return a random parameter set for the model.""" 
    102103    pars = dict( 
    103104        scale=10**np.random.uniform(1, 3), 
  • sasmodels/models/squarewell.py

    r304c775 rb297ba9  
    131131 
    132132def random(): 
     133    """Return a random parameter set for the model.""" 
    133134    pars = dict( 
    134135        scale=1, background=0, 
  • sasmodels/models/stacked_disks.py

    ref07e95 rb297ba9  
    147147 
    148148def random(): 
     149    """Return a random parameter set for the model.""" 
    149150    radius = 10**np.random.uniform(1, 4.7) 
    150151    total_stack = 10**np.random.uniform(1, 4.7) 
  • sasmodels/models/star_polymer.py

    r2d81cfe rb297ba9  
    8787 
    8888def random(): 
     89    """Return a random parameter set for the model.""" 
    8990    pars = dict( 
    9091        #background=0, 
  • sasmodels/models/stickyhardsphere.py

    r304c775 rb297ba9  
    100100 
    101101def random(): 
     102    """Return a random parameter set for the model.""" 
    102103    pars = dict( 
    103104        scale=1, background=0, 
  • sasmodels/models/surface_fractal.py

    r2d81cfe rb297ba9  
    7878 
    7979def random(): 
     80    """Return a random parameter set for the model.""" 
    8081    radius = 10**np.random.uniform(1, 4) 
    8182    fractal_dim_surf = np.random.uniform(1, 3-1e-6) 
  • sasmodels/models/teubner_strey.py

    r2d81cfe rb297ba9  
    103103 
    104104def random(): 
     105    """Return a random parameter set for the model.""" 
    105106    d = 10**np.random.uniform(1, 4) 
    106107    xi = 10**np.random.uniform(-0.3, 2)*d 
  • sasmodels/models/triaxial_ellipsoid.py

    r99658f6 rb297ba9  
    158158source = ["lib/sas_3j1x_x.c", "lib/gauss76.c", "triaxial_ellipsoid.c"] 
    159159have_Fq = True 
    160 effective_radius_type = ["equivalent biaxial ellipsoid average curvature", "equivalent volume sphere", "min radius", "max radius"] 
     160effective_radius_type = [ 
     161    "equivalent biaxial ellipsoid average curvature", 
     162    "equivalent volume sphere", "min radius", "max radius", 
     163    ] 
    161164 
    162165def random(): 
     166    """Return a random parameter set for the model.""" 
    163167    a, b, c = 10**np.random.uniform(1, 4.7, size=3) 
    164168    pars = dict( 
  • sasmodels/models/two_lorentzian.py

    r71b751d rb297ba9  
    9292 
    9393def random(): 
     94    """Return a random parameter set for the model.""" 
    9495    scale = 10**np.random.uniform(0, 4, 2) 
    9596    length = 10**np.random.uniform(1, 4, 2) 
  • sasmodels/models/two_power_law.py

    ref07e95 rb297ba9  
    7878       power_2=4.0, 
    7979      ): 
    80  
    8180    """ 
    8281    :param q:                   Input q-value (float or [float, float]) 
     
    9897 
    9998def random(): 
     99    """Return a random parameter set for the model.""" 
    100100    coefficient_1 = 1 
    101101    crossover = 10**np.random.uniform(-3, -1) 
  • sasmodels/models/unified_power_Rg.py

    r2d81cfe rb297ba9  
    9696 
    9797def Iq(q, level, rg, power, B, G): 
     98    """Return I(q) for unified power Rg model.""" 
    9899    level = int(level + 0.5) 
    99100    if level == 0: 
     
    118119 
    119120def random(): 
     121    """Return a random parameter set for the model.""" 
    120122    level = np.minimum(np.random.poisson(0.5) + 1, 6) 
    121123    n = level 
  • sasmodels/models/vesicle.py

    r304c775 rb297ba9  
    7070 
    7171import numpy as np 
    72 from numpy import pi, inf 
     72from numpy import inf 
    7373 
    7474name = "vesicle" 
     
    103103 
    104104def random(): 
     105    """Return a random parameter set for the model.""" 
    105106    total_radius = 10**np.random.uniform(1.3, 5) 
    106107    radius = total_radius * np.random.uniform(0, 1) 
  • sasmodels/multiscat.py

    r2c4a190 rb297ba9  
    103103USE_FAST = True  # OpenCL faster, less accurate math 
    104104 
    105 class ICalculator: 
     105class ICalculator(object): 
    106106    """ 
    107107    Multiple scattering calculator 
     
    113113        raise NotImplementedError() 
    114114 
    115     def ifft(self, Iq): 
     115    def ifft(self, fourier_frame): 
    116116        """ 
    117117        Compute the inverse FFT for an image, complex -> complex. 
     
    119119        raise NotImplementedError() 
    120120 
    121     def mulitple_scattering(self, Iq): 
     121    def multiple_scattering(self, Iq, p, coverage=0.99): 
    122122        r""" 
    123123        Compute multiple scattering for I(q) given scattering probability p. 
     
    250250        gpu_poly = cl_array.to_device(self.queue, poly) 
    251251        self.plan.execute(gpu_data.data) 
    252         degree, data_size= poly.shape[0], frame.shape[0]*frame.shape[1] 
     252        degree, data_size = poly.shape[0], frame.shape[0]*frame.shape[1] 
    253253        self.polyval1( 
    254254            self.queue, [data_size], None, 
     
    575575 
    576576def main(): 
     577    """Command line interface to multiple scattering calculator.""" 
    577578    parser = argparse.ArgumentParser( 
    578579        description="Compute multiple scattering", 
     
    612613    theory = call_kernel(kernel, pars) 
    613614    Iq = res.apply(theory) + bg 
    614     plot_and_save_powers(res, theory, Iq, outfile=opts.outfile, background=bg) 
    615  
    616 def plot_and_save_powers(res, theory, result, plot=True, outfile="", background=0.): 
     615    _plot_and_save_powers(res, theory, Iq, outfile=opts.outfile, background=bg) 
     616 
     617def _plot_and_save_powers(res, theory, result, plot=True, 
     618                          outfile="", background=0.): 
    617619    import pylab 
    618620    probability, coverage = res.probability, res.coverage 
     
    678680 
    679681def plotxy(q, Iq): 
     682    """Plot q, Iq or (qx, qy), Iqxy.""" 
    680683    import pylab 
    681684    # q is a tuple of (q,) or (qx, qy) 
  • sasmodels/product.py

    rfd7291e rb297ba9  
    1818import numpy as np  # type: ignore 
    1919 
    20 from .modelinfo import ParameterTable, ModelInfo, Parameter, parse_parameter 
     20from .modelinfo import ParameterTable, ModelInfo, parse_parameter 
    2121from .kernel import KernelModel, Kernel 
    22 from .details import make_details, dispersion_mesh 
     22from .details import make_details 
    2323 
    2424# pylint: disable=unused-import 
     
    2828    pass 
    2929else: 
    30     from .modelinfo import ParameterSet 
     30    from .modelinfo import ParameterSet, Parameter 
    3131# pylint: enable=unused-import 
    3232 
     
    4242VOLFRAC_ID = "volfraction" 
    4343def make_extra_pars(p_info): 
     44    # type: (ModelInfo) -> List[Parameter] 
     45    """ 
     46    Create parameters for structure_factor_mode and radius_effective_mode. 
     47    """ 
    4448    pars = [] 
    4549    if p_info.have_Fq: 
    4650        par = parse_parameter( 
    47                 STRUCTURE_MODE_ID, 
    48                 "", 
    49                 0, 
    50                 [["P*S","P*(1+beta*(S-1))"]], 
    51                 "", 
    52                 "Structure factor calculation") 
     51            STRUCTURE_MODE_ID, 
     52            "", 
     53            0, 
     54            [["P*S", "P*(1+beta*(S-1))"]], 
     55            "", 
     56            "Structure factor calculation") 
    5357        pars.append(par) 
    5458    if p_info.effective_radius_type is not None: 
    5559        par = parse_parameter( 
    56                 RADIUS_MODE_ID, 
    57                 "", 
    58                 1, 
    59                 [["unconstrained"] + p_info.effective_radius_type], 
    60                 "", 
    61                 "Effective radius calculation") 
     60            RADIUS_MODE_ID, 
     61            "", 
     62            1, 
     63            [["unconstrained"] + p_info.effective_radius_type], 
     64            "", 
     65            "Effective radius calculation") 
    6266        pars.append(par) 
    6367    return pars 
     
    104108    parameters.max_pd = p_pars.max_pd + s_pars.max_pd 
    105109    def random(): 
     110        """Random set of model parameters for product model""" 
    106111        combined_pars = p_info.random() 
    107112        s_names = set(par.id for par in s_pars.kernel_parameters) 
     
    132137        profile_pars = set(p.id for p in p_info.parameters.kernel_parameters) 
    133138        def profile(**kwargs): 
     139            """Return SLD profile of the form factor as a function of radius.""" 
    134140            # extract the profile args 
    135141            kwargs = dict((k, v) for k, v in kwargs.items() if k in profile_pars) 
     
    173179        effective_radius, # type: float 
    174180        beta_mode,        # type: bool 
    175         ): 
     181    ): 
    176182    # type: (...) -> OrderedDict[str, Union[np.ndarray, float]] 
    177183    """ 
     
    199205 
    200206class ProductModel(KernelModel): 
     207    """ 
     208    Model definition for product model. 
     209    """ 
    201210    def __init__(self, model_info, P, S): 
    202211        # type: (ModelInfo, KernelModel, KernelModel) -> None 
     
    229238        s_kernel = self.S.make_kernel(q_vectors) 
    230239        return ProductKernel(self.info, p_kernel, s_kernel) 
     240    make_kernel.__doc__ = KernelModel.make_kernel.__doc__ 
    231241 
    232242    def release(self): 
     
    240250 
    241251class ProductKernel(Kernel): 
     252    """ 
     253    Instantiated kernel for product model. 
     254    """ 
    242255    def __init__(self, model_info, p_kernel, s_kernel): 
    243256        # type: (ModelInfo, Kernel, Kernel) -> None 
     
    248261        self.results = []  # type: List[np.ndarray] 
    249262 
    250     def __call__(self, call_details, values, cutoff, magnetic): 
     263    def Iq(self, call_details, values, cutoff, magnetic): 
    251264        # type: (CallDetails, np.ndarray, float, bool) -> np.ndarray 
    252265 
     
    263276        beta_mode_offset = 2+p_npars+s_npars 
    264277        beta_mode = (values[beta_mode_offset] > 0) if have_beta_mode else False 
    265         if beta_mode and self.p_kernel.dim== '2d': 
     278        if beta_mode and self.p_kernel.dim == '2d': 
    266279            raise NotImplementedError("beta not yet supported for 2D") 
    267280 
     
    327340        # polydispersity distribution slot in the values array due to 
    328341        # implementation details in kernel_iq.c. 
    329         #print("R_eff=%d:%g, volfrac=%g, volume ratio=%g"%(radius_type, effective_radius, volfrac, volume_ratio)) 
     342        #print("R_eff=%d:%g, volfrac=%g, volume ratio=%g" 
     343        #      % (radius_type, effective_radius, volfrac, volume_ratio)) 
    330344        if radius_type > 0: 
    331345            # set the value to the model R_eff and set the weight to 1 
     
    360374        return final_result 
    361375 
     376    Iq.__doc__ = Kernel.Iq.__doc__ 
     377    __call__ = Iq 
     378 
    362379    def release(self): 
    363380        # type: () -> None 
     381        """Free resources associated with the kernel.""" 
    364382        self.p_kernel.release() 
    365383        self.s_kernel.release() 
  • sasmodels/rst2html.py

    r1fbadb2 rb297ba9  
    142142 
    143143def load_rst_as_html(filename): 
     144    # type: (str) -> str 
     145    """Load rst from file and convert to html""" 
    144146    from os.path import expanduser 
    145147    with open(expanduser(filename)) as fid: 
     
    149151 
    150152def wxview(html, url="", size=(850, 540)): 
     153    # type: (str, str, Tuple[int, int]) -> "wx.Frame" 
     154    """View HTML in a wx dialog""" 
    151155    import wx 
    152156    from wx.html2 import WebView 
     
    158162 
    159163def view_html_wxapp(html, url=""): 
     164    # type: (str, str) -> None 
     165    """HTML viewer app in wx""" 
    160166    import wx  # type: ignore 
    161167    app = wx.App() 
     
    164170 
    165171def view_url_wxapp(url): 
     172    # type: (str) -> None 
     173    """URL viewer app in wx""" 
    166174    import wx  # type: ignore 
    167175    from wx.html2 import WebView 
     
    174182 
    175183def qtview(html, url=""): 
     184    # type: (str, str) -> "QWebView" 
     185    """View HTML in a Qt dialog""" 
    176186    try: 
    177187        from PyQt5.QtWebKitWidgets import QWebView 
     
    186196 
    187197def view_html_qtapp(html, url=""): 
     198    # type: (str, str) -> None 
     199    """HTML viewer app in Qt""" 
    188200    import sys 
    189201    try: 
     
    196208 
    197209def view_url_qtapp(url): 
     210    # type: (str) -> None 
     211    """URL viewer app in Qt""" 
    198212    import sys 
    199213    try: 
     
    217231 
    218232def can_use_qt(): 
     233    # type: () -> bool 
    219234    """ 
    220235    Return True if QWebView exists. 
     
    233248 
    234249def view_help(filename, qt=False): 
     250    # type: (str, bool) -> None 
     251    """View rst or html file.  If *qt* use q viewer, otherwise use wx.""" 
    235252    import os 
    236253 
     
    252269 
    253270def main(): 
     271    # type: () -> None 
     272    """Command line interface to rst or html viewer.""" 
    254273    import sys 
    255274    view_help(sys.argv[1], qt=False) 
  • sasmodels/sasview_model.py

    rfd7291e rb297ba9  
    1515import traceback 
    1616import logging 
    17 from os.path import basename, splitext, abspath, getmtime 
     17from os.path import basename, splitext, abspath 
    1818try: 
    1919    import _thread as thread 
     
    3131from . import modelinfo 
    3232from .details import make_kernel_args, dispersion_mesh 
    33 from .kernelcl import reset_environment 
    3433 
    3534# pylint: disable=unused-import 
     
    688687                     qx,     # type: Sequence[float] 
    689688                     qy=None # type: Optional[Sequence[float]] 
    690                      ): 
     689                    ): 
    691690        # type: (...) -> Tuple[np.ndarray, Callable[[], collections.OrderedDict[str, np.ndarray]]] 
    692691        """ 
     
    938937    # type: () -> None 
    939938    """ 
    940     Load and run cylinder model as sas-models-CylinderModel 
     939    Load and run cylinder model as sas.models.CylinderModel 
    941940    """ 
    942941    if not SUPPORT_OLD_STYLE_PLUGINS: 
     
    980979 
    981980def magnetic_demo(): 
     981    """ 
     982    Demostrate call to magnetic model. 
     983    """ 
    982984    Model = _make_standard_model('sphere') 
    983985    model = Model() 
  • sasmodels/sesans.py

    rfa79f5c rb297ba9  
    4848 
    4949    def apply(self, Iq): 
    50         # tye: (np.ndarray) -> np.ndarray 
     50        # type: (np.ndarray) -> np.ndarray 
     51        """ 
     52        Apply the SESANS transform to the computed I(q). 
     53        """ 
    5154        G0 = np.dot(self._H0, Iq) 
    5255        G = np.dot(self._H.T, Iq) 
  • sasmodels/special.py

    rfba9ca0 rb297ba9  
    311311 
    312312# Gaussians 
    313 class Gauss: 
     313class Gauss(object): 
     314    """Gauss-Legendre integration weights""" 
    314315    def __init__(self, w, z): 
    315316        self.n = len(w) 
  • sasmodels/weights.py

    re2592f0 rb297ba9  
    5858            # For orientation, the jitter is relative to 0 not the angle 
    5959            center = 0 
    60             pass 
    6160        if sigma == 0 or self.npts < 2: 
    6261            if lb <= center <= ub: 
     
    123122    default = dict(npts=35, width=0, nsigmas=1.73205) 
    124123    def _weights(self, center, sigma, lb, ub): 
    125          x = self._linspace(center, sigma, lb, ub) 
    126          x = x[np.fabs(x-center) <= np.fabs(sigma)*sqrt(3.0)] 
    127          return x, np.ones_like(x) 
     124        x = self._linspace(center, sigma, lb, ub) 
     125        x = x[np.fabs(x-center) <= np.fabs(sigma)*sqrt(3.0)] 
     126        return x, np.ones_like(x) 
    128127 
    129128class LogNormalDispersion(Dispersion): 
Note: See TracChangeset for help on using the changeset viewer.