source: sasmodels/sasmodels/convert.py @ 790b16bb

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

Default to an empty dictionary when getting a value from CONVERSION_TABLE.

  • Property mode set to 100644
File size: 24.0 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, model_version=(3,1,2)):
298    """
299    Convert model from old style parameter names to new style.
300    """
301    newpars = pars
302    keys = sorted(CONVERSION_TABLE.keys())
303    for i, version in enumerate(keys):
304        # Don't allow indices outside list
305        next_i = i + 1
306        if next_i == len(keys):
307            next_i = i
308        # If the save state is from a later version, skip the check
309        if model_version <= keys[next_i]:
310            newname = _conversion_target(name, version)
311        else:
312            newname = None
313        # If no conversion is found, move on
314        if newname is None:
315            newname = name
316            continue
317        if ':' in newname:   # core_shell_ellipsoid:1
318            model_info = load_model_info(newname[:-2])
319            # Know the table exists and isn't multiplicity so grab it directly
320            # Can't use _get_translation_table since that will return the 'bare'
321            # version.
322            translation = CONVERSION_TABLE.get(version, {})[newname][1]
323        else:
324            model_info = load_model_info(newname)
325            translation = _get_translation_table(model_info, version)
326        newpars = _hand_convert(newname, newpars, version)
327        newpars = _convert_pars(newpars, translation)
328        # TODO: Still not convinced this is the best check
329        if not model_info.structure_factor and version == (3,1,2):
330            newpars = _rescale_sld(model_info, newpars, 1e6)
331        newpars.setdefault('scale', 1.0)
332        newpars.setdefault('background', 0.0)
333        if use_underscore:
334            newpars = _pd_to_underscores(newpars)
335        name = newname
336    return newname, newpars
337
338# ========= BACKWARD CONVERSION sasmodels => sasview 3.x ===========
339
340def _revert_pars(pars, mapping):
341    """
342    Rename the parameters and any associated polydispersity attributes.
343    """
344    newpars = pars.copy()
345
346    for new, old in mapping.items():
347        for underscore, dot in PD_DOT:
348            if old and old+underscore == new+dot:
349                continue
350            if new+underscore in newpars:
351                if old is not None:
352                    newpars[old+dot] = pars[new+underscore]
353                del newpars[new+underscore]
354    for k in list(newpars.keys()):
355        for underscore, dot in PD_DOT[1:]:  # skip "" => ""
356            if k.endswith(underscore):
357                newpars[k[:-len(underscore)]+dot] = newpars[k]
358                del newpars[k]
359    return newpars
360
361def revert_name(model_info):
362    oldname, _ = CONVERSION_TABLE.get(model_info.id, [None, {}])
363    return oldname
364
365def _remove_pd(pars, key, name):
366    """
367    Remove polydispersity from the parameter list.
368
369    Note: operates in place
370    """
371    # Bumps style parameter names
372    width = pars.pop(key+".width", 0.0)
373    n_points = pars.pop(key+".npts", 0)
374    if width != 0.0 and n_points != 0:
375        warnings.warn("parameter %s not polydisperse in sasview %s"%(key, name))
376    pars.pop(key+".nsigmas", None)
377    pars.pop(key+".type", None)
378    return pars
379
380def _trim_vectors(model_info, pars, oldpars):
381    _, translation = CONVERSION_TABLE.get(model_info.id, [None, {}])
382    for p in model_info.parameters.kernel_parameters:
383        if p.length_control is not None:
384            n = int(pars[p.length_control])
385            oldname = translation.get(p.id, p.id)
386            for k in range(n+1, p.length+1):
387                for _, old in PD_DOT:
388                    oldpars.pop(oldname+str(k)+old, None)
389    return oldpars
390
391def revert_pars(model_info, pars):
392    """
393    Convert model from new style parameter names to old style.
394    """
395    if model_info.composition is not None:
396        composition_type, parts = model_info.composition
397        if composition_type == 'product':
398            translation = _get_translation_table(parts[0])
399            # structure factor models include scale:scale_factor mapping
400            translation.update(_get_translation_table(parts[1]))
401        else:
402            raise NotImplementedError("cannot convert to sasview sum")
403    else:
404        translation = _get_translation_table(model_info)
405    oldpars = _revert_pars(_rescale_sld(model_info, pars, 1e-6), translation)
406    oldpars = _trim_vectors(model_info, pars, oldpars)
407
408    # Make sure the control parameter is an integer
409    if "CONTROL" in oldpars:
410        oldpars["CONTROL"] = int(oldpars["CONTROL"])
411
412    # Note: update compare.constrain_pars to match
413    name = model_info.id
414    if name in MODELS_WITHOUT_SCALE or model_info.structure_factor:
415        if oldpars.pop('scale', 1.0) != 1.0:
416            warnings.warn("parameter scale not used in sasview %s"%name)
417    if name in MODELS_WITHOUT_BACKGROUND or model_info.structure_factor:
418        if oldpars.pop('background', 0.0) != 0.0:
419            warnings.warn("parameter background not used in sasview %s"%name)
420
421    # Remove magnetic parameters from non-magnetic sasview models
422    if name not in MAGNETIC_SASVIEW_MODELS:
423        oldpars = dict((k, v) for k, v in oldpars.items() if ':' not in k)
424
425    # If it is a product model P*S, then check the individual forms for special
426    # cases.  Note: despite the structure factor alone not having scale or
427    # background, the product model does, so this is below the test for
428    # models without scale or background.
429    namelist = name.split('*') if '*' in name else [name]
430    for name in namelist:
431        if name in MODELS_WITHOUT_VOLFRACTION:
432            del oldpars['volfraction']
433        elif name == 'core_multi_shell':
434            # kill extra shells
435            for k in range(5, 11):
436                oldpars.pop('sld_shell'+str(k), 0)
437                oldpars.pop('thick_shell'+str(k), 0)
438                oldpars.pop('mtheta:sld'+str(k), 0)
439                oldpars.pop('mphi:sld'+str(k), 0)
440                oldpars.pop('M0:sld'+str(k), 0)
441                _remove_pd(oldpars, 'sld_shell'+str(k), 'sld')
442                _remove_pd(oldpars, 'thick_shell'+str(k), 'thickness')
443        elif name == 'core_shell_parallelepiped':
444            _remove_pd(oldpars, 'rimA', name)
445            _remove_pd(oldpars, 'rimB', name)
446            _remove_pd(oldpars, 'rimC', name)
447        elif name == 'hollow_cylinder':
448            # now uses radius and thickness
449            thickness = oldpars['core_radius']
450            oldpars['radius'] += thickness
451            oldpars['radius.width'] *= thickness/oldpars['radius']
452        #elif name in ['mono_gauss_coil', 'poly_gauss_coil']:
453        #    del oldpars['i_zero']
454        elif name == 'onion':
455            oldpars.pop('n_shells', None)
456        elif name == 'pearl_necklace':
457            _remove_pd(oldpars, 'num_pearls', name)
458            _remove_pd(oldpars, 'thick_string', name)
459        elif name == 'polymer_micelle':
460            if 'ndensity' in oldpars:
461                oldpars['ndensity'] *= 1e15
462        elif name == 'rpa':
463            # convert scattering lengths from femtometers to centimeters
464            for p in "L1", "L2", "L3", "L4":
465                if p in oldpars: oldpars[p] *= 1e-13
466            if pars['case_num'] < 2:
467                for k in ("a", "b"):
468                    for p in ("L", "N", "Phi", "b", "v"):
469                        oldpars.pop(p+k, None)
470                for k in "Kab,Kac,Kad,Kbc,Kbd".split(','):
471                    oldpars.pop(k, None)
472            elif pars['case_num'] < 5:
473                for k in ("a",):
474                    for p in ("L", "N", "Phi", "b", "v"):
475                        oldpars.pop(p+k, None)
476                for k in "Kab,Kac,Kad".split(','):
477                    oldpars.pop(k, None)
478        elif name == 'spherical_sld':
479            oldpars["CONTROL"] -= 1
480            # remove polydispersity from shells
481            for k in range(1, 11):
482                _remove_pd(oldpars, 'thick_flat'+str(k), 'thickness')
483                _remove_pd(oldpars, 'thick_inter'+str(k), 'interface')
484            # remove extra shells
485            for k in range(int(pars['n_shells']), 11):
486                oldpars.pop('sld_flat'+str(k), 0)
487                oldpars.pop('thick_flat'+str(k), 0)
488                oldpars.pop('thick_inter'+str(k), 0)
489                oldpars.pop('func_inter'+str(k), 0)
490                oldpars.pop('nu_inter'+str(k), 0)
491        elif name == 'stacked_disks':
492            _remove_pd(oldpars, 'n_stacking', name)
493        elif name == 'teubner_strey':
494            # basically redoing the entire Teubner-Strey calculations here.
495            volfraction = oldpars.pop('volfraction_a')
496            xi = oldpars.pop('xi')
497            d = oldpars.pop('d')
498            sld_a = oldpars.pop('sld_a')
499            sld_b = oldpars.pop('sld_b')
500            drho = 1e6*(sld_a - sld_b)  # conversion autoscaled these
501            k = 2.0*math.pi*xi/d
502            a2 = (1.0 + k**2)**2
503            c1 = 2.0 * xi**2 * (1.0 - k**2)
504            c2 = xi**4
505            prefactor = 8.0*math.pi*volfraction*(1.0-volfraction)*drho**2*c2/xi
506            scale = 1e-4*prefactor
507            oldpars['scale'] = a2/scale
508            oldpars['c1'] = c1/scale
509            oldpars['c2'] = c2/scale
510
511    #print("convert from",list(sorted(pars)))
512    #print("convert to",list(sorted(oldpars.items())))
513    return oldpars
514
515def constrain_new_to_old(model_info, pars):
516    """
517    Restrict parameter values to those that will match sasview.
518    """
519    name = model_info.id
520    # Note: update convert.revert_model to match
521    if name in MODELS_WITHOUT_SCALE or model_info.structure_factor:
522        pars['scale'] = 1
523    if name in MODELS_WITHOUT_BACKGROUND or model_info.structure_factor:
524        pars['background'] = 0
525    # sasview multiplies background by structure factor
526    if '*' in name:
527        pars['background'] = 0
528
529    # Shut off magnetism when comparing non-magnetic sasview models
530    if name not in MAGNETIC_SASVIEW_MODELS:
531        suppress_magnetism = False
532        for key in pars.keys():
533            if key.startswith("M0:"):
534                suppress_magnetism = suppress_magnetism or (pars[key] != 0)
535                pars[key] = 0
536        if suppress_magnetism:
537            warnings.warn("suppressing magnetism for comparison with sasview")
538
539    # Shut off theta polydispersity since algorithm has changed
540    if 'theta_pd_n' in pars:
541        if pars['theta_pd_n'] != 0:
542            warnings.warn("suppressing theta polydispersity for comparison with sasview")
543        pars['theta_pd_n'] = 0
544
545    # If it is a product model P*S, then check the individual forms for special
546    # cases.  Note: despite the structure factor alone not having scale or
547    # background, the product model does, so this is below the test for
548    # models without scale or background.
549    namelist = name.split('*') if '*' in name else [name]
550    for name in namelist:
551        if name in MODELS_WITHOUT_VOLFRACTION:
552            pars['volfraction'] = 1
553        if name == 'core_multi_shell':
554            pars['n'] = min(math.ceil(pars['n']), 4)
555        elif name == 'gel_fit':
556            pars['scale'] = 1
557        elif name == 'line':
558            pars['scale'] = 1
559            pars['background'] = 0
560        elif name == 'mono_gauss_coil':
561            pars['scale'] = 1
562        elif name == 'onion':
563            pars['n_shells'] = math.ceil(pars['n_shells'])
564        elif name == 'pearl_necklace':
565            pars['string_thickness_pd_n'] = 0
566            pars['number_of_pearls_pd_n'] = 0
567        elif name == 'poly_gauss_coil':
568            pars['scale'] = 1
569        elif name == 'rpa':
570            pars['case_num'] = int(pars['case_num'])
571        elif name == 'spherical_sld':
572            pars['n_shells'] = math.ceil(pars['n_shells'])
573            pars['n_steps'] = math.ceil(pars['n_steps'])
574            for k in range(1, 11):
575                pars['shape%d'%k] = math.trunc(pars['shape%d'%k]+0.5)
576            for k in range(2, 11):
577                pars['thickness%d_pd_n'%k] = 0
578                pars['interface%d_pd_n'%k] = 0
579        elif name == 'teubner_strey':
580            pars['scale'] = 1
581            if pars['volfraction_a'] > 0.5:
582                pars['volfraction_a'] = 1.0 - pars['volfraction_a']
583        elif name == 'unified_power_Rg':
584            pars['level'] = int(pars['level'])
585
586def _check_one(name, seed=None):
587    """
588    Generate a random set of parameters for *name*, and check that they can
589    be converted back to SasView 3.x and forward again to sasmodels.  Raises
590    an error if the parameters are changed.
591    """
592    from . import compare
593
594    model_info = load_model_info(name)
595
596    old_name = revert_name(model_info)
597    if old_name is None:
598        return
599
600    pars = compare.get_pars(model_info, use_demo=False)
601    pars = compare.randomize_pars(model_info, pars, seed=seed)
602    if name == "teubner_strey":
603        # T-S model is underconstrained, so fix the assumptions.
604        pars['sld_a'], pars['sld_b'] = 1.0, 0.0
605    compare.constrain_pars(model_info, pars)
606    constrain_new_to_old(model_info, pars)
607    old_pars = revert_pars(model_info, pars)
608    new_name, new_pars = convert_model(old_name, old_pars, use_underscore=True)
609    if 1:
610        print("==== %s in ====="%name)
611        print(str(compare.parlist(model_info, pars, True)))
612        print("==== %s ====="%old_name)
613        for k, v in sorted(old_pars.items()):
614            print(k, v)
615        print("==== %s out ====="%new_name)
616        print(str(compare.parlist(model_info, new_pars, True)))
617    assert name==new_name, "%r != %r"%(name, new_name)
618    for k, v in new_pars.items():
619        assert k in pars, "%s: %r appeared from conversion"%(name, k)
620        if isinstance(v, float):
621            assert abs(v-pars[k])<=abs(1e-12*v), "%s: %r  %s != %s"%(name, k, v, pars[k])
622        else:
623            assert v == pars[k], "%s: %r  %s != %s"%(name, k, v, pars[k])
624    for k, v in pars.items():
625        assert k in pars, "%s: %r not converted"%(name, k)
626
627def test_backward_forward():
628    from .core import list_models
629    for name in list_models('all'):
630        L = lambda: _check_one(name, seed=1)
631        L.description = name
632        yield L
Note: See TracBrowser for help on using the repository browser.