Changeset 32398dc in sasmodels
- Timestamp:
- Nov 29, 2017 8:23:16 AM (7 years ago)
- 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
- Location:
- sasmodels
- Files:
-
- 3 edited
Legend:
- Unmodified
- Added
- Removed
-
sasmodels/compare.py
re65c3ba r32398dc 43 43 from .data import plot_theory, empty_data1D, empty_data2D, load_data 44 44 from .direct_model import DirectModel, get_mesh 45 from .convert import revert_name, revert_pars , constrain_new_to_old45 from .convert import revert_name, revert_pars 46 46 from .generate import FLOAT_RE 47 47 from .weights import plot_weights 48 48 49 # pylint: disable=unused-import 49 50 try: 50 51 from typing import Optional, Dict, Any, Callable, Tuple 51 except Exception:52 except ImportError: 52 53 pass 53 54 else: … … 55 56 from .data import Data 56 57 Calculator = Callable[[float], np.ndarray] 58 # pylint: enable=unused-import 57 59 58 60 USAGE = """ … … 97 99 -single/-double/-half/-fast sets an OpenCL calculation engine 98 100 -single!/-double!/-quad! sets an OpenMP calculation engine 99 -sasview sets the sasview calculation engine100 101 101 102 === plotting === … … 237 238 pass 238 239 239 def __exit__(self, exc_type, exc_value, t b):240 def __exit__(self, exc_type, exc_value, trace): 240 241 # type: (Any, BaseException, Any) -> None 241 # TODO: better typing for __exit__ method242 242 np.random.set_state(self._state) 243 243 … … 258 258 """ 259 259 Add a beam stop of the given *radius*. If *outer*, make an annulus. 260 261 Note: this function does not require sasview262 260 """ 263 261 if hasattr(data, 'qx_data'): … … 625 623 return pars 626 624 627 # TODO: remove support for sasview 3.x models628 def eval_sasview(model_info, data):629 # type: (Modelinfo, Data) -> Calculator630 """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 to634 # import rather than the more obscure smear_selection not imported error635 import sas636 import sas.models637 from sas.models.qsmearing import smear_selection638 from sas.models.MultiplicationModel import MultiplicationModel639 from sas.models.dispersion_models import models as dispersers640 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 ModelClass649 650 # WARNING: ugly hack when handling model!651 # Sasview models with multiplicity need to be created with the target652 # multiplicity, so we cannot create the target model ahead of time for653 # for multiplicity models. Instead we store the model in a list and654 # update the first element of that list with the new multiplicity model655 # every time we evaluate.656 657 # grab the sasview model, or create it if it is a product model658 if model_info.composition:659 composition_type, parts = model_info.composition660 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 necessary675 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 bug682 smearer.accuracy = data.accuracy683 smearer.set_index(index)684 def _call_smearer():685 smearer.model = model[0]686 return smearer.get_value()687 theory = _call_smearer688 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.ndarray698 """699 Sasview calculator for model.700 """701 oldpars = revert_pars(model_info, pars)702 # For multiplicity models, create a model with the correct multiplicity703 control = oldpars.pop("CONTROL", None)704 if control is not None:705 # sphericalSLD has one fewer multiplicity. This update should706 # 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 fast709 for k, v in oldpars.items():710 if k.endswith('.type'):711 par = k[:-5]712 if v == 'gaussian': continue713 cls = dispersers[v if v != 'rectangle' else 'rectangula']714 handle = cls()715 model[0].disperser_handles[par] = handle716 try:717 model[0].set_dispersion(par, handle)718 except Exception:719 exception.annotate_exception("while setting %s to %r"720 %(par, v))721 raise722 723 724 #print("sasview pars",oldpars)725 for k, v in oldpars.items():726 name_attr = k.split('.') # polydispersity components727 if len(name_attr) == 2:728 par, disp_par = name_attr729 model[0].dispersion[par][disp_par] = v730 else:731 model[0].setParam(k, v)732 return theory()733 734 calculator.engine = "sasview"735 return calculator736 625 737 626 DTYPE_MAP = { … … 827 716 than OpenCL. 828 717 """ 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('!'): 832 719 return eval_opencl(model_info, data, dtype=dtype, cutoff=cutoff) 833 720 else: … … 1075 962 'engine=', 1076 963 'half', 'fast', 'single', 'double', 'single!', 'double!', 'quad!', 1077 'sasview', # TODO: remove sasview 3.x support1078 964 1079 965 # Output options … … 1258 1144 elif arg == '-double!': opts['engine'] = 'double!' 1259 1145 elif arg == '-quad!': opts['engine'] = 'quad!' 1260 elif arg == '-sasview': opts['engine'] = 'sasview'1261 1146 elif arg == '-edit': opts['explore'] = True 1262 1147 elif arg == '-demo': opts['use_demo'] = True -
sasmodels/compare_many.py
rf72d70a r32398dc 22 22 from .compare import (randomize_pars, suppress_pd, make_data, 23 23 make_engine, get_pars, columnize, 24 constrain_pars , constrain_new_to_old)24 constrain_pars) 25 25 26 26 MODELS = core.list_models() … … 80 80 'double!': 5e-14, 81 81 'quad!': 5e-18, 82 'sasview': 5e-14,83 82 } 84 83 def compare_instance(name, data, index, N=1, mono=True, cutoff=1e-5, 85 base='s asview', comp='double'):84 base='single', comp='double'): 86 85 r""" 87 86 Compare the model under different calculation engines. … … 164 163 print("Model %s %d"%(name, k+1), file=sys.stderr) 165 164 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) 167 167 constrain_pars(model_info, pars_i) 168 if 'sasview' in (base, comp):169 constrain_new_to_old(model_info, pars_i)170 168 if mono: 171 169 pars_i = suppress_pd(pars_i) -
sasmodels/convert.py
re65c3ba r32398dc 6 6 import math 7 7 import warnings 8 9 import numpy as np 8 10 9 11 from .conversion_table import CONVERSION_TABLE … … 146 148 return newpars 147 149 148 def _conversion_target(model_name, version=(3, 1,2)):150 def _conversion_target(model_name, version=(3, 1, 2)): 149 151 """ 150 152 Find the sasmodel name which translates into the sasview name. … … 600 602 601 603 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) 603 607 if name == "teubner_strey": 604 608 # T-S model is underconstrained, so fix the assumptions.
Note: See TracChangeset
for help on using the changeset viewer.