Changeset f0cf72f in sasmodels


Ignore:
Timestamp:
Apr 14, 2016 9:13:36 AM (8 years ago)
Author:
wojciech
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:
7835d462
Parents:
1ca1fd9 (diff), 7abcc59 (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
Message:

Merge branch 'master' of https://github.com/SasView/sasmodels

Location:
sasmodels
Files:
8 edited

Legend:

Unmodified
Added
Removed
  • sasmodels/compare.py

    rf247314 re78edc4  
    5858    -lowq*/-midq/-highq/-exq use q values up to 0.05, 0.2, 1.0, 10.0 
    5959    -nq=128 sets the number of Q points in the data set 
     60    -zero indicates that q=0 should be included 
    6061    -1d*/-2d computes 1d or 2d data 
    6162    -preset*/-random[=seed] preset or random parameters 
     
    476477        index = ~data.mask 
    477478    else: 
    478         if opts['view'] == 'log': 
     479        if opts['view'] == 'log' and not opts['zero']: 
    479480            qmax = math.log10(qmax) 
    480481            q = np.logspace(qmax-3, qmax, nq) 
    481482        else: 
    482483            q = np.linspace(0.001*qmax, qmax, nq) 
     484        if opts['zero']: 
     485            q = np.hstack((0, q)) 
    483486        data = empty_data1D(q, resolution=res) 
    484487        index = slice(None, None) 
     
    498501    else: 
    499502        return eval_opencl(model_info, data, dtype=dtype, cutoff=cutoff) 
     503 
     504def _show_invalid(data, theory): 
     505    if not theory.mask.any(): 
     506        return 
     507 
     508    if hasattr(data, 'x'): 
     509        bad = zip(data.x[theory.mask], theory[theory.mask]) 
     510        print("   *** ", ", ".join("I(%g)=%g"%(x, y) for x,y in bad)) 
     511 
    500512 
    501513def compare(opts, limits=None): 
     
    519531        try: 
    520532            base_value, base_time = time_calculation(base, pars, Nbase) 
     533            base_value = np.ma.masked_invalid(base_value) 
    521534            print("%s t=%.2f ms, intensity=%.0f" 
    522                   % (base.engine, base_time, sum(base_value))) 
     535                  % (base.engine, base_time, base_value.sum())) 
     536            _show_invalid(data, base_value) 
    523537        except ImportError: 
    524538            traceback.print_exc() 
     
    530544        try: 
    531545            comp_value, comp_time = time_calculation(comp, pars, Ncomp) 
     546            comp_value = np.ma.masked_invalid(comp_value) 
    532547            print("%s t=%.2f ms, intensity=%.0f" 
    533                   % (comp.engine, comp_time, sum(comp_value))) 
     548                  % (comp.engine, comp_time, comp_value.sum())) 
     549            _show_invalid(data, comp_value) 
    534550        except ImportError: 
    535551            traceback.print_exc() 
     
    554570        vmin, vmax = np.Inf, -np.Inf 
    555571        if Nbase > 0: 
    556             vmin = min(vmin, min(base_value)) 
    557             vmax = max(vmax, max(base_value)) 
     572            vmin = min(vmin, base_value.min()) 
     573            vmax = max(vmax, base_value.max()) 
    558574        if Ncomp > 0: 
    559             vmin = min(vmin, min(comp_value)) 
    560             vmax = max(vmax, max(comp_value)) 
     575            vmin = min(vmin, comp_value.min()) 
     576            vmax = max(vmax, comp_value.max()) 
    561577        limits = vmin, vmax 
    562578 
     
    581597        if view == 'linear': 
    582598            plt.xscale('linear') 
    583         plt.title("max %s = %.3g"%(errstr, max(abs(err)))) 
     599        plt.title("max %s = %.3g"%(errstr, abs(err).max())) 
    584600        #cbar_title = errstr if errview=="linear" else "log "+errstr 
    585601    #if is2D: 
     
    603619 
    604620def _print_stats(label, err): 
    605     sorted_err = np.sort(abs(err)) 
     621    sorted_err = np.sort(abs(err.compressed())) 
    606622    p50 = int((len(err)-1)*0.50) 
    607623    p98 = int((len(err)-1)*0.98) 
     
    623639    'half', 'fast', 'single', 'double', 
    624640    'single!', 'double!', 'quad!', 'sasview', 
    625     'lowq', 'midq', 'highq', 'exq', 
     641    'lowq', 'midq', 'highq', 'exq', 'zero', 
    626642    '2d', '1d', 
    627643    'preset', 'random', 
     
    700716    try: 
    701717        model_info = core.load_model_info(name) 
    702     except ImportError, exc: 
     718    except ImportError as exc: 
    703719        print(str(exc)) 
    704720        print("Could not find model; use one of:\n    " + models) 
     
    745761        elif arg == '-midq':    opts['qmax'] = 0.2 
    746762        elif arg == '-lowq':    opts['qmax'] = 0.05 
     763        elif arg == '-zero':    opts['zero'] = True 
    747764        elif arg.startswith('-nq='):       opts['nq'] = int(arg[4:]) 
    748765        elif arg.startswith('-res='):      opts['res'] = float(arg[5:]) 
  • sasmodels/data.py

    rd6f5da6 re78edc4  
    380380    use_calc = use_theory and Iq_calc is not None 
    381381    num_plots = (use_data or use_theory) + use_calc + use_resid 
    382  
     382    non_positive_x = (data.x<=0.0).any() 
    383383 
    384384    scale = data.x**4 if view == 'q4' else 1.0 
     
    402402 
    403403        if use_theory: 
     404            # Note: masks merge, so any masked theory points will stay masked, 
     405            # and the data mask will be added to it. 
    404406            mtheory = masked_array(theory, data.mask.copy()) 
    405407            mtheory[~np.isfinite(mtheory)] = masked 
     
    413415            plt.ylim(*limits) 
    414416 
    415         plt.xscale('linear' if not some_present else view) 
     417        plt.xscale('linear' if not some_present or non_positive_x  else view) 
    416418        plt.yscale('linear' 
    417419                   if view == 'q4' or not some_present or not all_positive 
     
    441443        plt.xlabel("$q$/A$^{-1}$") 
    442444        plt.ylabel('residuals') 
    443         plt.xscale('linear' if not some_present else view) 
     445        plt.xscale('linear' if not some_present or non_positive_x else view) 
    444446 
    445447 
  • sasmodels/generate.py

    re6408d0 r81ec7c8  
    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. 
     
    702699 
    703700    """ 
    704     # TODO: maybe turn model_info into a class ModelDefinition 
    705701    parameters = COMMON_PARAMETERS + kernel_module.parameters 
    706702    filename = abspath(kernel_module.__file__) 
     
    721717        single=getattr(kernel_module, 'single', True), 
    722718        structure_factor=getattr(kernel_module, 'structure_factor', False), 
    723         variant_info=getattr(kernel_module, 'invariant_info', None), 
     719        control=getattr(kernel_module, 'control', None), 
    724720        demo=getattr(kernel_module, 'demo', None), 
    725721        source=getattr(kernel_module, 'source', []), 
  • sasmodels/model_test.py

    r4d76711 re78edc4  
    145145        def _runTest(self): 
    146146            smoke_tests = [ 
     147                # test validity at reasonable values 
    147148                [{}, 0.1, None], 
    148149                [{}, (0.1, 0.1), None], 
     150                # test validity at q = 0 
     151                #[{}, 0.0, None], 
     152                #[{}, (0.0, 0.0), None], 
     153                # test that ER/VR will run if they exist 
    149154                [{}, 'ER', None], 
    150155                [{}, 'VR', None], 
     
    194199                actual = call_kernel(kernel, pars) 
    195200 
    196             self.assertGreater(len(actual), 0) 
     201            self.assertTrue(len(actual) > 0) 
    197202            self.assertEqual(len(y), len(actual)) 
    198203 
  • sasmodels/models/adsorbed_layer.py

    rec45c4f r7abcc59  
    33#converted by Steve King, Mar 2016 
    44 
     5r""" 
     6This model describes the scattering from a layer of surfactant or polymer 
     7adsorbed on large, smooth, notionally spherical particles under the conditions 
     8that (i) the particles (cores) are contrast-matched to the dispersion medium, 
     9(ii) $S(Q) \sim 1$ (ie, the particle volume fraction is dilute), (iii) the 
     10particle radius is >> layer thickness (ie, the interface is locally flat), 
     11and (iv) scattering from excess unadsorbed adsorbate in the bulk medium is 
     12absent or has been corrected for. 
    513 
    6  
    7 r""" 
    8 This model describes the scattering from a layer of surfactant or polymer adsorbed on large, smooth, notionally spherical particles under the conditions that (i) the particles (cores) are contrast-matched to the dispersion medium, (ii) *S(Q)* ~ 1 (ie, the particle volume fraction is dilute), (iii) the particle radius is >> layer thickness (ie, the interface is locally flat), and (iv) scattering from excess unadsorbed adsorbate in the bulk medium is absent or has been corrected for. 
    9  
    10 Unlike many other core-shell models, this model does not assume any form for the density distribution of the adsorbed species normal to the interface (cf, a core-shell model normally assumes the density distribution to be a homogeneous step-function). For comparison, if the thickness of a (traditional core-shell like) step function distribution is *t*, the second moment about the mean of the density distribution (ie, the distance of the centre-of-mass of the distribution from the interface), |sigma| =  sqrt((*t* :sup:`2` )/12). 
     14Unlike many other core-shell models, this model does not assume any form 
     15for the density distribution of the adsorbed species normal to the interface 
     16(cf, a core-shell model normally assumes the density distribution to be a 
     17homogeneous step-function). For comparison, if the thickness of a (traditional 
     18core-shell like) step function distribution is $t$, the second moment about 
     19the mean of the density distribution (ie, the distance of the centre-of-mass 
     20of the distribution from the interface), $\sigma = \sqrt{t^2/12}$. 
    1121 
    1222Definition 
     
    1525.. math:: 
    1626 
    17      I(q) = \text{scale} \cdot(\rho_\text{poly}-\rho_\text{solvent})^2    \left[\frac{6\pi\phi_\text{core}}{Q^2}\frac{\Gamma^2}{\delta_\text{poly}^2R_\text{core}} \exp(-Q^2\sigma^2)\right] + \text{background} 
     27     I(q) = \text{scale} \cdot (\rho_\text{poly}-\rho_\text{solvent})^2 
     28         \left[ 
     29             \frac{6\pi\phi_\text{core}}{Q^2} 
     30             \frac{\Gamma^2}{\delta_\text{poly}^2R_\text{core}} 
     31             \exp(-Q^2\sigma^2) 
     32         \right] + \text{background} 
    1833 
    19 where *scale* is a scale factor, |rho|\ :sub:`poly` is the sld of the polymer (or surfactant) layer, |rho|\ :sub:`solv` is the sld of the solvent/medium and cores, |phi|\ :sub:`core` is the volume fraction of the core particles, |delta|\ :sub:`poly` is the bulk density of the polymer, |biggamma| is the adsorbed amount, and |sigma| is the second moment of the thickness distribution. 
     34where *scale* is a scale factor, $\rho_\text{poly}$ is the sld of the 
     35polymer (or surfactant) layer, $\rho_\text{solv}$ is the sld of the 
     36solvent/medium and cores, $\phi_\text{core}$ is the volume fraction of 
     37the core particles, $\delta_\text{poly}$ is the bulk density of the 
     38polymer, $\Gamma$ is the adsorbed amount, and $\sigma$ is the second 
     39moment of the thickness distribution. 
    2040 
    21 Note that all parameters except the |sigma| are correlated so fitting more than one of these parameters will generally fail. Also note that unlike other shape models, no volume normalization is applied to this model (the calculation is exact). 
     41Note that all parameters except $\sigma$ are correlated so fitting more 
     42than one of these parameters will generally fail. Also note that unlike 
     43other shape models, no volume normalization is applied to this model (the 
     44calculation is exact). 
    2245 
    2346References 
    2447---------- 
    2548 
    26 S King, P Griffiths, J Hone, and T Cosgrove, *SANS from Adsorbed Polymer Layers*, 
    27 *Macromol. Symp.*, 190 (2002) 33-42. 
     49S King, P Griffiths, J Hone, and T Cosgrove, 
     50*SANS from Adsorbed Polymer Layers*, *Macromol. Symp.*, 190 (2002) 33-42. 
    2851""" 
    2952 
    3053from numpy import inf, sqrt, pi, exp 
    3154 
    32 name =  "adsorbed_layer" 
    33 title =  "Scattering from an adsorbed layer on particles" 
     55name = "adsorbed_layer" 
     56title = "Scattering from an adsorbed layer on particles" 
    3457 
    35 description =  """ 
     58description = """ 
    3659    Evaluates the scattering from large particles 
    3760    with an adsorbed layer of surfactant or 
     
    3962    density distribution. 
    4063    """ 
    41 category =  "shape:sphere" 
     64category = "shape:sphere" 
    4265 
    43 #             ["name", "units", default, [lower, upper], "type", "description"], 
    44 parameters =  [["second_moment", "Ang", 23.0, [0.0, inf], "", "Second moment of polymer distribution"], 
    45               ["adsorbed_amount", "mg/m2", 1.9, [0.0, inf], "", "Adsorbed amount of polymer"], 
    46               ["density_shell", "g/cm3", 0.7, [0.0, inf], "", "Bulk density of polymer in the shell"], 
    47               ["radius", "Ang", 500.0, [0.0, inf], "", "Core particle radius"], 
    48               ["volfraction", "None", 0.14, [0.0, inf], "", "Core particle volume fraction"], 
    49               ["sld_shell", "1e-6/Ang^2", 1.5, [-inf, inf], "sld", "Polymer shell SLD"], 
    50               ["sld_solvent", "1e-6/Ang^2", 6.3, [-inf, inf], "sld", "Solvent SLD"]] 
     66# pylint: disable=bad-whitespace, line-too-long 
     67#   ["name", "units", default, [lower, upper], "type", "description"], 
     68parameters = [ 
     69    ["second_moment", "Ang", 23.0, [0.0, inf], "", "Second moment of polymer distribution"], 
     70    ["adsorbed_amount", "mg/m2", 1.9, [0.0, inf], "", "Adsorbed amount of polymer"], 
     71    ["density_shell", "g/cm3", 0.7, [0.0, inf], "", "Bulk density of polymer in the shell"], 
     72    ["radius", "Ang", 500.0, [0.0, inf], "", "Core particle radius"], 
     73    ["volfraction", "None", 0.14, [0.0, inf], "", "Core particle volume fraction"], 
     74    ["sld_shell", "1e-6/Ang^2", 1.5, [-inf, inf], "sld", "Polymer shell SLD"], 
     75    ["sld_solvent", "1e-6/Ang^2", 6.3, [-inf, inf], "sld", "Solvent SLD"], 
     76] 
     77# pylint: enable=bad-whitespace, line-too-long 
    5178 
    5279# NB: Scale and Background are implicit parameters on every model 
    53 def Iq(q, second_moment, adsorbed_amount, density_shell, radius,  
    54         volfraction, sld_shell, sld_solvent): 
     80def Iq(q, second_moment, adsorbed_amount, density_shell, radius, 
     81       volfraction, sld_shell, sld_solvent): 
    5582    # pylint: disable = missing-docstring 
    56 #    deltarhosqrd =  (sld_shell - sld_solvent) * (sld_shell - sld_solvent) 
    57 #    numerator =  6.0 * pi * volfraction * (adsorbed_amount * adsorbed_amount) 
    58 #    denominator =  (q * q) * (density_shell * density_shell) * radius 
    59 #    eterm =  exp(-1.0 * (q * q) * (second_moment * second_moment)) 
    60 #    #scale by 10^-2 for units conversion to cm^-1 
    61 #    inten =  1.0e-02 * deltarhosqrd * ((numerator / denominator) * eterm) 
    62     aa =  (sld_shell - sld_solvent) * adsorbed_amount / q / density_shell  
     83    #deltarhosqrd =  (sld_shell - sld_solvent) * (sld_shell - sld_solvent) 
     84    #numerator =  6.0 * pi * volfraction * (adsorbed_amount * adsorbed_amount) 
     85    #denominator =  (q * q) * (density_shell * density_shell) * radius 
     86    #eterm =  exp(-1.0 * (q * q) * (second_moment * second_moment)) 
     87    ##scale by 10^-2 for units conversion to cm^-1 
     88    #inten =  1.0e-02 * deltarhosqrd * ((numerator / denominator) * eterm) 
     89    aa = (sld_shell - sld_solvent) * adsorbed_amount / q / density_shell 
    6390    bb = q * second_moment 
    6491    #scale by 10^-2 for units conversion to cm^-1 
    65     inten =  6.0e-02 * pi * volfraction * aa * aa * exp(-bb * bb) / radius 
     92    inten = 6.0e-02 * pi * volfraction * aa * aa * exp(-bb * bb) / radius 
    6693    return inten 
    6794Iq.vectorized =  True  # Iq accepts an array of q values 
     
    7097    # pylint: disable = missing-docstring 
    7198    return Iq(sqrt(qx ** 2 + qy ** 2), *args) 
    72 Iqxy.vectorized =  True # Iqxy accepts an array of qx, qy values 
     99Iqxy.vectorized = True # Iqxy accepts an array of qx, qy values 
    73100 
    74 demo =  dict(scale = 1.0, 
    75             second_moment = 23.0, 
    76             adsorbed_amount = 1.9, 
    77             density_shell = 0.7, 
    78             radius = 500.0, 
    79             volfraction = 0.14, 
    80             sld_shell = 1.5, 
    81             sld_solvent = 6.3, 
    82             background = 0.0) 
     101# unit test values taken from SasView 3.1.2 
     102tests =  [ 
     103    [{'scale': 1.0, 'second_moment': 23.0, 'adsorbed_amount': 1.9, 
     104      'density_shell': 0.7, 'radius': 500.0, 'volfraction': 0.14, 
     105      'sld_shell': 1.5, 'sld_solvent': 6.3, 'background': 0.0}, 
     106     [0.0106939, 0.1], [73.741, 4.51684e-3]], 
     107] 
    83108 
    84 # these unit test values taken from SasView 3.1.2 
    85 tests =  [ 
    86     [{'scale': 1.0, 'second_moment': 23.0, 'adsorbed_amount': 1.9,  
    87      'density_shell': 0.7, 'radius': 500.0, 'volfraction': 0.14,  
    88      'sld_shell': 1.5, 'sld_solvent': 6.3, 'background': 0.0}, 
    89      [0.0106939, 0.1], [73.741, 4.51684e-3]], 
    90     ] 
    91 # ADDED by: SMK  ON: 16Mar2016  convert from sasview, check vs SANDRA, 18Mar2016 RKH some edits & renaming 
     109# 2016-03-16 SMK converted from sasview, checked vs SANDRA 
     110# 2016-03-18 RKH some edits & renaming 
     111# 2016-04-14 PAK reformatting 
  • sasmodels/sasview_model.py

    r4d76711 r81ec7c8  
    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) 
    74     ConstructedModel = type(model_info['name'], (SasviewModel,), attrs) 
     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__ 
     93    ConstructedModel = type(model_info['id'], (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['id'] = model_info['id'] 
     110    attrs['description'] = model_info['description'] 
     111    attrs['category'] = model_info['category'] 
     112 
     113    # TODO: allow model to override axis labels input/output name/unit 
     114 
     115    #self.is_multifunc = False 
     116    non_fittable = []  # type: List[str] 
     117    variants = MultiplicityInfo(0, "", [], "") 
     118    attrs['is_structure_factor'] = model_info['structure_factor'] 
     119    attrs['is_form_factor'] = model_info['ER'] is not None 
     120    attrs['is_multiplicity_model'] = variants[0] > 1 
     121    attrs['multiplicity_info'] = variants 
     122 
     123    partype = model_info['partype'] 
     124    orientation_params = ( 
     125            partype['orientation'] 
     126            + [n + '.width' for n in partype['orientation']] 
     127            + partype['magnetic']) 
     128    magnetic_params = partype['magnetic'] 
     129    fixed = [n + '.width' for n in partype['pd-2d']] 
     130 
     131    attrs['orientation_params'] = tuple(orientation_params) 
     132    attrs['magnetic_params'] = tuple(magnetic_params) 
     133    attrs['fixed'] = tuple(fixed) 
     134 
     135    attrs['non_fittable'] = tuple(non_fittable) 
     136 
     137    return attrs 
    77138 
    78139class SasviewModel(object): 
     
    80141    Sasview wrapper for opencl/ctypes model. 
    81142    """ 
    82     _model_info = {} 
    83     def __init__(self): 
     143    # Model parameters for the specific model are set in the class constructor 
     144    # via the _generate_model_attributes function, which subclasses 
     145    # SasviewModel.  They are included here for typing and documentation 
     146    # purposes. 
     147    _model = None       # type: KernelModel 
     148    _model_info = None  # type: ModelInfo 
     149    #: load/save name for the model 
     150    id = None           # type: str 
     151    #: display name for the model 
     152    name = None         # type: str 
     153    #: short model description 
     154    description = None  # type: str 
     155    #: default model category 
     156    category = None     # type: str 
     157 
     158    #: names of the orientation parameters in the order they appear 
     159    orientation_params = None # type: Sequence[str] 
     160    #: names of the magnetic parameters in the order they appear 
     161    magnetic_params = None    # type: Sequence[str] 
     162    #: names of the fittable parameters 
     163    fixed = None              # type: Sequence[str] 
     164    # TODO: the attribute fixed is ill-named 
     165 
     166    # Axis labels 
     167    input_name = "Q" 
     168    input_unit = "A^{-1}" 
     169    output_name = "Intensity" 
     170    output_unit = "cm^{-1}" 
     171 
     172    #: default cutoff for polydispersity 
     173    cutoff = 1e-5 
     174 
     175    # Note: Use non-mutable values for class attributes to avoid errors 
     176    #: parameters that are not fitted 
     177    non_fittable = ()        # type: Sequence[str] 
     178 
     179    #: True if model should appear as a structure factor 
     180    is_structure_factor = False 
     181    #: True if model should appear as a form factor 
     182    is_form_factor = False 
     183    #: True if model has multiplicity 
     184    is_multiplicity_model = False 
     185    #: Mulitplicity information 
     186    multiplicity_info = None # type: MultiplicityInfoType 
     187 
     188    # Per-instance variables 
     189    #: parameter {name: value} mapping 
     190    params = None      # type: Dict[str, float] 
     191    #: values for dispersion width, npts, nsigmas and type 
     192    dispersion = None  # type: Dict[str, Any] 
     193    #: units and limits for each parameter 
     194    details = None     # type: Mapping[str, Tuple(str, float, float)] 
     195    #: multiplicity used, or None if no multiplicity controls 
     196    multiplicity = None     # type: Optional[int] 
     197 
     198    def __init__(self, multiplicity): 
     199        # type: () -> None 
     200        print("initializing", self.name) 
     201        #raise Exception("first initialization") 
    84202        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() 
     203 
     204        ## _persistency_dict is used by sas.perspectives.fitting.basepage 
     205        ## to store dispersity reference. 
     206        self._persistency_dict = {} 
     207 
     208        self.multiplicity = multiplicity 
     209 
    96210        self.params = collections.OrderedDict() 
    97         self.dispersion = dict() 
    98         partype = model_info['partype'] 
    99  
    100         for p in model_info['parameters']: 
     211        self.dispersion = {} 
     212        self.details = {} 
     213 
     214        for p in self._model_info['parameters']: 
    101215            self.params[p.name] = p.default 
    102216            self.details[p.name] = [p.units] + p.limits 
    103217 
    104         for name in partype['pd-2d']: 
     218        for name in self._model_info['partype']['pd-2d']: 
    105219            self.dispersion[name] = { 
    106220                'width': 0, 
     
    109223                'type': 'gaussian', 
    110224            } 
    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 
    133225 
    134226    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 
  • sasmodels/models/__init__.py

    r32c160a r1ca1fd9  
     1""" 
     2    1D Modeling for SAS 
     3""" 
     4#from sas.models import * 
     5 
     6import os 
     7from distutils.filelist import findall 
     8 
     9__version__ = "2.1.0" 
     10 
     11def get_data_path(media): 
     12    """ 
     13    """ 
     14    # Check for data path in the package 
     15    path = os.path.join(os.path.dirname(__file__), media) 
     16    if os.path.isdir(path): 
     17        return path 
     18 
     19    # Check for data path next to exe/zip file. 
     20    # If we are inside a py2exe zip file, we need to go up 
     21    # to get to the directory containing  
     22    # the media for this module 
     23    path = os.path.dirname(__file__) 
     24    #Look for maximum n_dir up of the current dir to find media 
     25    n_dir = 12 
     26    for i in range(n_dir): 
     27        path, _ = os.path.split(path) 
     28        media_path = os.path.join(path, media) 
     29        if os.path.isdir(media_path): 
     30            module_media_path = os.path.join(media_path, 'models_media') 
     31            if os.path.isdir(module_media_path): 
     32                return module_media_path 
     33            return media_path 
     34    
     35    raise RuntimeError('Could not find models media files') 
     36 
     37def data_files(): 
     38    """ 
     39    Return the data files associated with media. 
     40     
     41    The format is a list of (directory, [files...]) pairs which can be 
     42    used directly in setup(...,data_files=...) for setup.py. 
     43 
     44    """ 
     45    data_files = [] 
     46    path_img = get_data_path(media=os.path.join("sasmodels","sasmodels","models","img")) 
     47    #path_img = get_data_path(media="img") 
     48    im_list = findall(path_img) 
     49    #for f in findall(path): 
     50    #    if os.path.isfile(f) and f not in im_list: 
     51    #        data_files.append(('media/models_media', [f])) 
     52     
     53    for f in im_list: 
     54        data_files.append(('media/models_media/img', [f])) 
     55    return data_files 
     56 
Note: See TracChangeset for help on using the changeset viewer.