source: sasmodels/sasmodels/convert.py @ 54fb5d8

core_shell_microgelscostrafo411magnetic_modelticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since 54fb5d8 was 54fb5d8, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

slightly cleaner handling of version specific hand-coded conversions

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