Changeset a936688 in sasmodels


Ignore:
Timestamp:
Apr 13, 2016 8:45:00 AM (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:
81ec7c8
Parents:
416609b
Message:

update sasview wrapper so that model details are class attributes

Location:
sasmodels
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • sasmodels/generate.py

    re6408d0 ra936688  
    679679    * *single* is True if the model allows single precision 
    680680    * *structure_factor* is True if the model is useable in a product 
    681     * *variant_info* contains the information required to select between 
    682       model variants (e.g., the list of cases) or is None if there are no 
    683       model variants 
    684681    * *defaults* is the *{parameter: value}* table built from the parameter 
    685682      description table. 
     
    721718        single=getattr(kernel_module, 'single', True), 
    722719        structure_factor=getattr(kernel_module, 'structure_factor', False), 
    723         variant_info=getattr(kernel_module, 'invariant_info', None), 
     720        control=getattr(kernel_module, 'control', None), 
    724721        demo=getattr(kernel_module, 'demo', None), 
    725722        source=getattr(kernel_module, 'source', []), 
  • sasmodels/sasview_model.py

    r4d76711 ra936688  
    2626from . import custom 
    2727from . import generate 
     28 
     29try: 
     30    from typing import Dict, Mapping, Any, Sequence, Tuple, NamedTuple, List, Optional 
     31    from .kernel import KernelModel 
     32    MultiplicityInfoType = NamedTuple( 
     33        'MuliplicityInfo', 
     34        [("number", int), ("control", str), ("choices", List[str]), 
     35         ("x_axis_label", str)]) 
     36except ImportError: 
     37    pass 
     38 
     39# TODO: separate x_axis_label from multiplicity info 
     40# The x-axis label belongs with the profile generating function 
     41MultiplicityInfo = collections.namedtuple( 
     42    'MultiplicityInfo', 
     43    ["number", "control", "choices", "x_axis_label"], 
     44) 
    2845 
    2946def load_standard_models(): 
     
    6986    Convert *model_info* into a SasView model wrapper. 
    7087    """ 
    71     def __init__(self, multfactor=1): 
    72         SasviewModel.__init__(self) 
    73     attrs = dict(__init__=__init__, _model_info=model_info) 
     88    model_info['variant_info'] = None  # temporary hack for older sasview 
     89    def __init__(self, multiplicity=1): 
     90        SasviewModel.__init__(self, multiplicity=multiplicity) 
     91    attrs = _generate_model_attributes(model_info) 
     92    attrs['__init__'] = __init__ 
    7493    ConstructedModel = type(model_info['name'], (SasviewModel,), attrs) 
    7594    return ConstructedModel 
    7695 
     96def _generate_model_attributes(model_info): 
     97    # type: (ModelInfo) -> Dict[str, Any] 
     98    """ 
     99    Generate the class attributes for the model. 
     100 
     101    This should include all the information necessary to query the model 
     102    details so that you do not need to instantiate a model to query it. 
     103 
     104    All the attributes should be immutable to avoid accidents. 
     105    """ 
     106    attrs = {}  # type: Dict[str, Any] 
     107    attrs['_model_info'] = model_info 
     108    attrs['name'] = model_info['name'] 
     109    attrs['description'] = model_info['description'] 
     110    attrs['category'] = model_info['category'] 
     111 
     112    # TODO: allow model to override axis labels input/output name/unit 
     113 
     114    #self.is_multifunc = False 
     115    non_fittable = []  # type: List[str] 
     116    variants = MultiplicityInfo(0, "", [], "") 
     117    attrs['is_structure_factor'] = model_info['structure_factor'] 
     118    attrs['is_form_factor'] = model_info['ER'] is not None 
     119    attrs['is_multiplicity_model'] = variants[0] > 1 
     120    attrs['multiplicity_info'] = variants 
     121 
     122    partype = model_info['partype'] 
     123    orientation_params = ( 
     124            partype['orientation'] 
     125            + [n + '.width' for n in partype['orientation']] 
     126            + partype['magnetic']) 
     127    magnetic_params = partype['magnetic'] 
     128    fixed = [n + '.width' for n in partype['pd-2d']] 
     129 
     130    attrs['orientation_params'] = tuple(orientation_params) 
     131    attrs['magnetic_params'] = tuple(magnetic_params) 
     132    attrs['fixed'] = tuple(fixed) 
     133 
     134    attrs['non_fittable'] = tuple(non_fittable) 
     135 
     136    return attrs 
    77137 
    78138class SasviewModel(object): 
     
    80140    Sasview wrapper for opencl/ctypes model. 
    81141    """ 
    82     _model_info = {} 
    83     def __init__(self): 
     142    # Model parameters for the specific model are set in the class constructor 
     143    # via the _generate_model_attributes function, which subclasses 
     144    # SasviewModel.  They are included here for typing and documentation 
     145    # purposes. 
     146    _model = None       # type: KernelModel 
     147    _model_info = None  # type: ModelInfo 
     148    #: load/save name for the model 
     149    id = None           # type: str 
     150    #: display name for the model 
     151    name = None         # type: str 
     152    #: short model description 
     153    description = None  # type: str 
     154    #: default model category 
     155    category = None     # type: str 
     156 
     157    #: names of the orientation parameters in the order they appear 
     158    orientation_params = None # type: Sequence[str] 
     159    #: names of the magnetic parameters in the order they appear 
     160    magnetic_params = None    # type: Sequence[str] 
     161    #: names of the fittable parameters 
     162    fixed = None              # type: Sequence[str] 
     163    # TODO: the attribute fixed is ill-named 
     164 
     165    # Axis labels 
     166    input_name = "Q" 
     167    input_unit = "A^{-1}" 
     168    output_name = "Intensity" 
     169    output_unit = "cm^{-1}" 
     170 
     171    #: default cutoff for polydispersity 
     172    cutoff = 1e-5 
     173 
     174    # Note: Use non-mutable values for class attributes to avoid errors 
     175    #: parameters that are not fitted 
     176    non_fittable = ()        # type: Sequence[str] 
     177 
     178    #: True if model should appear as a structure factor 
     179    is_structure_factor = False 
     180    #: True if model should appear as a form factor 
     181    is_form_factor = False 
     182    #: True if model has multiplicity 
     183    is_multiplicity_model = False 
     184    #: Mulitplicity information 
     185    multiplicity_info = None # type: MultiplicityInfoType 
     186 
     187    # Per-instance variables 
     188    #: parameter {name: value} mapping 
     189    params = None      # type: Dict[str, float] 
     190    #: values for dispersion width, npts, nsigmas and type 
     191    dispersion = None  # type: Dict[str, Any] 
     192    #: units and limits for each parameter 
     193    details = None     # type: Mapping[str, Tuple(str, float, float)] 
     194    #: multiplicity used, or None if no multiplicity controls 
     195    multiplicity = None     # type: Optional[int] 
     196 
     197    def __init__(self, multiplicity): 
     198        # type: () -> None 
     199        print("initializing", self.name) 
     200        #raise Exception("first initialization") 
    84201        self._model = None 
    85         model_info = self._model_info 
    86  
    87         self.name = model_info['name'] 
    88         self.description = model_info['description'] 
    89         self.category = None 
    90         self.multiplicity_info = None 
    91         self.is_multifunc = False 
    92  
    93         ## interpret the parameters 
    94         ## TODO: reorganize parameter handling 
    95         self.details = dict() 
     202 
     203        ## _persistency_dict is used by sas.perspectives.fitting.basepage 
     204        ## to store dispersity reference. 
     205        self._persistency_dict = {} 
     206 
     207        self.multiplicity = multiplicity 
     208 
    96209        self.params = collections.OrderedDict() 
    97         self.dispersion = dict() 
    98         partype = model_info['partype'] 
    99  
    100         for p in model_info['parameters']: 
     210        self.dispersion = {} 
     211        self.details = {} 
     212 
     213        for p in self._model_info['parameters']: 
    101214            self.params[p.name] = p.default 
    102215            self.details[p.name] = [p.units] + p.limits 
    103216 
    104         for name in partype['pd-2d']: 
     217        for name in self._model_info['partype']['pd-2d']: 
    105218            self.dispersion[name] = { 
    106219                'width': 0, 
     
    109222                'type': 'gaussian', 
    110223            } 
    111  
    112         self.orientation_params = ( 
    113             partype['orientation'] 
    114             + [n + '.width' for n in partype['orientation']] 
    115             + partype['magnetic']) 
    116         self.magnetic_params = partype['magnetic'] 
    117         self.fixed = [n + '.width' for n in partype['pd-2d']] 
    118         self.non_fittable = [] 
    119  
    120         ## independent parameter name and unit [string] 
    121         self.input_name = model_info.get("input_name", "Q") 
    122         self.input_unit = model_info.get("input_unit", "A^{-1}") 
    123         self.output_name = model_info.get("output_name", "Intensity") 
    124         self.output_unit = model_info.get("output_unit", "cm^{-1}") 
    125  
    126         ## _persistency_dict is used by sas.perspectives.fitting.basepage 
    127         ## to store dispersity reference. 
    128         ## TODO: _persistency_dict to persistency_dict throughout sasview 
    129         self._persistency_dict = {} 
    130  
    131         ## New fields introduced for opencl rewrite 
    132         self.cutoff = 1e-5 
    133224 
    134225    def __get_state__(self): 
  • sasmodels/weights.py

    r5c962df ra936688  
    174174 
    175175# dispersion name -> disperser lookup table. 
    176 models = dict((d.type, d) for d in ( 
     176MODELS = dict((d.type, d) for d in ( 
    177177    GaussianDispersion, RectangleDispersion, 
    178178    ArrayDispersion, SchulzDispersion, LogNormalDispersion 
     
    201201    Returns *(value, weight)*, where *value* and *weight* are vectors. 
    202202    """ 
    203     cls = models[disperser] 
     203    cls = MODELS[disperser] 
    204204    obj = cls(n, width, nsigmas) 
    205205    v, w = obj.get_weights(value, limits[0], limits[1], relative) 
     
    207207 
    208208# Hack to allow sasview dispersion objects to interoperate with sasmodels 
    209 dispersers = dict((v.__name__, k) for k, v in models.items()) 
     209dispersers = dict((v.__name__, k) for k, v in MODELS.items()) 
    210210dispersers['DispersionModel'] = RectangleDispersion.type 
    211211 
Note: See TracChangeset for help on using the changeset viewer.