source: sasmodels/sasmodels/convert.py @ 5778279

ticket_1156
Last change on this file since 5778279 was 78f8308, checked in by Paul Kienzle <pkienzle@…>, 6 years ago

convert saved paracrystal parameters from 4.1 to 4.2

  • Property mode set to 100644
File size: 24.4 KB
Line 
1"""
2Convert models to and from sasview.
3"""
4from __future__ import print_function, division
5
6import math
7import warnings
8
9import numpy as np
10
11from .conversion_table import CONVERSION_TABLE
12from .core import load_model_info
13
14# List of models which SasView versions don't contain the explicit 'scale' argument.
15# When converting such a model, please update this list.
16MODELS_WITHOUT_SCALE = [
17    'teubner_strey',
18    'broad_peak',
19    'two_lorentzian',
20    "two_power_law",
21    'gauss_lorentz_gel',
22    'be_polyelectrolyte',
23    'correlation_length',
24    'fractal_core_shell',
25    'binary_hard_sphere',
26    'raspberry'
27]
28
29# List of models which SasView versions don't contain the explicit 'background' argument.
30# When converting such a model, please update this list.
31MODELS_WITHOUT_BACKGROUND = [
32    'guinier',
33]
34
35MODELS_WITHOUT_VOLFRACTION = [
36    'fractal',
37    'vesicle',
38    'multilayer_vesicle',
39]
40
41MAGNETIC_SASVIEW_MODELS = [
42    'core_shell',
43    'core_multi_shell',
44    'cylinder',
45    'parallelepiped',
46    'sphere',
47]
48
49
50# Convert new style names for polydispersity info to old style names
51PD_DOT = [
52    ("_pd", ".width"),
53    ("_pd_n", ".npts"),
54    ("_pd_nsigma", ".nsigmas"),
55    ("_pd_type", ".type"),
56    (".lower", ".lower"),
57    (".upper", ".upper"),
58    (".fittable", ".fittable"),
59    (".std", ".std"),
60    (".units", ".units"),
61    ("", "")
62    ]
63
64def _rescale(par, scale):
65    return [pk*scale for pk in par] if isinstance(par, list) else par*scale
66
67def _is_sld(model_info, par):
68    """
69    Return True if parameter is a magnetic magnitude or SLD parameter.
70    """
71    if par.startswith('M0:'):
72        return True
73    if '_pd' in par or '.' in par:
74        return False
75    for p in model_info.parameters.call_parameters:
76        if p.id == par:
77            return p.type == 'sld'
78    # check through kernel parameters in case it is a named as a vector
79    for p in model_info.parameters.kernel_parameters:
80        if p.id == par:
81            return p.type == 'sld'
82    return False
83
84def _rescale_sld(model_info, pars, scale):
85    """
86    rescale all sld parameters in the new model definition by *scale* so the
87    numbers are nicer.  Relies on the fact that all sld parameters in the
88    new model definition end with sld.  For backward conversion use
89    *scale=1e-6*.  For forward conversion use *scale=1e6*.
90    """
91    return dict((par, (_rescale(v, scale) if _is_sld(model_info, par) else v))
92                for par, v in pars.items())
93
94
95def _get_translation_table(model_info, version=(3, 1, 2)):
96    conv_param = CONVERSION_TABLE.get(version, {}).get(model_info.id, [None, {}])
97    translation = conv_param[1].copy()
98    for p in model_info.parameters.kernel_parameters:
99        if p.length > 1:
100            newid = p.id
101            oldid = translation.get(p.id, p.id)
102            translation.pop(newid, None)
103            for k in range(1, p.length+1):
104                if newid+str(k) not in translation:
105                    translation[newid+str(k)] = oldid+str(k)
106    # Remove control parameter from the result
107    if model_info.control:
108        translation[model_info.control] = "CONTROL"
109    return translation
110
111# ========= FORWARD CONVERSION sasview 3.x => sasmodels ===========
112def _dot_pd_to_underscore_pd(par):
113    if par.endswith(".width"):
114        return par[:-6]+"_pd"
115    elif par.endswith(".type"):
116        return par[:-5]+"_pd_type"
117    elif par.endswith(".nsigmas"):
118        return par[:-8]+"_pd_nsigma"
119    elif par.endswith(".npts"):
120        return par[:-5]+"_pd_n"
121    else:
122        return par
123
124def _pd_to_underscores(pars):
125    return dict((_dot_pd_to_underscore_pd(k), v) for k, v in pars.items())
126
127def _convert_pars(pars, mapping):
128    """
129    Rename the parameters and any associated polydispersity attributes.
130    """
131    newpars = pars.copy()
132    for new, old in mapping.items():
133        if old == new:
134            continue
135        if old is None:
136            continue
137        for _, dot in PD_DOT:
138            source = old+dot
139            if source in newpars:
140                if new is not None:
141                    target = new+dot
142                else:
143                    target = None
144                if source != target:
145                    if target:
146                        newpars[target] = pars[old+dot]
147                    del newpars[source]
148    return newpars
149
150def _conversion_target(model_name, version=(3, 1, 2)):
151    """
152    Find the sasmodel name which translates into the sasview name.
153
154    Note: *CoreShellEllipsoidModel* translates into *core_shell_ellipsoid:1*.
155    This is necessary since there is only one variant in sasmodels for the
156    two variants in sasview.
157    """
158    for sasmodels_name, sasview_dict in \
159            CONVERSION_TABLE.get(version, {}).items():
160        if sasview_dict[0] == model_name:
161            return sasmodels_name
162    return None
163
164def _hand_convert(name, oldpars, version=(3, 1, 2)):
165    if version == (3, 1, 2):
166        oldpars = _hand_convert_3_1_2_to_4_1(name, oldpars)
167    if version < (4, 2, 0):
168        oldpars = _hand_convert_4_1_to_4_2(name, oldpars)
169    return oldpars
170
171def _hand_convert_4_1_to_4_2(name, oldpars):
172    if name in ('bcc_paracrystal', 'fcc_paracrystal', 'sc_paracrystal'):
173        oldpars['lattice_spacing'] = oldpars.pop('dnn')
174        oldpars['lattice_distortion'] = oldpars.pop('d_factor')
175    return oldpars
176
177def _hand_convert_3_1_2_to_4_1(name, oldpars):
178    if name == 'core_shell_parallelepiped':
179        # Make sure pd on rim parameters defaults to zero
180        # ... probably not necessary.
181        oldpars['rimA.width'] = 0.0
182        oldpars['rimB.width'] = 0.0
183        oldpars['rimC.width'] = 0.0
184    elif name == 'core_shell_ellipsoid:1':
185        # Reverse translation (from new to old), from core_shell_ellipsoid.c
186        #    equat_shell = equat_core + thick_shell
187        #    polar_core = equat_core * x_core
188        #    polar_shell = equat_core * x_core + thick_shell*x_polar_shell
189        # Forward translation (from old to new), inverting reverse translation:
190        #    thick_shell = equat_shell - equat_core
191        #    x_core = polar_core / equat_core
192        #    x_polar_shell = (polar_shell - polar_core)/(equat_shell - equat_core)
193        # Auto translation (old <=> new) happens after hand_convert
194        #    equat_shell <=> thick_shell
195        #    polar_core <=> x_core
196        #    polar_shell <=> x_polar_shell
197        # So...
198        equat_core, equat_shell = oldpars['equat_core'], oldpars['equat_shell']
199        polar_core, polar_shell = oldpars['polar_core'], oldpars['polar_shell']
200        oldpars['equat_shell'] = equat_shell - equat_core
201        oldpars['polar_core'] = polar_core / equat_core
202        oldpars['polar_shell'] = (polar_shell-polar_core)/(equat_shell-equat_core)
203    elif name == 'hollow_cylinder':
204        # now uses radius and thickness
205        thickness = oldpars['radius'] - oldpars['core_radius']
206        oldpars['radius'] = thickness
207        if 'radius.width' in oldpars:
208            pd = oldpars['radius.width']*oldpars['radius']/thickness
209            oldpars['radius.width'] = pd
210    elif name == 'multilayer_vesicle':
211        if 'scale' in oldpars:
212            oldpars['volfraction'] = oldpars['scale']
213            oldpars['scale'] = 1.0
214        if 'scale.lower' in oldpars:
215            oldpars['volfraction.lower'] = oldpars['scale.lower']
216        if 'scale.upper' in oldpars:
217            oldpars['volfraction.upper'] = oldpars['scale.upper']
218        if 'scale.fittable' in oldpars:
219            oldpars['volfraction.fittable'] = oldpars['scale.fittable']
220        if 'scale.std' in oldpars:
221            oldpars['volfraction.std'] = oldpars['scale.std']
222        if 'scale.units' in oldpars:
223            oldpars['volfraction.units'] = oldpars['scale.units']
224    elif name == 'pearl_necklace':
225        pass
226        #_remove_pd(oldpars, 'num_pearls', name)
227        #_remove_pd(oldpars, 'thick_string', name)
228    elif name == 'polymer_micelle':
229        if 'ndensity' in oldpars:
230            oldpars['ndensity'] /= 1e15
231        if 'ndensity.lower' in oldpars:
232            oldpars['ndensity.lower'] /= 1e15
233        if 'ndensity.upper' in oldpars:
234            oldpars['ndensity.upper'] /= 1e15
235    elif name == 'rpa':
236        # convert scattering lengths from femtometers to centimeters
237        for p in "L1", "L2", "L3", "L4":
238            if p in oldpars:
239                oldpars[p] /= 1e-13
240            if p + ".lower" in oldpars:
241                oldpars[p + ".lower"] /= 1e-13
242            if p + ".upper" in oldpars:
243                oldpars[p + ".upper"] /= 1e-13
244    elif name == 'spherical_sld':
245        j = 0
246        while "func_inter" + str(j) in oldpars:
247            name = "func_inter" + str(j)
248            new_name = "shape" + str(j + 1)
249            if oldpars[name] == 'Erf(|nu|*z)':
250                oldpars[new_name] = int(0)
251            elif oldpars[name] == 'RPower(z^|nu|)':
252                oldpars[new_name] = int(1)
253            elif oldpars[name] == 'LPower(z^|nu|)':
254                oldpars[new_name] = int(2)
255            elif oldpars[name] == 'RExp(-|nu|*z)':
256                oldpars[new_name] = int(3)
257            elif oldpars[name] == 'LExp(-|nu|*z)':
258                oldpars[new_name] = int(4)
259            else:
260                oldpars[new_name] = int(0)
261            oldpars.pop(name)
262            oldpars['n_shells'] = str(j + 1)
263            j += 1
264    elif name == 'teubner_strey':
265        # basically undoing the entire Teubner-Strey calculations here.
266        #    drho = (sld_a - sld_b)
267        #    k = 2.0*math.pi*xi/d
268        #    a2 = (1.0 + k**2)**2
269        #    c1 = 2.0 * xi**2 * (1.0 - k**2)
270        #    c2 = xi**4
271        #    prefactor = 8.0*math.pi*phi*(1.0-phi)*drho**2*c2/xi
272        #    scale = 1e-4*prefactor
273        #    oldpars['scale'] = a2/scale
274        #    oldpars['c1'] = c1/scale
275        #    oldpars['c2'] = c2/scale
276
277        # need xi, d, sld_a, sld_b, phi=volfraction_a
278        # assume contrast is 1.0e-6, scale=1, background=0
279        sld_a, sld_b = 1.0, 0.
280        drho = sld_a - sld_b
281
282        # find xi
283        p_scale = oldpars['scale']
284        p_c1 = oldpars['c1']
285        p_c2 = oldpars['c2']
286        i_1 = 0.5*p_c1/p_c2
287        i_2 = math.sqrt(math.fabs(p_scale/p_c2))
288        i_3 = 2/(i_1 + i_2)
289        xi = math.sqrt(math.fabs(i_3))
290
291        # find d from xi
292        k = math.sqrt(math.fabs(1 - 0.5*p_c1/p_c2*xi**2))
293        d = 2*math.pi*xi/k
294
295        # solve quadratic phi (1-phi) = xi/(1e-4 8 pi drho^2 c2)
296        # favour volume fraction in [0, 0.5]
297        c = xi / (1e-4 * 8.0 * math.pi * drho**2 * p_c2)
298        phi = 0.5 - math.sqrt(0.25 - c)
299
300        # scale sld_a by 1e-6 because the translator will scale it back
301        oldpars.update(volfraction_a=phi, xi=xi, d=d, sld_a=sld_a*1e-6,
302                       sld_b=sld_b, scale=1.0)
303        oldpars.pop('c1')
304        oldpars.pop('c2')
305
306    return oldpars
307
308def convert_model(name, pars, use_underscore=False, model_version=(3, 1, 2)):
309    """
310    Convert model from old style parameter names to new style.
311    """
312    newpars = pars
313    keys = sorted(CONVERSION_TABLE.keys())
314    for i, version in enumerate(keys):
315        # Don't allow indices outside list
316        next_i = i + 1
317        if next_i == len(keys):
318            next_i = i
319        # If the save state is from a later version, skip the check
320        if model_version <= keys[next_i]:
321            newname = _conversion_target(name, version)
322        else:
323            newname = None
324        # If no conversion is found, move on
325        if newname is None:
326            newname = name
327            continue
328        if ':' in newname:   # core_shell_ellipsoid:1
329            model_info = load_model_info(newname[:-2])
330            # Know the table exists and isn't multiplicity so grab it directly
331            # Can't use _get_translation_table since that will return the 'bare'
332            # version.
333            translation = CONVERSION_TABLE.get(version, {})[newname][1]
334        else:
335            model_info = load_model_info(newname)
336            translation = _get_translation_table(model_info, version)
337        newpars = _hand_convert(newname, newpars, version)
338        newpars = _convert_pars(newpars, translation)
339        # TODO: Still not convinced this is the best check
340        if not model_info.structure_factor and version == (3, 1, 2):
341            newpars = _rescale_sld(model_info, newpars, 1e6)
342        newpars.setdefault('scale', 1.0)
343        newpars.setdefault('background', 0.0)
344        if use_underscore:
345            newpars = _pd_to_underscores(newpars)
346        name = newname
347    return newname, newpars
348
349# ========= BACKWARD CONVERSION sasmodels => sasview 3.x ===========
350
351def _revert_pars(pars, mapping):
352    """
353    Rename the parameters and any associated polydispersity attributes.
354    """
355    newpars = pars.copy()
356
357    for new, old in mapping.items():
358        for underscore, dot in PD_DOT:
359            if old and old+underscore == new+dot:
360                continue
361            if new+underscore in newpars:
362                if old is not None:
363                    newpars[old+dot] = pars[new+underscore]
364                del newpars[new+underscore]
365    for k in list(newpars.keys()):
366        for underscore, dot in PD_DOT[1:]:  # skip "" => ""
367            if k.endswith(underscore):
368                newpars[k[:-len(underscore)]+dot] = newpars[k]
369                del newpars[k]
370    return newpars
371
372def revert_name(model_info):
373    oldname, _ = CONVERSION_TABLE.get(model_info.id, [None, {}])
374    return oldname
375
376def _remove_pd(pars, key, name):
377    """
378    Remove polydispersity from the parameter list.
379
380    Note: operates in place
381    """
382    # Bumps style parameter names
383    width = pars.pop(key+".width", 0.0)
384    n_points = pars.pop(key+".npts", 0)
385    if width != 0.0 and n_points != 0:
386        warnings.warn("parameter %s not polydisperse in sasview %s"%(key, name))
387    pars.pop(key+".nsigmas", None)
388    pars.pop(key+".type", None)
389    return pars
390
391def _trim_vectors(model_info, pars, oldpars):
392    _, translation = CONVERSION_TABLE.get(model_info.id, [None, {}])
393    for p in model_info.parameters.kernel_parameters:
394        if p.length_control is not None:
395            n = int(pars[p.length_control])
396            oldname = translation.get(p.id, p.id)
397            for k in range(n+1, p.length+1):
398                for _, old in PD_DOT:
399                    oldpars.pop(oldname+str(k)+old, None)
400    return oldpars
401
402def revert_pars(model_info, pars):
403    """
404    Convert model from new style parameter names to old style.
405    """
406    if model_info.composition is not None:
407        composition_type, parts = model_info.composition
408        if composition_type == 'product':
409            translation = _get_translation_table(parts[0])
410            # structure factor models include scale:scale_factor mapping
411            translation.update(_get_translation_table(parts[1]))
412        else:
413            raise NotImplementedError("cannot convert to sasview sum")
414    else:
415        translation = _get_translation_table(model_info)
416    oldpars = _revert_pars(_rescale_sld(model_info, pars, 1e-6), translation)
417    oldpars = _trim_vectors(model_info, pars, oldpars)
418
419    # Make sure the control parameter is an integer
420    if "CONTROL" in oldpars:
421        oldpars["CONTROL"] = int(oldpars["CONTROL"])
422
423    # Note: update compare.constrain_pars to match
424    name = model_info.id
425    if name in MODELS_WITHOUT_SCALE or model_info.structure_factor:
426        if oldpars.pop('scale', 1.0) != 1.0:
427            warnings.warn("parameter scale not used in sasview %s"%name)
428    if name in MODELS_WITHOUT_BACKGROUND or model_info.structure_factor:
429        if oldpars.pop('background', 0.0) != 0.0:
430            warnings.warn("parameter background not used in sasview %s"%name)
431
432    # Remove magnetic parameters from non-magnetic sasview models
433    if name not in MAGNETIC_SASVIEW_MODELS:
434        oldpars = dict((k, v) for k, v in oldpars.items() if ':' not in k)
435
436    # If it is a product model P*S, then check the individual forms for special
437    # cases.  Note: despite the structure factor alone not having scale or
438    # background, the product model does, so this is below the test for
439    # models without scale or background.
440    namelist = name.split('*') if '*' in name else [name]
441    for name in namelist:
442        if name in MODELS_WITHOUT_VOLFRACTION:
443            del oldpars['volfraction']
444        elif name == 'core_multi_shell':
445            # kill extra shells
446            for k in range(5, 11):
447                oldpars.pop('sld_shell'+str(k), 0)
448                oldpars.pop('thick_shell'+str(k), 0)
449                oldpars.pop('mtheta:sld'+str(k), 0)
450                oldpars.pop('mphi:sld'+str(k), 0)
451                oldpars.pop('M0:sld'+str(k), 0)
452                _remove_pd(oldpars, 'sld_shell'+str(k), 'sld')
453                _remove_pd(oldpars, 'thick_shell'+str(k), 'thickness')
454        elif name == 'core_shell_parallelepiped':
455            _remove_pd(oldpars, 'rimA', name)
456            _remove_pd(oldpars, 'rimB', name)
457            _remove_pd(oldpars, 'rimC', name)
458        elif name == 'hollow_cylinder':
459            # now uses radius and thickness
460            thickness = oldpars['core_radius']
461            oldpars['radius'] += thickness
462            oldpars['radius.width'] *= thickness/oldpars['radius']
463        #elif name in ['mono_gauss_coil', 'poly_gauss_coil']:
464        #    del oldpars['i_zero']
465        elif name == 'onion':
466            oldpars.pop('n_shells', None)
467        elif name == 'pearl_necklace':
468            _remove_pd(oldpars, 'num_pearls', name)
469            _remove_pd(oldpars, 'thick_string', name)
470        elif name == 'polymer_micelle':
471            if 'ndensity' in oldpars:
472                oldpars['ndensity'] *= 1e15
473        elif name == 'rpa':
474            # convert scattering lengths from femtometers to centimeters
475            for p in "L1", "L2", "L3", "L4":
476                if p in oldpars: oldpars[p] *= 1e-13
477            if pars['case_num'] < 2:
478                for k in ("a", "b"):
479                    for p in ("L", "N", "Phi", "b", "v"):
480                        oldpars.pop(p+k, None)
481                for k in "Kab,Kac,Kad,Kbc,Kbd".split(','):
482                    oldpars.pop(k, None)
483            elif pars['case_num'] < 5:
484                for k in ("a",):
485                    for p in ("L", "N", "Phi", "b", "v"):
486                        oldpars.pop(p+k, None)
487                for k in "Kab,Kac,Kad".split(','):
488                    oldpars.pop(k, None)
489        elif name == 'spherical_sld':
490            oldpars["CONTROL"] -= 1
491            # remove polydispersity from shells
492            for k in range(1, 11):
493                _remove_pd(oldpars, 'thick_flat'+str(k), 'thickness')
494                _remove_pd(oldpars, 'thick_inter'+str(k), 'interface')
495            # remove extra shells
496            for k in range(int(pars['n_shells']), 11):
497                oldpars.pop('sld_flat'+str(k), 0)
498                oldpars.pop('thick_flat'+str(k), 0)
499                oldpars.pop('thick_inter'+str(k), 0)
500                oldpars.pop('func_inter'+str(k), 0)
501                oldpars.pop('nu_inter'+str(k), 0)
502        elif name == 'stacked_disks':
503            _remove_pd(oldpars, 'n_stacking', name)
504        elif name == 'teubner_strey':
505            # basically redoing the entire Teubner-Strey calculations here.
506            volfraction = oldpars.pop('volfraction_a')
507            xi = oldpars.pop('xi')
508            d = oldpars.pop('d')
509            sld_a = oldpars.pop('sld_a')
510            sld_b = oldpars.pop('sld_b')
511            drho = 1e6*(sld_a - sld_b)  # conversion autoscaled these
512            k = 2.0*math.pi*xi/d
513            a2 = (1.0 + k**2)**2
514            c1 = 2.0 * xi**2 * (1.0 - k**2)
515            c2 = xi**4
516            prefactor = 8.0*math.pi*volfraction*(1.0-volfraction)*drho**2*c2/xi
517            scale = 1e-4*prefactor
518            oldpars['scale'] = a2/scale
519            oldpars['c1'] = c1/scale
520            oldpars['c2'] = c2/scale
521
522    #print("convert from",list(sorted(pars)))
523    #print("convert to",list(sorted(oldpars.items())))
524    return oldpars
525
526def constrain_new_to_old(model_info, pars):
527    """
528    Restrict parameter values to those that will match sasview.
529    """
530    name = model_info.id
531    # Note: update convert.revert_model to match
532    if name in MODELS_WITHOUT_SCALE or model_info.structure_factor:
533        pars['scale'] = 1
534    if name in MODELS_WITHOUT_BACKGROUND or model_info.structure_factor:
535        pars['background'] = 0
536    # sasview multiplies background by structure factor
537    if '*' in name:
538        pars['background'] = 0
539
540    # Shut off magnetism when comparing non-magnetic sasview models
541    if name not in MAGNETIC_SASVIEW_MODELS:
542        suppress_magnetism = False
543        for key in pars.keys():
544            if key.startswith("M0:"):
545                suppress_magnetism = suppress_magnetism or (pars[key] != 0)
546                pars[key] = 0
547        if suppress_magnetism:
548            warnings.warn("suppressing magnetism for comparison with sasview")
549
550    # Shut off theta polydispersity since algorithm has changed
551    if 'theta_pd_n' in pars:
552        if pars['theta_pd_n'] != 0:
553            warnings.warn("suppressing theta polydispersity for comparison with sasview")
554        pars['theta_pd_n'] = 0
555
556    # If it is a product model P*S, then check the individual forms for special
557    # cases.  Note: despite the structure factor alone not having scale or
558    # background, the product model does, so this is below the test for
559    # models without scale or background.
560    namelist = name.split('*') if '*' in name else [name]
561    for name in namelist:
562        if name in MODELS_WITHOUT_VOLFRACTION:
563            pars['volfraction'] = 1
564        if name == 'core_multi_shell':
565            pars['n'] = min(math.ceil(pars['n']), 4)
566        elif name == 'gel_fit':
567            pars['scale'] = 1
568        elif name == 'line':
569            pars['scale'] = 1
570            pars['background'] = 0
571        elif name == 'mono_gauss_coil':
572            pars['scale'] = 1
573        elif name == 'onion':
574            pars['n_shells'] = math.ceil(pars['n_shells'])
575        elif name == 'pearl_necklace':
576            pars['string_thickness_pd_n'] = 0
577            pars['number_of_pearls_pd_n'] = 0
578        elif name == 'poly_gauss_coil':
579            pars['scale'] = 1
580        elif name == 'rpa':
581            pars['case_num'] = int(pars['case_num'])
582        elif name == 'spherical_sld':
583            pars['n_shells'] = math.ceil(pars['n_shells'])
584            pars['n_steps'] = math.ceil(pars['n_steps'])
585            for k in range(1, 11):
586                pars['shape%d'%k] = math.trunc(pars['shape%d'%k]+0.5)
587            for k in range(2, 11):
588                pars['thickness%d_pd_n'%k] = 0
589                pars['interface%d_pd_n'%k] = 0
590        elif name == 'teubner_strey':
591            pars['scale'] = 1
592            if pars['volfraction_a'] > 0.5:
593                pars['volfraction_a'] = 1.0 - pars['volfraction_a']
594        elif name == 'unified_power_Rg':
595            pars['level'] = int(pars['level'])
596
597def _check_one(name, seed=None):
598    """
599    Generate a random set of parameters for *name*, and check that they can
600    be converted back to SasView 3.x and forward again to sasmodels.  Raises
601    an error if the parameters are changed.
602    """
603    from . import compare
604
605    model_info = load_model_info(name)
606
607    old_name = revert_name(model_info)
608    if old_name is None:
609        return
610
611    pars = compare.get_pars(model_info, use_demo=False)
612    if seed is not None:
613        np.random.seed(seed)
614    pars = compare.randomize_pars(model_info, pars)
615    if name == "teubner_strey":
616        # T-S model is underconstrained, so fix the assumptions.
617        pars['sld_a'], pars['sld_b'] = 1.0, 0.0
618    compare.constrain_pars(model_info, pars)
619    constrain_new_to_old(model_info, pars)
620    old_pars = revert_pars(model_info, pars)
621    new_name, new_pars = convert_model(old_name, old_pars, use_underscore=True)
622    if 1:
623        print("==== %s in ====="%name)
624        print(str(compare.parlist(model_info, pars, True)))
625        print("==== %s ====="%old_name)
626        for k, v in sorted(old_pars.items()):
627            print(k, v)
628        print("==== %s out ====="%new_name)
629        print(str(compare.parlist(model_info, new_pars, True)))
630    assert name == new_name, "%r != %r"%(name, new_name)
631    for k, v in new_pars.items():
632        assert k in pars, "%s: %r appeared from conversion"%(name, k)
633        if isinstance(v, float):
634            assert abs(v-pars[k]) <= abs(1e-12*v), \
635                "%s: %r  %s != %s"%(name, k, v, pars[k])
636        else:
637            assert v == pars[k], "%s: %r  %s != %s"%(name, k, v, pars[k])
638    for k, v in pars.items():
639        assert k in pars, "%s: %r not converted"%(name, k)
640
641def test_backward_forward():
642    from .core import list_models
643    L = lambda name: _check_one(name, seed=1)
644    for name in list_models('all'):
645        yield L, name
Note: See TracBrowser for help on using the repository browser.