API Reference
SANSFitter
The main class for SANS data fitting.
sans_fitter.fitter.SANSFitter
A flexible SANS model fitter that works with any SasModels model.
Features: - Loads data from various file formats (CSV, XML, HDF5) - Model-agnostic: works with any model from SasModels library - Supports multiple fitting engines (BUMPS, LMFit) - User-friendly parameter management
For model-free P(r) inversion (pair distance distribution analysis), see
:mod:sans_fitter.inversion — it operates directly on datasets
(fitter.data or data_ops results) and needs no model setup.
Example
fitter = SANSFitter() fitter.load_data('my_sans_data.csv') fitter.set_model('cylinder') fitter.set_param('radius', value=20, min=1, max=100) fitter.set_param('length', value=400, min=10, max=1000) result = fitter.fit(engine='bumps') fitter.plot_results()
Source code in src/sans_fitter/fitter.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 | |
load_data(filename)
Load SANS data from a file.
Supports CSV, XML, and HDF5 formats through sasdata. Columnar text/CSV files are interpreted in the order Q, I, dI, dQ (per the sasdata ASCII convention) — a file whose third column is dQ rather than dI will have its uncertainties and resolution swapped. Check the column summary printed after loading.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to the data file |
required |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file doesn't exist |
ValueError
|
If the data cannot be loaded or is invalid |
Source code in src/sans_fitter/fitter.py
set_data(data)
Use an in-memory dataset for fitting.
This is the injection point for datasets that were not loaded from a
file: results of dataset arithmetic (see :mod:sans_fitter.data.ops),
simulated data, or any sasdata Data1D built programmatically. The
dataset is validated and normalized (qmin/qmax/mask are
recomputed as needed) so it is fit-ready.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
A sasdata |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the object is 2D data or lacks |
ValueError
|
If |
Source code in src/sans_fitter/fitter.py
set_q_range(qmin=None, qmax=None)
Restrict the Q range used for fitting.
Data points outside [qmin, qmax] are excluded from the fit (and from the exported fit curve/residuals) but remain visible in plots. Typical uses: trimming beam-stop spillover at low Q or background-dominated high-Q points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
qmin
|
float | None
|
Lower Q limit in Å⁻¹. If omitted, the current lower limit is reset to the full data range. |
None
|
qmax
|
float | None
|
Upper Q limit in Å⁻¹. If omitted, the current upper limit is reset to the full data range. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If no data is loaded, if qmin >= qmax, or if no data points remain in the requested range (the previous range is kept in that case). |
Source code in src/sans_fitter/fitter.py
reset_q_range()
Reset the fitting Q range to the full range of the loaded data.
Raises:
| Type | Description |
|---|---|
ValueError
|
If no data is loaded. |
Source code in src/sans_fitter/fitter.py
get_q_range()
Get the Q range currently used for fitting.
Returns:
| Type | Description |
|---|---|
tuple[float, float] | None
|
Tuple (qmin, qmax) in Å⁻¹, or None if no data is loaded. |
Source code in src/sans_fitter/fitter.py
set_model(model_name, platform='cpu')
Set the SANS model to use for fitting.
Accepts both single models and composite expressions understood by
sasmodels: 'dab+peak_lorentz' (sum mixture), 'modelA*modelB'
(product mixture), and 'sphere@hardsphere' (form factor with
structure factor). Every atomic model name in the expression is
validated against the sasmodels model list before loading, with a
nearest-match suggestion for unknown names.
This resets any active structure factor to ensure a clean state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
|
str
|
Name of the model from SasModels (e.g., 'cylinder', 'sphere', 'dab+peak_lorentz') |
required |
platform
|
str
|
Computation platform ('cpu' or 'opencl') |
'cpu'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the model name is not valid |
Source code in src/sans_fitter/fitter.py
set_models(*model_names, operation='+', shared=(), **monikers)
Combine multiple models against the current dataset.
The friendly-name entry point for composite models. Parameters are
exposed with model-name (or moniker) prefixes instead of sasmodels'
A_/B_ prefixes, e.g. dab_cor_length instead of
A_cor_length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*model_names
|
str
|
Model names, positionally. Each may itself contain
|
()
|
operation
|
str
|
How to combine the models: |
'+'
|
shared
|
Sequence[str]
|
Unprefixed parameter names that must exist in at least 2
components. Each becomes a single unprefixed parameter driving
every component that has it (e.g. |
()
|
**monikers
|
str
|
Components given as |
{}
|
Example
fitter.set_models('dab', 'peak_lorentz') fitter.set_param('dab_cor_length', value=50, vary=True) fitter.set_models(small='sphere', large='sphere', shared=['sld'])
Raises:
| Type | Description |
|---|---|
ValueError
|
If fewer than 2 models are given, the operation is
invalid, a moniker is invalid, a shared name is missing from
enough components or names a global parameter
( |
Source code in src/sans_fitter/fitter.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 | |
link_params(name, to)
Create an equality link between two parameters.
The follower (name) is forced to vary=False and mirrors the
target's (to) value at all times — before, during, and after the
fit. Links are equality-only; no expressions. Works for any pair of
parameters, including cross-component ones ('large_sld' following
'small_sld') and differently named ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The follower parameter name. |
required |
to
|
str
|
The target parameter name. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If either name does not exist. |
ValueError
|
On self-links, link chains, or conflicting links. |
Source code in src/sans_fitter/fitter.py
unlink_params(name)
Remove an equality link, restoring the follower's independence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The follower parameter name. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the name does not exist. |
ValueError
|
If the parameter is not linked. |
Source code in src/sans_fitter/fitter.py
get_links()
get_components()
Return the composite-model components.
Returns:
| Type | Description |
|---|---|
list[tuple[str, str, str]]
|
List of |
list[tuple[str, str, str]]
|
|
list[tuple[str, str, str]]
|
Empty for atomic models. |
Source code in src/sans_fitter/fitter.py
set_structure_factor(structure_factor_name, radius_effective_mode='unconstrained')
Apply a structure factor to the current model.
This creates a product model (form_factor * structure_factor) to account for inter-particle interactions in concentrated systems.
Supported structure factors: - 'hardsphere': Hard sphere structure factor (Percus-Yevick closure) - 'hayter_msa': Hayter-Penfold rescaled MSA for charged spheres - 'squarewell': Square well potential - 'stickyhardsphere': Sticky hard sphere (Baxter model)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure_factor_name
|
str
|
Name of the structure factor (e.g., 'hardsphere') |
required |
radius_effective_mode
|
str
|
How to handle the effective radius. - 'unconstrained': 'radius_effective' is a separate fitting parameter. - 'link_radius': 'radius_effective' is constrained to the form factor's 'radius'. |
'unconstrained'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If no form factor model is set, or if the structure factor is invalid |
Source code in src/sans_fitter/fitter.py
get_structure_factor()
Get the name of the currently applied structure factor.
Returns:
| Type | Description |
|---|---|
str | None
|
Name of the structure factor, or None if no structure factor is set |
remove_structure_factor()
Remove the current structure factor and revert to the form factor only.
Raises:
| Type | Description |
|---|---|
ValueError
|
If no structure factor is currently set |
Source code in src/sans_fitter/fitter.py
get_params()
set_param(name, value=None, min=None, max=None, vary=None)
Configure a model parameter for fitting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Parameter name |
required |
value
|
float | None
|
Initial value (optional) |
None
|
min
|
float | None
|
Minimum bound (optional) |
None
|
max
|
float | None
|
Maximum bound (optional) |
None
|
vary
|
bool | None
|
Whether to vary during fit (optional) |
None
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If parameter name doesn't exist for the current model |
Source code in src/sans_fitter/fitter.py
fit(engine='bumps', method=None, **kwargs)
Perform the fit using the specified engine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
engine
|
Literal['bumps', 'lmfit']
|
Fitting engine ('bumps' or 'lmfit') |
'bumps'
|
method
|
str | None
|
Optimization method (engine-specific) - BUMPS: 'amoeba', 'lm', 'newton', 'de' (default: 'amoeba') - LMFit: 'leastsq', 'least_squares', 'differential_evolution', etc. |
None
|
**kwargs
|
Any
|
Additional arguments passed to the fitting engine |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with fit results including chi-squared and parameter values |
Raises:
| Type | Description |
|---|---|
ValueError
|
If data or model not loaded, or invalid engine |
NotImplementedError
|
If a composite model or parameter links are used with an engine other than 'bumps'. |
Source code in src/sans_fitter/fitter.py
fit_bayesian(method='dream', samples=DEFAULT_DREAM_SAMPLES, burn=DEFAULT_DREAM_BURN, thin=DEFAULT_DREAM_THIN, pop=DEFAULT_DREAM_POP, **kwargs)
Perform a Bayesian (MCMC) fit using bumps' DREAM sampler.
Samples the posterior distribution of the varying parameters and stores the chain alongside the usual point-estimate results, enabling the posterior displays: plot_posterior_pairs(), plot_param_distribution(), plot_posterior_predictive(), plot_param_correlations(), and plot_trace().
The reported parameter values are the best (maximum-likelihood) posterior sample; the reported stderr is the posterior 68% credible half-width.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Sampler method (default 'dream'). |
'dream'
|
samples
|
int
|
Number of posterior samples to draw. |
DEFAULT_DREAM_SAMPLES
|
burn
|
int
|
Number of burn-in generations to discard (DREAM's native unit: each generation advances every chain by one step). |
DEFAULT_DREAM_BURN
|
thin
|
int
|
Keep every nth sample. |
DEFAULT_DREAM_THIN
|
pop
|
int
|
Population (chain) scale factor per varying parameter. |
DEFAULT_DREAM_POP
|
**kwargs
|
Any
|
Additional arguments passed to bumps.fitters.fit. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with fit results including chi-squared and parameter |
dict[str, Any]
|
values. The posterior itself is available via get_posterior(). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If data or model is not loaded, or no parameter varies. |
NotImplementedError
|
If a composite model or parameter links are used — the DREAM path does not support them yet. |
Source code in src/sans_fitter/fitter.py
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 | |
get_posterior()
Return the posterior summary from the last Bayesian fit.
Raises:
| Type | Description |
|---|---|
ValueError
|
If no fit has been run or the last fit was not Bayesian. |
Source code in src/sans_fitter/fitter.py
plot_results(show_residuals=True, log_scale=True, show=None, show_components=False)
Plot experimental data and fitted model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
show_residuals
|
bool
|
If True, show residuals in a separate panel |
True
|
log_scale
|
bool
|
If True, use log scale for both axes |
True
|
show
|
bool | None
|
If True, display the figure via fig.show(); if False, only return it. The default (None) displays the figure except in Jupyter notebooks, where the returned figure is rendered by the notebook itself (avoids showing the plot twice). |
None
|
show_components
|
bool
|
If True and the fitted model is a '+' mixture, overlay one dashed curve per component (labelled by moniker). A documented no-op for atomic models and '*' mixtures. |
False
|
Returns:
| Type | Description |
|---|---|
Figure
|
Plotly Figure object |
Source code in src/sans_fitter/fitter.py
plot_posterior_pairs(params=None, show_contours=True, show=None)
Corner plot of the posterior: marginal densities and pairwise clouds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
list[str] | None
|
Optional subset of parameter names (default: all sampled). |
None
|
show_contours
|
bool
|
Overlay density contours on the pairwise panels. |
True
|
show
|
bool | None
|
Same display convention as plot_results(). |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the last fit was not Bayesian. |
Source code in src/sans_fitter/fitter.py
plot_param_distribution(param, bins=50, show=None)
Marginal posterior distribution for one parameter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
param
|
str
|
Name of a sampled (varying) parameter. |
required |
bins
|
int
|
Number of histogram bins. |
50
|
show
|
bool | None
|
Same display convention as plot_results(). |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the last fit was not Bayesian. |
KeyError
|
If the parameter was not sampled. |
Source code in src/sans_fitter/fitter.py
plot_posterior_predictive(style='band', n_draws=DEFAULT_POSTERIOR_PREDICTIVE_DRAWS, log_scale=True, show=None)
Posterior predictive check: credible band and/or draws over the data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
style
|
str
|
'band' (95% credible interval), 'draws' (sampled curves), or 'band+draws'. |
'band'
|
n_draws
|
int
|
Number of posterior samples to evaluate through the model. Each draw costs one sasmodels evaluation, so large values can be slow (especially with polydispersity). |
DEFAULT_POSTERIOR_PREDICTIVE_DRAWS
|
log_scale
|
bool
|
Use log axes. |
True
|
show
|
bool | None
|
Same display convention as plot_results(). |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the last fit was not Bayesian or no data is loaded. |
Source code in src/sans_fitter/fitter.py
plot_param_correlations(threshold=0.0, show=None)
Heatmap of the posterior parameter correlation matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
threshold
|
float
|
Hide cells with |correlation| below this value. |
0.0
|
show
|
bool | None
|
Same display convention as plot_results(). |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the last fit was not Bayesian. |
Source code in src/sans_fitter/fitter.py
plot_trace(params=None, show=None)
Trace plot of the MCMC chains for each sampled parameter.
Falls back to the combined chain when per-chain data is unavailable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
list[str] | None
|
Optional subset of parameter names (default: all sampled). |
None
|
show
|
bool | None
|
Same display convention as plot_results(). |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the last fit was not Bayesian. |
Source code in src/sans_fitter/fitter.py
save_results(filename)
Save fit results to a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Output file path (CSV format) |
required |
Source code in src/sans_fitter/fitter.py
supports_polydispersity()
Check if current model has polydisperse parameters.
Returns:
| Type | Description |
|---|---|
bool
|
True if model supports polydispersity, False otherwise |
get_polydisperse_parameters()
Get list of polydisperse parameter names.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of parameter names that support polydispersity |
set_pd_param(param_name, pd_width=None, pd_n=None, pd_nsigma=None, pd_type=None, vary=None)
Configure polydispersity for a parameter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
param_name
|
str
|
Name of the base parameter (e.g., 'radius') |
required |
pd_width
|
float | None
|
Polydispersity width (relative, 0.0 = monodisperse) |
None
|
pd_n
|
int | None
|
Number of Gaussian quadrature points (default: 35) |
None
|
pd_nsigma
|
float | None
|
Number of sigmas to include (default: 3.0) |
None
|
pd_type
|
str | None
|
Distribution type ('gaussian', 'rectangle', 'lognormal', 'schulz', 'boltzmann') |
None
|
vary
|
bool | None
|
Whether to vary the pd_width during fitting |
None
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If param_name is not a polydisperse parameter |
ValueError
|
If pd_type is not a valid distribution type |
Source code in src/sans_fitter/fitter.py
get_pd_param(param_name)
Get polydispersity configuration for a parameter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
param_name
|
str
|
Name of the base parameter (e.g., 'radius') |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with pd, pd_n, pd_nsigma, pd_type, vary, and active values. |
dict[str, Any]
|
'active' indicates whether polydispersity is active for this parameter (pd > 0). |
Raises:
| Type | Description |
|---|---|
KeyError
|
If param_name is not a polydisperse parameter |
Source code in src/sans_fitter/fitter.py
enable_polydispersity(enabled=True)
Enable or disable polydispersity globally.
When disabled, polydispersity parameters are excluded from fitting but their values are preserved for when PD is re-enabled.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
enabled
|
bool
|
Whether to enable polydispersity (default: True) |
True
|
Source code in src/sans_fitter/fitter.py
is_polydispersity_enabled()
Check if polydispersity is enabled.
Returns:
| Type | Description |
|---|---|
bool
|
True if polydispersity is globally enabled, False otherwise |
get_pd_params()
get_varying_pd_params()
Get list of polydispersity parameters that are set to vary.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of parameter names (e.g., ['radius_pd']) that will vary during fitting |
Source code in src/sans_fitter/fitter.py
Composite model naming
set_models() exposes parameters under friendly alias names; set_model()
with a composite expression keeps sasmodels' canonical names. Both spellings
are accepted by set_param(), link_params(), set_pd_param() and
get_pd_param(). For set_models('dab', 'peak_lorentz'):
Friendly alias (set_models) |
Canonical name (set_model) |
|---|---|
scale, background |
scale, background (shared natively) |
dab_scale |
A_scale |
dab_cor_length |
A_cor_length |
peak_lorentz_scale |
B_scale |
peak_lorentz_peak_pos |
B_peak_pos |
peak_lorentz_peak_hwhm |
B_peak_hwhm |
With keyword monikers (set_models(small='sphere', large='sphere')) the
prefix is the moniker (small_radius → A_radius). Parameters listed in
shared= collapse to a single unprefixed name (sld → A_sld + B_sld);
their prefixed aliases remain addressable for polydispersity configuration.
PosteriorSummary
Posterior sample chain and per-parameter statistics returned by fit_bayesian().
sans_fitter.results.PosteriorSummary
dataclass
Posterior sample chain and per-parameter statistics from a Bayesian fit.
labels follows the sampler's chain order (problem.labels() for
bumps DREAM) and indexes the columns of samples.
Source code in src/sans_fitter/results.py
index_of(param)
Return the chain column for a parameter name.
Source code in src/sans_fitter/results.py
format_summary()
Return a table of per-parameter posterior statistics.
Source code in src/sans_fitter/results.py
save_posterior_csv(filename)
Dump the raw posterior chain to CSV for external analysis.
Source code in src/sans_fitter/results.py
data_ops
Dataset arithmetic: add, subtract, multiply and divide datasets (or a dataset
and a scalar) with propagated uncertainties, returning fit-ready Data1D
objects.
sans_fitter.data.ops
Dataset arithmetic for SANS data (issue #45).
Notebook-friendly functions to add, subtract, multiply and divide datasets — similar to SasView's Data Operation utility. Typical uses:
subtract(sample, background)— empty-cell / solvent subtractionmultiply(data, 2.0)ordivide(data, transmission)— rescalingsubtract(data, 0.05)— flat background subtraction
The arithmetic itself (including error propagation, e.g.
dy = sqrt(dy_a² + dy_b²) for addition/subtraction) is delegated to
sasdata's Data1D operators; this module wraps them so the results are
fit-ready (qmin/qmax/mask set), carry provenance metadata, and
fail with actionable messages.
Example
from sans_fitter import SANSFitter, data_ops sample = data_ops.load('sample.csv') background = data_ops.load('empty_cell.csv') result = data_ops.subtract(sample, background) result = data_ops.multiply(result, 0.85) fitter = SANSFitter() fitter.set_data(result) fitter.set_model('sphere') fitter.fit()
Limitations
- Both datasets must share the same Q grid (sasdata requires x-values to match within 1% relative tolerance). Interpolation onto a common grid is not yet supported.
- Resolution (
dx/dxl/dxw) propagation through arithmetic is not validated — sasdata combinesdxin an RMS-like way and skips slit-smearing widths. A warning is emitted when resolution data is present on any operand; treat resolution on results with care, especially for slit-smeared data.
load(filename)
Load a SANS dataset from a file and return a fit-ready Data1D.
This is the canonical standalone loader: SANSFitter.load_data() uses
the same implementation, so datasets loaded here behave identically to
those loaded through the fitter. Supports CSV, XML and HDF5 formats via
sasdata (columnar text files are read in the order Q, I, dI, dQ).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to the data file. |
required |
Returns:
| Type | Description |
|---|---|
Data1D
|
A |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file cannot be loaded or contains no data. |
Source code in src/sans_fitter/data/ops.py
add(a, b)
Return a + b as a new fit-ready dataset.
b may be a Data1D on the same Q grid as a (intensities are
added point-wise, uncertainties combine as dy = sqrt(dy_a² + dy_b²))
or a scalar (y' = y + b; dy and the Q grid are unchanged).
Source code in src/sans_fitter/data/ops.py
subtract(a, b)
Return a − b as a new fit-ready dataset. Order matters.
Typical use: subtract(sample, background) for empty-cell / solvent
subtraction. b may be a Data1D on the same Q grid as a
(uncertainties combine as dy = sqrt(dy_a² + dy_b²)) or a scalar for
flat background subtraction (y' = y − b; dy and the Q grid are
unchanged).
Source code in src/sans_fitter/data/ops.py
multiply(a, b)
Return a × b as a new fit-ready dataset.
b may be a Data1D on the same Q grid as a (relative
uncertainties combine in quadrature) or a scalar (y' = b·y,
dy' = b·dy; the Q grid is unchanged). Typical scalar use: rescaling
to absolute units.
Source code in src/sans_fitter/data/ops.py
divide(a, b)
Return a / b as a new fit-ready dataset. Order matters.
b may be a Data1D on the same Q grid as a (relative
uncertainties combine in quadrature) or a scalar (y' = y/b,
dy' = dy/b; the Q grid is unchanged). Typical scalar use: dividing by
a transmission factor.
Source code in src/sans_fitter/data/ops.py
pr_inversion
Model-free P(r) inversion (indirect Fourier transform): recover the pair distance distribution function from I(q), with automatic parameter estimation and D_max exploration.
sans_fitter.inversion
P(r) inversion — indirect Fourier transform of I(q) (issue #57).
Model-free analysis recovering the real-space pair distance distribution
function P(r) from measured I(q), using Moore's sine-basis expansion
(J. Appl. Cryst. 13 (1980) 168). This is a Moore-style IFT inspired by
SasView's Inversion perspective, not a numeric port: the regularization
operator, uncertainty semantics and heuristics are re-derived, with SasView's
exact operator available as regularizer='sasview' for comparison.
Units and conventions: q in 1/Angstrom, r and d_max in Angstrom; intensity in
whatever units the file uses. P(r) is defined by I(0) = 4*pi * integral(P dr)
in those same intensity units. P(0) = P(d_max) = 0 by construction of the
basis; the fit is unconstrained, so P(r) can go negative (unlike GNOM/ATSAS) —
the positive_fraction diagnostics quantify this.
Example
from sans_fitter import data_ops, pr_inversion data = data_ops.load('protein.csv') scan = pr_inversion.explore_dmax(data, d_max=120.0, fit_background=False) scan.plot() result = pr_inversion.auto_invert(data, d_max=120.0, fit_background=False) print(result.format_summary()) result.plot_pr() result.plot_fit(data)
Limitations
- Slit smearing (USANS) and pinhole dQ resolution are not supported; a warning is emitted when slit-smearing columns carry real data.
- Buffer-subtracted data (the usual protein case) should use
fit_background=False— the fitted flat background of the default can absorb I(0) and bias Rg on already-subtracted data.
DEFAULT_N_TERMS = 10
module-attribute
DEFAULT_R_POINTS = 101
module-attribute
REGULARIZERS = ('corrected', 'sasview')
module-attribute
SASVIEW_N_REG = 20
module-attribute
PrResult
dataclass
Result of a P(r) inversion.
coefficients[k] is c_(k+1) (basis index n = 1..n_terms); the
background is never a coefficient entry. covariance is the full
matrix — background row/column first when the background was fitted —
and is a conditional linearized uncertainty: valid at the chosen alpha
and d_max, assuming known independent Gaussian errors, biased by the
regularization. q_fit/iq_fit/sigma_fit are the accepted data
q-points, the fit evaluated there, and the sigma actually used (needed
for residuals when uncertainties were fabricated); smooth curves come
from :meth:evaluate_iq on a dense grid.
regularization_penalty is alpha * ||L c||^2 in the active
regularizer's own scaling: approximately alpha * integral(P''(r)^2 dr)
for 'corrected', SasView's native (D/N_r)^2 row scaling for
'sasview' — the values are not comparable across modes.
Source code in src/sans_fitter/inversion/result.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
coefficient_covariance
property
Coefficient block of the covariance (background row/column removed).
evaluate_iq(q)
Evaluate the fitted I(q) (including the background) on an arbitrary q grid.
Source code in src/sans_fitter/inversion/result.py
evaluate_pr(r)
Evaluate P(r) on an arbitrary r grid.
Source code in src/sans_fitter/inversion/result.py
evaluate_pr_err(r)
Evaluate the P(r) uncertainty band via the full quadratic form.
Source code in src/sans_fitter/inversion/result.py
format_summary()
Return an ASCII table of inputs, quality diagnostics and derived outputs.
The goodness-of-fit line is labelled "approx. chi2 per residual dof":
data_chisq / (n_points_used - effective_dof), where
effective_dof counts the fitted dimensions of data space
(tr(H)), not the number of parameters. It is an approximate
diagnostic for a regularized fit, and not interpretable at all when
uncertainties were fabricated.
Source code in src/sans_fitter/inversion/result.py
plot_fit(data, show=None, log_scale=True)
Plot data vs the fitted I(q) with residuals.
The dataset is passed explicitly — the result stores the model and the
accepted mask, not the observed intensities. Same display convention
as plot_results(). Pass log_scale=False when intensities include
zero or negative values (a log axis silently omits such points).
Source code in src/sans_fitter/inversion/result.py
plot_pr(show=None)
Plot P(r) with its uncertainty band. Same display convention as plot_results().
save_csv(filename)
Save inputs, diagnostics and the P(r) curve (r, P, dP columns) to CSV.
Source code in src/sans_fitter/inversion/result.py
DmaxScan
dataclass
Result of :func:explore_dmax.
Arrays are success-only: every quantity array has the same length as
d_max_values; D_max points whose inversion failed are omitted and
recorded in failures as (d_max, message) pairs.
Source code in src/sans_fitter/inversion/estimate.py
format_summary()
Return an ASCII table of the scanned quantities per D_max.
Source code in src/sans_fitter/inversion/estimate.py
plot(quantity='rg', show=None)
Plot a scanned quantity (or 'all') vs D_max. Same display convention as plot_results().
Source code in src/sans_fitter/inversion/estimate.py
AlphaEstimate
dataclass
NTermsEstimate
dataclass
Result of :func:estimate_n_terms. alpha was evaluated at the
chosen n_terms during the scan and is the authoritative companion
value — use it directly rather than re-estimating.
Source code in src/sans_fitter/inversion/estimate.py
InsufficientDataError
PrEstimationError
invert(data, d_max, n_terms=DEFAULT_N_TERMS, alpha=0.0, fit_background=True, background=0.0, r_points=DEFAULT_R_POINTS, regularizer='corrected')
Invert I(q) into the pair distance distribution P(r) on [0, d_max].
P(r) is expanded in Moore's sine basis and the coefficients come from a
regularized linear least-squares fit solved by SVD. The fit honours the
dataset's qmin/qmax/mask (as set by SANSFitter.set_q_range)
when present; raw datasets are used in full. The input dataset is never
modified.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
A 1D dataset ( |
required |
d_max
|
float
|
Maximum particle dimension in Angstrom; P(d_max) = 0 by construction. |
required |
n_terms
|
int
|
Number of sine-basis terms. |
DEFAULT_N_TERMS
|
alpha
|
float
|
Regularization constant; 0 means an unregularized fit (a
warning is emitted — use :func: |
0.0
|
fit_background
|
bool
|
Fit a flat background as an extra (unregularized)
column. Use |
True
|
background
|
float
|
Constant background subtracted from the data when
|
0.0
|
r_points
|
int
|
Number of points of the r grid for P(r) evaluation and the derived integrals. |
DEFAULT_R_POINTS
|
regularizer
|
str
|
|
'corrected'
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
PrResult
|
class: |
PrResult
|
diagnostics and derived scalars (Rg, I(0), oscillations, positive |
|
PrResult
|
fractions). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the dataset is not 1D (2D or SESANS data). |
ValueError
|
For invalid arguments or unusable datasets. |
InsufficientDataError
|
When too few usable points remain. |
Source code in src/sans_fitter/inversion/solver.py
auto_invert(data, d_max, fit_background=True, background=0.0, r_points=DEFAULT_R_POINTS, regularizer='corrected')
One-shot inversion with automatic selection of n_terms and alpha.
Runs the :func:estimate_n_terms scan and inverts with the estimate's
(n_terms, alpha) pair. The background (used when fit_background
is False) is applied during the selection scan as well, so the parameters
are chosen on the same problem the final inversion solves. The chosen
values are recorded on the result (result.n_terms, result.alpha).
Source code in src/sans_fitter/inversion/estimate.py
estimate_alpha(data, d_max, n_terms, fit_background=True, regularizer='corrected', background=0.0)
Estimate the regularization constant alpha for a given number of terms.
Starts from the Frobenius-balance suggestion (the alpha that balances the data and unit-alpha penalty blocks) and descends geometrically, returning the largest alpha just before spurious structure (a second peak) appears in P(r), or — for smooth single-peak shapes where that never happens — the largest alpha satisfying the discrepancy principle (data chi-squared down to the number of points).
background is the fixed level subtracted when fit_background is
False (ignored otherwise) — pass the same value you will pass to
:func:invert, so the estimate is made on the problem actually solved.
The heuristic evaluates candidates on the default 101-point r grid
regardless of the r_points used for the final inversion.
Raises:
| Type | Description |
|---|---|
TypeError
|
If the dataset is not 1D (2D or SESANS data). |
PrEstimationError
|
When no alpha in the scan yields a solvable inversion. |
Source code in src/sans_fitter/inversion/estimate.py
estimate_n_terms(data, d_max, fit_background=True, regularizer='corrected', background=0.0)
Estimate the number of basis terms (and the matching alpha).
Scans admissible N, preferring the smallest N that fits the data with a significantly positive P(r) (1-sigma positive fraction >= 0.9, with 0.8 and 0.7 fallback buckets). The scan stops early once P(r) becomes wildly oscillatory.
background is the fixed level subtracted when fit_background is
False (ignored otherwise) — pass the same value you will pass to
:func:invert, so the selection is made on the problem actually solved.
The heuristic evaluates candidates on the default 101-point r grid
regardless of the r_points used for the final inversion.
Raises:
| Type | Description |
|---|---|
TypeError
|
If the dataset is not 1D (2D or SESANS data). |
InsufficientDataError
|
When no N is admissible for the dataset. |
PrEstimationError
|
When the scan has no acceptable candidate. |
Source code in src/sans_fitter/inversion/estimate.py
explore_dmax(data, d_max, n_terms=None, alpha=None, dmin=None, dmax=None, n_points=DMAX_SCAN_POINTS, refit_alpha=False, fit_background=True, regularizer='corrected', background=0.0)
Re-invert over a range of D_max values to locate a stable choice.
A good D_max shows a plateau in Rg and I(0) and a minimum in the data
chi-squared. Defaults: scan 0.9*d_max .. 1.1*d_max in n_points
steps, with n_terms/alpha estimated once at the central d_max
and held fixed across the scan (comparable across D_max thanks to the
corrected operator's resolved quadrature). refit_alpha=True recomputes
the alpha suggestion at each D_max instead.
background is the fixed level subtracted when fit_background is
False (ignored otherwise) — pass the same value you use with
:func:invert/:func:auto_invert, so the scan explores the same problem
the final inversion solves.
Note
The scan suppresses the per-point Shannon-support warnings via the
process-global warnings filter, so it is not thread-safe:
inversions running concurrently in other threads may have those
warnings swallowed while a scan is in flight.
Raises:
| Type | Description |
|---|---|
TypeError
|
If the dataset is not 1D (2D or SESANS data). |
ValueError
|
For an invalid scan range. |
InsufficientDataError / PrEstimationError
|
From the central estimation
when |
Source code in src/sans_fitter/inversion/estimate.py
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 | |
examples
Curated example datasets and a simulator for generating data. See the Example Data guide for the full collection.
sans_fitter.examples
Example datasets and simulated data (issue #53).
Two complementary ways to get data without hunting for a file:
Bundled example datasets — the same collection SasView ships, curated here with the model that fits each one and sensible starting parameters::
>>> from sans_fitter import examples
>>> examples.describe() # what is available
>>> data = examples.load('silica_spheres') # fit-ready Data1D
>>> fitter = examples.load_fitter('silica_spheres') # data + model + parameters
>>> result = fitter.fit()
The files themselves are not vendored into this package. They live inside
the installed sasdata distribution (sasdata/example_data/1d_data), which
is already a hard dependency, so the set stays in sync with sasdata and costs
nothing to ship. :func:load resolves them through :mod:importlib.resources
and raises an actionable error if the layout ever changes.
Simulated data — computed on demand from any sasmodels model, with known ground truth::
>>> data = examples.simulate('sphere', radius=50, noise=0.03, seed=0)
>>> data.truth
{'radius': 50.0, 'sld': 1.0, ...}
Simulated data is the better teaching tool when you want a self-checking exercise ("fit this, you should recover radius = 50"), works for any of the ~100 sasmodels models, and needs no files on disk. Real bundled data is the better tool for everything a simulation will not show you: instrument resolution, sloping backgrounds, noisy high-Q tails and negative intensities after subtraction.
Both routes return a fit-ready Data1D — qmin/qmax/mask set —
that can be handed straight to :meth:SANSFitter.set_data or to
:mod:sans_fitter.data.ops.
Example
dataclass
A curated bundled dataset and how to fit it.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Short key used by :func: |
filename |
str
|
File name within the sasdata 1D example directory. |
model |
str
|
sasmodels model name that describes this sample. |
description |
str
|
What the sample is and what it is useful for teaching. |
params |
dict[str, dict[str, Any]]
|
Suggested starting configuration, as
|
structure_factor |
str | None
|
Structure factor to apply, if the sample is concentrated enough to need one. |
polydispersity |
dict[str, dict[str, Any]]
|
|
truth |
dict[str, float] | None
|
Generating parameters, for simulated files only. |
notes |
str
|
Caveats worth knowing before fitting — engine restrictions, known difficulties. Empty when there are none. |
tags |
tuple[str, ...]
|
Free-form labels for filtering with :func: |
source |
str
|
Provenance note. |
Source code in src/sans_fitter/examples.py
list_examples(tag=None)
Return the names of the bundled examples, optionally filtered by tag.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tag
|
str | None
|
Only return examples carrying this tag (e.g. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Sorted example names. |
Source code in src/sans_fitter/examples.py
describe(name=None)
Print a human-readable summary of the bundled examples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
Print the full detail for a single example. When omitted, print a one-line-per-example overview of the whole collection. |
None
|
Source code in src/sans_fitter/examples.py
get_example(name)
Return the :class:Example record for name.
Raises:
| Type | Description |
|---|---|
KeyError
|
If name is not a known example. |
Source code in src/sans_fitter/examples.py
example_path(name)
Return the filesystem path of a bundled example file.
Useful when you want to pass the file to :func:sans_fitter.data.ops.load
or to any other reader yourself.
Raises:
| Type | Description |
|---|---|
KeyError
|
If name is not a known example. |
FileNotFoundError
|
If the file is missing from the sasdata install. |
Source code in src/sans_fitter/examples.py
load(name)
Load a bundled example dataset and return a fit-ready Data1D.
Goes through the same loader as :meth:SANSFitter.load_data, so the result
behaves identically to any dataset you load yourself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Example name — see :func: |
required |
Returns:
| Type | Description |
|---|---|
Data1D
|
A |
Raises:
| Type | Description |
|---|---|
KeyError
|
If name is not a known example. |
FileNotFoundError
|
If the file is missing from the sasdata install. |
ValueError
|
If the file cannot be parsed. |
Source code in src/sans_fitter/examples.py
load_fitter(name, quiet=True)
Return a :class:SANSFitter preloaded with an example and ready to fit.
Sets the data, the model, any structure factor and polydispersity, and the
suggested starting parameters — so a tutorial reaches fitter.fit() in
one line::
>>> fitter = examples.load_fitter('silica_spheres')
>>> result = fitter.fit()
The starting parameters are coarse values chosen to put the model in the
right basin, not published results. Check get_example(name).truth to see
whether ground truth is known.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Example name — see :func: |
required |
quiet
|
bool
|
Suppress the progress messages that |
True
|
Returns:
| Type | Description |
|---|---|
SANSFitter
|
A configured |
Source code in src/sans_fitter/examples.py
simulate(model='sphere', qmin=0.005, qmax=0.5, npoints=100, noise=0.02, seed=0, dq=None, q=None, **params)
Simulate a SANS dataset from any sasmodels model, with known truth.
The generating parameters are attached to the result as data.truth, so
a tutorial can state the answer up front and the reader can check whether
the fit recovers it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
sasmodels model name, e.g. |
'sphere'
|
qmin
|
float
|
Lowest Q, in 1/A. Ignored when q is given. |
0.005
|
qmax
|
float
|
Highest Q, in 1/A. Ignored when q is given. |
0.5
|
npoints
|
int
|
Number of log-spaced Q points. Ignored when q is given. |
100
|
noise
|
float
|
Relative noise level. |
0.02
|
seed
|
int | None
|
Seed for the noise, so results are reproducible. Pass |
0
|
dq
|
float | None
|
Relative resolution width. When given, |
None
|
q
|
ndarray | None
|
Explicit Q array, overriding qmin/qmax/npoints. Use this to simulate onto the grid of a real dataset. |
None
|
**params
|
Any
|
Model parameters, e.g. |
{}
|
Returns:
| Type | Description |
|---|---|
Data1D
|
A fit-ready |
Data1D
|
full parameter set used to generate it. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the model name is unknown, a parameter is not valid for the model, or the Q range is not positive and increasing. |
Example
data = simulate('sphere', radius=50, noise=0.03, seed=1) data.truth['radius'] 50.0
Source code in src/sans_fitter/examples.py
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 | |
simulate_pair(model='sphere', background_level=0.5, noise=0.02, seed=0, **kwargs)
Simulate a matched sample and background pair for dataset arithmetic.
Both datasets land on an identical Q grid, which is what
:mod:sans_fitter.data.ops requires — the sample is model + flat
background, and the background dataset is that flat level alone::
>>> sample, background = simulate_pair('sphere', radius=50)
>>> subtracted = data_ops.subtract(sample, background)
>>> fitter = SANSFitter()
>>> fitter.set_data(subtracted)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
sasmodels model name for the sample. |
'sphere'
|
background_level
|
float
|
Flat intensity added to the sample and carried by the
background dataset. An explicit |
0.5
|
noise
|
float
|
Relative Gaussian noise, applied independently to each dataset. |
0.02
|
seed
|
int | None
|
Seed for reproducibility. The background uses |
0
|
**kwargs
|
Any
|
Forwarded to :func: |
{}
|
Returns:
| Type | Description |
|---|---|
tuple[Data1D, Data1D]
|
|
Source code in src/sans_fitter/examples.py
ParameterManager
Internal class for managing model parameters and polydispersity settings.
sans_fitter.modeling.parameters.ParameterManager
Manages model parameters for SANS fitting.
Handles parameter initialization, validation, bounds management, special logic for structure factor parameter linking, and polydispersity support.
Attributes:
| Name | Type | Description |
|---|---|---|
params |
dict[str, dict[str, Any]]
|
Dictionary of parameter configurations |
model_name |
str | None
|
Name of the current model |
structure_factor_name |
str | None
|
Name of applied structure factor (if any) |
radius_effective_mode |
str | None
|
Mode for handling radius_effective ('unconstrained' or 'link_radius') |
polydisperse_params |
dict[str, dict[str, Any]]
|
Dictionary of polydispersity parameters |
pd_enabled |
dict[str, dict[str, Any]]
|
Whether polydispersity is globally enabled |
Source code in src/sans_fitter/modeling/parameters.py
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 | |
get_polydisperse_parameters()
Return list of parameter names that support polydispersity.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of parameter names that can have polydispersity applied |
Source code in src/sans_fitter/modeling/parameters.py
has_polydisperse_parameters()
Check if the current model has any polydisperse parameters.
Returns:
| Type | Description |
|---|---|
bool
|
True if model has polydisperse parameters, False otherwise |
Source code in src/sans_fitter/modeling/parameters.py
set_pd_param(base_param, pd_width=None, pd_n=None, pd_nsigma=None, pd_type=None, vary=None)
Configure polydispersity for a specific parameter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_param
|
str
|
Name of the base parameter (e.g., 'radius') |
required |
pd_width
|
float | None
|
Polydispersity width (relative, 0.0 = monodisperse) |
None
|
pd_n
|
int | None
|
Number of Gaussian quadrature points (default: 35) |
None
|
pd_nsigma
|
float | None
|
Number of sigmas to include (default: 3.0) |
None
|
pd_type
|
str | None
|
Distribution type ('gaussian', 'rectangle', 'lognormal', 'schulz', 'boltzmann') |
None
|
vary
|
bool | None
|
Whether to vary the pd_width during fitting |
None
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If base_param is not a polydisperse parameter |
ValueError
|
If pd_type is not a valid distribution type |
Source code in src/sans_fitter/modeling/parameters.py
get_pd_param(base_param)
Get polydispersity configuration for a specific parameter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_param
|
str
|
Name of the base parameter (e.g., 'radius') |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with pd, pd_n, pd_nsigma, pd_type, vary, and active values. |
dict[str, Any]
|
'active' indicates whether polydispersity is active for this parameter (pd > 0). |
Raises:
| Type | Description |
|---|---|
KeyError
|
If base_param is not a polydisperse parameter |
Source code in src/sans_fitter/modeling/parameters.py
toggle_pd_visibility(enabled)
Enable/disable polydispersity globally.
When disabled, polydispersity parameters are excluded from fitting but their values are preserved for when PD is re-enabled.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
enabled
|
bool
|
Whether polydispersity should be enabled |
required |
Source code in src/sans_fitter/modeling/parameters.py
is_pd_enabled()
Check if polydispersity is globally enabled.
Returns:
| Type | Description |
|---|---|
bool
|
True if polydispersity is enabled, False otherwise |
get_pd_params_for_fitting()
Return polydispersity parameters to include in fitting.
Only returns PD parameters when pd_enabled is True. Returns parameters in the format expected by SasModels: - {param}_pd: polydispersity width - {param}_pd_n: number of quadrature points - {param}_pd_nsigma: number of sigmas - {param}_pd_type: distribution type
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary of PD parameters ready for fitting |
Source code in src/sans_fitter/modeling/parameters.py
display_pd_params()
Display polydispersity parameter values and settings.
On the set_models path the canonical prefixed names are translated
to their user-facing aliases for display.
Source code in src/sans_fitter/modeling/parameters.py
PolydispersityManager
Internal class for managing per-parameter polydispersity state.
sans_fitter.modeling.polydispersity.PolydispersityManager
Manage polydispersity configuration and backup/restore state.
Source code in src/sans_fitter/modeling/polydispersity.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | |
initialize(param_names)
Source code in src/sans_fitter/modeling/polydispersity.py
get_parameters()
has_parameters()
set_param(base_param, pd_width=None, pd_n=None, pd_nsigma=None, pd_type=None, vary=None)
Source code in src/sans_fitter/modeling/polydispersity.py
get_param(base_param)
Source code in src/sans_fitter/modeling/polydispersity.py
set_enabled(enabled)
is_enabled()
get_fitting_params()
Source code in src/sans_fitter/modeling/polydispersity.py
get_varying_params()
display(name_map=None)
Print the polydispersity table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name_map
|
dict[str, str] | None
|
Optional canonical-to-display name translation, used on
the |
None
|
Source code in src/sans_fitter/modeling/polydispersity.py
backup()
restore()
Source code in src/sans_fitter/modeling/polydispersity.py
has_backup()
StructureFactorManager
Internal class for managing structure factor selection and parameter backup/restore.
sans_fitter.modeling.structure_factor.StructureFactorManager
Manage structure factor state and form-factor parameter backups.
Source code in src/sans_fitter/modeling/structure_factor.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | |
apply(kernel, sf_name, re_mode, current_params)
Source code in src/sans_fitter/modeling/structure_factor.py
remove()
Source code in src/sans_fitter/modeling/structure_factor.py
backup_params(current_params)
restore_params()
has_backup()
sans_fitter.modeling.structure_factor.default_parameter_bounds(default, limits)
Finite, sign-permissive fallback bounds for a kernel parameter.
Finite declared limits are kept as-is. Each infinite side of a
(-inf, inf)-style declaration is replaced by a range derived from the
default value: default ± max(10·|default|, 1.0), with the lower side
additionally capped at 0 so SLD-like parameters can go negative. This
guarantees a non-degenerate range even for zero-default parameters.
Note: this is a deliberate policy — parameters whose old fallback produced
[0, 10·default] now get sign-permissive ranges; users who relied on
the implicit positivity should set explicit bounds via set_param.
Source code in src/sans_fitter/modeling/structure_factor.py
Polydispersity Constants
The following constants are available in sans_fitter.modeling.parameters:
PD_DISTRIBUTION_TYPES
Supported polydispersity distribution types:
| Type | Description |
|---|---|
gaussian |
Gaussian/normal distribution (default) |
rectangle |
Uniform/rectangular distribution |
lognormal |
Log-normal distribution |
schulz |
Schulz distribution (common for polymers) |
boltzmann |
Boltzmann distribution |
Default Values
| Constant | Default Value | Description |
|---|---|---|
DEFAULT_PD_WIDTH |
0.0 |
Default polydispersity width (monodisperse) |
DEFAULT_PD_N |
35 |
Default number of quadrature points |
DEFAULT_PD_NSIGMA |
3.0 |
Default number of sigmas to include |
DEFAULT_PD_TYPE |
'gaussian' |
Default distribution type |