Changeset 110f69c in sasmodels for sasmodels/compare.py
- Timestamp:
- Nov 28, 2017 1:17:57 PM (6 years ago)
- 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
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
sasmodels/compare.py
r3bfd924 r110f69c 150 150 kerneldll.ALLOW_SINGLE_PRECISION_DLLS = True 151 151 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('_')) 152 def 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 159 MATH = build_math_context() 154 160 155 161 # CRUFT python 2.6 … … 231 237 pass 232 238 233 def __exit__(self, exc_type, exc_value, t raceback):239 def __exit__(self, exc_type, exc_value, tb): 234 240 # type: (Any, BaseException, Any) -> None 235 241 # TODO: better typing for __exit__ method … … 374 380 375 381 def _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 """ 376 394 pd = [p for p in model_info.parameters.kernel_parameters if p.polydisperse] 377 395 pd_volume = [] … … 444 462 value = pars[p.name] 445 463 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) 447 465 448 466 def constrain_pars(model_info, pars): … … 490 508 if pars['radius'] < pars['thick_string']: 491 509 pars['radius'], pars['thick_string'] = pars['thick_string'], pars['radius'] 492 pass493 510 494 511 elif name == 'rpa': … … 608 625 return pars 609 626 627 # TODO: remove support for sasview 3.x models 610 628 def eval_sasview(model_info, data): 611 629 # type: (Modelinfo, Data) -> Calculator … … 621 639 from sas.models.dispersion_models import models as dispersers 622 640 623 def get_model_class(name):641 def _get_model_class(name): 624 642 # type: (str) -> "sas.models.BaseComponent" 625 643 #print("new",sorted(_pars.items())) … … 641 659 composition_type, parts = model_info.composition 642 660 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] 644 662 model = [MultiplicationModel(P, S)] 645 663 else: … … 649 667 if old_name is None: 650 668 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) 653 671 model = [ModelClass()] 654 672 model[0].disperser_handles = {} … … 847 865 # print a separate seed for each dataset for better reproducibility 848 866 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)) 850 868 np.random.seed(new_seed) 851 869 opts['pars'] = parse_pars(opts, maxdim=maxdim) … … 868 886 def run_models(opts, verbose=False): 869 887 # type: (Dict[str, Any]) -> Dict[str, Any] 888 """ 889 Process a parameter set, return calculation results and times. 890 """ 870 891 871 892 base, comp = opts['engines'] … … 941 962 def plot_models(opts, result, limits=None, setnum=0): 942 963 # type: (Dict[str, Any], Dict[str, Any], Optional[Tuple[float, float]]) -> Tuple[float, float] 964 """ 965 Plot the results from :func:`run_model`. 966 """ 943 967 import matplotlib.pyplot as plt 944 968 … … 987 1011 errview = 'linear' 988 1012 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)] 991 1015 err[err > cutoff] = cutoff 992 1016 #err,errstr = base/comp,"ratio" … … 1106 1130 1107 1131 INTEGER_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) 1132 def 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) 1112 1138 1113 1139 # For distinguishing pairs of models for comparison … … 1314 1340 1315 1341 def set_spherical_integration_parameters(opts, steps): 1342 # type: (Dict[str, Any], int) -> None 1316 1343 """ 1317 1344 Set integration parameters for spherical integration over the entire … … 1337 1364 'psi_pd_type=rectangle', 1338 1365 ]) 1339 pass1340 1366 1341 1367 def 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 """ 1342 1379 model_info, model_info2 = opts['info'] 1343 1380 … … 1378 1415 print("%r invalid; parameters are: %s"%(k, ", ".join(sorted(s)))) 1379 1416 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) 1381 1418 if v1 and k in pars: 1382 1419 presets[k] = float(v1) if isnumber(v1) else v1 … … 1434 1471 html = make_html(info) 1435 1472 path = os.path.dirname(info.filename) 1436 url = "file://" +path.replace("\\","/")[2:]+"/"1473 url = "file://" + path.replace("\\", "/")[2:] + "/" 1437 1474 rst2html.view_html_qtapp(html, url) 1438 1475 … … 1458 1495 frame.panel.Layout() 1459 1496 frame.panel.aui.Split(0, wx.TOP) 1460 def reset_parameters(event):1497 def _reset_parameters(event): 1461 1498 model.revert_values() 1462 1499 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)) 1464 1501 if is_mac: frame.Show() 1465 1502 # If running withing an app, start the main loop … … 1504 1541 1505 1542 def revert_values(self): 1543 # type: () -> None 1544 """ 1545 Restore starting values of the parameters. 1546 """ 1506 1547 for k, v in self.starting_values.items(): 1507 1548 self.pars[k].value = v 1508 1549 1509 1550 def model_update(self): 1551 # type: () -> None 1552 """ 1553 Respond to signal that model parameters have been changed. 1554 """ 1510 1555 pass 1511 1556
Note: See TracChangeset
for help on using the changeset viewer.