Changeset 110f69c in sasmodels for sasmodels/compare.py


Ignore:
Timestamp:
Nov 28, 2017 1:17:57 PM (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:
e65c3ba
Parents:
167d0f1
Message:

lint

File:
1 edited

Legend:

Unmodified
Added
Removed
  • sasmodels/compare.py

    r3bfd924 r110f69c  
    150150kerneldll.ALLOW_SINGLE_PRECISION_DLLS = True 
    151151 
    152 # list of math functions for use in evaluating parameters 
    153 MATH = dict((k,getattr(math, k)) for k in dir(math) if not k.startswith('_')) 
     152def build_math_context(): 
     153    # type: () -> Dict[str, Callable] 
     154    """build dictionary of functions from math module""" 
     155    return dict((k, getattr(math, k)) 
     156                for k in dir(math) if not k.startswith('_')) 
     157 
     158#: list of math functions for use in evaluating parameters 
     159MATH = build_math_context() 
    154160 
    155161# CRUFT python 2.6 
     
    231237        pass 
    232238 
    233     def __exit__(self, exc_type, exc_value, traceback): 
     239    def __exit__(self, exc_type, exc_value, tb): 
    234240        # type: (Any, BaseException, Any) -> None 
    235241        # TODO: better typing for __exit__ method 
     
    374380 
    375381def _random_pd(model_info, pars): 
     382    # type: (ModelInfo, Dict[str, float]) -> None 
     383    """ 
     384    Generate a random dispersity distribution for the model. 
     385 
     386    1% no shape dispersity 
     387    85% single shape parameter 
     388    13% two shape parameters 
     389    1% three shape parameters 
     390 
     391    If oriented, then put dispersity in theta, add phi and psi dispersity 
     392    with 10% probability for each. 
     393    """ 
    376394    pd = [p for p in model_info.parameters.kernel_parameters if p.polydisperse] 
    377395    pd_volume = [] 
     
    444462        value = pars[p.name] 
    445463        if p.units == 'Ang' and value > maxdim: 
    446             pars[p.name] = maxdim*10**np.random.uniform(-3,0) 
     464            pars[p.name] = maxdim*10**np.random.uniform(-3, 0) 
    447465 
    448466def constrain_pars(model_info, pars): 
     
    490508        if pars['radius'] < pars['thick_string']: 
    491509            pars['radius'], pars['thick_string'] = pars['thick_string'], pars['radius'] 
    492         pass 
    493510 
    494511    elif name == 'rpa': 
     
    608625    return pars 
    609626 
     627# TODO: remove support for sasview 3.x models 
    610628def eval_sasview(model_info, data): 
    611629    # type: (Modelinfo, Data) -> Calculator 
     
    621639    from sas.models.dispersion_models import models as dispersers 
    622640 
    623     def get_model_class(name): 
     641    def _get_model_class(name): 
    624642        # type: (str) -> "sas.models.BaseComponent" 
    625643        #print("new",sorted(_pars.items())) 
     
    641659        composition_type, parts = model_info.composition 
    642660        if composition_type == 'product': 
    643             P, S = [get_model_class(revert_name(p))() for p in parts] 
     661            P, S = [_get_model_class(revert_name(p))() for p in parts] 
    644662            model = [MultiplicationModel(P, S)] 
    645663        else: 
     
    649667        if old_name is None: 
    650668            raise ValueError("model %r does not exist in old sasview" 
    651                             % model_info.id) 
    652         ModelClass = get_model_class(old_name) 
     669                             % model_info.id) 
     670        ModelClass = _get_model_class(old_name) 
    653671        model = [ModelClass()] 
    654672    model[0].disperser_handles = {} 
     
    847865            # print a separate seed for each dataset for better reproducibility 
    848866            new_seed = np.random.randint(1000000) 
    849             print("Set %d uses -random=%i"%(k+1,new_seed)) 
     867            print("Set %d uses -random=%i"%(k+1, new_seed)) 
    850868            np.random.seed(new_seed) 
    851869        opts['pars'] = parse_pars(opts, maxdim=maxdim) 
     
    868886def run_models(opts, verbose=False): 
    869887    # type: (Dict[str, Any]) -> Dict[str, Any] 
     888    """ 
     889    Process a parameter set, return calculation results and times. 
     890    """ 
    870891 
    871892    base, comp = opts['engines'] 
     
    941962def plot_models(opts, result, limits=None, setnum=0): 
    942963    # type: (Dict[str, Any], Dict[str, Any], Optional[Tuple[float, float]]) -> Tuple[float, float] 
     964    """ 
     965    Plot the results from :func:`run_model`. 
     966    """ 
    943967    import matplotlib.pyplot as plt 
    944968 
     
    9871011                errview = 'linear' 
    9881012        if 0:  # 95% cutoff 
    989             sorted = np.sort(err.flatten()) 
    990             cutoff = sorted[int(sorted.size*0.95)] 
     1013            sorted_err = np.sort(err.flatten()) 
     1014            cutoff = sorted_err[int(sorted_err.size*0.95)] 
    9911015            err[err > cutoff] = cutoff 
    9921016        #err,errstr = base/comp,"ratio" 
     
    11061130 
    11071131INTEGER_RE = re.compile("^[+-]?[1-9][0-9]*$") 
    1108 def isnumber(str): 
    1109     match = FLOAT_RE.match(str) 
    1110     isfloat = (match and not str[match.end():]) 
    1111     return isfloat or INTEGER_RE.match(str) 
     1132def isnumber(s): 
     1133    # type: (str) -> bool 
     1134    """Return True if string contains an int or float""" 
     1135    match = FLOAT_RE.match(s) 
     1136    isfloat = (match and not s[match.end():]) 
     1137    return isfloat or INTEGER_RE.match(s) 
    11121138 
    11131139# For distinguishing pairs of models for comparison 
     
    13141340 
    13151341def set_spherical_integration_parameters(opts, steps): 
     1342    # type: (Dict[str, Any], int) -> None 
    13161343    """ 
    13171344    Set integration parameters for spherical integration over the entire 
     
    13371364            'psi_pd_type=rectangle', 
    13381365        ]) 
    1339         pass 
    13401366 
    13411367def parse_pars(opts, maxdim=np.inf): 
     1368    # type: (Dict[str, Any], float) -> Tuple[Dict[str, float], Dict[str, float]] 
     1369    """ 
     1370    Generate a parameter set. 
     1371 
     1372    The default values come from the model, or a randomized model if a seed 
     1373    value is given.  Next, evaluate any parameter expressions, constraining 
     1374    the value of the parameter within and between models.  If *maxdim* is 
     1375    given, limit parameters with units of Angstrom to this value. 
     1376 
     1377    Returns a pair of parameter dictionaries for base and comparison models. 
     1378    """ 
    13421379    model_info, model_info2 = opts['info'] 
    13431380 
     
    13781415            print("%r invalid; parameters are: %s"%(k, ", ".join(sorted(s)))) 
    13791416            return None 
    1380         v1, v2 = v.split(PAR_SPLIT, 2) if PAR_SPLIT in v else (v,v) 
     1417        v1, v2 = v.split(PAR_SPLIT, 2) if PAR_SPLIT in v else (v, v) 
    13811418        if v1 and k in pars: 
    13821419            presets[k] = float(v1) if isnumber(v1) else v1 
     
    14341471    html = make_html(info) 
    14351472    path = os.path.dirname(info.filename) 
    1436     url = "file://"+path.replace("\\","/")[2:]+"/" 
     1473    url = "file://" + path.replace("\\", "/")[2:] + "/" 
    14371474    rst2html.view_html_qtapp(html, url) 
    14381475 
     
    14581495    frame.panel.Layout() 
    14591496    frame.panel.aui.Split(0, wx.TOP) 
    1460     def reset_parameters(event): 
     1497    def _reset_parameters(event): 
    14611498        model.revert_values() 
    14621499        signal.update_parameters(problem) 
    1463     frame.Bind(wx.EVT_TOOL, reset_parameters, frame.ToolBar.GetToolByPos(1)) 
     1500    frame.Bind(wx.EVT_TOOL, _reset_parameters, frame.ToolBar.GetToolByPos(1)) 
    14641501    if is_mac: frame.Show() 
    14651502    # If running withing an app, start the main loop 
     
    15041541 
    15051542    def revert_values(self): 
     1543        # type: () -> None 
     1544        """ 
     1545        Restore starting values of the parameters. 
     1546        """ 
    15061547        for k, v in self.starting_values.items(): 
    15071548            self.pars[k].value = v 
    15081549 
    15091550    def model_update(self): 
     1551        # type: () -> None 
     1552        """ 
     1553        Respond to signal that model parameters have been changed. 
     1554        """ 
    15101555        pass 
    15111556 
Note: See TracChangeset for help on using the changeset viewer.