source: sasmodels/sasmodels/convert.py @ 16fd9e5

core_shell_microgelscostrafo411magnetic_modelticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since 16fd9e5 was 16fd9e5, checked in by krzywon, 7 years ago

#795: A check for the spherical SLD is now in place and versioning is now based off of the SasView? version being converted from.

  • Property mode set to 100644
File size: 23.6 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    base_version = '3.1.2'
163    if name == 'core_shell_parallelepiped' and version == base_version:
164        # Make sure pd on rim parameters defaults to zero
165        # ... probably not necessary.
166        oldpars['rimA.width'] = 0.0
167        oldpars['rimB.width'] = 0.0
168        oldpars['rimC.width'] = 0.0
169    elif name == 'core_shell_ellipsoid:1' and version == base_version:
170        # Reverse translation (from new to old), from core_shell_ellipsoid.c
171        #    equat_shell = equat_core + thick_shell
172        #    polar_core = equat_core * x_core
173        #    polar_shell = equat_core * x_core + thick_shell*x_polar_shell
174        # Forward translation (from old to new), inverting reverse translation:
175        #    thick_shell = equat_shell - equat_core
176        #    x_core = polar_core / equat_core
177        #    x_polar_shell = (polar_shell - polar_core)/(equat_shell - equat_core)
178        # Auto translation (old <=> new) happens after hand_convert
179        #    equat_shell <=> thick_shell
180        #    polar_core <=> x_core
181        #    polar_shell <=> x_polar_shell
182        # So...
183        equat_core, equat_shell = oldpars['equat_core'], oldpars['equat_shell']
184        polar_core, polar_shell = oldpars['polar_core'], oldpars['polar_shell']
185        oldpars['equat_shell'] = equat_shell - equat_core
186        oldpars['polar_core'] = polar_core / equat_core
187        oldpars['polar_shell'] = (polar_shell-polar_core)/(equat_shell-equat_core)
188    elif name == 'hollow_cylinder' and version == base_version:
189        # now uses radius and thickness
190        thickness = oldpars['radius'] - oldpars['core_radius']
191        oldpars['radius'] = thickness
192        if 'radius.width' in oldpars:
193            pd = oldpars['radius.width']*oldpars['radius']/thickness
194            oldpars['radius.width'] = pd
195    elif name == 'multilayer_vesicle' and version == base_version:
196        if 'scale' in oldpars:
197            oldpars['volfraction'] = oldpars['scale']
198            oldpars['scale'] = 1.0
199        if 'scale.lower' in oldpars:
200            oldpars['volfraction.lower'] = oldpars['scale.lower']
201        if 'scale.upper' in oldpars:
202            oldpars['volfraction.upper'] = oldpars['scale.upper']
203        if 'scale.fittable' in oldpars:
204            oldpars['volfraction.fittable'] = oldpars['scale.fittable']
205        if 'scale.std' in oldpars:
206            oldpars['volfraction.std'] = oldpars['scale.std']
207        if 'scale.units' in oldpars:
208            oldpars['volfraction.units'] = oldpars['scale.units']
209    elif name == 'pearl_necklace' and version == base_version:
210        pass
211        #_remove_pd(oldpars, 'num_pearls', name)
212        #_remove_pd(oldpars, 'thick_string', name)
213    elif name == 'polymer_micelle' and version == base_version:
214        if 'ndensity' in oldpars:
215            oldpars['ndensity'] /= 1e15
216        if 'ndensity.lower' in oldpars:
217            oldpars['ndensity.lower'] /= 1e15
218        if 'ndensity.upper' in oldpars:
219            oldpars['ndensity.upper'] /= 1e15
220    elif name == 'rpa' and version == base_version:
221        # convert scattering lengths from femtometers to centimeters
222        for p in "L1", "L2", "L3", "L4":
223            if p in oldpars:
224                oldpars[p] /= 1e-13
225            if p + ".lower" in oldpars:
226                oldpars[p + ".lower"] /= 1e-13
227            if p + ".upper" in oldpars:
228                oldpars[p + ".upper"] /= 1e-13
229    elif name == 'spherical_sld' and version == base_version:
230        j = 0
231        while "func_inter" + str(j) in oldpars:
232            name = "func_inter" + str(j)
233            new_name = "shape" + str(j + 1)
234            if oldpars[name] == 'Erf(|nu|*z)':
235                oldpars[new_name] = int(0)
236            elif oldpars[name] == 'RPower(z^|nu|)':
237                oldpars[new_name] = int(1)
238            elif oldpars[name] == 'LPower(z^|nu|)':
239                oldpars[new_name] = int(2)
240            elif oldpars[name] == 'RExp(-|nu|*z)':
241                oldpars[new_name] = int(3)
242            elif oldpars[name] == 'LExp(-|nu|*z)':
243                oldpars[new_name] = int(4)
244            else:
245                oldpars[new_name] = int(0)
246            oldpars.pop(name)
247            oldpars['n_shells'] = str(j + 1)
248            j += 1
249    elif name == 'teubner_strey' and version == base_version:
250        # basically undoing the entire Teubner-Strey calculations here.
251        #    drho = (sld_a - sld_b)
252        #    k = 2.0*math.pi*xi/d
253        #    a2 = (1.0 + k**2)**2
254        #    c1 = 2.0 * xi**2 * (1.0 - k**2)
255        #    c2 = xi**4
256        #    prefactor = 8.0*math.pi*phi*(1.0-phi)*drho**2*c2/xi
257        #    scale = 1e-4*prefactor
258        #    oldpars['scale'] = a2/scale
259        #    oldpars['c1'] = c1/scale
260        #    oldpars['c2'] = c2/scale
261
262        # need xi, d, sld_a, sld_b, phi=volfraction_a
263        # assume contrast is 1.0e-6, scale=1, background=0
264        sld_a, sld_b = 1.0, 0.
265        drho = sld_a - sld_b
266
267        # find xi
268        p_scale = oldpars['scale']
269        p_c1 = oldpars['c1']
270        p_c2= oldpars['c2']
271        i_1 = 0.5*p_c1/p_c2
272        i_2 = math.sqrt(math.fabs(p_scale/p_c2))
273        i_3 = 2/(i_1 + i_2)
274        xi = math.sqrt(math.fabs(i_3))
275
276        # find d from xi
277        k = math.sqrt(math.fabs(1 - 0.5*p_c1/p_c2*xi**2))
278        d = 2*math.pi*xi/k
279
280        # solve quadratic phi (1-phi) = xi/(1e-4 8 pi drho^2 c2)
281        # favour volume fraction in [0, 0.5]
282        c = xi / (1e-4 * 8.0 * math.pi * drho**2 * p_c2)
283        phi = 0.5 - math.sqrt(0.25 - c)
284
285        # scale sld_a by 1e-6 because the translator will scale it back
286        oldpars.update(volfraction_a=phi, xi=xi, d=d, sld_a=sld_a*1e-6,
287                       sld_b=sld_b, scale=1.0)
288        oldpars.pop('c1')
289        oldpars.pop('c2')
290
291    return oldpars
292
293def convert_model(name, pars, use_underscore=False):
294    """
295    Convert model from old style parameter names to new style.
296    """
297    newpars = pars
298    for version, _ in sorted(CONVERSION_TABLE.iteritems()):
299        newname = _conversion_target(name, version)
300        if newname is None:
301            newname = name
302            continue
303        if ':' in newname:   # core_shell_ellipsoid:1
304            model_info = load_model_info(newname[:-2])
305            # Know the table exists and isn't multiplicity so grab it directly
306            # Can't use _get_translation_table since that will return the 'bare'
307            # version.
308            translation = CONVERSION_TABLE.get(version)[newname][1]
309        else:
310            model_info = load_model_info(newname)
311            translation = _get_translation_table(model_info, version)
312        newpars = _hand_convert(newname, newpars, version)
313        newpars = _convert_pars(newpars, translation)
314        if not model_info.structure_factor:
315            newpars = _rescale_sld(model_info, newpars, 1e6)
316        newpars.setdefault('scale', 1.0)
317        newpars.setdefault('background', 0.0)
318        if use_underscore:
319            newpars = _pd_to_underscores(newpars)
320        name = newname
321    return newname, newpars
322
323# ========= BACKWARD CONVERSION sasmodels => sasview 3.x ===========
324
325def _revert_pars(pars, mapping):
326    """
327    Rename the parameters and any associated polydispersity attributes.
328    """
329    newpars = pars.copy()
330
331    for new, old in mapping.items():
332        for underscore, dot in PD_DOT:
333            if old and old+underscore == new+dot:
334                continue
335            if new+underscore in newpars:
336                if old is not None:
337                    newpars[old+dot] = pars[new+underscore]
338                del newpars[new+underscore]
339    for k in list(newpars.keys()):
340        for underscore, dot in PD_DOT[1:]:  # skip "" => ""
341            if k.endswith(underscore):
342                newpars[k[:-len(underscore)]+dot] = newpars[k]
343                del newpars[k]
344    return newpars
345
346def revert_name(model_info):
347    oldname, _ = CONVERSION_TABLE.get(model_info.id, [None, {}])
348    return oldname
349
350def _remove_pd(pars, key, name):
351    """
352    Remove polydispersity from the parameter list.
353
354    Note: operates in place
355    """
356    # Bumps style parameter names
357    width = pars.pop(key+".width", 0.0)
358    n_points = pars.pop(key+".npts", 0)
359    if width != 0.0 and n_points != 0:
360        warnings.warn("parameter %s not polydisperse in sasview %s"%(key, name))
361    pars.pop(key+".nsigmas", None)
362    pars.pop(key+".type", None)
363    return pars
364
365def _trim_vectors(model_info, pars, oldpars):
366    _, translation = CONVERSION_TABLE.get(model_info.id, [None, {}])
367    for p in model_info.parameters.kernel_parameters:
368        if p.length_control is not None:
369            n = int(pars[p.length_control])
370            oldname = translation.get(p.id, p.id)
371            for k in range(n+1, p.length+1):
372                for _, old in PD_DOT:
373                    oldpars.pop(oldname+str(k)+old, None)
374    return oldpars
375
376def revert_pars(model_info, pars):
377    """
378    Convert model from new style parameter names to old style.
379    """
380    if model_info.composition is not None:
381        composition_type, parts = model_info.composition
382        if composition_type == 'product':
383            translation = _get_translation_table(parts[0])
384            # structure factor models include scale:scale_factor mapping
385            translation.update(_get_translation_table(parts[1]))
386        else:
387            raise NotImplementedError("cannot convert to sasview sum")
388    else:
389        translation = _get_translation_table(model_info)
390    oldpars = _revert_pars(_rescale_sld(model_info, pars, 1e-6), translation)
391    oldpars = _trim_vectors(model_info, pars, oldpars)
392
393    # Make sure the control parameter is an integer
394    if "CONTROL" in oldpars:
395        oldpars["CONTROL"] = int(oldpars["CONTROL"])
396
397    # Note: update compare.constrain_pars to match
398    name = model_info.id
399    if name in MODELS_WITHOUT_SCALE or model_info.structure_factor:
400        if oldpars.pop('scale', 1.0) != 1.0:
401            warnings.warn("parameter scale not used in sasview %s"%name)
402    if name in MODELS_WITHOUT_BACKGROUND or model_info.structure_factor:
403        if oldpars.pop('background', 0.0) != 0.0:
404            warnings.warn("parameter background not used in sasview %s"%name)
405
406    # Remove magnetic parameters from non-magnetic sasview models
407    if name not in MAGNETIC_SASVIEW_MODELS:
408        oldpars = dict((k, v) for k, v in oldpars.items() if ':' not in k)
409
410    # If it is a product model P*S, then check the individual forms for special
411    # cases.  Note: despite the structure factor alone not having scale or
412    # background, the product model does, so this is below the test for
413    # models without scale or background.
414    namelist = name.split('*') if '*' in name else [name]
415    for name in namelist:
416        if name in MODELS_WITHOUT_VOLFRACTION:
417            del oldpars['volfraction']
418        elif name == 'core_multi_shell':
419            # kill extra shells
420            for k in range(5, 11):
421                oldpars.pop('sld_shell'+str(k), 0)
422                oldpars.pop('thick_shell'+str(k), 0)
423                oldpars.pop('mtheta:sld'+str(k), 0)
424                oldpars.pop('mphi:sld'+str(k), 0)
425                oldpars.pop('M0:sld'+str(k), 0)
426                _remove_pd(oldpars, 'sld_shell'+str(k), 'sld')
427                _remove_pd(oldpars, 'thick_shell'+str(k), 'thickness')
428        elif name == 'core_shell_parallelepiped':
429            _remove_pd(oldpars, 'rimA', name)
430            _remove_pd(oldpars, 'rimB', name)
431            _remove_pd(oldpars, 'rimC', name)
432        elif name == 'hollow_cylinder':
433            # now uses radius and thickness
434            thickness = oldpars['core_radius']
435            oldpars['radius'] += thickness
436            oldpars['radius.width'] *= thickness/oldpars['radius']
437        #elif name in ['mono_gauss_coil', 'poly_gauss_coil']:
438        #    del oldpars['i_zero']
439        elif name == 'onion':
440            oldpars.pop('n_shells', None)
441        elif name == 'pearl_necklace':
442            _remove_pd(oldpars, 'num_pearls', name)
443            _remove_pd(oldpars, 'thick_string', name)
444        elif name == 'polymer_micelle':
445            if 'ndensity' in oldpars:
446                oldpars['ndensity'] *= 1e15
447        elif name == 'rpa':
448            # convert scattering lengths from femtometers to centimeters
449            for p in "L1", "L2", "L3", "L4":
450                if p in oldpars: oldpars[p] *= 1e-13
451            if pars['case_num'] < 2:
452                for k in ("a", "b"):
453                    for p in ("L", "N", "Phi", "b", "v"):
454                        oldpars.pop(p+k, None)
455                for k in "Kab,Kac,Kad,Kbc,Kbd".split(','):
456                    oldpars.pop(k, None)
457            elif pars['case_num'] < 5:
458                for k in ("a",):
459                    for p in ("L", "N", "Phi", "b", "v"):
460                        oldpars.pop(p+k, None)
461                for k in "Kab,Kac,Kad".split(','):
462                    oldpars.pop(k, None)
463        elif name == 'spherical_sld':
464            oldpars["CONTROL"] -= 1
465            # remove polydispersity from shells
466            for k in range(1, 11):
467                _remove_pd(oldpars, 'thick_flat'+str(k), 'thickness')
468                _remove_pd(oldpars, 'thick_inter'+str(k), 'interface')
469            # remove extra shells
470            for k in range(int(pars['n_shells']), 11):
471                oldpars.pop('sld_flat'+str(k), 0)
472                oldpars.pop('thick_flat'+str(k), 0)
473                oldpars.pop('thick_inter'+str(k), 0)
474                oldpars.pop('func_inter'+str(k), 0)
475                oldpars.pop('nu_inter'+str(k), 0)
476        elif name == 'stacked_disks':
477            _remove_pd(oldpars, 'n_stacking', name)
478        elif name == 'teubner_strey':
479            # basically redoing the entire Teubner-Strey calculations here.
480            volfraction = oldpars.pop('volfraction_a')
481            xi = oldpars.pop('xi')
482            d = oldpars.pop('d')
483            sld_a = oldpars.pop('sld_a')
484            sld_b = oldpars.pop('sld_b')
485            drho = 1e6*(sld_a - sld_b)  # conversion autoscaled these
486            k = 2.0*math.pi*xi/d
487            a2 = (1.0 + k**2)**2
488            c1 = 2.0 * xi**2 * (1.0 - k**2)
489            c2 = xi**4
490            prefactor = 8.0*math.pi*volfraction*(1.0-volfraction)*drho**2*c2/xi
491            scale = 1e-4*prefactor
492            oldpars['scale'] = a2/scale
493            oldpars['c1'] = c1/scale
494            oldpars['c2'] = c2/scale
495
496    #print("convert from",list(sorted(pars)))
497    #print("convert to",list(sorted(oldpars.items())))
498    return oldpars
499
500def constrain_new_to_old(model_info, pars):
501    """
502    Restrict parameter values to those that will match sasview.
503    """
504    name = model_info.id
505    # Note: update convert.revert_model to match
506    if name in MODELS_WITHOUT_SCALE or model_info.structure_factor:
507        pars['scale'] = 1
508    if name in MODELS_WITHOUT_BACKGROUND or model_info.structure_factor:
509        pars['background'] = 0
510    # sasview multiplies background by structure factor
511    if '*' in name:
512        pars['background'] = 0
513
514    # Shut off magnetism when comparing non-magnetic sasview models
515    if name not in MAGNETIC_SASVIEW_MODELS:
516        suppress_magnetism = False
517        for key in pars.keys():
518            if key.startswith("M0:"):
519                suppress_magnetism = suppress_magnetism or (pars[key] != 0)
520                pars[key] = 0
521        if suppress_magnetism:
522            warnings.warn("suppressing magnetism for comparison with sasview")
523
524    # Shut off theta polydispersity since algorithm has changed
525    if 'theta_pd_n' in pars:
526        if pars['theta_pd_n'] != 0:
527            warnings.warn("suppressing theta polydispersity for comparison with sasview")
528        pars['theta_pd_n'] = 0
529
530    # If it is a product model P*S, then check the individual forms for special
531    # cases.  Note: despite the structure factor alone not having scale or
532    # background, the product model does, so this is below the test for
533    # models without scale or background.
534    namelist = name.split('*') if '*' in name else [name]
535    for name in namelist:
536        if name in MODELS_WITHOUT_VOLFRACTION:
537            pars['volfraction'] = 1
538        if name == 'core_multi_shell':
539            pars['n'] = min(math.ceil(pars['n']), 4)
540        elif name == 'gel_fit':
541            pars['scale'] = 1
542        elif name == 'line':
543            pars['scale'] = 1
544            pars['background'] = 0
545        elif name == 'mono_gauss_coil':
546            pars['scale'] = 1
547        elif name == 'onion':
548            pars['n_shells'] = math.ceil(pars['n_shells'])
549        elif name == 'pearl_necklace':
550            pars['string_thickness_pd_n'] = 0
551            pars['number_of_pearls_pd_n'] = 0
552        elif name == 'poly_gauss_coil':
553            pars['scale'] = 1
554        elif name == 'rpa':
555            pars['case_num'] = int(pars['case_num'])
556        elif name == 'spherical_sld':
557            pars['n_shells'] = math.ceil(pars['n_shells'])
558            pars['n_steps'] = math.ceil(pars['n_steps'])
559            for k in range(1, 11):
560                pars['shape%d'%k] = math.trunc(pars['shape%d'%k]+0.5)
561            for k in range(2, 11):
562                pars['thickness%d_pd_n'%k] = 0
563                pars['interface%d_pd_n'%k] = 0
564        elif name == 'teubner_strey':
565            pars['scale'] = 1
566            if pars['volfraction_a'] > 0.5:
567                pars['volfraction_a'] = 1.0 - pars['volfraction_a']
568        elif name == 'unified_power_Rg':
569            pars['level'] = int(pars['level'])
570
571def _check_one(name, seed=None):
572    """
573    Generate a random set of parameters for *name*, and check that they can
574    be converted back to SasView 3.x and forward again to sasmodels.  Raises
575    an error if the parameters are changed.
576    """
577    from . import compare
578
579    model_info = load_model_info(name)
580
581    old_name = revert_name(model_info)
582    if old_name is None:
583        return
584
585    pars = compare.get_pars(model_info, use_demo=False)
586    pars = compare.randomize_pars(model_info, pars, seed=seed)
587    if name == "teubner_strey":
588        # T-S model is underconstrained, so fix the assumptions.
589        pars['sld_a'], pars['sld_b'] = 1.0, 0.0
590    compare.constrain_pars(model_info, pars)
591    constrain_new_to_old(model_info, pars)
592    old_pars = revert_pars(model_info, pars)
593    new_name, new_pars = convert_model(old_name, old_pars, use_underscore=True)
594    if 1:
595        print("==== %s in ====="%name)
596        print(str(compare.parlist(model_info, pars, True)))
597        print("==== %s ====="%old_name)
598        for k, v in sorted(old_pars.items()):
599            print(k, v)
600        print("==== %s out ====="%new_name)
601        print(str(compare.parlist(model_info, new_pars, True)))
602    assert name==new_name, "%r != %r"%(name, new_name)
603    for k, v in new_pars.items():
604        assert k in pars, "%s: %r appeared from conversion"%(name, k)
605        if isinstance(v, float):
606            assert abs(v-pars[k])<=abs(1e-12*v), "%s: %r  %s != %s"%(name, k, v, pars[k])
607        else:
608            assert v == pars[k], "%s: %r  %s != %s"%(name, k, v, pars[k])
609    for k, v in pars.items():
610        assert k in pars, "%s: %r not converted"%(name, k)
611
612def test_backward_forward():
613    from .core import list_models
614    for name in list_models('all'):
615        L = lambda: _check_one(name, seed=1)
616        L.description = name
617        yield L
Note: See TracBrowser for help on using the repository browser.