Changeset 32398dc in sasmodels


Ignore:
Timestamp:
Nov 29, 2017 6:23:16 AM (6 years ago)
Author:
Paul Kienzle <pkienzle@…>
Branches:
master, core_shell_microgels, magnetic_model, ticket-1257-vesicle-product, ticket_1156, ticket_1265_superball, ticket_822_more_unit_tests
Children:
fa79f5c
Parents:
e65c3ba
Message:

remove sascomp support for sasview 3.x models

Location:
sasmodels
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • sasmodels/compare.py

    re65c3ba r32398dc  
    4343from .data import plot_theory, empty_data1D, empty_data2D, load_data 
    4444from .direct_model import DirectModel, get_mesh 
    45 from .convert import revert_name, revert_pars, constrain_new_to_old 
     45from .convert import revert_name, revert_pars 
    4646from .generate import FLOAT_RE 
    4747from .weights import plot_weights 
    4848 
     49# pylint: disable=unused-import 
    4950try: 
    5051    from typing import Optional, Dict, Any, Callable, Tuple 
    51 except Exception: 
     52except ImportError: 
    5253    pass 
    5354else: 
     
    5556    from .data import Data 
    5657    Calculator = Callable[[float], np.ndarray] 
     58# pylint: enable=unused-import 
    5759 
    5860USAGE = """ 
     
    9799    -single/-double/-half/-fast sets an OpenCL calculation engine 
    98100    -single!/-double!/-quad! sets an OpenMP calculation engine 
    99     -sasview sets the sasview calculation engine 
    100101 
    101102    === plotting === 
     
    237238        pass 
    238239 
    239     def __exit__(self, exc_type, exc_value, tb): 
     240    def __exit__(self, exc_type, exc_value, trace): 
    240241        # type: (Any, BaseException, Any) -> None 
    241         # TODO: better typing for __exit__ method 
    242242        np.random.set_state(self._state) 
    243243 
     
    258258    """ 
    259259    Add a beam stop of the given *radius*.  If *outer*, make an annulus. 
    260  
    261     Note: this function does not require sasview 
    262260    """ 
    263261    if hasattr(data, 'qx_data'): 
     
    625623    return pars 
    626624 
    627 # TODO: remove support for sasview 3.x models 
    628 def eval_sasview(model_info, data): 
    629     # type: (Modelinfo, Data) -> Calculator 
    630     """ 
    631     Return a model calculator using the pre-4.0 SasView models. 
    632     """ 
    633     # importing sas here so that the error message will be that sas failed to 
    634     # import rather than the more obscure smear_selection not imported error 
    635     import sas 
    636     import sas.models 
    637     from sas.models.qsmearing import smear_selection 
    638     from sas.models.MultiplicationModel import MultiplicationModel 
    639     from sas.models.dispersion_models import models as dispersers 
    640  
    641     def _get_model_class(name): 
    642         # type: (str) -> "sas.models.BaseComponent" 
    643         #print("new",sorted(_pars.items())) 
    644         __import__('sas.models.' + name) 
    645         ModelClass = getattr(getattr(sas.models, name, None), name, None) 
    646         if ModelClass is None: 
    647             raise ValueError("could not find model %r in sas.models"%name) 
    648         return ModelClass 
    649  
    650     # WARNING: ugly hack when handling model! 
    651     # Sasview models with multiplicity need to be created with the target 
    652     # multiplicity, so we cannot create the target model ahead of time for 
    653     # for multiplicity models.  Instead we store the model in a list and 
    654     # update the first element of that list with the new multiplicity model 
    655     # every time we evaluate. 
    656  
    657     # grab the sasview model, or create it if it is a product model 
    658     if model_info.composition: 
    659         composition_type, parts = model_info.composition 
    660         if composition_type == 'product': 
    661             P, S = [_get_model_class(revert_name(p))() for p in parts] 
    662             model = [MultiplicationModel(P, S)] 
    663         else: 
    664             raise ValueError("sasview mixture models not supported by compare") 
    665     else: 
    666         old_name = revert_name(model_info) 
    667         if old_name is None: 
    668             raise ValueError("model %r does not exist in old sasview" 
    669                              % model_info.id) 
    670         ModelClass = _get_model_class(old_name) 
    671         model = [ModelClass()] 
    672     model[0].disperser_handles = {} 
    673  
    674     # build a smearer with which to call the model, if necessary 
    675     smearer = smear_selection(data, model=model) 
    676     if hasattr(data, 'qx_data'): 
    677         q = np.sqrt(data.qx_data**2 + data.qy_data**2) 
    678         index = ((~data.mask) & (~np.isnan(data.data)) 
    679                  & (q >= data.qmin) & (q <= data.qmax)) 
    680         if smearer is not None: 
    681             smearer.model = model  # because smear_selection has a bug 
    682             smearer.accuracy = data.accuracy 
    683             smearer.set_index(index) 
    684             def _call_smearer(): 
    685                 smearer.model = model[0] 
    686                 return smearer.get_value() 
    687             theory = _call_smearer 
    688         else: 
    689             theory = lambda: model[0].evalDistribution([data.qx_data[index], 
    690                                                         data.qy_data[index]]) 
    691     elif smearer is not None: 
    692         theory = lambda: smearer(model[0].evalDistribution(data.x)) 
    693     else: 
    694         theory = lambda: model[0].evalDistribution(data.x) 
    695  
    696     def calculator(**pars): 
    697         # type: (float, ...) -> np.ndarray 
    698         """ 
    699         Sasview calculator for model. 
    700         """ 
    701         oldpars = revert_pars(model_info, pars) 
    702         # For multiplicity models, create a model with the correct multiplicity 
    703         control = oldpars.pop("CONTROL", None) 
    704         if control is not None: 
    705             # sphericalSLD has one fewer multiplicity.  This update should 
    706             # happen in revert_pars, but it hasn't been called yet. 
    707             model[0] = ModelClass(control) 
    708         # paying for parameter conversion each time to keep life simple, if not fast 
    709         for k, v in oldpars.items(): 
    710             if k.endswith('.type'): 
    711                 par = k[:-5] 
    712                 if v == 'gaussian': continue 
    713                 cls = dispersers[v if v != 'rectangle' else 'rectangula'] 
    714                 handle = cls() 
    715                 model[0].disperser_handles[par] = handle 
    716                 try: 
    717                     model[0].set_dispersion(par, handle) 
    718                 except Exception: 
    719                     exception.annotate_exception("while setting %s to %r" 
    720                                                  %(par, v)) 
    721                     raise 
    722  
    723  
    724         #print("sasview pars",oldpars) 
    725         for k, v in oldpars.items(): 
    726             name_attr = k.split('.')  # polydispersity components 
    727             if len(name_attr) == 2: 
    728                 par, disp_par = name_attr 
    729                 model[0].dispersion[par][disp_par] = v 
    730             else: 
    731                 model[0].setParam(k, v) 
    732         return theory() 
    733  
    734     calculator.engine = "sasview" 
    735     return calculator 
    736625 
    737626DTYPE_MAP = { 
     
    827716    than OpenCL. 
    828717    """ 
    829     if dtype == 'sasview': 
    830         return eval_sasview(model_info, data) 
    831     elif dtype is None or not dtype.endswith('!'): 
     718    if dtype is None or not dtype.endswith('!'): 
    832719        return eval_opencl(model_info, data, dtype=dtype, cutoff=cutoff) 
    833720    else: 
     
    1075962    'engine=', 
    1076963    'half', 'fast', 'single', 'double', 'single!', 'double!', 'quad!', 
    1077     'sasview',  # TODO: remove sasview 3.x support 
    1078964 
    1079965    # Output options 
     
    12581144        elif arg == '-double!': opts['engine'] = 'double!' 
    12591145        elif arg == '-quad!':   opts['engine'] = 'quad!' 
    1260         elif arg == '-sasview': opts['engine'] = 'sasview' 
    12611146        elif arg == '-edit':    opts['explore'] = True 
    12621147        elif arg == '-demo':    opts['use_demo'] = True 
  • sasmodels/compare_many.py

    rf72d70a r32398dc  
    2222from .compare import (randomize_pars, suppress_pd, make_data, 
    2323                      make_engine, get_pars, columnize, 
    24                       constrain_pars, constrain_new_to_old) 
     24                      constrain_pars) 
    2525 
    2626MODELS = core.list_models() 
     
    8080    'double!': 5e-14, 
    8181    'quad!': 5e-18, 
    82     'sasview': 5e-14, 
    8382} 
    8483def compare_instance(name, data, index, N=1, mono=True, cutoff=1e-5, 
    85                      base='sasview', comp='double'): 
     84                     base='single', comp='double'): 
    8685    r""" 
    8786    Compare the model under different calculation engines. 
     
    164163        print("Model %s %d"%(name, k+1), file=sys.stderr) 
    165164        seed = np.random.randint(1e6) 
    166         pars_i = randomize_pars(model_info, pars, seed) 
     165        np.random.seed(seed) 
     166        pars_i = randomize_pars(model_info, pars) 
    167167        constrain_pars(model_info, pars_i) 
    168         if 'sasview' in (base, comp): 
    169             constrain_new_to_old(model_info, pars_i) 
    170168        if mono: 
    171169            pars_i = suppress_pd(pars_i) 
  • sasmodels/convert.py

    re65c3ba r32398dc  
    66import math 
    77import warnings 
     8 
     9import numpy as np 
    810 
    911from .conversion_table import CONVERSION_TABLE 
     
    146148    return newpars 
    147149 
    148 def _conversion_target(model_name, version=(3,1,2)): 
     150def _conversion_target(model_name, version=(3, 1, 2)): 
    149151    """ 
    150152    Find the sasmodel name which translates into the sasview name. 
     
    600602 
    601603    pars = compare.get_pars(model_info, use_demo=False) 
    602     pars = compare.randomize_pars(model_info, pars, seed=seed) 
     604    if seed is not None: 
     605        np.random.seed(seed) 
     606    pars = compare.randomize_pars(model_info, pars) 
    603607    if name == "teubner_strey": 
    604608        # T-S model is underconstrained, so fix the assumptions. 
Note: See TracChangeset for help on using the changeset viewer.