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