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