API Reference
Module-level helpers
sans_fitter.fitter.get_all_models()
Fetch all available models from sasmodels.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of model names |
Raises:
| Type | Description |
|---|---|
Exception
|
Whatever |
Source code in src/sans_fitter/fitter.py
sans_fitter.fitter.get_structure_factors()
cached
Return the structure-factor model names available in sasmodels.
Derived from sasmodels rather than a hardcoded whitelist: every built-in
model whose ModelInfo.structure_factor flag is set (via
sasmodels.core.load_model_info). New structure factors added upstream
(e.g. two_yukawa) are picked up automatically, so this list cannot go
stale. The result is cached; the immutable tuple prevents accidental
mutation of the cached value.
Returns:
| Type | Description |
|---|---|
tuple[str, ...]
|
Sorted tuple of structure-factor names. |
Source code in src/sans_fitter/fitter.py
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
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 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 | |
load_data(filename, dataset=0)
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.
Files may hold several datasets (e.g. CanSAS XML with multiple
SASentry blocks). Pass dataset to select one by 0-based index or
by name (title, run id or filename); the first dataset is used by
default. If the file contains more than one dataset, a warning lists
them all.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to the data file |
required |
dataset
|
int | str
|
Which dataset to load — a 0-based index or a name (title, run id or filename). Defaults to the first dataset. |
0
|
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_resolution(mode='data', dq_over_q=None, slit_length=None, slit_width=None)
State how instrument resolution is applied when the model is evaluated.
Resolution smearing changes the fitted parameters, so it is a stated choice rather than a property of the input file. The four modes mirror SasView's Fit Page (None / Use dQ Data / Custom Pinhole / Custom Slit)::
fitter.set_resolution('data') # default
fitter.set_resolution('none')
fitter.set_resolution('pinhole', dq_over_q=0.10)
fitter.set_resolution('slit', slit_length=0.05)
The setting is applied to a copy of the dataset made for
evaluation; fitter.data is never modified. It reaches
fit(engine='bumps'), fit(engine='lmfit'), fit_bayesian()
and the post-fit curve displays alike.
The mode is fitter state, not data state: it persists across
load_data() / set_data(), exactly as the model, the parameters
and the links do. Mode 'data' already means "use this dataset's
columns", so swapping datasets under the default needs no reset; the
load summary reports the active mode so a custom width cannot be
applied to a new file unnoticed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
str
|
Which resolution to apply.
|
'data'
|
dq_over_q
|
float | None
|
Relative pinhole width σ_q/q, a Gaussian 1-σ — the
same quantity as the file's dQ column and as
:func: |
None
|
slit_length
|
float | None
|
Slit length along q, an absolute width in Å⁻¹
(sasmodels' |
None
|
slit_width
|
float | None
|
Slit width perpendicular to q, an absolute width in
Å⁻¹ (sasmodels' |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the mode is unknown, an argument does not belong to the mode, a required argument is missing, or a width is non-finite, negative or degenerate (a pinhole or slit length of zero). Every check runs before any state is touched, so a rejected call leaves the fitter exactly as it was. |
Note
Per-point custom widths, constant absolute σ_q, 2D/oriented
resolution and fittable resolution parameters are out of scope.
P(r) inversion is unaffected: it reads fitter.data, which this
setting deliberately leaves alone.
Source code in src/sans_fitter/fitter.py
get_resolution()
Return the active resolution setting.
Works before any data is loaded — the mode is fitter state, and the evaluation copy it describes is only built at fit time.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A fresh dict with all four keys always present, e.g. |
dict[str, Any]
|
``{'mode': 'pinhole', 'dq_over_q': 0.1, 'slit_length': None, |
dict[str, Any]
|
'slit_width': None}``. Mutating it does not affect the fitter. |
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
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 | |
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.
This is the same mechanism as
set_structure_factor(..., radius_effective_mode='link_radius'),
which links 'radius_effective' to 'radius'; get_links()
reports both alike.
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.
Available structure factors are queried from sasmodels at runtime —
see :func:get_structure_factors for the full, up-to-date list
(e.g. 'hardsphere', 'hayter_msa', 'squarewell', 'stickyhardsphere').
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 name or radius_effective_mode is invalid. Every check runs before any state is touched, so a rejected call leaves the fitter exactly as it was. |
Source code in src/sans_fitter/fitter.py
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 | |
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
calculate(q=None, dq=None)
Evaluate the model at the current parameter values, without fitting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
ndarray | None
|
Q values in Å⁻¹ to evaluate on. When omitted, the loaded dataset's Q values are used and its resolution (dQ or slit columns) is applied, exactly as during a fit. |
None
|
dq
|
float | None
|
Relative resolution width ΔQ/Q applied to the q grid. Only valid together with q; the dataset carries its own resolution. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Intensities as a float64 array. On the data grid the result has |
ndarray
|
one entry per data point, with NaN where a point is excluded from |
ndarray
|
the fit (outside the Q range, masked, or NaN), so it can be |
ndarray
|
plotted directly against |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no model is loaded, if no data is loaded and q is omitted, if dq is given without q, or if q/dq are invalid. |
Source code in src/sans_fitter/fitter.py
plot_model(show_residuals=True, log_scale=True, show=None, show_components=False)
Plot the data and the model at the current parameters, without fitting.
The notebook equivalent of watching SasView redraw the theory as you
change a parameter: it answers "are my starting values sane?" before
committing to a fit. Fit results are untouched — plot_results()
keeps showing the last real fit.
The reported goodness of fit is χ²/dof — the same convention every
engine reports as result['reduced_chisq'], and the same number the
bumps engine prints as "Initial χ²" at the start of a fit. The model is
evaluated through the active resolution mode, exactly as a fit would,
so the preview and the fit that follows it are directly comparable. The
value is reported as not available when the data carries no intensity
uncertainties, and when the free parameters outnumber the fitted points.
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
|
Same display convention as plot_results(). |
None
|
show_components
|
bool
|
If True and the model is a '+' mixture, overlay one dashed curve per component. |
False
|
Returns:
| Type | Description |
|---|---|
Figure
|
Plotly Figure object |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no data or no model is loaded. |
Source code in src/sans_fitter/fitter.py
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 | |
compare(cases=None, q=None, dq=None, log_scale=True, show=None, show_data=True, **sweep)
Overlay theory curves for several parameter sets on one plot.
Each case starts from the current parameters and applies its own overrides; the fitter's own parameters are never changed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cases
|
dict[str, dict[str, float]] | None
|
Label -> parameter overrides, e.g.
|
None
|
q
|
ndarray | None
|
Q values to evaluate on. When omitted, the loaded dataset's Q values and resolution are used. |
None
|
dq
|
float | None
|
Relative resolution width ΔQ/Q for the q grid. |
None
|
log_scale
|
bool
|
If True, use log scale for both axes. |
True
|
show
|
bool | None
|
Same display convention as plot_results(). |
None
|
show_data
|
bool
|
If True and data is loaded, draw the measured points. With an explicit q, the data keeps its own Q grid. |
True
|
**sweep
|
Sequence[float]
|
One parameter name mapped to a sequence of values, as an
alternative to cases: |
{}
|
Returns:
| Type | Description |
|---|---|
Figure
|
Plotly Figure object |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no model is loaded, if neither or both spellings are used, if more than one sweep parameter is given, or if data is required but not loaded. |
KeyError
|
If an override names an unknown parameter. |
Source code in src/sans_fitter/fitter.py
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 | |
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 |
dict[str, Any]
|
engine-independent goodness-of-fit block: |
dict[str, Any]
|
weighted sum of squared residuals), |
dict[str, Any]
|
( |
dict[str, Any]
|
|
dict[str, Any]
|
which reports success unconditionally), |
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
as a self-rendering object. |
dict[str, Any]
|
The |
dict[str, Any]
|
model parameter, each carrying |
dict[str, Any]
|
a |
dict[str, Any]
|
varied) and |
dict[str, Any]
|
A follower reports its target's fitted value. |
dict[str, Any]
|
Changed in 0.4: |
dict[str, Any]
|
χ²/dof. Use |
Raises:
| Type | Description |
|---|---|
ValueError
|
If data or model not loaded, or invalid engine |
NotImplementedError
|
If a composite model is 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]
|
The same dictionary shape as :meth: |
dict[str, Any]
|
goodness-of-fit block. |
dict[str, Any]
|
posterior draw rather than a Jacobian estimate, and |
dict[str, Any]
|
None — a sampler has no optimizer verdict, so the |
dict[str, Any]
|
carries the sampler settings and the largest R-hat instead. The |
dict[str, Any]
|
posterior itself is available via get_posterior(), and |
dict[str, Any]
|
get_fit_report() renders everything as a table. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If data or model is not loaded, or no parameter varies. |
NotImplementedError
|
If a composite model is used — the DREAM path does not support them yet. |
Source code in src/sans_fitter/fitter.py
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 | |
get_fit_report()
Return a :class:~sans_fitter.report.FitReport for the last fit.
The report carries the goodness-of-fit statistics, the parameter table, the
covariance and correlation matrices, the convergence verdict and any
parameter resting on a bound. It renders itself as a table in a notebook
(_repr_html_), as plain text (print(report)) and as Markdown
(report.to_markdown()), and serializes through report.to_dict().
Returns:
| Type | Description |
|---|---|
FitReport
|
A snapshot of the current fit result. Mutating the fitter afterwards |
FitReport
|
does not change a report already returned. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no fit has been run in this session. A theory preview
( |
Source code in src/sans_fitter/fitter.py
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
save_analysis(filename, include_result=True)
Save the complete analysis setup, and the last fit result, as JSON.
What save_results() writes is the outcome of a fit. This writes
how the fit was set up: the model expression and its component names,
every parameter value, bound and vary flag, polydispersity, links, the
structure factor, the resolution mode and the Q range. Reload it with
:meth:load_analysis.
JSON rather than pickle, so the file is readable, diffable, reviewable in a pull request, and safe to accept from a collaborator.
The result is only saved while it still describes the setup. No setter clears a fit result, so a fitter can hold one produced by settings that have since changed (a parameter edited, the Q range restricted, the resolution switched, the data replaced). Saving the two together would pair a chi-squared with a configuration that never produced it. When they disagree, the setup is written, the result is left out, and the log line says which facet moved. Fit before you save, or save before you experiment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Output path for the JSON analysis file. |
required |
include_result
|
bool
|
When False, write the setup alone. Useful as a template: a configured model with no sample-specific outcome, ready to apply to the next dataset. |
True
|
Raises:
| Type | Description |
|---|---|
AnalysisFileError
|
If no model is set, or the target directory does not exist. A subclass of ValueError. |
Source code in src/sans_fitter/fitter.py
load_analysis(filename, data=None, allow_custom_models=False)
classmethod
Rebuild a fitter from a file written by :meth:save_analysis.
The data file is looked for next to the analysis file first (by the relative path recorded when it was saved) and then at its original absolute path, so an analysis that travelled together with its data loads on another machine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to the JSON analysis file. |
required |
data
|
Any
|
Dataset to use instead of the recorded one: a path, or an
in-memory dataset. Required for an analysis saved from
|
None
|
allow_custom_models
|
bool
|
Permit a model expression that is not built into sasmodels. Off by default: loading such an expression imports a plugin module named by the file, so it is code execution chosen by whoever wrote the file, not by you. |
False
|
Returns:
| Type | Description |
|---|---|
SANSFitter
|
A configured fitter. When the saved result still describes the |
SANSFitter
|
restored setup and the same data, it is attached too, so |
SANSFitter
|
|
SANSFitter
|
work without refitting. |
Raises:
| Type | Description |
|---|---|
AnalysisFileError
|
If the file is missing, malformed, written by a newer schema, describes a different model, or its data cannot be found. A subclass of ValueError. |
Source code in src/sans_fitter/fitter.py
report(filename=None, fmt=None, offline=False)
Render a shareable report: settings, result tables and the fit plot.
One document holding everything a colleague needs to judge the fit: the
model and data it used, how it was smeared and weighted, the Q range,
the goodness-of-fit and parameter tables from
:meth:get_fit_report, and the plot. After fit_bayesian() the
posterior summary comes along with it.
Before any fit this produces a configuration report instead of raising:
the settings and the current parameter values, with a theory preview in
place of the fit plot. That is also what an analysis loaded with
include_result=False renders.
HTML needs nothing beyond the standard dependencies; Markdown needs an image renderer. A Markdown report references a sidecar PNG, named after the report file so two reports in one directory cannot overwrite each other's figure. With no usable renderer the figure is left out and a warning says how to install one. HTML embeds the interactive plot either way.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str | None
|
Where to write. The extension chooses the format
( |
None
|
fmt
|
str | None
|
Format override, |
None
|
offline
|
bool
|
Embed the Plotly library in the HTML instead of loading it from a CDN. Produces a much larger file that needs no network. |
False
|
Returns:
| Type | Description |
|---|---|
Report
|
A Report. |
Report
|
a notebook renders it directly. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the extension does not name a supported format, or the target directory does not exist. |
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.
FitReport
Goodness-of-fit summary returned by SANSFitter.get_fit_report(): the χ²
statistics, the parameter table, the covariance and correlation matrices, the
convergence verdict and any parameter resting on a bound. Renders itself as a
table in a notebook, as plain text, and as Markdown.
sans_fitter.report.FitReport
dataclass
Goodness-of-fit summary for one completed fit.
Built by :meth:sans_fitter.SANSFitter.get_fit_report. Not exported at the
top level of the package, but a public type all the same: the import path
sans_fitter.report.FitReport and the methods below are stable.
Source code in src/sans_fitter/report.py
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 | |
corr
property
Correlation matrix derived from :attr:cov, or None when unavailable.
from_contract(contract, model_name)
classmethod
Snapshot contract into a report.
Nothing mutable is shared with the fitter: the parameter block is copied
one level deep (each entry becomes a fresh dictionary), the covariance is
copied, and the posterior is deep-copied — its samples array and its
per-parameter statistic and diagnostic dictionaries are all mutable, and a
caller holding the object from get_posterior() would otherwise be able
to change a report that was already handed out.
Source code in src/sans_fitter/report.py
strongly_correlated(threshold=DEFAULT_CORRELATION_THRESHOLD)
Parameter pairs whose correlation magnitude reaches threshold.
Walks the strict upper triangle, so each pair appears once, and skips cells that are not finite (a zero-variance dimension). The returned coefficient keeps its sign: an anti-correlation of -0.99 is as informative as +0.99.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
threshold
|
float
|
Magnitude at or above which a pair is reported, in [0, 1]. |
DEFAULT_CORRELATION_THRESHOLD
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If threshold lies outside [0, 1]. |
Source code in src/sans_fitter/report.py
to_markdown()
Markdown report, for a document, an issue comment or a pull request.
Writes the Unicode χ² directly: the result is a string the caller places, not console output, so the ASCII fallback would only make it uglier.
Source code in src/sans_fitter/report.py
to_dict()
The report as strictly JSON-serializable data.
Every non-finite float becomes None and every array becomes nested lists,
at any depth, so json.dumps(report.to_dict(), allow_nan=False) always
succeeds. This is the payload a future save_analysis() will store.
Source code in src/sans_fitter/report.py
to_json(indent=2)
The report as a JSON string, with non-finite values already handled.
Report
The analysis document returned by SANSFitter.report(): the settings block, the
FitReport tables and the fit plot, as one HTML page or Markdown document.
sans_fitter.reporting.Report
A rendered analysis report.
Returned by SANSFitter.report(). A plain string could not be this: it
has no _repr_html_, so it would not render in a notebook, and the
format would have to be chosen before the caller knew what to do with it.
Source code in src/sans_fitter/reporting.py
to_markdown()
to_html()
write(filename, fmt=None)
Write the report to filename, plus any sidecar assets.
Rendered before anything is replaced, through a temporary sibling and an atomic rename, so a failed write cannot destroy a report that is already there.
Source code in src/sans_fitter/reporting.py
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
PosteriorDigest
Posterior statistics without the sample chain: what an analysis loaded from a file carries. The statistics tables render exactly as they would after a fit, while displays that need the samples themselves raise instead of inventing them.
sans_fitter.results.PosteriorDigest
dataclass
Posterior statistics without the sample chain.
What a saved analysis restores. PosteriorSummary cannot serve here: it
requires samples and derives its counts from that array, so a
summary-only instance would either be impossible or would misreport having
a chain. This carries exactly the read surface FitReport uses, and
nothing that implies a chain is available.
Sample-dependent displays (trace, pair and posterior-predictive plots)
check for the real thing and raise; see SANSFitter.get_posterior.
Source code in src/sans_fitter/results.py
format_summary = PosteriorSummary.format_summary
class-attribute
instance-attribute
from_summary(posterior)
classmethod
Drop the chain from a full posterior, keeping every statistic.
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, dataset=0)
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).
Files may hold several datasets (e.g. CanSAS XML with multiple
SASentry blocks). Pass dataset to select one by 0-based index or by
name (title, run id or filename); the first dataset is used by default. A
warning is emitted whenever the file contains more than one dataset,
listing them so a different selection is possible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to the data file. |
required |
dataset
|
int | str
|
Which dataset to load — a 0-based index or a name (title, run id or filename). Defaults to the first dataset. |
0
|
Returns:
| Type | Description |
|---|---|
Data1D
|
A |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file cannot be loaded, contains no data, or the requested dataset does not exist or is ambiguous. |
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 pinhole resolution width σ_q/q (Gaussian 1-σ, not FWHM).
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
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 | |
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
Console output
Methods such as load_data, set_model and fit report what they did through
the sans_fitter logger rather than with print, so the running commentary can
be turned off:
import sans_fitter
sans_fitter.set_verbosity('quiet') # keep warnings, drop the progress messages
sans_fitter.set_verbosity('info') # back to the default
Tables you ask for explicitly - get_params(), get_pd_params(),
examples.describe() - are printed either way; they are the result of the call
rather than a side effect of it.
sans_fitter.console
Console output: the package logger and encoding-safe glyphs.
Status messages that are a side effect of a call — data loaded, model set,
fit finished — go through logging.getLogger('sans_fitter') instead of
print, so a caller can turn them off::
import sans_fitter
sans_fitter.set_verbosity('quiet')
The logger owns a stdout handler and does not propagate, so by default the
output is byte-for-byte what the print calls produced and it does not
duplicate into an application's own logging configuration. To hand it over to
that configuration instead::
import logging
log = logging.getLogger('sans_fitter')
log.handlers.clear()
log.propagate = True
Tables the user asks for explicitly (display_params, display_pd_params,
examples.describe) still print: they are the result of the call
rather than a side effect of it, so routing them through the logger would
leave those methods doing nothing when the package is silenced.
The glyph constants fall back to ASCII when the active stdout cannot encode
them. A legacy Windows console (cp1252) has no ✓, χ, → or ⁻,
and printing them there raises UnicodeEncodeError.
set_verbosity(level='info')
Set how much SANS-fitter reports about what it is doing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
int | str
|
|
'info'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If level is not a recognized level name. |
Source code in src/sans_fitter/console.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, equality links between parameters, 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
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 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 | |
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
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 207 208 | |
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
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 | |
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 |