Changeset 786117e in sasmodels


Ignore:
Timestamp:
Nov 12, 2015 9:43:33 AM (9 years ago)
Author:
krzywon
Branches:
master, core_shell_microgels, costrafo411, magnetic_model, release_v0.94, release_v0.95, ticket-1257-vesicle-product, ticket_1156, ticket_1265_superball, ticket_822_more_unit_tests
Children:
77ad412
Parents:
eff3d66 (diff), dbde9f8 (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
Message:

Merge branch 'master' of https://github.com/SasView/sasmodels.git

Files:
8 added
9 edited

Legend:

Unmodified
Added
Removed
  • compare.py

    r3e6aaad r0763009  
    100100    model = sasview_model(name, **pars) 
    101101    smearer = smear_selection(data, model=model) 
     102    value = None  # silence the linter 
    102103    toc = tic() 
    103     for _ in range(Nevals): 
     104    for _ in range(max(Nevals, 1)):  # make sure there is at least one eval 
    104105        if hasattr(data, 'qx_data'): 
    105106            q = np.sqrt(data.qx_data**2 + data.qy_data**2) 
     
    120121    return value, average_time 
    121122 
    122 def eval_opencl(model_definition, pars, data, dtype='single', Nevals=1, cutoff=0): 
     123def eval_opencl(model_definition, pars, data, dtype='single', Nevals=1, cutoff=0.): 
    123124    try: 
    124125        model = core.load_model(model_definition, dtype=dtype, platform="ocl") 
     
    128129        model = core.load_model(model_definition, dtype='single', platform="ocl") 
    129130    problem = Experiment(data, Model(model, **pars), cutoff=cutoff) 
     131    value = None  # silence the linter 
    130132    toc = tic() 
    131     for _ in range(Nevals): 
     133    for _ in range(max(Nevals, 1)):  # force at least one eval 
    132134        #pars['scale'] = np.random.rand() 
    133135        problem.update() 
     
    136138    return value, average_time 
    137139 
    138 def eval_ctypes(model_definition, pars, data, dtype='double', Nevals=1, cutoff=0): 
     140def eval_ctypes(model_definition, pars, data, dtype='double', Nevals=1, cutoff=0.): 
    139141    model = core.load_model(model_definition, dtype=dtype, platform="dll") 
    140142    problem = Experiment(data, Model(model, **pars), cutoff=cutoff) 
     143    value = None  # silence the linter 
    141144    toc = tic() 
    142     for _ in range(Nevals): 
     145    for _ in range(max(Nevals, 1)):  # force at least one eval 
    143146        problem.update() 
    144147        value = problem.theory() 
     
    224227        #bad = (relerr>1e-4) 
    225228        #print relerr[bad],cpu[bad],ocl[bad],data.qx_data[bad],data.qy_data[bad] 
    226         def stats(label,err): 
    227             sorted_err = np.sort(abs(err)) 
    228             p50 = int((len(err)-1)*0.50) 
    229             p98 = int((len(err)-1)*0.98) 
    230             data = [ 
    231                 "max:%.3e"%sorted_err[-1], 
    232                 "median:%.3e"%sorted_err[p50], 
    233                 "98%%:%.3e"%sorted_err[p98], 
    234                 "rms:%.3e"%np.sqrt(np.mean(err**2)), 
    235                 "zero-offset:%+.3e"%np.mean(err), 
    236                 ] 
    237             print label,"  ".join(data) 
    238         stats("|ocl-%s|"%comp+(" "*(3+len(comp))), resid) 
    239         stats("|(ocl-%s)/%s|"%(comp,comp), relerr) 
     229        _print_stats("|ocl-%s|"%comp+(" "*(3+len(comp))), resid) 
     230        _print_stats("|(ocl-%s)/%s|"%(comp,comp), relerr) 
    240231 
    241232    # Plot if requested 
     
    277268    plt.show() 
    278269 
     270def _print_stats(label, err): 
     271    sorted_err = np.sort(abs(err)) 
     272    p50 = int((len(err)-1)*0.50) 
     273    p98 = int((len(err)-1)*0.98) 
     274    data = [ 
     275        "max:%.3e"%sorted_err[-1], 
     276        "median:%.3e"%sorted_err[p50], 
     277        "98%%:%.3e"%sorted_err[p98], 
     278        "rms:%.3e"%np.sqrt(np.mean(err**2)), 
     279        "zero-offset:%+.3e"%np.mean(err), 
     280        ] 
     281    print label,"  ".join(data) 
     282 
     283 
     284 
    279285# =========================================================================== 
    280286# 
  • doc/genapi.py

    r19dcb933 r3d5c6f8  
    5757modules=[ 
    5858    #('__init__', 'Top level namespace'), 
     59    #('alignment', 'GPU data alignment [unused]'), 
    5960    ('bumps_model', 'Bumps interface'), 
     61    ('convert', 'Sasview to sasmodel converter'), 
     62    ('core', 'Model access'), 
     63    ('direct_model', 'Simple interface'), 
     64    ('exception', 'Annotate exceptions'), 
     65    ('generate', 'Model parser'), 
     66    ('kernelcl', 'OpenCL model evaluator'), 
     67    ('kerneldll', 'Ctypes model evaluator'), 
     68    ('kernelpy', 'Python model evaluator'), 
     69    ('model_test', 'Unit test support'), 
     70    ('resolution', '1-D resolution functions'), 
     71    ('resolution2d', '2-D resolution functions'), 
    6072    ('sasview_model', 'Sasview interface'), 
     73    ('sesans', 'SESANS model evaluator'), 
    6174    ('weights', 'Distribution functions'), 
    62     ('gen', 'Model generator'), 
    63     ('convert', 'Model parameter converter'), 
    64     ('gpu', 'OpenCL model loader'), 
    65     ('dll', 'Ctypes model loader'), 
    6675    #('transition', 'Model stepper for automatic model selection'), 
    6776] 
  • sasmodels/exception.py

    r9e430d0 r0763009  
    22Utility to add annotations to python exceptions. 
    33""" 
     4 
     5# Platform cruft: WindowsError is only defined on Windows. 
     6try: 
     7    WindowsError 
     8except NameError: 
     9    class WindowsError(Exception): 
     10        pass 
    411 
    512def annotate_exception(exc, msg): 
     
    1926        KeyError: "hello while accessing 'D'" 
    2027    """ 
     28    # Can't extend WindowsError exceptions; instead raise a new exception. 
     29    # TODO: try to incorporate current stack trace in the raised exception 
     30    if isinstance(exc, WindowsError): 
     31        raise OSError(str(exc)+msg) 
     32 
    2133    args = exc.args 
    2234    if not args: 
     
    2840        except: 
    2941            exc.args = (" ".join((str(exc),msg)),) 
    30  
  • sasmodels/kernelcl.py

    raf1d68c r0763009  
    3939 
    4040from . import generate 
    41 from .kernelpy import PyModel 
    4241 
    4342F64_DEFS = """\ 
  • sasmodels/kerneldll.py

    rf3f46cd r0763009  
    148148        try: 
    149149            self.dll = ct.CDLL(self.dllpath) 
    150         except WindowsError, exc: 
    151             # TODO: update annotate_exception so it can handle WindowsError 
    152             raise RuntimeError(str(exc)+" while loading "+self.dllpath) 
    153150        except Exception, exc: 
    154151            annotate_exception(exc, "while loading "+self.dllpath) 
  • sasmodels/model_test.py

    r9e430d0 r2781b2e  
    6868        model_definition = load_model_definition(model_name) 
    6969 
    70         smoke_tests = [ 
    71             [{},0.1,None], 
    72             [{},(0.1,0.1),None], 
    73             [{},'ER',None], 
    74             [{},'VR',None], 
    75             ] 
    76         tests = smoke_tests + getattr(model_definition, 'tests', []) 
    77  
    78         if tests: # in case there are no smoke tests... 
    79             #print '------' 
    80             #print 'found tests in', model_name 
    81             #print '------' 
    82  
    83             # if ispy then use the dll loader to call pykernel 
    84             # don't try to call cl kernel since it will not be 
    85             # available in some environmentes. 
    86             ispy = callable(getattr(model_definition,'Iq', None)) 
    87  
    88             # test using opencl if desired 
    89             if not ispy and ('opencl' in loaders and HAVE_OPENCL): 
     70        #print '------' 
     71        #print 'found tests in', model_name 
     72        #print '------' 
     73 
     74        # if ispy then use the dll loader to call pykernel 
     75        # don't try to call cl kernel since it will not be 
     76        # available in some environmentes. 
     77        is_py = callable(getattr(model_definition,'Iq', None)) 
     78 
     79        if is_py:  # kernel implemented in python 
     80            test_name = "Model: %s, Kernel: python"%model_name 
     81            test_method_name = "test_%s_python" % model_name 
     82            test = ModelTestCase(test_name, model_definition, 
     83                                 test_method_name, 
     84                                 platform="dll",  # so that 
     85                                 dtype="double") 
     86            suite.addTest(test) 
     87        else:   # kernel implemented in C 
     88            # test using opencl if desired and available 
     89            if 'opencl' in loaders and HAVE_OPENCL: 
    9090                test_name = "Model: %s, Kernel: OpenCL"%model_name 
    91                 test_method = "test_%s_opencl" % model_name 
     91                test_method_name = "test_%s_opencl" % model_name 
    9292                test = ModelTestCase(test_name, model_definition, 
    93                                      tests, test_method, 
     93                                     test_method_name, 
    9494                                     platform="ocl", dtype='single') 
    9595                #print "defining", test_name 
     
    9797 
    9898            # test using dll if desired 
    99             if ispy or 'dll' in loaders: 
     99            if 'dll' in loaders: 
    100100                test_name = "Model: %s, Kernel: dll"%model_name 
    101                 test_method = "test_%s_dll" % model_name 
     101                test_method_name = "test_%s_dll" % model_name 
    102102                test = ModelTestCase(test_name, model_definition, 
    103                                      tests, test_method, 
    104                                      platform="dll", dtype="double") 
     103                                     test_method_name, 
     104                                     platform="dll", 
     105                                     dtype="double") 
    105106                suite.addTest(test) 
    106107 
     
    110111def _hide_model_case_from_nosetests(): 
    111112    class ModelTestCase(unittest.TestCase): 
    112         def __init__(self, test_name, definition, tests, test_method, 
     113        def __init__(self, test_name, definition, test_method_name, 
    113114                     platform, dtype): 
    114115            self.test_name = test_name 
    115116            self.definition = definition 
    116             self.tests = tests 
    117117            self.platform = platform 
    118118            self.dtype = dtype 
    119119 
    120             setattr(self, test_method, self._runTest) 
    121             unittest.TestCase.__init__(self, test_method) 
     120            setattr(self, test_method_name, self._runTest) 
     121            unittest.TestCase.__init__(self, test_method_name) 
    122122 
    123123        def _runTest(self): 
     124            smoke_tests = [ 
     125                [{},0.1,None], 
     126                [{},(0.1,0.1),None], 
     127                [{},'ER',None], 
     128                [{},'VR',None], 
     129                ] 
     130 
     131            tests = getattr(self.definition, 'tests', []) 
    124132            try: 
    125133                model = load_model(self.definition, dtype=self.dtype, 
    126134                                   platform=self.platform) 
    127                 for test in self.tests: 
     135                for test in smoke_tests + tests: 
    128136                    self._run_one_test(model, test) 
     137 
     138                if not tests and self.platform == "dll": 
     139                    ## Uncomment the following to make forgetting the test 
     140                    ## values an error.  Only do so for the "dll" tests 
     141                    ## to reduce noise from both opencl and dll, and because 
     142                    ## python kernels us 
     143                    #raise Exception("No test cases provided") 
     144                    pass 
    129145 
    130146            except Exception,exc: 
     
    199215        loaders = ['opencl', 'dll'] 
    200216    if not models: 
    201         print >>sys.stderr, "usage: python -m sasmodels.model_test [opencl|dll|opencl_and_dll] model1 model2 ..." 
    202         print >>sys.stderr, "if model1 is 'all', then all except the remaining models will be tested" 
     217        print >>sys.stderr, """\ 
     218usage: 
     219  python -m sasmodels.model_test [opencl|dll|opencl_and_dll] model1 model2 ... 
     220 
     221If model1 is 'all', then all except the remaining models will be tested. 
     222If no compute target is specified, then models will be tested with both opencl 
     223and dll; the compute target is ignored for pure python models.""" 
     224 
    203225        return 1 
    204226 
  • sasmodels/models/gaussian_peak.py

    r3e428ec r9d76d29  
    11r""" 
     2 
     3Definition 
     4---------- 
     5 
    26This model describes a Gaussian shaped peak on a flat background 
    37 
    4 .. image:: img/image198.PNG 
     8.. math:: 
    59 
    6 with the peak having height of *I0* centered at *q0* and having a standard deviation of *B*. The FWHM (full-width 
    7 half-maximum) is 2.354 B. 
     10    I(q) = (\text{scale}) \exp\left[ -\tfrac12 (q-q_0)^2 / \sigma^2 \right] 
     11        + \text{background} 
    812 
    9 For 2D data: The 2D scattering intensity is calculated in the same way as 1D, where the *q* vector is defined as 
     13with the peak having height of *scale* centered at $q_0$ and having a standard 
     14deviation of $\sigma$. The FWHM (full-width half-maximum) is $2.354 \sigma$. 
    1015 
    11 .. image:: img/image040.gif 
     16For 2D data, scattering intensity is calculated in the same way as 1D, 
     17where the $q$ vector is defined as 
    1218 
    13 .. image:: img/image199.jpg 
     19.. math:: 
    1420 
    15 *Figure. 1D plot using the default values (w/500 data points).* 
     21    q = \sqrt{q_x^2 + q_y^2} 
    1622 
    17 REFERENCE 
     23 
     24.. image:: img/gaussian_peak_1d.jpg 
     25 
     26    1D plot using the default values (w/500 data points). 
     27 
     28Reference 
    1829--------- 
    1930 
     
    2738description = """ 
    2839    Model describes a Gaussian shaped peak including a flat background 
    29     Provide F(q) = scale*exp( -1/2 *[(q-q0)/B]^2 )+ background 
     40    Provide F(q) = scale*exp( -1/2 *[(q-q0)/sigma]^2 )+ background 
    3041""" 
    3142category = "shape-independent" 
     
    3344#             ["name", "units", default, [lower, upper], "type","description"], 
    3445parameters = [["q0", "1/Ang", 0.05, [-inf, inf], "", "Peak position"], 
    35               ["sigma", "1/Ang", 0.005, [-inf, inf], "", 
     46              ["sigma", "1/Ang", 0.005, [0, inf], "", 
    3647               "Peak width (standard deviation)"], 
    3748             ] 
  • sasmodels/models/spherepy.py

    r3e428ec rade352a  
    9191    qr = q * radius 
    9292    sn, cn = sin(qr), cos(qr) 
    93     # FOR VECTORIZED VERSION, UNCOMMENT THE NEXT TWO LINES 
     93    ## The natural expression for the bessel function is the following: 
     94    ##     bes = 3 * (sn-qr*cn)/qr**3 if qr>0 else 1 
     95    ## however, to support vector q values we need to handle the conditional 
     96    ## as a vector, which we do by first evaluating the full expression 
     97    ## everywhere, then fixing it up where it is broken.   We should probably 
     98    ## set numpy to ignore the 0/0 error before we do though... 
    9499    bes = 3 * (sn - qr * cn) / qr ** 3 # may be 0/0 but we fix that next line 
    95100    bes[qr == 0] = 1 
    96     # FOR NON VECTORIZED VERSION, UNCOMMENT THE NEXT LINE 
    97     #bes = 3 * (sn-qr*cn)/qr**3 if qr>0 else 1 
    98101    fq = bes * (sld - solvent_sld) * form_volume(radius) 
    99102    return 1.0e-4 * fq ** 2 
    100 # FOR VECTORIZED VERSION, UNCOMMENT THE NEXT LINE 
    101 Iq.vectorized = True 
     103Iq.vectorized = True  # Iq accepts an array of Q values 
    102104 
    103105def Iqxy(qx, qy, sld, solvent_sld, radius): 
    104106    return Iq(sqrt(qx ** 2 + qy ** 2), sld, solvent_sld, radius) 
    105 Iqxy.vectorized = True 
     107Iqxy.vectorized = True  # Iqxy accepts arrays of Qx, Qy values 
    106108 
    107109def sesans(z, sld, solvent_sld, radius): 
     
    119121    g[low] = sqrt(1 - dlow2 / 4.) * (1 + dlow2 / 8.) + dlow2 / 2.*(1 - dlow2 / 16.) * log(dlow / (2. + sqrt(4. - dlow2))) 
    120122    return g 
    121 sesans.vectorized = True 
     123sesans.vectorized = True  # sesans accepts and array of z values 
    122124 
    123125def ER(radius): 
  • sasmodels/resolution.py

    r346bc88 rdbde9f8  
    7474 
    7575    def apply(self, theory): 
    76         print "q calc", self.q_calc 
    77         print "weights", self.weight_matrix.shape 
    7876        return apply_resolution_matrix(self.weight_matrix, theory) 
    7977 
     
    9492    The *weight_matrix* is computed by :func:`slit1d_resolution` 
    9593    """ 
    96     def __init__(self, q, width, height, q_calc=None): 
    97         # TODO: maybe issue warnings rather than raising errors 
    98         if not np.isscalar(width): 
    99             if np.any(np.diff(width) > 0.0): 
    100                 raise ValueError("Slit resolution requires fixed width slits") 
    101             width = width[0] 
    102         if not np.isscalar(height): 
    103             if np.any(np.diff(height) > 0.0): 
    104                 raise ValueError("Slit resolution requires fixed height slits") 
    105             height = height[0] 
    106  
     94    def __init__(self, q, width, height=0., q_calc=None): 
    10795        # Remember what width/height was used even though we won't need them 
    10896        # after the weight matrix is constructed 
    10997        self.width, self.height = width, height 
     98 
     99        # Allow independent resolution on each point even though it is not 
     100        # needed in practice. 
     101        if np.isscalar(width): 
     102            width = np.ones(len(q))*width 
     103        else: 
     104            width = np.asarray(width) 
     105        if np.isscalar(height): 
     106            height = np.ones(len(q))*height 
     107        else: 
     108            height = np.asarray(height) 
    110109 
    111110        self.q = q.flatten() 
     
    171170            \int_{-\Delta q_v}^{\Delta q_v} I(u) du 
    172171    """ 
    173     if width == 0.0 and height == 0.0: 
    174         #print "condition zero" 
    175         return 1 
    176  
     172    #np.set_printoptions(precision=6, linewidth=10000) 
     173 
     174    # The current algorithm is a midpoint rectangle rule. 
    177175    q_edges = bin_edges(q_calc) # Note: requires q > 0 
    178176    q_edges[q_edges<0.0] = 0.0 # clip edges below zero 
    179  
    180     #np.set_printoptions(linewidth=10000) 
    181     if width <= 100.0 * height or height == 0: 
    182         # The current algorithm is a midpoint rectangle rule.  In the test case, 
    183         # neither trapezoid nor Simpson's rule improved the accuracy. 
    184         #print "condition h", q_edges.shape, q.shape, q_calc.shape 
    185         weights = np.zeros((len(q), len(q_calc)), 'd') 
    186         for i, qi in enumerate(q): 
    187             weights[i, :] = np.diff(q_to_u(q_edges, qi)) 
    188         weights /= width 
    189         weights = weights.T 
    190     else: 
    191         #print "condition w" 
    192         # Make q_calc into a row vector, and q into a column vector 
    193         q, q_calc = q[None,:], q_calc[:,None] 
    194         in_x = (q_calc >= q-width) * (q_calc <= q+width) 
    195         weights = np.diff(q_edges)[:,None] * in_x 
    196  
    197     return weights 
     177    weights = np.zeros((len(q), len(q_calc)), 'd') 
     178 
     179    for i, (qi, w, h) in enumerate(zip(q, width, height)): 
     180        if w == 0. and h == 0.: 
     181            # Perfect resolution, so return the theory value directly. 
     182            # Note: assumes that q is a subset of q_calc.  If qi need not be 
     183            # in q_calc, then we can do a weighted interpolation by looking 
     184            # up qi in q_calc, then weighting the result by the relative 
     185            # distance to the neighbouring points. 
     186            weights[i, :] = (q_calc == qi) 
     187        elif h == 0 or w > 100.0 * h: 
     188            # Convert bin edges from q to u 
     189            u_limit = np.sqrt(qi**2 + w**2) 
     190            u_edges = q_edges**2 - qi**2 
     191            u_edges[q_edges < qi] = 0. 
     192            u_edges[q_edges > u_limit] = u_limit**2 - qi**2 
     193            weights[i, :] = np.diff(np.sqrt(u_edges))/w 
     194            #print "i, qi",i,qi,qi+width 
     195            #print q_calc 
     196            #print weights[i,:] 
     197        elif w == 0: 
     198            in_x = (q_calc >= qi-h) * (q_calc <= qi+h) 
     199            weights[i,:] = in_x * np.diff(q_edges) / (2*h) 
     200 
     201    return weights.T 
    198202 
    199203 
     
    214218    function. 
    215219    """ 
    216     height # keep lint happy 
    217220    q_min, q_max = np.min(q), np.max(np.sqrt(q**2 + width**2)) 
    218221    return geometric_extrapolation(q, q_min, q_max) 
     
    235238        ]) 
    236239    return edges 
    237  
    238  
    239 def q_to_u(q, q0): 
    240     """ 
    241     Convert *q* values to *u* values for the integral computed at *q0*. 
    242     """ 
    243     # array([value])**2 - value**2 is not always zero 
    244     qpsq = q**2 - q0**2 
    245     qpsq[qpsq<0] = 0 
    246     return sqrt(qpsq) 
    247240 
    248241 
     
    359352 
    360353 
    361 def romberg_slit_1d(q, delta_qv, form, pars): 
     354def romberg_slit_1d(q, width, height, form, pars): 
    362355    """ 
    363356    Romberg integration for slit resolution. 
     
    366359    that make it slow to evaluate but give it good accuracy. 
    367360    """ 
    368     from scipy.integrate import romberg 
     361    from scipy.integrate import romberg, dblquad 
    369362 
    370363    if any(k not in form.info['defaults'] for k in pars.keys()): 
     
    374367                         (", ".join(sorted(extra)), ", ".join(sorted(keys)))) 
    375368 
    376     _fn = lambda u, q0: eval_form(sqrt(q0**2 + u**2), form, pars) 
    377     r = [romberg(_fn, 0, delta_qv[0], args=(qi,), 
    378                  divmax=100, vec_func=True, tol=0, rtol=1e-8) 
    379          for qi in q] 
     369    if np.isscalar(width): 
     370        width = [width]*len(q) 
     371    if np.isscalar(height): 
     372        height = [height]*len(q) 
     373    _int_w = lambda w, qi: eval_form(sqrt(qi**2 + w**2), form, pars) 
     374    _int_h = lambda h, qi: eval_form(abs(qi+h), form, pars) 
     375    _int_wh = lambda w, h, qi: eval_form(sqrt((qi+h)**2 + w**2), form, pars) 
     376    result = np.empty(len(q)) 
     377    for i, (qi, w, h) in enumerate(zip(q, width, height)): 
     378        if h == 0.: 
     379            r = romberg(_int_w, 0, w, args=(qi,), 
     380                        divmax=100, vec_func=True, tol=0, rtol=1e-8) 
     381            result[i] = r/w 
     382        elif w == 0.: 
     383            r = romberg(_int_h, -h, h, args=(qi,), 
     384                        divmax=100, vec_func=True, tol=0, rtol=1e-8) 
     385            result[i] = r/(2*h) 
     386        else: 
     387            r, err = dblquad(_int_wh, -h, h, lambda h: 0., lambda h: width, 
     388                             args=(qi,)) 
     389            result[i] = r/(w*2*h) 
     390 
    380391    # r should be [float, ...], but it is [array([float]), array([float]),...] 
    381     return np.asarray(r).flatten()/delta_qv[0] 
     392    return result 
    382393 
    383394 
     
    520531 
    521532    def compare(self, q, output, answer, tolerance): 
    522         err = (output - answer)/answer 
    523         idx = abs(err) >= tolerance 
    524         problem = zip(q[idx], output[idx], answer[idx], err[idx]) 
    525         print "\n".join(str(v) for v in problem) 
     533        #err = (output - answer)/answer 
     534        #idx = abs(err) >= tolerance 
     535        #problem = zip(q[idx], output[idx], answer[idx], err[idx]) 
     536        #print "\n".join(str(v) for v in problem) 
    526537        np.testing.assert_allclose(output, answer, rtol=tolerance) 
    527538 
     
    609620        data = np.loadtxt(data_string.split('\n')).T 
    610621        q, delta_qv, _, answer = data 
    611         answer = romberg_slit_1d(q, delta_qv, self.model, pars) 
     622        answer = romberg_slit_1d(q, delta_qv, 0., self.model, pars) 
    612623        q_calc = slit_extend_q(interpolate(q, 2*np.pi/radius/20), 
    613                                delta_qv[0], delta_qv[0]) 
     624                               delta_qv[0], 0.) 
    614625        resolution = Slit1D(q, width=delta_qv, height=0, q_calc=q_calc) 
    615626        output = self.Iq_sphere(pars, resolution) 
     
    629640        form = load_model('ellipsoid', dtype='double') 
    630641        q = np.logspace(log10(4e-5),log10(2.5e-2), 68) 
    631         delta_qv = [0.117] 
    632         resolution = Slit1D(q, width=delta_qv, height=0) 
    633         answer = romberg_slit_1d(q, delta_qv, form, pars) 
     642        width, height = 0.117, 0. 
     643        resolution = Slit1D(q, width=width, height=height) 
     644        answer = romberg_slit_1d(q, width, height, form, pars) 
    634645        output = resolution.apply(eval_form(resolution.q_calc, form, pars)) 
    635646        # TODO: 10% is too much error; use better algorithm 
     647        #print np.max(abs(answer-output)/answer) 
    636648        self.compare(q, output, answer, 0.1) 
    637649 
     
    860872 
    861873def _eval_demo_1d(resolution, title): 
     874    import sys 
    862875    from sasmodels import core 
    863     from sasmodels.models import cylinder 
    864     ## or alternatively: 
    865     # cylinder = core.load_model_definition('cylinder') 
    866     model = core.load_model(cylinder) 
     876    name = sys.argv[1] if len(sys.argv) > 1 else 'cylinder' 
     877 
     878    if name == 'cylinder': 
     879        pars = {'length':210, 'radius':500} 
     880    elif name == 'teubner_strey': 
     881        pars = {'a2':0.003, 'c1':-1e4, 'c2':1e10, 'background':0.312643} 
     882    elif name == 'sphere' or name == 'spherepy': 
     883        pars = TEST_PARS_SLIT_SPHERE 
     884    elif name == 'ellipsoid': 
     885        pars = { 
     886            'scale':0.05, 
     887            'rpolar':500, 'requatorial':15000, 
     888            'sld':6, 'solvent_sld': 1, 
     889            } 
     890    else: 
     891        pars = {} 
     892    defn = core.load_model_definition(name) 
     893    model = core.load_model(defn) 
    867894 
    868895    kernel = core.make_kernel(model, [resolution.q_calc]) 
    869     theory = core.call_kernel(kernel, {'length':210, 'radius':500}) 
     896    theory = core.call_kernel(kernel, pars) 
    870897    Iq = resolution.apply(theory) 
     898 
     899    if isinstance(resolution, Slit1D): 
     900        width, height = resolution.width, resolution.height 
     901        Iq_romb = romberg_slit_1d(resolution.q, width, height, model, pars) 
     902    else: 
     903        dq = resolution.q_width 
     904        Iq_romb = romberg_pinhole_1d(resolution.q, dq, model, pars) 
    871905 
    872906    import matplotlib.pyplot as plt 
    873907    plt.loglog(resolution.q_calc, theory, label='unsmeared') 
    874908    plt.loglog(resolution.q, Iq, label='smeared', hold=True) 
     909    plt.loglog(resolution.q, Iq_romb, label='romberg smeared', hold=True) 
    875910    plt.legend() 
    876911    plt.title(title) 
     
    879914 
    880915def demo_pinhole_1d(): 
    881     q = np.logspace(-3, -1, 400) 
     916    q = np.logspace(-4, np.log10(0.2), 400) 
    882917    q_width = 0.1*q 
    883918    resolution = Pinhole1D(q, q_width) 
     
    885920 
    886921def demo_slit_1d(): 
    887     q = np.logspace(-3, -1, 400) 
    888     qx_width = 0.005 
    889     qy_width = 0.0 
    890     resolution = Slit1D(q, qx_width, qy_width) 
    891     _eval_demo_1d(resolution, title="0.005 Qx Slit Resolution") 
     922    q = np.logspace(-4, np.log10(0.2), 400) 
     923    w = h = 0. 
     924    #w = 0.005 
     925    w = 0.0277790 
     926    #h = 0.00277790 
     927    resolution = Slit1D(q, w, h) 
     928    _eval_demo_1d(resolution, title="(%g,%g) Slit Resolution"%(w,h)) 
    892929 
    893930def demo(): 
     
    895932    plt.subplot(121) 
    896933    demo_pinhole_1d() 
     934    #plt.yscale('linear') 
    897935    plt.subplot(122) 
    898936    demo_slit_1d() 
     937    #plt.yscale('linear') 
    899938    plt.show() 
    900939 
Note: See TracChangeset for help on using the changeset viewer.