Changeset aa4946b in sasmodels


Ignore:
Timestamp:
Mar 11, 2015 9:15:40 PM (9 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:
af1d68c
Parents:
49d1d42f
Message:

refactor so kernels are loaded via core.load_model

Files:
9 edited

Legend:

Unmodified
Added
Removed
  • compare.py

    r750ffa5 raa4946b  
    1010 
    1111from sasmodels.bumps_model import BumpsModel, plot_data, tic 
    12 try: from sasmodels import kernelcl 
    13 except: from sasmodels import kerneldll as kernelcl 
     12from sasmodels import core 
    1413from sasmodels import kerneldll 
    1514from sasmodels.convert import revert_model 
     
    2221 
    2322 
    24 def sasview_model(modelname, **pars): 
     23def sasview_model(model_definition, **pars): 
    2524    """ 
    2625    Load a sasview model given the model name. 
     
    2827    # convert model parameters from sasmodel form to sasview form 
    2928    #print "old",sorted(pars.items()) 
    30     modelname, pars = revert_model(modelname, pars) 
     29    modelname, pars = revert_model(model_definition, pars) 
    3130    #print "new",sorted(pars.items()) 
    3231    sas = __import__('sas.models.'+modelname) 
     
    4847            model.setParam(k, v) 
    4948    return model 
    50  
    51 def load_opencl(modelname, dtype='single'): 
    52     sasmodels = __import__('sasmodels.models.'+modelname) 
    53     module = getattr(sasmodels.models, modelname, None) 
    54     kernel = kernelcl.load_model(module, dtype=dtype) 
    55     return kernel 
    56  
    57 def load_ctypes(modelname, dtype='single'): 
    58     sasmodels = __import__('sasmodels.models.'+modelname) 
    59     module = getattr(sasmodels.models, modelname, None) 
    60     kernel = kerneldll.load_model(module, dtype=dtype) 
    61     return kernel 
    6249 
    6350def randomize(p, v): 
     
    120107    return value, average_time 
    121108 
    122 def eval_opencl(name, pars, data, dtype='single', Nevals=1, cutoff=0): 
     109def eval_opencl(model_definition, pars, data, dtype='single', Nevals=1, cutoff=0): 
    123110    try: 
    124         model = load_opencl(name, dtype=dtype) 
     111        model = core.load_model(model_definition, dtype=dtype, platform="ocl") 
    125112    except Exception,exc: 
    126113        print exc 
    127114        print "... trying again with single precision" 
    128         model = load_opencl(name, dtype='single') 
     115        model = core.load_model(model_definition, dtype='single', platform="ocl") 
    129116    problem = BumpsModel(data, model, cutoff=cutoff, **pars) 
    130117    toc = tic() 
     
    136123    return value, average_time 
    137124 
    138 def eval_ctypes(name, pars, data, dtype='double', Nevals=1, cutoff=0): 
    139     model = load_ctypes(name, dtype=dtype) 
     125def eval_ctypes(model_definition, pars, data, dtype='double', Nevals=1, cutoff=0): 
     126    model = core.load_model(model_definition, dtype=dtype, platform="dll") 
    140127    problem = BumpsModel(data, model, cutoff=cutoff, **pars) 
    141128    toc = tic() 
     
    193180        print "pars",parlist(pars) 
    194181 
     182    model_definition = core.load_model_definition(name) 
    195183    # OpenCl calculation 
    196184    if Nocl > 0: 
    197         ocl, ocl_time = eval_opencl(name, pars, data, dtype, Nocl) 
     185        ocl, ocl_time = eval_opencl(model_definition, pars, data, 
     186                                    dtype=dtype, cutoff=cutoff, Nevals=Nocl) 
    198187        print "opencl t=%.1f ms, intensity=%.0f"%(ocl_time, sum(ocl[index])) 
    199188        #print max(ocl), min(ocl) 
     
    201190    # ctypes/sasview calculation 
    202191    if Ncpu > 0 and "-ctypes" in opts: 
    203         cpu, cpu_time = eval_ctypes(name, pars, data, dtype=dtype, cutoff=cutoff, Nevals=Ncpu) 
     192        cpu, cpu_time = eval_ctypes(model_definition, pars, data, 
     193                                    dtype=dtype, cutoff=cutoff, Nevals=Ncpu) 
    204194        comp = "ctypes" 
    205195        print "ctypes t=%.1f ms, intensity=%.0f"%(cpu_time, sum(cpu[index])) 
    206196    elif Ncpu > 0: 
    207         cpu, cpu_time = eval_sasview(name, pars, data, Ncpu) 
     197        cpu, cpu_time = eval_sasview(model_definition, pars, data, Ncpu) 
    208198        comp = "sasview" 
    209199        print "sasview t=%.1f ms, intensity=%.0f"%(cpu_time, sum(cpu[index])) 
     
    219209        #bad = (relerr>1e-4) 
    220210        #print relerr[bad],cpu[bad],ocl[bad],data.qx_data[bad],data.qy_data[bad] 
    221         print "max(|ocl-%s|)"%comp, max(abs(resid[index])) 
    222         print "max(|(ocl-%s)/%s|)"%(comp,comp), max(abs(relerr[index])) 
    223         p98 = int(len(relerr[index])*0.98) 
    224         print "98%% (|(ocl-%s)/%s|) <"%(comp,comp), np.sort(abs(relerr[index]))[p98] 
    225  
     211        def stats(label,err): 
     212            sorted_err = np.sort(abs(err)) 
     213            p50 = int((len(err)-1)*0.50) 
     214            p98 = int((len(err)-1)*0.98) 
     215            data = [ 
     216                "max:%.3e"%sorted_err[-1], 
     217                "median:%.3e"%sorted_err[p50], 
     218                "98%%:%.3e"%sorted_err[p98], 
     219                "rms:%.3e"%np.sqrt(np.mean(err**2)), 
     220                "zero-offset:%+.3e"%np.mean(err), 
     221                ] 
     222            print label,"  ".join(data) 
     223        stats("|ocl-%s|"%comp+(" "*(3+len(comp))), resid[index]) 
     224        stats("|(ocl-%s)/%s|"%(comp,comp), relerr[index]) 
    226225 
    227226    # Plot if requested 
  • sasmodels/bumps_model.py

    r63b32bb raa4946b  
    11""" 
    2 Sasmodels core. 
     2Wrap sasmodels for direct use by bumps. 
    33""" 
     4 
    45import datetime 
    56 
    6 from sasmodels import sesans 
     7import numpy as np 
     8 
     9from . import sesans 
    710 
    811# CRUFT python 2.6 
     
    1518        """Return number date-time delta as number seconds""" 
    1619        return dt.total_seconds() 
    17  
    18 import numpy as np 
    19  
    20 try: 
    21     from .kernelcl import load_model as _loader 
    22 except RuntimeError, exc: 
    23     import warnings 
    24     warnings.warn(str(exc)) 
    25     warnings.warn("OpenCL not available --- using ctypes instead") 
    26     from .kerneldll import load_model as _loader 
    27  
    28 def load_model(modelname, dtype='single'): 
    29     """ 
    30     Load model by name. 
    31     """ 
    32     sasmodels = __import__('sasmodels.models.' + modelname) 
    33     module = getattr(sasmodels.models, modelname, None) 
    34     model = _loader(module, dtype=dtype) 
    35     return model 
    3620 
    3721 
     
    263247    *data* is the data to be fitted. 
    264248 
    265     *model* is the SAS model, e.g., from :func:`gen.opencl_model`. 
     249    *model* is the SAS model from :func:`core.load_model`. 
    266250 
    267251    *cutoff* is the integration cutoff, which avoids computing the 
     
    280264        self.model = model 
    281265        self.cutoff = cutoff 
    282 # TODO       if  isinstance(data,SESANSData1D) 
    283266        if hasattr(data, 'lam'): 
    284267            self.data_type = 'sesans' 
     
    431414    def _get_weights(self, par): 
    432415        """ 
    433             Get parameter dispersion weights 
     416        Get parameter dispersion weights 
    434417        """ 
    435418        from . import weights 
  • sasmodels/convert.py

    r3c56da87 raa4946b  
    5151                for p,v in pars.items()) 
    5252 
    53 def revert_model(name, pars): 
     53def revert_model(model_definition, pars): 
    5454    """ 
    5555    Convert model from new style parameter names to old style. 
    5656    """ 
    57     __import__('sasmodels.models.'+name) 
    58     from . import models 
    59     model = getattr(models, name, None) 
    60     mapping = model.oldpars 
    61     oldname = model.oldname 
     57    mapping = model_definition.oldpars 
     58    oldname = model_definition.oldname 
    6259    oldpars = _rename_pars(_unscale_sld(pars), mapping) 
    6360    return oldname, oldpars 
  • sasmodels/core.py

    r3c56da87 raa4946b  
    1 __all__ = ["list_models", "load_model_cl", "load_model_dll", 
    2            "load_model_definition", ] 
     1""" 
     2Core model handling routines. 
     3""" 
     4__all__ = ["list_models", "load_model_definition",  "precompile_dll", 
     5           "load_model", "make_kernel", "call_kernel", "call_ER", "call_VR" ] 
    36 
    47from os.path import basename, dirname, join as joinpath 
     
    912from . import models 
    1013from . import weights 
     14from . import generate 
    1115 
     16from . import kernelpy 
     17from . import kerneldll 
    1218try: 
    13     from .kernelcl import load_model as load_model_cl 
     19    from . import kernelcl 
     20    HAVE_OPENCL = True 
    1421except: 
    15     # pylint: disable=invalid-name 
    16     load_model_cl = None 
    17 from .kerneldll import load_model as load_model_dll 
     22    HAVE_OPENCL = False 
     23 
    1824 
    1925def list_models(): 
     26    """ 
     27    Return the list of available models on the model path. 
     28    """ 
    2029    root = dirname(__file__) 
    2130    files = sorted(glob(joinpath(root, 'models', "[a-zA-Z]*.py"))) 
     
    2332    return available_models 
    2433 
     34 
    2535def load_model_definition(model_name): 
     36    """ 
     37    Load a model definition given the model name. 
     38    """ 
    2639    __import__('sasmodels.models.'+model_name) 
    2740    model_definition = getattr(models, model_name, None) 
    2841    return model_definition 
     42 
     43 
     44def precompile_dll(model_name, dtype="double"): 
     45    """ 
     46    Precompile the dll for a model. 
     47 
     48    Returns the path to the compiled model. 
     49 
     50    This can be used when build the windows distribution of sasmodels 
     51    (which may be missing the OpenCL driver and the dll compiler), or 
     52    otherwise sharing models with windows users who do not have a compiler. 
     53 
     54    See :func:`sasmodels.kerneldll.make_dll` for details on controlling the 
     55    dll path and the allowed floating point precision. 
     56    """ 
     57    model_definition = load_model_definition(model_name) 
     58    source, info = generate.make(model_definition) 
     59    return kerneldll.make_dll(source, info, dtype=dtype) 
     60 
     61 
     62def load_model(model_definition, dtype="single", platform="ocl"): 
     63    """ 
     64    Prepare the model for the default execution platform. 
     65 
     66    This will return an OpenCL model, a DLL model or a python model depending 
     67    on the model and the computing platform. 
     68 
     69    *dtype* indicates whether the model should use single or double precision 
     70    for the calculation. Any valid numpy single or double precision identifier 
     71    is valid, such as 'single', 'f', 'f32', or np.float32 for single, or 
     72    'double', 'd', 'f64'  and np.float64 for double. 
     73 
     74    *platform* should be "dll" to force the dll to be used for C models, 
     75    otherwise it uses the default "ocl". 
     76    """ 
     77    source, info = generate.make(model_definition) 
     78    if callable(info.get('Iq', None)): 
     79        return kernelpy.PyModel(info) 
     80 
     81    ## for debugging: 
     82    ##  1. uncomment open().write so that the source will be saved next time 
     83    ##  2. run "python -m sasmodels.direct_model $MODELNAME" to save the source 
     84    ##  3. recomment the open.write() and uncomment open().read() 
     85    ##  4. rerun "python -m sasmodels.direct_model $MODELNAME" 
     86    ##  5. uncomment open().read() so that source will be regenerated from model 
     87    # open(info['name']+'.c','w').write(source) 
     88    # source = open(info['name']+'.cl','r').read() 
     89 
     90    dtype = np.dtype(dtype) 
     91    if (platform=="dll" 
     92            or not HAVE_OPENCL 
     93            or (dtype == np.float64 and not kernelcl.environment().has_double)): 
     94        return kerneldll.load_dll(source, info, dtype) 
     95    else: 
     96        return kernelcl.GpuModel(source, info, dtype) 
    2997 
    3098def make_kernel(model, q_vectors): 
     
    40108    in *pars*. 
    41109 
    42     Searches for "name", "name_pd", "name_pd_type", "name_pd_n", "name_pd_sigma" 
     110    Uses "name", "name_pd", "name_pd_type", "name_pd_n", "name_pd_sigma" 
     111    from the *pars* dictionary for parameter value and parameter dispersion. 
    43112    """ 
    44113    relative = name in info['partype']['pd-rel'] 
     
    69138    return value, weight 
    70139 
    71 def call_kernel(kernel, pars, cutoff=1e-5): 
     140def call_kernel(kernel, pars, cutoff=0): 
     141    """ 
     142    Call *kernel* returned from :func:`make_kernel` with parameters *pars*. 
     143 
     144    *cutoff* is the limiting value for the product of dispersion weights used 
     145    to perform the multidimensional dispersion calculation more quickly at a 
     146    slight cost to accuracy. The default value of *cutoff=0* integrates over 
     147    the entire dispersion cube.  Using *cutoff=1e-5* can be 50% faster, but 
     148    with an error of about 1%, which is usually less than the measurement 
     149    uncertainty. 
     150    """ 
    72151    fixed_pars = [pars.get(name, kernel.info['defaults'][name]) 
    73152                  for name in kernel.fixed_pars] 
     
    76155 
    77156def call_ER(info, pars): 
     157    """ 
     158    Call the model ER function using *pars*. 
     159 
     160    *info* is either *model.info* if you have a loaded model, or *kernel.info* 
     161    if you have a model kernel prepared for evaluation. 
     162    """ 
    78163    ER = info.get('ER', None) 
    79164    if ER is None: 
     
    88173 
    89174def call_VR(info, pars): 
     175    """ 
     176    Call the model VR function using *pars*. 
     177 
     178    *info* is either *model.info* if you have a loaded model, or *kernel.info* 
     179    if you have a model kernel prepared for evaluation. 
     180    """ 
    90181    VR = info.get('VR', None) 
    91182    if VR is None: 
  • sasmodels/direct_model.py

    rf734e7d raa4946b  
    33import numpy as np 
    44 
    5 from .core import load_model_definition, make_kernel, call_kernel 
    6 from .core import load_model_cl as load_model 
    7 if load_model is None: 
    8     warnings.warn("unable to load opencl; using ctypes instead") 
    9     from .core import load_model_dll as load_model 
     5from .core import load_model_definition, load_model, make_kernel 
     6from .core import call_kernel, call_ER, call_VR 
    107 
    118class DirectModel: 
    12     def __init__(self, name, q_vectors, dtype='single'): 
     9    def __init__(self, name, q_vectors=None, dtype='single'): 
    1310        self.model_definition = load_model_definition(name) 
    1411        self.model = load_model(self.model_definition, dtype=dtype) 
    15         q_vectors = [np.ascontiguousarray(q,dtype=dtype) for q in q_vectors] 
    16         self.kernel = make_kernel(self.model, q_vectors) 
     12        if q_vectors is not None: 
     13            q_vectors = [np.ascontiguousarray(q,dtype=dtype) for q in q_vectors] 
     14            self.kernel = make_kernel(self.model, q_vectors) 
    1715    def __call__(self, **pars): 
    1816        return call_kernel(self.kernel, pars) 
     17    def ER(self, **pars): 
     18        return call_ER(self.model.info, pars) 
     19    def VR(self, **pars): 
     20        return call_VR(self.model.info, pars) 
    1921 
    2022def demo(): 
     
    2426        sys.exit(1) 
    2527    model_name = sys.argv[1] 
    26     values = [float(v) for v in sys.argv[2].split(',')] 
    27     if len(values) == 1: 
    28         q = values[0] 
    29         q_vectors = [[q]] 
    30     elif len(values) == 2: 
    31         qx,qy = values 
    32         q_vectors = [[qx],[qy]] 
     28    call = sys.argv[2].upper() 
     29    if call in ("ER","VR"): 
     30        q_vectors = None 
    3331    else: 
    34         print "use q or qx,qy" 
    35         sys.exit(1) 
     32        values = [float(v) for v in sys.argv[2].split(',')] 
     33        if len(values) == 1: 
     34            q = values[0] 
     35            q_vectors = [[q]] 
     36        elif len(values) == 2: 
     37            qx,qy = values 
     38            q_vectors = [[qx],[qy]] 
     39        else: 
     40            print "use q or qx,qy or ER or VR" 
     41            sys.exit(1) 
    3642    model = DirectModel(model_name, q_vectors) 
    3743    pars = dict((k,float(v)) 
    3844                for pair in sys.argv[3:] 
    3945                for k,v in [pair.split('=')]) 
    40     Iq = model(**pars) 
    41     print Iq[0] 
     46    if call == "ER": 
     47        print model.ER(**pars) 
     48    elif call == "VR": 
     49        print model.VR(**pars) 
     50    else: 
     51        Iq = model(**pars) 
     52        print Iq[0] 
    4253 
    4354if __name__ == "__main__": 
  • sasmodels/kernelcl.py

    r63b32bb raa4946b  
    5555MAX_LOOPS = 2048 
    5656 
    57 def load_model(kernel_module, dtype="single"): 
     57def _load_model(kernel_module, dtype="single"): 
    5858    """ 
    5959    Load the OpenCL model defined by *kernel_module*. 
     
    6262    so models can be defined without using too many resources. 
    6363    """ 
     64    raise DeprecationWarning 
    6465    source, info = generate.make(kernel_module) 
    6566    if callable(info.get('Iq', None)): 
  • sasmodels/kerneldll.py

    r63b32bb raa4946b  
    5454 
    5555 
    56 def load_model(kernel_module, dtype="double"): 
     56def make_dll(source, info, dtype="double"): 
    5757    """ 
    5858    Load the compiled model defined by *kernel_module*. 
     
    6060    Recompile if any files are newer than the model file. 
    6161 
    62     *dtype* is ignored.  Compiled files are always double. 
    63  
    64     The DLL is not loaded until the kernel is called so models an 
     62    *dtype* is a numpy floating point precision specifier indicating whether 
     63    the model should be single or double precision.  The default is double 
     64    precision. 
     65 
     66    The DLL is not loaded until the kernel is called so models can 
    6567    be defined without using too many resources. 
     68 
     69    Set *sasmodels.kerneldll.DLL_PATH* to the compiled dll output path. 
     70    The default is the system temporary directory. 
     71 
     72    Set *sasmodels.ALLOW_SINGLE_PRECISION_DLLS* to True if single precision 
     73    models are allowed as DLLs. 
    6674    """ 
    6775    if not ALLOW_SINGLE_PRECISION_DLLS: dtype = "double"   # Force 64-bit dll 
    6876    dtype = np.dtype(dtype) 
    6977 
    70     source, info = generate.make(kernel_module) 
    7178    if callable(info.get('Iq',None)): 
    7279        return PyModel(info) 
     
    7986 
    8087    source_files = generate.sources(info) + [info['filename']] 
    81     dllpath = dll_path(info, dtype) 
     88    dll= dll_path(info, dtype) 
    8289    newest = max(os.path.getmtime(f) for f in source_files) 
    83     if not os.path.exists(dllpath) or os.path.getmtime(dllpath)<newest: 
     90    if not os.path.exists(dll) or os.path.getmtime(dll)<newest: 
    8491        # Replace with a proper temp file 
    8592        fid, filename = tempfile.mkstemp(suffix=".c",prefix=tempfile_prefix) 
    8693        os.fdopen(fid,"w").write(source) 
    87         command = COMPILE%{"source":filename, "output":dllpath} 
     94        command = COMPILE%{"source":filename, "output":dll} 
    8895        print "Compile command:",command 
    8996        status = os.system(command) 
    90         if status != 0: 
     97        if status != 0 or not os.path.exists(dll): 
    9198            raise RuntimeError("compile failed.  File is in %r"%filename) 
    9299        else: 
    93100            ## uncomment the following to keep the generated c file 
    94             #os.unlink(filename); print "saving compiled file in %r"%filename 
    95             pass 
    96     return DllModel(dllpath, info, dtype=dtype) 
     101            os.unlink(filename); print "saving compiled file in %r"%filename 
     102    return dll 
     103 
     104 
     105def load_dll(source, info, dtype="double"): 
     106    """ 
     107    Create and load a dll corresponding to the source,info pair returned 
     108    from :func:`sasmodels.generate.make` compiled for the target precision. 
     109 
     110    See :func:`make_dll` for details on controlling the dll path and the 
     111    allowed floating point precision. 
     112    """ 
     113    filename = make_dll(source, info, dtype=dtype) 
     114    return DllModel(filename, info, dtype=dtype) 
    97115 
    98116 
  • sasmodels/model_test.py

    ra217f7d raa4946b  
    5050import numpy as np 
    5151 
    52 from .core import list_models, load_model_definition 
    53 from .core import load_model_cl, load_model_dll 
     52from .core import list_models, load_model_definition, load_model, HAVE_OPENCL 
    5453from .core import make_kernel, call_kernel, call_ER, call_VR 
     54 
    5555 
    5656def annotate_exception(exc, msg): 
     
    8080            exc.args = (" ".join((str(exc),msg)),) 
    8181 
     82 
    8283def make_suite(loaders, models): 
    8384 
     
    113114 
    114115            # test using opencl if desired 
    115             if not ispy and ('opencl' in loaders and load_model_cl): 
     116            if not ispy and ('opencl' in loaders and HAVE_OPENCL): 
    116117                test_name = "Model: %s, Kernel: OpenCL"%model_name 
    117118                test_method = "test_%s_opencl" % model_name 
    118119                test = ModelTestCase(test_name, model_definition, 
    119                                      load_model_cl, tests, test_method) 
     120                                     tests, test_method, 
     121                                     platform="ocl", dtype='single') 
    120122                #print "defining", test_name 
    121123                suite.addTest(test) 
    122124 
    123125            # test using dll if desired 
    124             if ispy or ('dll' in loaders and load_model_dll): 
     126            if ispy or 'dll' in loaders: 
    125127                test_name = "Model: %s, Kernel: dll"%model_name 
    126128                test_method = "test_%s_dll" % model_name 
    127129                test = ModelTestCase(test_name, model_definition, 
    128                                      load_model_dll, tests, test_method) 
     130                                     tests, test_method, 
     131                                     platform="dll", dtype="double") 
    129132                suite.addTest(test) 
    130133 
    131134    return suite 
     135 
    132136 
    133137def _hide_model_case_from_nosetests(): 
    134138    class ModelTestCase(unittest.TestCase): 
    135         def __init__(self, test_name, definition, loader, tests, test_method): 
     139        def __init__(self, test_name, definition, tests, test_method, 
     140                     platform, dtype): 
    136141            self.test_name = test_name 
    137142            self.definition = definition 
    138             self.loader = loader 
    139143            self.tests = tests 
     144            self.platform = platform 
     145            self.dtype = dtype 
    140146 
    141147            setattr(self, test_method, self._runTest) 
     
    144150        def _runTest(self): 
    145151            try: 
    146                 model = self.loader(self.definition) 
     152                model = load_model(self.definition, dtype=self.dtype, 
     153                                   platform=self.platform) 
    147154                for test in self.tests: 
    148155                    self._run_one_test(model, test) 
     
    195202 
    196203def main(): 
     204    """ 
     205    Run tests given is sys.argv. 
     206 
     207    Returns 0 if success or 1 if any tests fail. 
     208    """ 
    197209    models = sys.argv[1:] 
    198210    if models and models[0] == 'opencl': 
    199         if load_model_cl is None: 
     211        if not HAVE_OPENCL: 
    200212            print >>sys.stderr, "opencl is not available" 
    201213            return 1 
     
    207219        models = models[1:] 
    208220    elif models and models[0] == 'opencl_and_dll': 
    209         if load_model_cl is None: 
    210             print >>sys.stderr, "opencl is not available" 
    211             return 1 
    212221        loaders = ['opencl', 'dll'] 
    213222        models = models[1:] 
     
    225234 
    226235 
    227 # let nosetests sniff out the tests 
    228236def model_tests(): 
     237    """ 
     238    Test runner visible to nosetests. 
     239 
     240    Run "nosetests sasmodels" on the command line to invoke it. 
     241    """ 
    229242    tests = make_suite(['opencl','dll'],['all']) 
    230243    for test_i in tests: 
    231244        yield test_i._runTest 
    232245 
     246 
    233247if __name__ == "__main__": 
    234248    sys.exit(main()) 
  • sasmodels/sasview_model.py

    r63b32bb raa4946b  
    1414""" 
    1515 
    16 # TODO: add a sasview=>sasmodels parameter translation layer 
    17 # this will allow us to use the new sasmodels as drop in replacements, and 
    18 # delay renaming parameters until all models have been converted. 
    19  
    2016import math 
    2117from copy import deepcopy 
     
    2420import numpy as np 
    2521 
    26 try: 
    27     from .kernelcl import load_model 
    28 except ImportError, exc: 
    29     warnings.warn(str(exc)) 
    30     warnings.warn("using ctypes instead") 
    31     from .kerneldll import load_model 
    32  
    33  
    34 def make_class(kernel_module, dtype='single', namestyle='name'): 
     22from . import core 
     23 
     24def make_class(model_definition, dtype='single', namestyle='name'): 
    3525    """ 
    3626    Load the sasview model defined in *kernel_module*. 
     
    3828    Returns a class that can be used directly as a sasview model. 
    3929 
    40     Defaults to using the new name for a model. Setting namestyle='name' 
    41     will produce a class with a name compatible with SasView 
     30    Defaults to using the new name for a model.  Setting 
     31    *namestyle='oldname'* will produce a class with a name 
     32    compatible with SasView. 
    4233    """ 
    43     model = load_model(kernel_module, dtype=dtype) 
     34    model = core.load_model(model_definition, dtype=dtype) 
    4435    def __init__(self, multfactor=1): 
    4536        SasviewModel.__init__(self, model) 
     
    313304            return 1.0 
    314305        else: 
    315             vol_pars = self._model.info['partype']['volume'] 
    316             values, weights = self._dispersion_mesh(vol_pars) 
     306            values, weights = self._dispersion_mesh() 
    317307            fv = ER(*values) 
    318308            #print values[0].shape, weights.shape, fv.shape 
     
    329319            return 1.0 
    330320        else: 
    331             vol_pars = self._model.info['partype']['volume'] 
    332             values, weights = self._dispersion_mesh(vol_pars) 
     321            values, weights = self._dispersion_mesh() 
    333322            whole, part = VR(*values) 
    334323            return np.sum(weights * part) / np.sum(weights * whole) 
     
    362351            raise ValueError("%r is not a dispersity or orientation parameter") 
    363352 
    364     def _dispersion_mesh(self, pars): 
     353    def _dispersion_mesh(self): 
    365354        """ 
    366355        Create a mesh grid of dispersion parameters and weights. 
     
    370359        parameter set in the vector. 
    371360        """ 
    372         values, weights = zip(*[self._get_weights(p) for p in pars]) 
    373         values = [v.flatten() for v in np.meshgrid(*values)] 
    374         weights = np.vstack([v.flatten() for v in np.meshgrid(*weights)]) 
    375         weights = np.prod(weights, axis=0) 
    376         return values, weights 
     361        pars = self._model.info['partype']['volume'] 
     362        return core.dispersion_mesh([self._get_weights(p) for p in pars]) 
    377363 
    378364    def _get_weights(self, par): 
Note: See TracChangeset for help on using the changeset viewer.