source: sasmodels/sasmodels/convert.py @ 353e899

core_shell_microgelsmagnetic_modelticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since 353e899 was 610ef23, checked in by Paul Kienzle <pkienzle@…>, 5 years ago

rename magnetic parameters to not contain colon. Refs #1188

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