Changeset 59c4c4e in sasmodels


Ignore:
Timestamp:
Mar 3, 2015 4:31:42 PM (10 years ago)
Author:
Paul Kienzle <pkienzle@…>
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:
bfb195e
Parents:
9890053 (diff), 33e91b1 (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 github.com:sasview/sasmodels

Files:
13 edited

Legend:

Unmodified
Added
Removed
  • extra/pylint.rc

    r49f92c1 r6c8db9e  
    5757 
    5858# Disable the message(s) with the given id(s). 
    59 disable=W0702,W0613 
     59disable=W0702,W0613,W0703,W0142 
    6060 
    6161[REPORTS] 
     
    343343 
    344344# Minimum number of public methods for a class (see R0903). 
    345 min-public-methods=2 
     345min-public-methods=0 
    346346 
    347347# Maximum number of public methods for a class (see R0904). 
  • sasmodels/generate.py

    ra5d0d00 r33e91b1  
    201201# Scale and background, which are parameters common to every form factor 
    202202COMMON_PARAMETERS = [ 
    203     [ "scale", "", 1, [0, np.inf], "", "Source intensity" ], 
    204     [ "background", "1/cm", 0, [0, np.inf], "", "Source background" ], 
     203    ["scale", "", 1, [0, np.inf], "", "Source intensity"], 
     204    ["background", "1/cm", 0, [0, np.inf], "", "Source background"], 
    205205    ] 
    206206 
     
    233233# description and its parameter table.  The remainder of the doc comes 
    234234# from the module docstring. 
    235 DOC_HEADER=""".. _%(name)s: 
     235DOC_HEADER = """.. _%(name)s: 
    236236 
    237237%(label)s 
     
    259259        ] 
    260260    column_widths = [max(w, len(h)) 
    261                      for w,h in zip(column_widths, PARTABLE_HEADERS)] 
     261                     for w, h in zip(column_widths, PARTABLE_HEADERS)] 
    262262 
    263263    sep = " ".join("="*w for w in column_widths) 
    264264    lines = [ 
    265265        sep, 
    266         " ".join("%-*s"%(w,h) for w,h in zip(column_widths, PARTABLE_HEADERS)), 
     266        " ".join("%-*s" % (w, h) for w, h in zip(column_widths, PARTABLE_HEADERS)), 
    267267        sep, 
    268268        ] 
    269269    for p in pars: 
    270270        lines.append(" ".join([ 
    271             "%-*s"%(column_widths[0],p[0]), 
    272             "%-*s"%(column_widths[1],p[-1]), 
    273             "%-*s"%(column_widths[2],RST_UNITS[p[1]]), 
    274             "%*g"%(column_widths[3],p[2]), 
     271            "%-*s" % (column_widths[0], p[0]), 
     272            "%-*s" % (column_widths[1], p[-1]), 
     273            "%-*s" % (column_widths[2], RST_UNITS[p[1]]), 
     274            "%*g" % (column_widths[3], p[2]), 
    275275            ])) 
    276276    lines.append(sep) 
     
    287287        if exists(target): 
    288288            return target 
    289     raise ValueError("%r not found in %s"%(filename, search_path)) 
     289    raise ValueError("%r not found in %s" % (filename, search_path)) 
    290290 
    291291def sources(info): 
     
    293293    Return a list of the sources file paths for the module. 
    294294    """ 
    295     search_path = [ dirname(info['filename']), 
    296                     abspath(joinpath(dirname(__file__),'models')) ] 
     295    search_path = [dirname(info['filename']), 
     296                   abspath(joinpath(dirname(__file__), 'models'))] 
    297297    return [_search(search_path, f) for f in info['source']] 
    298298 
     
    333333 
    334334    for p in pars: 
    335         name,ptype = p[0],p[4] 
     335        name, ptype = p[0], p[4] 
    336336        if ptype == 'volume': 
    337337            partype['pd-1d'].append(name) 
     
    346346            partype['fixed-2d'].append(name) 
    347347        else: 
    348             raise ValueError("unknown parameter type %r"%ptype) 
     348            raise ValueError("unknown parameter type %r" % ptype) 
    349349        partype[ptype].append(name) 
    350350 
     
    356356    """ 
    357357    spaces = " "*depth 
    358     sep = "\n"+spaces 
     358    sep = "\n" + spaces 
    359359    return spaces + sep.join(s.split("\n")) 
    360360 
     
    366366    Returns loop opening and loop closing 
    367367    """ 
    368     LOOP_OPEN="""\ 
     368    LOOP_OPEN = """\ 
    369369for (int %(name)s_i=0; %(name)s_i < N%(name)s; %(name)s_i++) { 
    370370  const double %(name)s = loops[2*(%(name)s_i%(offset)s)]; 
     
    376376    loop_end = [] 
    377377    for name in pd_pars: 
    378         subst = { 'name': name, 'offset': offset } 
    379         loop_head.append(indent(LOOP_OPEN%subst, depth)) 
     378        subst = {'name': name, 'offset': offset} 
     379        loop_head.append(indent(LOOP_OPEN % subst, depth)) 
    380380        loop_end.insert(0, (" "*depth) + "}") 
    381         offset += '+N'+name 
     381        offset += '+N' + name 
    382382        depth += 2 
    383383    return "\n".join(loop_head), "\n".join(loop_end) 
    384384 
    385 C_KERNEL_TEMPLATE=None 
     385C_KERNEL_TEMPLATE = None 
    386386def make_model(info): 
    387387    """ 
     
    416416 
    417417    iq_parameters = [p[0] 
    418         for p in info['parameters'][2:] # skip scale, background 
    419         if p[0] in set(fixed_1d+pd_1d)] 
     418                     for p in info['parameters'][2:] # skip scale, background 
     419                     if p[0] in set(fixed_1d + pd_1d)] 
    420420    iqxy_parameters = [p[0] 
    421         for p in info['parameters'][2:] # skip scale, background 
    422         if p[0] in set(fixed_2d+pd_2d)] 
     421                       for p in info['parameters'][2:] # skip scale, background 
     422                       if p[0] in set(fixed_2d + pd_2d)] 
    423423    volume_parameters = [p[0] 
    424         for p in info['parameters'] 
    425         if p[4]=='volume'] 
     424                         for p in info['parameters'] 
     425                         if p[4] == 'volume'] 
    426426 
    427427    # Fill in defintions for volume parameters 
     
    430430                        ','.join(volume_parameters))) 
    431431        defines.append(('VOLUME_WEIGHT_PRODUCT', 
    432                         '*'.join(p+'_w' for p in volume_parameters))) 
     432                        '*'.join(p + '_w' for p in volume_parameters))) 
    433433 
    434434    # Generate form_volume function from body only 
    435435    if info['form_volume'] is not None: 
    436436        if volume_parameters: 
    437             vol_par_decl = ', '.join('double '+p for p in volume_parameters) 
     437            vol_par_decl = ', '.join('double ' + p for p in volume_parameters) 
    438438        else: 
    439439            vol_par_decl = 'void' 
     
    445445    %(body)s 
    446446} 
    447 """%{'body':info['form_volume']} 
     447""" % {'body':info['form_volume']} 
    448448        source.append(fn) 
    449449 
    450450    # Fill in definitions for Iq parameters 
    451     defines.append(('IQ_KERNEL_NAME', info['name']+'_Iq')) 
     451    defines.append(('IQ_KERNEL_NAME', info['name'] + '_Iq')) 
    452452    defines.append(('IQ_PARAMETERS', ', '.join(iq_parameters))) 
    453453    if fixed_1d: 
    454454        defines.append(('IQ_FIXED_PARAMETER_DECLARATIONS', 
    455                         ', \\\n    '.join('const double %s'%p for p in fixed_1d))) 
     455                        ', \\\n    '.join('const double %s' % p for p in fixed_1d))) 
    456456    if pd_1d: 
    457457        defines.append(('IQ_WEIGHT_PRODUCT', 
    458                         '*'.join(p+'_w' for p in pd_1d))) 
     458                        '*'.join(p + '_w' for p in pd_1d))) 
    459459        defines.append(('IQ_DISPERSION_LENGTH_DECLARATIONS', 
    460                         ', \\\n    '.join('const int N%s'%p for p in pd_1d))) 
     460                        ', \\\n    '.join('const int N%s' % p for p in pd_1d))) 
    461461        defines.append(('IQ_DISPERSION_LENGTH_SUM', 
    462                         '+'.join('N'+p for p in pd_1d))) 
     462                        '+'.join('N' + p for p in pd_1d))) 
    463463        open_loops, close_loops = build_polydispersity_loops(pd_1d) 
    464464        defines.append(('IQ_OPEN_LOOPS', 
    465                         open_loops.replace('\n',' \\\n'))) 
     465                        open_loops.replace('\n', ' \\\n'))) 
    466466        defines.append(('IQ_CLOSE_LOOPS', 
    467                         close_loops.replace('\n',' \\\n'))) 
     467                        close_loops.replace('\n', ' \\\n'))) 
    468468    if info['Iq'] is not None: 
    469469        defines.append(('IQ_PARAMETER_DECLARATIONS', 
    470                        ', '.join('double '+p for p in iq_parameters))) 
     470                        ', '.join('double ' + p for p in iq_parameters))) 
    471471        fn = """\ 
    472472double Iq(double q, IQ_PARAMETER_DECLARATIONS); 
     
    474474    %(body)s 
    475475} 
    476 """%{'body':info['Iq']} 
     476""" % {'body':info['Iq']} 
    477477        source.append(fn) 
    478478 
    479479    # Fill in definitions for Iqxy parameters 
    480     defines.append(('IQXY_KERNEL_NAME', info['name']+'_Iqxy')) 
     480    defines.append(('IQXY_KERNEL_NAME', info['name'] + '_Iqxy')) 
    481481    defines.append(('IQXY_PARAMETERS', ', '.join(iqxy_parameters))) 
    482482    if fixed_2d: 
    483483        defines.append(('IQXY_FIXED_PARAMETER_DECLARATIONS', 
    484                         ', \\\n    '.join('const double %s'%p for p in fixed_2d))) 
     484                        ', \\\n    '.join('const double %s' % p for p in fixed_2d))) 
    485485    if pd_2d: 
    486486        defines.append(('IQXY_WEIGHT_PRODUCT', 
    487                         '*'.join(p+'_w' for p in pd_2d))) 
     487                        '*'.join(p + '_w' for p in pd_2d))) 
    488488        defines.append(('IQXY_DISPERSION_LENGTH_DECLARATIONS', 
    489                         ', \\\n    '.join('const int N%s'%p for p in pd_2d))) 
     489                        ', \\\n    '.join('const int N%s' % p for p in pd_2d))) 
    490490        defines.append(('IQXY_DISPERSION_LENGTH_SUM', 
    491                         '+'.join('N'+p for p in pd_2d))) 
     491                        '+'.join('N' + p for p in pd_2d))) 
    492492        open_loops, close_loops = build_polydispersity_loops(pd_2d) 
    493493        defines.append(('IQXY_OPEN_LOOPS', 
    494                         open_loops.replace('\n',' \\\n'))) 
     494                        open_loops.replace('\n', ' \\\n'))) 
    495495        defines.append(('IQXY_CLOSE_LOOPS', 
    496                         close_loops.replace('\n',' \\\n'))) 
     496                        close_loops.replace('\n', ' \\\n'))) 
    497497    if info['Iqxy'] is not None: 
    498498        defines.append(('IQXY_PARAMETER_DECLARATIONS', 
    499                        ', '.join('double '+p for p in iqxy_parameters))) 
     499                        ', '.join('double ' + p for p in iqxy_parameters))) 
    500500        fn = """\ 
    501501double Iqxy(double qx, double qy, IQXY_PARAMETER_DECLARATIONS); 
     
    503503    %(body)s 
    504504} 
    505 """%{'body':info['Iqxy']} 
     505""" % {'body':info['Iqxy']} 
    506506        source.append(fn) 
    507507 
     
    513513 
    514514    #for d in defines: print d 
    515     DEFINES='\n'.join('#define %s %s'%(k,v) for k,v in defines) 
    516     SOURCES='\n\n'.join(source) 
    517     return C_KERNEL_TEMPLATE%{ 
     515    DEFINES = '\n'.join('#define %s %s' % (k, v) for k, v in defines) 
     516    SOURCES = '\n\n'.join(source) 
     517    return C_KERNEL_TEMPLATE % { 
    518518        'DEFINES':DEFINES, 
    519519        'SOURCES':SOURCES, 
     
    531531    #print kernelfile 
    532532    info = dict( 
    533         filename = abspath(kernel_module.__file__), 
    534         name = kernel_module.name, 
    535         title = kernel_module.title, 
    536         description = kernel_module.description, 
    537         parameters = COMMON_PARAMETERS + kernel_module.parameters, 
    538         source = getattr(kernel_module, 'source', []), 
    539         oldname = kernel_module.oldname, 
    540         oldpars = kernel_module.oldpars, 
     533        filename=abspath(kernel_module.__file__), 
     534        name=kernel_module.name, 
     535        title=kernel_module.title, 
     536        description=kernel_module.description, 
     537        parameters=COMMON_PARAMETERS + kernel_module.parameters, 
     538        source=getattr(kernel_module, 'source', []), 
     539        oldname=kernel_module.oldname, 
     540        oldpars=kernel_module.oldpars, 
    541541        ) 
    542542    # Fill in attributes which default to None 
    543     info.update((k,getattr(kernel_module, k, None)) 
     543    info.update((k, getattr(kernel_module, k, None)) 
    544544                for k in ('ER', 'VR', 'form_volume', 'Iq', 'Iqxy')) 
    545545    # Fill in the derived attributes 
    546     info['limits'] = dict((p[0],p[3]) for p in info['parameters']) 
     546    info['limits'] = dict((p[0], p[3]) for p in info['parameters']) 
    547547    info['partype'] = categorize_parameters(info['parameters']) 
    548     info['defaults'] = dict((p[0],p[2]) for p in info['parameters']) 
     548    info['defaults'] = dict((p[0], p[2]) for p in info['parameters']) 
    549549 
    550550    # Assume if one part of the kernel is python then all parts are. 
     
    556556    Return the documentation for the model. 
    557557    """ 
    558     subst = dict(name=kernel_module.name.replace('_','-'), 
     558    subst = dict(name=kernel_module.name.replace('_', '-'), 
    559559                 label=" ".join(kernel_module.name.split('_')).capitalize(), 
    560560                 title=kernel_module.title, 
    561561                 parameters=make_partable(kernel_module.parameters), 
    562562                 docs=kernel_module.__doc__) 
    563     return DOC_HEADER%subst 
     563    return DOC_HEADER % subst 
    564564 
    565565 
     
    568568    import datetime 
    569569    from .models import cylinder 
    570     toc = lambda: (datetime.datetime.now()-tic).total_seconds() 
    571570    tic = datetime.datetime.now() 
    572     source, info = make(cylinder) 
    573     print "time:",toc() 
     571    toc = lambda: (datetime.datetime.now() - tic).total_seconds() 
     572    make(cylinder) 
     573    print "time:", toc() 
    574574 
    575575def main(): 
     
    579579        name = sys.argv[1] 
    580580        import sasmodels.models 
    581         __import__('sasmodels.models.'+name) 
     581        __import__('sasmodels.models.' + name) 
    582582        model = getattr(sasmodels.models, name) 
    583         source, info = make(model); print source 
    584         #print doc(model) 
     583        source, _ = make(model) 
     584        print source 
    585585 
    586586if __name__ == "__main__": 
  • sasmodels/kernelcl.py

    r664c8e7 rc85db69  
    3232    context = cl.create_some_context(interactive=False) 
    3333    del context 
    34 except Exception,exc: 
     34except Exception, exc: 
    3535    warnings.warn(str(exc)) 
    3636    raise RuntimeError("OpenCL not available") 
     
    3939 
    4040from . import generate 
    41 from .kernelpy import PyInput, PyModel 
     41from .kernelpy import PyModel 
    4242 
    4343F64_DEFS = """\ 
     
    6363    """ 
    6464    source, info = generate.make(kernel_module) 
    65     if callable(info.get('Iq',None)): 
     65    if callable(info.get('Iq', None)): 
    6666        return PyModel(info) 
    6767    ## for debugging, save source to a .cl file, edit it, and reload as model 
     
    110110    device.min_data_type_align_size//4. 
    111111    """ 
    112     remainder = vector.size%boundary 
     112    remainder = vector.size % boundary 
    113113    if remainder != 0: 
    114114        size = vector.size + (boundary - remainder) 
    115         vector = np.hstack((vector, [extra]*(size-vector.size))) 
     115        vector = np.hstack((vector, [extra] * (size - vector.size))) 
    116116    return np.ascontiguousarray(vector, dtype=dtype) 
    117117 
     
    126126    """ 
    127127    dtype = np.dtype(dtype) 
    128     if dtype==generate.F64 and not all(has_double(d) for d in context.devices): 
     128    if dtype == generate.F64 and not all(has_double(d) for d in context.devices): 
    129129        raise RuntimeError("Double precision not supported for devices") 
    130130 
     
    135135    if context.devices[0].type == cl.device_type.GPU: 
    136136        header += "#define USE_SINCOS\n" 
    137     program  = cl.Program(context, header+source).build() 
     137    program = cl.Program(context, header + source).build() 
    138138    return program 
    139139 
     
    173173        try: 
    174174            self.context = cl.create_some_context(interactive=False) 
    175         except Exception,exc: 
     175        except Exception, exc: 
    176176            warnings.warn(str(exc)) 
    177177            warnings.warn("pyopencl.create_some_context() failed") 
     
    230230        self.__dict__ = state.copy() 
    231231 
    232     def __call__(self, input): 
    233         if self.dtype != input.dtype: 
     232    def __call__(self, input_value): 
     233        if self.dtype != input_value.dtype: 
    234234            raise TypeError("data and kernel have different types") 
    235235        if self.program is None: 
    236             self.program = environment().compile_program(self.info['name'],self.source, self.dtype) 
    237         kernel_name = generate.kernel_name(self.info, input.is_2D) 
     236            self.program = environment().compile_program(self.info['name'], self.source, self.dtype) 
     237        kernel_name = generate.kernel_name(self.info, input_value.is_2D) 
    238238        kernel = getattr(self.program, kernel_name) 
    239         return GpuKernel(kernel, self.info, input) 
     239        return GpuKernel(kernel, self.info, input_value) 
    240240 
    241241    def release(self): 
     
    285285        self.q_vectors = [_stretch_input(q, self.dtype, 32) for q in q_vectors] 
    286286        self.q_buffers = [ 
    287             cl.Buffer(env.context,  mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=q) 
     287            cl.Buffer(env.context, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=q) 
    288288            for q in self.q_vectors 
    289289        ] 
     
    320320        self.res = np.empty(input.nq, input.dtype) 
    321321        dim = '2d' if input.is_2D else '1d' 
    322         self.fixed_pars = info['partype']['fixed-'+dim] 
    323         self.pd_pars = info['partype']['pd-'+dim] 
     322        self.fixed_pars = info['partype']['fixed-' + dim] 
     323        self.pd_pars = info['partype']['pd-' + dim] 
    324324 
    325325        # Inputs and outputs for each kernel call 
     
    327327        env = environment() 
    328328        self.loops_b = [cl.Buffer(env.context, mf.READ_WRITE, 
    329                                   2*MAX_LOOPS*input.dtype.itemsize) 
     329                                  2 * MAX_LOOPS * input.dtype.itemsize) 
    330330                        for _ in env.queues] 
    331331        self.res_b = [cl.Buffer(env.context, mf.READ_WRITE, 
    332                                 input.global_size[0]*input.dtype.itemsize) 
     332                                input.global_size[0] * input.dtype.itemsize) 
    333333                      for _ in env.queues] 
    334334 
     
    344344            cutoff = real(cutoff) 
    345345            loops_N = [np.uint32(len(p[0])) for p in pd_pars] 
    346             loops = np.hstack(pd_pars) if pd_pars else np.empty(0,dtype=self.input.dtype) 
     346            loops = np.hstack(pd_pars) if pd_pars else np.empty(0, dtype=self.input.dtype) 
    347347            loops = np.ascontiguousarray(loops.T, self.input.dtype).flatten() 
    348348            #print "loops",Nloops, loops 
     
    350350            #import sys; print >>sys.stderr,"opencl eval",pars 
    351351            #print "opencl eval",pars 
    352             if len(loops) > 2*MAX_LOOPS: 
     352            if len(loops) > 2 * MAX_LOOPS: 
    353353                raise ValueError("too many polydispersity points") 
    354354 
  • sasmodels/kernelpy.py

    rf734e7d rc85db69  
    11import numpy as np 
    2 from numpy import pi, sin, cos, sqrt 
    3  
    4 from .generate import F32, F64 
     2from numpy import pi, cos 
     3 
     4from .generate import F64 
    55 
    66class PyModel(object): 
    77    def __init__(self, info): 
    88        self.info = info 
    9     def __call__(self, input): 
    10         kernel = self.info['Iqxy'] if input.is_2D else self.info['Iq'] 
    11         return PyKernel(kernel, self.info, input) 
     9    def __call__(self, input_value): 
     10        kernel = self.info['Iqxy'] if input_value.is_2D else self.info['Iq'] 
     11        return PyKernel(kernel, self.info, input_value) 
    1212    def make_input(self, q_vectors): 
    1313        return PyInput(q_vectors, dtype=F64) 
     
    3838        self.dtype = dtype 
    3939        self.is_2D = (len(q_vectors) == 2) 
    40         self.q_vectors = [np.ascontiguousarray(q,self.dtype) for q in q_vectors] 
     40        self.q_vectors = [np.ascontiguousarray(q, self.dtype) for q in q_vectors] 
    4141        self.q_pointers = [q.ctypes.data for q in q_vectors] 
    4242 
     
    7373            if dim == '2d': 
    7474                def vector_kernel(qx, qy, *args): 
    75                     return np.array([kernel(qxi,qyi,*args) for qxi,qyi in zip(qx,qy)]) 
     75                    return np.array([kernel(qxi, qyi, *args) for qxi, qyi in zip(qx, qy)]) 
    7676            else: 
    7777                def vector_kernel(q, *args): 
    78                     return np.array([kernel(qi,*args) for qi in q]) 
     78                    return np.array([kernel(qi, *args) for qi in q]) 
    7979            self.kernel = vector_kernel 
    8080        else: 
    8181            self.kernel = kernel 
    82         fixed_pars = info['partype']['fixed-'+dim] 
    83         pd_pars = info['partype']['pd-'+dim] 
     82        fixed_pars = info['partype']['fixed-' + dim] 
     83        pd_pars = info['partype']['pd-' + dim] 
    8484        vol_pars = info['partype']['volume'] 
    8585 
     
    8787        pars = [p[0] for p in info['parameters'][2:]] 
    8888        offset = len(self.input.q_vectors) 
    89         self.args = self.input.q_vectors + [None]*len(pars) 
    90         self.fixed_index = np.array([pars.index(p)+offset for p in fixed_pars[2:] ]) 
    91         self.pd_index = np.array([pars.index(p)+offset for p in pd_pars]) 
    92         self.vol_index = np.array([pars.index(p)+offset for p in vol_pars]) 
    93         try: self.theta_index = pars.index('theta')+offset 
     89        self.args = self.input.q_vectors + [None] * len(pars) 
     90        self.fixed_index = np.array([pars.index(p) + offset for p in fixed_pars[2:]]) 
     91        self.pd_index = np.array([pars.index(p) + offset for p in pd_pars]) 
     92        self.vol_index = np.array([pars.index(p) + offset for p in vol_pars]) 
     93        try: self.theta_index = pars.index('theta') + offset 
    9494        except ValueError: self.theta_index = -1 
    9595 
     
    105105        # First two fixed 
    106106        scale, background = fixed[:2] 
    107         for index,value in zip(self.fixed_index, fixed[2:]): 
     107        for index, value in zip(self.fixed_index, fixed[2:]): 
    108108            args[index] = float(value) 
    109         res = _loops(form, form_volume, cutoff, scale, background,  args, 
     109        res = _loops(form, form_volume, cutoff, scale, background, args, 
    110110                     pd, self.pd_index, self.vol_index, self.theta_index) 
    111111 
     
    185185    for k in range(stride[-1]): 
    186186        # update polydispersity parameter values 
    187         fast_index = k%stride[0] 
     187        fast_index = k % stride[0] 
    188188        if fast_index == 0:  # bottom loop complete ... check all other loops 
    189189            if weight.size > 0: 
    190                 for i,index, in enumerate(k%stride): 
     190                for i, index, in enumerate(k % stride): 
    191191                    args[pd_index[i]] = pd[i][0][index] 
    192192                    weight[i] = pd[i][1][index] 
     
    202202        if w > cutoff: 
    203203            I = form(*args) 
    204             positive = (I>=0.0) 
     204            positive = (I >= 0.0) 
    205205 
    206206            # Note: can precompute spherical correction if theta_index is not the fast index 
    207207            # Correction factor for spherical integration p(theta) I(q) sin(theta) dtheta 
    208208            #spherical_correction = abs(sin(pi*args[theta_index])) if theta_index>=0 else 1.0 
    209             spherical_correction = abs(cos(pi*args[theta_index]))*pi/2 if theta_index>=0 else 1.0 
     209            spherical_correction = abs(cos(pi * args[theta_index])) * pi / 2 if theta_index >= 0 else 1.0 
    210210            #spherical_correction = 1.0 
    211             ret += w*I*spherical_correction*positive 
    212             norm += w*positive 
     211            ret += w * I * spherical_correction * positive 
     212            norm += w * positive 
    213213 
    214214            # Volume normalization. 
     
    220220                vol_args = [args[index] for index in vol_index] 
    221221                vol_weight = np.prod(weight[vol_weight_index]) 
    222                 vol += vol_weight*form_volume(*vol_args)*positive 
    223                 vol_norm += vol_weight*positive 
    224  
    225     positive = (vol*vol_norm != 0.0) 
     222                vol += vol_weight * form_volume(*vol_args) * positive 
     223                vol_norm += vol_weight * positive 
     224 
     225    positive = (vol * vol_norm != 0.0) 
    226226    ret[positive] *= vol_norm[positive] / vol[positive] 
    227     result = scale*ret/norm+background 
     227    result = scale * ret / norm + background 
    228228    return result 
  • sasmodels/models/parallelepiped.py

    r9890053 r33e91b1  
    99---------- 
    1010 
    11 This model provides the form factor, *P(q)*, for a rectangular parallelepiped  
    12 (below) where the form factor is normalized by the volume of the  
    13 parallelepiped. If you need to apply polydispersity, see also the  
     11This model provides the form factor, *P(q)*, for a rectangular parallelepiped 
     12(below) where the form factor is normalized by the volume of the 
     13parallelepiped. If you need to apply polydispersity, see also the 
    1414RectangularPrismModel_. 
    1515 
     
    2020    P(Q) = {\text{scale} \over V} F^2(Q) + \text{background} 
    2121 
    22 where the volume *V* = *A B C* and the averaging < > is applied over all  
     22where the volume *V* = *A B C* and the averaging < > is applied over all 
    2323orientations for 1D. 
    2424 
     
    2727*Figure. Parallelepiped with the corresponding Definition of sides. 
    2828 
    29 The edge of the solid must satisfy the condition that** *A* < *B* < *C*.  
    30 Then, assuming *a* = *A* / *B* < 1, *b* = *B* / *B* = 1, and  
     29The edge of the solid must satisfy the condition that** *A* < *B* < *C*. 
     30Then, assuming *a* = *A* / *B* < 1, *b* = *B* / *B* = 1, and 
    3131*c* = *C* / *B* > 1, the form factor is 
    3232 
    3333.. math:: 
    3434 
    35     P(q) = \frac{\textstyle{scale}}{V}\int_0^1 \phi(\mu \sqrt{1-\sigma^2},a)  
     35    P(q) = \frac{\textstyle{scale}}{V}\int_0^1 \phi(\mu \sqrt{1-\sigma^2},a) 
    3636    [S(\mu c \sigma/2)]^2 d\sigma 
    3737 
     
    4040.. math:: 
    4141 
    42     \phi(\mu,a) = \int_0^1 \{S[\frac{\mu}{2}\cos(\frac{\pi}{2}u)]  
     42    \phi(\mu,a) = \int_0^1 \{S[\frac{\mu}{2}\cos(\frac{\pi}{2}u)] 
    4343    S[\frac{\mu a}{2}\sin(\frac{\pi}{2}u)]\}^2 du 
    4444 
    4545    S(x) = \frac{\sin x}{x} 
    46      
     46 
    4747    \mu = qB 
    4848 
     
    5353    \Delta\rho = \rho_{\textstyle p} - \rho_{\textstyle solvent} 
    5454 
    55 The scattering intensity per unit volume is returned in units of |cm^-1|;  
     55The scattering intensity per unit volume is returned in units of |cm^-1|; 
    5656ie, *I(q)* = |phi| *P(q)*\ . 
    5757 
    58 NB: The 2nd virial coefficient of the parallelpiped is calculated based on  
    59 the averaged effective radius (= sqrt(*short_a* \* *short_b* / |pi|)) and  
     58NB: The 2nd virial coefficient of the parallelpiped is calculated based on 
     59the averaged effective radius (= sqrt(*short_a* \* *short_b* / |pi|)) and 
    6060length(= *long_c*) values, and used as the effective radius for 
    6161*S(Q)* when *P(Q)* \* *S(Q)* is applied. 
    6262 
    63 To provide easy access to the orientation of the parallelepiped, we define  
     63To provide easy access to the orientation of the parallelepiped, we define 
    6464three angles |theta|, |phi| and |bigpsi|. The definition of |theta| and |phi| 
    65 is the same as for the cylinder model (see also figures below).  
    66 The angle |bigpsi| is the rotational angle around the *long_c* axis against  
    67 the *q* plane. For example, |bigpsi| = 0 when the *short_b* axis is parallel  
     65is the same as for the cylinder model (see also figures below). 
     66The angle |bigpsi| is the rotational angle around the *long_c* axis against 
     67the *q* plane. For example, |bigpsi| = 0 when the *short_b* axis is parallel 
    6868to the *x*-axis of the detector. 
    6969 
     
    8383---------- 
    8484 
    85 Validation of the code was done by comparing the output of the 1D calculation  
    86 to the angular average of the output of a 2D calculation over all possible  
    87 angles. The Figure below shows the comparison where the solid dot refers to  
    88 averaged 2D while the line represents the result of the 1D calculation (for  
    89 the averaging, 76, 180, 76 points are taken for the angles of |theta|, |phi|,  
     85Validation of the code was done by comparing the output of the 1D calculation 
     86to the angular average of the output of a 2D calculation over all possible 
     87angles. The Figure below shows the comparison where the solid dot refers to 
     88averaged 2D while the line represents the result of the 1D calculation (for 
     89the averaging, 76, 180, 76 points are taken for the angles of |theta|, |phi|, 
    9090and |psi| respectively). 
    9191 
     
    9696*Figure. Comparison between 1D and averaged 2D.* 
    9797 
    98 This model reimplements the form factor calculations implemented in a c-library  
     98This model reimplements the form factor calculations implemented in a c-library 
    9999provided by the NIST Center for Neutron Research (Kline, 2006). 
    100100 
     
    108108     P(q)= scale/V*integral from 0 to 1 of ... 
    109109           phi(mu*sqrt(1-sigma^2),a) * S(mu*c*sigma/2)^2 * dsigma 
    110       
     110 
    111111            phi(mu,a) = integral from 0 to 1 of .. 
    112             (S((mu/2)*cos(pi*u/2))*S((mu*a/2)*sin(pi*u/2)))^2 * du 
     112        (S((mu/2)*cos(pi*u/2))*S((mu*a/2)*sin(pi*u/2)))^2 * du 
    113113            S(x) = sin(x)/x 
    114             mu = q*B 
     114        mu = q*B 
    115115""" 
    116116category = "shape:parallelpiped" 
    117117 
    118118parameters = [ 
    119 #   [ "name", "units", default, [lower, upper], "type", 
    120 #     "description" ], 
    121     [ "sld", "1e-6/Ang^2", 4, [-inf,inf], "", 
    122       "Parallelepiped scattering length density" ], 
    123     [ "solvent_sld", "1e-6/Ang^2", 1, [-inf,inf], "", 
    124       "Solvent scattering length density" ], 
    125     [ "a_side", "Ang", 35, [0, inf], "volume", 
    126       "Shorter side of the parallelepiped" ], 
    127     [ "b_side", "Ang", 75, [0, inf], "volume", 
    128       "Second side of the parallelepiped" ], 
    129     [ "c_side", "Ang", 400, [0, inf], "volume", 
    130       "Larger side of the parallelepiped" ], 
    131     [ "theta", "degrees", 60, [-inf, inf], "orientation", 
    132       "In plane angle" ], 
    133     [ "phi", "degrees", 60, [-inf, inf], "orientation", 
    134       "Out of plane angle" ], 
    135     [ "psi", "degrees", 60, [-inf, inf], "orientation", 
    136       "Rotation angle around its own c axis against q plane" ], 
     119    #   [ "name", "units", default, [lower, upper], "type", 
     120    #     "description" ], 
     121    ["sld", "1e-6/Ang^2", 4, [-inf, inf], "", 
     122     "Parallelepiped scattering length density"], 
     123    ["solvent_sld", "1e-6/Ang^2", 1, [-inf, inf], "", 
     124     "Solvent scattering length density"], 
     125    ["a_side", "Ang", 35, [0, inf], "volume", 
     126     "Shorter side of the parallelepiped"], 
     127    ["b_side", "Ang", 75, [0, inf], "volume", 
     128     "Second side of the parallelepiped"], 
     129    ["c_side", "Ang", 400, [0, inf], "volume", 
     130     "Larger side of the parallelepiped"], 
     131    ["theta", "degrees", 60, [-inf, inf], "orientation", 
     132     "In plane angle"], 
     133    ["phi", "degrees", 60, [-inf, inf], "orientation", 
     134     "Out of plane angle"], 
     135    ["psi", "degrees", 60, [-inf, inf], "orientation", 
     136     "Rotation angle around its own c axis against q plane"], 
    137137    ] 
    138138 
    139 source = [ "lib/J1.c", "lib/gauss76.c", "parallelepiped.c" ] 
     139source = ["lib/J1.c", "lib/gauss76.c", "parallelepiped.c"] 
    140140 
    141141def ER(a_side, b_side, c_side): 
     
    148148    b = 0.5 * c_side 
    149149    t1 = a * a * b 
    150     t2 = 1.0 + (b/a)*(1.0+a/b/2.0)*(1.0+pi*a/b/2.0) 
     150    t2 = 1.0 + (b / a) * (1.0 + a / b / 2.0) * (1.0 + pi * a / b / 2.0) 
    151151    ddd = 3.0 * t1 * t2 
    152152 
    153     return 0.5 * (ddd)**(1./3.) 
     153    return 0.5 * (ddd) ** (1. / 3.) 
    154154 
    155155# parameters for demo 
     
    169169# For testing against the old sasview models, include the converted parameter 
    170170# names and the target sasview model name. 
    171 oldname='ParallelepipedModel' 
    172 oldpars=dict(theta='parallel_theta', phi='parallel_phi', psi='parallel_psi', 
    173              a_side='short_a', b_side='short_b', c_side='long_c', 
    174              sld='sldPipe', solvent_sld='sldSolv') 
     171oldname = 'ParallelepipedModel' 
     172oldpars = dict(theta='parallel_theta', phi='parallel_phi', psi='parallel_psi', 
     173               a_side='short_a', b_side='short_b', c_side='long_c', 
     174               sld='sldPipe', solvent_sld='sldSolv') 
    175175 
  • sasmodels/sasview_model.py

    r0a82216 rde0c4ba  
    2626try: 
    2727    from .kernelcl import load_model 
    28 except ImportError,exc: 
     28except ImportError, exc: 
    2929    warnings.warn(str(exc)) 
    3030    warnings.warn("using ctypes instead") 
     
    4141    will produce a class with a name compatible with SasView 
    4242    """ 
    43     model =  load_model(kernel_module, dtype=dtype) 
     43    model = load_model(kernel_module, dtype=dtype) 
    4444    def __init__(self, multfactor=1): 
    4545        SasviewModel.__init__(self, model) 
    4646    attrs = dict(__init__=__init__) 
    47     ConstructedModel = type(model.info[namestyle],  (SasviewModel,), attrs) 
     47    ConstructedModel = type(model.info[namestyle], (SasviewModel,), attrs) 
    4848    return ConstructedModel 
    4949 
     
    6969        self.dispersion = dict() 
    7070        partype = model.info['partype'] 
    71         for name,units,default,limits,ptype,description in model.info['parameters']: 
     71        for name, units, default, limits, ptype, description in model.info['parameters']: 
    7272            self.params[name] = default 
    73             self.details[name] = [units]+limits 
     73            self.details[name] = [units] + limits 
    7474 
    7575        for name in partype['pd-2d']: 
     
    8383        self.orientation_params = ( 
    8484            partype['orientation'] 
    85             + [n+'.width' for n in partype['orientation']] 
     85            + [n + '.width' for n in partype['orientation']] 
    8686            + partype['magnetic']) 
    8787        self.magnetic_params = partype['magnetic'] 
    88         self.fixed = [n+'.width' for n in partype['pd-2d']] 
     88        self.fixed = [n + '.width' for n in partype['pd-2d']] 
    8989        self.non_fittable = [] 
    9090 
    9191        ## independent parameter name and unit [string] 
    92         self.input_name = model.info.get("input_name","Q") 
    93         self.input_unit = model.info.get("input_unit","A^{-1}") 
    94         self.output_name = model.info.get("output_name","Intensity") 
    95         self.output_unit = model.info.get("output_unit","cm^{-1}") 
     92        self.input_name = model.info.get("input_name", "Q") 
     93        self.input_unit = model.info.get("input_unit", "A^{-1}") 
     94        self.output_name = model.info.get("output_name", "Intensity") 
     95        self.output_unit = model.info.get("output_unit", "cm^{-1}") 
    9696 
    9797        ## _persistency_dict is used by sas.perspectives.fitting.basepage 
     
    139139        # Look for dispersion parameters 
    140140        toks = name.split('.') 
    141         if len(toks)==2: 
     141        if len(toks) == 2: 
    142142            for item in self.dispersion.keys(): 
    143                 if item.lower()==toks[0].lower(): 
     143                if item.lower() == toks[0].lower(): 
    144144                    for par in self.dispersion[item]: 
    145145                        if par.lower() == toks[1].lower(): 
     
    149149            # Look for standard parameter 
    150150            for item in self.params.keys(): 
    151                 if item.lower()==name.lower(): 
     151                if item.lower() == name.lower(): 
    152152                    self.params[item] = value 
    153153                    return 
     
    164164        # Look for dispersion parameters 
    165165        toks = name.split('.') 
    166         if len(toks)==2: 
     166        if len(toks) == 2: 
    167167            for item in self.dispersion.keys(): 
    168                 if item.lower()==toks[0].lower(): 
     168                if item.lower() == toks[0].lower(): 
    169169                    for par in self.dispersion[item]: 
    170170                        if par.lower() == toks[1].lower(): 
     
    173173            # Look for standard parameter 
    174174            for item in self.params.keys(): 
    175                 if item.lower()==name.lower(): 
     175                if item.lower() == name.lower(): 
    176176                    return self.params[item] 
    177177 
     
    182182        Return a list of all available parameters for the model 
    183183        """ 
    184         list = self.params.keys() 
     184        param_list = self.params.keys() 
    185185        # WARNING: Extending the list with the dispersion parameters 
    186         list.extend(self.getDispParamList()) 
    187         return list 
     186        param_list.extend(self.getDispParamList()) 
     187        return param_list 
    188188 
    189189    def getDispParamList(self): 
     
    192192        """ 
    193193        # TODO: fix test so that parameter order doesn't matter 
    194         ret = ['%s.%s'%(d.lower(), p) 
     194        ret = ['%s.%s' % (d.lower(), p) 
    195195               for d in self._model.info['partype']['pd-2d'] 
    196196               for p in ('npts', 'nsigmas', 'width')] 
     
    212212        **DEPRECATED**: use calculate_Iq instead 
    213213        """ 
    214         if isinstance(x, (list,tuple)): 
     214        if isinstance(x, (list, tuple)): 
    215215            q, phi = x 
    216216            return self.calculate_Iq([q * math.cos(phi)], 
     
    230230        **DEPRECATED**: use calculate_Iq instead 
    231231        """ 
    232         if isinstance(x, (list,tuple)): 
    233             return self.calculate_Iq([float(x[0])],[float(x[1])])[0] 
     232        if isinstance(x, (list, tuple)): 
     233            return self.calculate_Iq([float(x[0])], [float(x[1])])[0] 
    234234        else: 
    235235            return self.calculate_Iq([float(x)])[0] 
     
    265265        :param qdist: ndarray of scalar q-values or list [qx,qy] where qx,qy are 1D ndarrays 
    266266        """ 
    267         if isinstance(qdist, (list,tuple)): 
     267        if isinstance(qdist, (list, tuple)): 
    268268            # Check whether we have a list of ndarrays [qx,qy] 
    269269            qx, qy = qdist 
    270270            partype = self._model.info['partype'] 
    271271            if not partype['orientation'] and not partype['magnetic']: 
    272                 return self.calculate_Iq(np.sqrt(qx**2+qy**2)) 
     272                return self.calculate_Iq(np.sqrt(qx ** 2 + qy ** 2)) 
    273273            else: 
    274274                return self.calculate_Iq(qx, qy) 
     
    279279 
    280280        else: 
    281             raise TypeError("evalDistribution expects q or [qx, qy], not %r"%type(qdist)) 
     281            raise TypeError("evalDistribution expects q or [qx, qy], not %r" % type(qdist)) 
    282282 
    283283    def calculate_Iq(self, *args): 
     
    313313            fv = ER(*values) 
    314314            #print values[0].shape, weights.shape, fv.shape 
    315             return np.sum(weights*fv) / np.sum(weights) 
     315            return np.sum(weights * fv) / np.sum(weights) 
    316316 
    317317    def calculate_VR(self): 
     
    327327            vol_pars = self._model.info['partype']['volume'] 
    328328            values, weights = self._dispersion_mesh(vol_pars) 
    329             whole,part = VR(*values) 
    330             return np.sum(weights*part)/np.sum(weights*whole) 
     329            whole, part = VR(*values) 
     330            return np.sum(weights * part) / np.sum(weights * whole) 
    331331 
    332332    def set_dispersion(self, parameter, dispersion): 
     
    373373 
    374374    def _get_weights(self, par): 
     375        """ 
     376            Return dispersion weights 
     377            :param par parameter name 
     378        """ 
    375379        from . import weights 
    376380 
     
    378382        limits = self._model.info['limits'] 
    379383        dis = self.dispersion[par] 
    380         v,w = weights.get_weights( 
     384        v, w = weights.get_weights( 
    381385            dis['type'], dis['npts'], dis['width'], dis['nsigmas'], 
    382386            self.params[par], limits[par], par in relative) 
    383         return v,w/w.max() 
    384  
     387        return v, w / w.max() 
     388 
  • sasmodels/bumps_model.py

    r5134b2c r9890053  
    437437    data = load_data('DEC07086.DAT') 
    438438    set_beam_stop(data, 0.004) 
    439     plot_data(data) 
     439    plot_data(data, data.data) 
    440440    import matplotlib.pyplot as plt; plt.show() 
    441441 
  • sasmodels/core.py

    r84e01d2 r9890053  
    5353    return v,w/np.sum(w) 
    5454 
     55def dispersion_mesh(pars): 
     56    """ 
     57    Create a mesh grid of dispersion parameters and weights. 
     58 
     59    Returns [p1,p2,...],w where pj is a vector of values for parameter j 
     60    and w is a vector containing the products for weights for each 
     61    parameter set in the vector. 
     62    """ 
     63    values, weights = zip(*pars) 
     64    if len(values) > 1: 
     65        values = [v.flatten() for v in np.meshgrid(*values)] 
     66        weights = np.vstack([v.flatten() for v in np.meshgrid(*weights)]) 
     67        weights = np.prod(weights, axis=0) 
     68    return values, weights 
     69 
    5570def call_kernel(kernel, pars, cutoff=1e-5): 
    5671    fixed_pars = [pars.get(name, kernel.info['defaults'][name]) 
     
    5974    return kernel(fixed_pars, pd_pars, cutoff=cutoff) 
    6075 
     76def call_ER(kernel, pars): 
     77    ER = kernel.info.get('ER', None) 
     78    if ER is None: 
     79        return 1.0 
     80    else: 
     81        vol_pars = [get_weights(kernel, pars, name) 
     82                    for name in kernel.info['partype']['volume']] 
     83        values, weights = dispersion_mesh(vol_pars) 
     84        fv = ER(*values) 
     85        #print values[0].shape, weights.shape, fv.shape 
     86        return np.sum(weights*fv) / np.sum(weights) 
     87 
     88def call_VR(kernel, pars): 
     89    VR = kernel.info.get('VR', None) 
     90    if VR is None: 
     91        return 1.0 
     92    else: 
     93        vol_pars = [get_weights(kernel, pars, name) 
     94                    for name in kernel.info['partype']['volume']] 
     95        values, weights = dispersion_mesh(vol_pars) 
     96        whole,part = VR(*values) 
     97        return np.sum(weights*part)/np.sum(weights*whole) 
     98 
  • sasmodels/model_test.py

    r84e01d2 r9890053  
    11# -*- coding: utf-8 -*- 
    22""" 
    3 Created on Tue Feb 17 11:43:56 2015 
    4  
    5 @author: David 
     3Run model unit tests. 
     4 
     5Usage:: 
     6 
     7     python -m sasmodels.model_test [opencl|dll|opencl_and_dll] model1 model2 ... 
     8 
     9     if model1 is 'all', then all except the remaining models will be tested 
     10 
     11Each model is tested using the default parameters at q=0.1, (qx,qy)=(0.1,0.1), 
     12and the ER and VR are computed.  The return values at these points are not 
     13considered.  The test is only to verify that the models run to completion, 
     14and do not produce inf or NaN. 
     15 
     16Tests are defined with the *tests* attribute in the model.py file.  *tests* 
     17is a list of individual tests to run, where each test consists of the 
     18parameter values for the test, the q-values and the expected results.  For 
     19the effective radius test, the q-value should be 'ER'.  For the VR test, 
     20the q-value should be 'VR'.  For 1-D tests, either specify the q value or 
     21a list of q-values, and the corresponding I(q) value, or list of I(q) values. 
     22 
     23That is:: 
     24 
     25    tests = [ 
     26        [ {parameters}, q, I(q)], 
     27        [ {parameters}, [q], [I(q)] ], 
     28        [ {parameters}, [q1, q2, ...], [I(q1), I(q2), ...]], 
     29 
     30        [ {parameters}, (qx, qy), I(qx, Iqy)], 
     31        [ {parameters}, [(qx1, qy1), (qx2, qy2), ...], [I(qx1,qy1), I(qx2,qy2), ...], 
     32 
     33        [ {parameters}, 'ER', ER(pars) ], 
     34        [ {parameters}, 'VR', VR(pars) ], 
     35        ... 
     36    ] 
     37 
     38Parameters are *key:value* pairs, where key is one of the parameters of the 
     39model and value is the value to use for the test.  Any parameters not given 
     40in the parameter list will take on the default parameter value. 
     41 
     42Precision defaults to 5 digits (relative). 
    643""" 
    744 
     
    1350from .core import list_models, load_model_definition 
    1451from .core import load_model_cl, load_model_dll 
    15 from .core import make_kernel, call_kernel 
     52from .core import make_kernel, call_kernel, call_ER, call_VR 
    1653 
    1754def annotate_exception(exc, msg): 
     
    5491        model_definition = load_model_definition(model_name) 
    5592 
    56         smoke_tests = [[{},0.1,None],[{},(0.1,0.1),None]] 
     93        smoke_tests = [ 
     94            [{},0.1,None], 
     95            [{},(0.1,0.1),None], 
     96            [{},'ER',None], 
     97            [{},'VR',None], 
     98            ] 
    5799        tests = smoke_tests + getattr(model_definition, 'tests', []) 
    58100         
     
    102144                pars, Q, I = test 
    103145 
     146                if not isinstance(I, list): 
     147                    I = [I] 
    104148                if not isinstance(Q, list): 
    105149                    Q = [Q] 
    106                 if not isinstance(I, list): 
    107                     I = [I] 
    108                      
    109                 if isinstance(Q[0], tuple): 
     150 
     151                self.assertEqual(len(I), len(Q)) 
     152 
     153                if Q[0] == 'ER': 
     154                    Iq = [call_ER(kernel, pars)] 
     155                elif Q[0] == 'VR': 
     156                    Iq = [call_VR(kernel, pars)] 
     157                elif isinstance(Q[0], tuple): 
    110158                    Qx,Qy = zip(*Q) 
    111159                    Q_vectors = [np.array(Qx), np.array(Qy)] 
     160                    kernel = make_kernel(model, Q_vectors) 
     161                    Iq = call_kernel(kernel, pars) 
    112162                else: 
    113163                    Q_vectors = [np.array(Q)] 
    114  
    115                 self.assertEqual(len(I), len(Q)) 
    116  
    117                 kernel = make_kernel(model, Q_vectors) 
    118                 Iq = call_kernel(kernel, pars) 
     164                    kernel = make_kernel(model, Q_vectors) 
     165                    Iq = call_kernel(kernel, pars) 
    119166             
    120167                self.assertGreater(len(Iq), 0)     
     
    122169                 
    123170                for q, i, iq in zip(Q, I, Iq): 
    124                     if i is None: continue # smoke test --- make sure it runs 
    125                     err = abs(i - iq) 
    126                     nrm = abs(i) 
    127              
    128                     self.assertLess(err * 10**5, nrm, 'q:%s; expected:%s; actual:%s' % (q, i, iq)) 
     171                    if i is None: 
     172                        # smoke test --- make sure it runs and produces a value 
     173                        self.assertTrue(np.isfinite(iq), 'q:%s; not finite; actual:%s' % (q, iq)) 
     174                    else: 
     175                        err = abs(i - iq) 
     176                        nrm = abs(i) 
     177                        self.assertLess(err * 10**5, nrm, 'q:%s; expected:%s; actual:%s' % (q, i, iq)) 
    129178                     
    130179        except Exception,exc:  
  • sasmodels/models/barbell.py

    ra5d0d00 r9890053  
    127127source = [ "lib/J1.c", "lib/gauss76.c", "barbell.c" ] 
    128128 
    129 def ER(radius, length): 
    130     return 1.0 
    131  
    132129# parameters for demo 
    133130demo = dict( 
  • sasmodels/models/bcc.py

    r6272968 r9890053  
    128128source = [ "lib/J1.c", "lib/gauss150.c", "bcc.c" ] 
    129129 
    130 def ER(radius, length): 
    131     return 0 
    132  
    133130# parameters for demo 
    134131demo = dict( 
  • sasmodels/models/cylinder.py

    ra5d0d00 r9890053  
    172172 
    173173 
    174 # test values: 
    175 # [ 
    176 #   [ {parameters}, q, I(q)], 
    177 #   [ {parameters}, [q], [I(q)] ], 
    178 #   [ {parameters}, [q1, q2, ...], [I(q1), I(q2), ...]], 
    179  
    180 #   [ {parameters}, (qx, qy), I(qx, Iqy)], 
    181 #   [ {parameters}, [(qx1, qy1), (qx2, qy2), ...], [I(qx1,qy1), I(qx2,qy2), ...], 
    182 #   ... 
    183 # ] 
    184 # Precision defaults to 7 digits (relative) for single, 14 for double 
    185 # May want a limited precision version that checks for 8-n or 15-n digits respectively 
    186174qx,qy = 0.2*np.cos(2.5), 0.2*np.sin(2.5) 
    187175tests = [ 
  • sasmodels/models/fcc.py

    ra5d0d00 r9890053  
    103103source = [ "lib/J1.c", "lib/gauss150.c", "fcc.c" ] 
    104104 
    105 def ER(radius, length): 
    106     return 0 
    107  
    108105# parameters for demo 
    109106demo = dict( 
Note: See TracChangeset for help on using the changeset viewer.