Skip to content

Bader

Bases: BaseAnalysis

Class for running Bader analysis on a regular grid. For information on each method, see our docs

Parameters:

Name Type Description Default
charge_grid Grid

The Grid object with the charge density that will be integrated.

required
total_charge_grid Grid | None

The Grid object used for determining vacuum regions in the system. For pseudopotential codes this represents the total electron density and should be provided whenever possible. If None, defaults to the charge_grid.

required
reference_grid Grid | None

The Grid object whose values will be used to construct the basins. This should typically only be set when partitioning functions other than the charge density (e.g. ELI-D, ELF, etc.).If None, defaults to the total_charge_grid.

required
valence_counts dict | None

A dictionary where each key is an atomic species in the system and each value is the number of valence electrons used in the pseudo potential. This is used for methods that calculate oxidation states.

required
method str | Method

The algorithm to use for generating bader basins.

weight
vacuum_tol float | bool

If a float is provided, this is the value below which a point will be considered part of the vacuum. If a bool is provided, no vacuum will be used on False, and the default tolerance (0.001) will be used on True.

required
nna_cutoff float | bool

If a float is provided, any basins found at a distance in Angstroms greater than this cutoff will be considered non-nuclear attractors. If any are found, dummy atoms will be appended to the structure and regarded as separate species. If a bool is provided, NNAs will be assigned to the nearest atom on False or a default value (1 Ang) will be used on True.

False
persistence_tol float

It is common for false maxima to be found using only nearest neighbor points. To deal with this we combine pairs of basins that have low topological persistence.

The persistence score is calculated as:

score = abs(lower_max - connection_value) / connection_value
0.01
Source code in src/baderkit/core/bader/bader.py
  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
 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
class Bader(BaseAnalysis):
    """
    Class for running Bader analysis on a regular grid. For information on each
    method, see our [docs](https://sweav02.github.io/baderkit/)

    Parameters
    ----------
    charge_grid : Grid
        The Grid object with the charge density that will be integrated.
    total_charge_grid : Grid | None, optional
        The Grid object used for determining vacuum regions in the system. For
        pseudopotential codes this represents the total electron density and should
        be provided whenever possible. If None, defaults to the charge_grid.
    reference_grid : Grid | None, optional
        The Grid object whose values will be used to construct the basins. This
        should typically only be set when partitioning functions other than the
        charge density (e.g. ELI-D, ELF, etc.).If None, defaults to the
        total_charge_grid.
    valence_counts : dict | None, optional
        A dictionary where each key is an atomic species in the system and each
        value is the number of valence electrons used in the pseudo potential.
        This is used for methods that calculate oxidation states.
    method : str | Method, optional
        The algorithm to use for generating bader basins.
    vacuum_tol : float | bool, optional
        If a float is provided, this is the value below which a point will
        be considered part of the vacuum. If a bool is provided, no vacuum
        will be used on False, and the default tolerance (0.001) will be used on True.
    nna_cutoff : float | bool, optional
        If a float is provided, any basins found at a distance in Angstroms greater
        than this cutoff will be considered non-nuclear attractors. If any are
        found, dummy atoms will be appended to the structure and regarded as
        separate species. If a bool is provided, NNAs will be assigned to the
        nearest atom on False or a default value (1 Ang) will be used on True.
    persistence_tol : float, optional
        It is common for false maxima to be found using only nearest neighbor
        points. To deal with this we combine pairs of basins that have low
        topological persistence.

        The persistence score is calculated as:

            score = abs(lower_max - connection_value) / connection_value



    """

    _method_kwargs = [
        "method",
        "nna_cutoff",
        "persistence_tol",
    ]

    _maxima_results = [
        "maxima_frac",
        "maxima_cart",
        "maxima_vox",
        "maxima_charge_values",
        "maxima_ref_values",
        "basin_charges",
        "basin_volumes",
        "basin_min_surface_distances",
        "basin_avg_surface_distances",
        "basin_surface_areas",
        "basin_contact_surface_areas",
    ]

    _minima_results = [
        "minima_frac",
        "minima_cart",
        "minima_vox",
        "minima_charge_values",
        "minima_ref_values",
    ]

    _saddle_results = [
        "saddle1_frac",
        "saddle1_cart",
        "saddle1_vox",
        "saddle2_frac",
        "saddle2_cart",
        "saddle2_vox",
        "saddle1_ref_values",
        "saddle2_ref_values",
        "saddle1_connections",
        "saddle2_connections",
    ]

    _atom_results = [
        "basin_atoms",
        "basin_atom_dists",
        "atom_charges",
        "atom_volumes",
        "atom_min_surface_distances",
        "atom_avg_surface_distances",
        "atom_surface_areas",
        "atom_contact_surface_areas",
        "oxidation_states",
    ]

    _nonsummary_results = [
        # maxima properties
        "maxima_basin_labels",
        "maxima_basin_images",
        "ongrid_maxima_groups",
        "maxima_persistence_values",
        # minima properties
        "minima_basin_labels",
        "minima_basin_images",
        "ongrid_minima_groups",
        "minima_persistence_values",
        # saddle props
        # edge props
        "basin_edges",
        "atom_edges",
        # atom props
        "atom_labels",
    ]

    _reset_props = (
        _maxima_results
        + _minima_results
        + _saddle_results
        + _atom_results
        + _nonsummary_results
    )
    _summary_props = [
        "maxima_results",
        "atom_results",
    ]

    def __init__(
        self,
        method: str | Method = Method.weight,
        nna_cutoff: float | bool = False,
        persistence_tol: float = 0.01,
        **kwargs,
    ):
        super().__init__(**kwargs)

        # ensure the method is valid
        valid_methods = [m.value for m in Method]
        if isinstance(method, Method):
            self._method = method
        elif method in valid_methods:
            self._method = Method(method)
        else:
            raise ValueError(
                f"Invalid method '{method}'. Available options are: {valid_methods}"
            )

        if nna_cutoff is True:
            nna_cutoff = 1.0
        self._nna_cutoff = nna_cutoff
        self._persistence_tol = persistence_tol

        # whether or not to use overdetermined gradients in neargrid methods.
        self._use_overdetermined = False

    ###########################################################################
    # Set Properties
    ###########################################################################

    @property
    def method(self) -> str:
        """

        Returns
        -------
        str
            The algorithm to use for generating bader basins. If None, defaults
            to neargrid.

        """
        return self._method

    @method.setter
    def method(self, value: str | Method):
        # Support both Method instances and their string values
        valid_values = [m.value for m in Method]
        if isinstance(value, Method):
            self._method = value
        elif value in valid_values:
            self._method = Method(value)
        else:
            raise ValueError(
                f"Invalid method '{value}'. Available options are: {valid_values}"
            )
        self._reset_properties(
            exclude_properties=[
                "vacuum_mask",
                "num_vacuum",
                "vacuum_charge",
                "vacuum_volume",
            ]
        )

    @property
    def nna_cutoff(self) -> float:
        """

        Returns
        -------
        float
            The distance cutoff in angstroms above which a basin will be considered
            a non-nuclear attractor.

            If a float is provided, any basins found at a distance in Angstroms greater
            than this cutoff will be considered non-nuclear attractors. If any are
            found, dummy atoms will be appended to the structure and regarded as
            separate species. If a bool is provided, NNAs will be assigned to the
            nearest atom on False or a default value (1 Ang) will be used on True.

        """
        return self._nna_cutoff

    @nna_cutoff.setter
    def nna_cutoff(self, value: str | Method):
        self._nna_cutoff = value
        # reset atom properties
        self._reset_properties(
            include_properties=[
                "structure",
                "atom_edges",
                "atom_surface_areas",
                "atom_contact_surface_areas",
                "basin_atoms",
                "basin_atom_dists",
                "atom_labels",
                "atom_charges",
                "atom_volumes",
                "atom_min_surface_distances",
                "atom_avg_surface_distances",
            ]
        )

    @property
    def persistence_tol(self) -> float:
        """

        Returns
        -------
        float
            It is common for false maxima to be found using only nearest neighbor
            points. To deal with this we combine pairs of basins that have low
            topological persistence.

            The persistence score is calculated as:

                score = (lower_maximum - connection_value) / connection_value


        """
        return self._persistence_tol

    @persistence_tol.setter
    def persistence_tol(self, value: str | Method):
        self._persistence_tol = value
        # reset atom properties
        self._reset_properties(
            exclude_properties=[
                "vacuum_mask",
                "num_vacuum",
                "vacuum_charge",
                "vacuum_volume",
                "structure",
            ]
        )

    ###########################################################################
    # Maxima Basin Properties
    ###########################################################################

    @property
    def maxima_basin_labels(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            A 3D array of the same shape as the reference grid with entries
            representing the basin the voxel belongs to.

        """
        if self._maxima_basin_labels is None:
            self._run_bader()
        return self._maxima_basin_labels

    @property
    def maxima_basin_images(self) -> NDArray[int]:
        """

        Returns
        -------
        NDArray[int]
            a 3D array of the same shape as the reference grid with entries
            representing which periodic neighbor each point is assigned to. For
            example, a point may be assigned to atom 0, but following the gradient
            leads to atom zero in the unit cell at (1, 0, 0). Images are represented
            by integers to save memory and follow the values created by itertools:
                0: [-1, -1, -1]
                 1: [-1, -1,  0]
                 2: [-1, -1,  1]
                 3: [-1,  0, -1]
                 4: [-1,  0,  0]
                 5: [-1,  0,  1]
                 6: [-1,  1, -1]
                 7: [-1,  1,  0]
                 8: [-1,  1,  1]
                 9: [ 0, -1, -1]
                10: [ 0, -1,  0]
                11: [ 0, -1,  1]
                12: [ 0,  0, -1]
                13: [ 0,  0,  0]
                14: [ 0,  0,  1]
                15: [ 0,  1, -1]
                16: [ 0,  1,  0]
                17: [ 0,  1,  1]
                18: [ 1, -1, -1]
                19: [ 1, -1,  0]
                20: [ 1, -1,  1]
                21: [ 1,  0, -1]
                22: [ 1,  0,  0]
                23: [ 1,  0,  1]
                24: [ 1,  1, -1]
                25: [ 1,  1,  0]
                26: [ 1,  1,  1]

        """
        if self._maxima_basin_images is None:
            self._run_bader()
        return self._maxima_basin_images

    @property
    def maxima_vox(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The grid coordinates of each attractor.

        """
        if self._maxima_vox is None:
            self._run_bader()
        return self._maxima_vox

    @property
    def maxima_frac(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The fractional coordinates of each attractor.

        """
        if self._maxima_frac is None:
            self._run_bader()
        return self._maxima_frac

    @property
    def maxima_cart(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[int]
            The cartesian coordinates of each attractor.

        """
        if self._maxima_cart is None:
            self._maxima_cart = self.reference_grid.frac_to_cart(self._maxima_frac)
        return self._maxima_vox

    @property
    def maxima_charge_values(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The charge data value at each maximum.

        """
        if self._maxima_charge_values is None:
            self._maxima_charge_values = self.charge_grid.total[
                self.maxima_vox[:, 0],
                self.maxima_vox[:, 1],
                self.maxima_vox[:, 2],
            ]
        return self._maxima_charge_values.round(10)

    @property
    def maxima_ref_values(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The reference data value at each maximum. If the maximum is
            off grid, this value will be interpolated.

        """
        if self._maxima_ref_values is None:
            # we get these values during each bader method anyways, so
            # we run this here.
            self._maxima_ref_values = self.reference_grid.total[
                self.maxima_vox[:, 0],
                self.maxima_vox[:, 1],
                self.maxima_vox[:, 2],
            ]
        return self._maxima_ref_values

    @property
    def ongrid_maxima_groups(self) -> NDArray[int]:
        """

        Returns
        -------
        NDArray[int]
            In many systems multiple nearby points will be found to be maxima
            usually due to voxelation. We combine these maxima into one with a
            persistence metric. This property provides all of the "false" maxima
            that are associated with the final maxima list.

            For scalar fields like the ELF, LOL, or ELI-D, there may also be
            ring and cage-like maxima that are not well described by a single
            point. This also provides some indication of these maxima.

        """
        if self._ongrid_maxima_groups is None:
            self._run_bader()
        return self._ongrid_maxima_groups

    @property
    def maxima_persistence_values(self) -> NDArray[int]:
        """

        Returns
        -------
        NDArray[int]
            Each maxima may have been combined with several voxelated maxima
            (see ongrid_maxima_groups). For each maxima group, this  is the
            lowest value at which all of the maxima in the group are topologically
            connected if one takes the all voxels at or above that value
        """
        if self._maxima_persistence_values is None:
            # get groups
            tol = max(self.persistence_tol, 0)
            maxima_groups = self.ongrid_maxima_groups
            maxima_values = self.maxima_ref_values
            # get the lowest value that the maximum would connect to with the
            # current persistence tol
            persistence_values = []
            for group, max_val in zip(maxima_groups, maxima_values):
                group_vals = self.reference_grid.total[
                    group[:, 0],
                    group[:, 1],
                    group[:, 2],
                ]
                valid_mask = ((max_val - group_vals) / group_vals) - 1e-12 <= tol
                best_val = group_vals[valid_mask].min()

                # get lowest possible persistence below this value
                # (max_val - val) / val < persistence_tol
                # --> val = max_val / (1+persistence_tol)
                persistence_values.append(best_val / (1 + self.persistence_tol))

            self._maxima_persistence_values = np.array(persistence_values)
        return self._maxima_persistence_values

    @property
    def basin_charges(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The charges assigned to each attractor.

        """
        if self._basin_charges is None:
            self._run_bader()
        return self._basin_charges.round(10)

    @property
    def basin_volumes(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The volume assigned to each attractor.

        """
        if self._basin_volumes is None:
            self._run_bader()
        return self._basin_volumes.round(10)

    @property
    def basin_min_surface_distances(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The distance from each basin maxima to the nearest point on
            the basins surface

        """
        if self._basin_min_surface_distances is None:
            self._get_basin_surface_distances()
        return self._basin_min_surface_distances.round(10)

    @property
    def basin_avg_surface_distances(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The avg distance from each basin maxima to the edges of its basin

        """
        if self._basin_avg_surface_distances is None:
            self._get_basin_surface_distances()
        return self._basin_avg_surface_distances.round(10)

    @property
    def basin_atoms(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The atom index of each basin is assigned to.

        """
        if self._basin_atoms is None:
            self.run_atom_assignment()
        return self._basin_atoms

    @property
    def basin_atom_dists(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The distance from each attractor to the nearest atom

        """
        if self._basin_atom_dists is None:
            self.run_atom_assignment()
        return self._basin_atom_dists.round(10)

    @property
    def basin_edges(self) -> NDArray[np.bool_]:
        """

        Returns
        -------
        NDArray[np.bool_]
            A mask with the same shape as the input grids that is True at points
            on basin edges.

        """
        if self._basin_edges is None:
            self._basin_edges = get_edges_w_images(
                labeled_array=self.maxima_basin_labels,
                images=self.maxima_basin_images,
                vacuum_mask=np.zeros(self.maxima_basin_labels.shape, dtype=np.bool_),
                neighbor_transforms=self.reference_grid.point_neighbor_transforms[0],
            )
        return self._basin_edges

    @property
    def basin_contact_surface_areas(self) -> NDArray[np.float64]:
        """

        Returns
        -------
        NDArray[np.float64]
            A 2D array with indices i, j where i is the basin index, j is the neighboring
            basin index, and the entry at i, j is the total area in contact between
            these labels. One extra index is added that stores the number of connections
            to the vacuum.

            This value is calculated using voronoi cells of the voxels to
            approximate the shared area between a voxel point and a neighbor in
            another basin.

        """
        if self._basin_contact_surface_areas is None:
            neighbor_transforms, _, neighbor_areas, _ = (
                self.reference_grid.point_neighbor_voronoi_transforms
            )
            self._basin_contact_surface_areas = get_neighboring_basin_surface_area(
                labeled_array=self.maxima_basin_labels,
                neighbor_transforms=neighbor_transforms,
                neighbor_areas=neighbor_areas,
                vacuum_mask=self.vacuum_mask,
                label_num=len(self.maxima_frac),
            )
        return self._basin_contact_surface_areas.round(8)

    @property
    def basin_surface_areas(self) -> NDArray[np.float64]:
        """

        Returns
        -------
        NDArray[np.float64]
            The approximate surface area of each basin.

            This value is calculated using voronoi cells of the voxels to
            approximate the shared area between a voxel point and a neighbor in
            another basin.

        """
        if self._basin_surface_areas is None:
            # get the contact surface area of each basin
            contact_surfaces = self.basin_contact_surface_areas
            # sum across axis 0 to get the total
            self._basin_surface_areas = np.sum(contact_surfaces, axis=1)
        return self._basin_surface_areas.round(8)

    ###########################################################################
    # Minima Basin Properties
    ###########################################################################
    @property
    def minima_basin_labels(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The equivalent of bader basins for the desending gradient to local
            minima. This is each minima's ascending manifold and can be used
            in combination with the bader basins to locate important topological
            features.

        """
        if self._minima_basin_labels is None:
            self._run_minima_bader()
        return self._minima_basin_labels

    @property
    def minima_basin_images(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The equivalent of the basin_images property for minima basins.

        """
        if self._minima_basin_images is None:
            self._run_minima_bader()
        return self._minima_basin_images

    @property
    def minima_vox(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The grid coordinates of each local minimum.

        """
        if self._minima_vox is None:
            self._run_minima_bader()
        return self._minima_vox

    @property
    def minima_frac(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The fractional coordinates of each local minimum.

        """
        if self._minima_frac is None:
            self._run_minima_bader()
        return self._minima_frac

    @property
    def minima_cart(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[int]
            The cartesian coordinates of each attractor.

        """
        if self._minima_cart is None:
            self._minima_cart = self.reference_grid.frac_to_cart(self._minima_frac)
        return self._minima_vox

    @property
    def minima_charge_values(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The charge data value at each maximum. If the maximum is
            off grid, this value will be interpolated.

        """

        if self._minima_charge_values is None:
            self._minima_charge_values = self.charge_grid.total[
                self.minima_vox[:, 0],
                self.minima_vox[:, 1],
                self.minima_vox[:, 2],
            ]
        return self._minima_charge_values.round(10)

    @property
    def minima_ref_values(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The reference data value at each maximum. If the maximum is
            off grid, this value will be interpolated.

        """
        if self._minima_ref_values is None:
            self._minima_ref_values = self.reference_grid.total[
                self.minima_vox[:, 0],
                self.minima_vox[:, 1],
                self.minima_vox[:, 2],
            ]
        return self._minima_ref_values.round(10)

    @property
    def ongrid_minima_groups(self) -> NDArray[int]:
        """

        Returns
        -------
        NDArray[int]
            In many systems multiple nearby points will be found to be minima
            usually due to voxelation. We combine these minima into one with a
            persistence metric. This property provides all of the "false" minima
            that are associated with the final minima list.

            For scalar fields like the ELF, LOL, or ELI-D, there may also be
            ring and cage-like minima that are not well described by a single
            point. This also provides some indication of these minima.

        """
        if self._ongrid_minima_groups is None:
            self._run_minima_bader()
        return self._ongrid_minima_groups

    @property
    def minima_persistence_values(self) -> NDArray[int]:
        """

        Returns
        -------
        NDArray[int]
            Each minima may have been combined with several voxelated minima
            (see ongrid_minima_groups). For each minima group, this  is the
            highest value at which all of the minima in the group are topologically
            connected if one takes the all voxels at or below that value
        """
        if self._minima_persistence_values is None:
            tol = max(self.persistence_tol, 0)
            # self._run_minima_bader()
            # get groups
            minima_groups = self.ongrid_minima_groups
            minima_values = self.minima_ref_values
            # get the lowest value that the maximum would connect to with the
            # current persistence tol
            persistence_values = []
            for group, min_val in zip(minima_groups, minima_values):
                group_vals = self.reference_grid.total[
                    group[:, 0],
                    group[:, 1],
                    group[:, 2],
                ]
                valid_mask = ((group_vals - min_val) / group_vals) - 1e-12 <= tol
                best_val = group_vals[valid_mask].max()
                # get lowest possible persistence below this value
                # (val - max_val) / val < persistence_tol
                # --> val = max_val / (1+persistence_tol)
                persistence_values.append(best_val / (1 - self.persistence_tol))

            self._minima_persistence_values = np.array(persistence_values)
        return self._minima_persistence_values

    ###########################################################################
    # Saddle Properties
    ###########################################################################

    @property
    def saddle1_vox(self) -> NDArray[int]:
        """

        Returns
        -------
        NDArray[int]
            Grid coordinates of the type 1 saddles found in the system

        """
        if self._saddle1_vox is None:
            self._run_minima_bader()
        return self._saddle1_vox.round(10)

    @property
    def saddle1_frac(self) -> NDArray[int]:
        """

        Returns
        -------
        NDArray[int]
            Fractional coordinates of the type 1 saddles found in the system

        """
        if self._saddle1_frac is None:
            self._run_minima_bader()
        return self._saddle1_frac.round(10)

    @property
    def saddle1_cart(self) -> NDArray[int]:
        """

        Returns
        -------
        NDArray[int]
            Cartesian coordinates of the type 1 saddles found in the system

        """
        if self._saddle1_cart is None:
            self._saddle1_cart = self.reference_grid.frac_to_cart(self._saddle1_frac)
        return self._saddle1_cart.round(10)

    @property
    def saddle2_vox(self) -> NDArray[int]:
        """

        Returns
        -------
        NDArray[int]
            Voxel coordinates of the type 2 saddles found in the system

        """
        if self._saddle2_vox is None:
            self._run_maxima_bader()
        return self._saddle2_vox.round(10)

    @property
    def saddle2_frac(self) -> NDArray[int]:
        """

        Returns
        -------
        NDArray[int]
            Fractional coordinates of the type 2 saddles found in the system

        """
        if self._saddle2_frac is None:
            self._run_maxima_bader()
        return self._saddle2_frac.round(10)

    @property
    def saddle2_cart(self) -> NDArray[int]:
        """

        Returns
        -------
        NDArray[int]
            Cartesian coordinates of the type 2 saddles found in the system

        """
        if self._saddle2_cart is None:
            self._saddle2_cart = self.reference_grid.frac_to_cart(self._saddle2_frac)
        return self._saddle2_cart.round(10)

    @property
    def saddle1_ref_values(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The reference data value at each saddle1.

        """
        if self._saddle1_ref_values is None:
            # we get these values during each bader method anyways, so
            # we run this here.
            self._saddle1_ref_values = self.reference_grid.total[
                self.saddle1_vox[:, 0],
                self.saddle1_vox[:, 1],
                self.saddle1_vox[:, 2],
            ]

        return self._saddle1_ref_values.round(10)

    @property
    def saddle2_ref_values(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The reference data value at each saddle2.

        """
        if self._saddle2_ref_values is None:
            # we get these values during each bader method anyways, so
            # we run this here.
            self._saddle2_ref_values = self.reference_grid.total[
                self.saddle2_vox[:, 0],
                self.saddle2_vox[:, 1],
                self.saddle2_vox[:, 2],
            ]

        return self._saddle2_ref_values.round(10)

    @property
    def saddle1_connections(self) -> NDArray[int]:
        """

        Returns
        -------
        NDArray[int]
            An Nx3 array where the first two entries of each row represent
            the two minima the corresponding saddle connects to and the
            third entry represents the image the second minimum sits in.
            The first minima sits inside the cell.

        """
        if self._saddle1_connections is None:
            self._run_minima_bader()
        return self._saddle1_connections

    @property
    def saddle2_connections(self) -> NDArray[int]:
        """

        Returns
        -------
        NDArray[int]
            An Nx3 array where the first two entries of each row represent
            the two maxima the corresponding saddle connects to and the
            third entry represents the image the second maximum sits in.
            The first maxima sits inside the cell.

        """
        if self._saddle2_connections is None:
            self._run_maxima_bader()
        return self._saddle2_connections

    ###########################################################################
    # Atom Properties
    ###########################################################################
    @property
    def atom_labels(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            A 3D array of the same shape as the reference grid with entries
            representing the atoms the voxel belongs to.

            Note that for some methods (e.g. weight) some voxels have fractional
            assignments for each basin and this will not represent exactly how
            charges are assigned.

        """
        if self._atom_labels is None:
            self.run_atom_assignment()
        return self._atom_labels

    @property
    def atom_charges(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The charge assigned to each atom

        """
        if self._atom_charges is None:
            self.run_atom_assignment()
        return self._atom_charges.round(10)

    @property
    def atom_volumes(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The volume assigned to each atom

        """
        if self._atom_volumes is None:
            self.run_atom_assignment()
        return self._atom_volumes.round(10)

    @property
    def atom_min_surface_distances(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The distance from each atom to the nearest point on the atoms surface.

        """
        if self._atom_min_surface_distances is None:
            self._get_atom_surface_distances()
        return self._atom_min_surface_distances.round(10)

    @property
    def atom_avg_surface_distances(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The avg distance from each atom to the edges of its basin

        """
        if self._atom_avg_surface_distances is None:
            self._get_basin_surface_distances()
        return self._atom_avg_surface_distances.round(10)

    @property
    def atom_edges(self) -> NDArray[np.bool_]:
        """

        Returns
        -------
        NDArray[np.bool_]
            A mask with the same shape as the input grids that is True at points
            on atom edges.

        """
        if self._atom_edges is None:
            self._atom_edges = get_edges_w_images(
                labeled_array=self.atom_labels,
                images=self.maxima_basin_images,
                vacuum_mask=np.zeros(self.atom_labels.shape, dtype=np.bool_),
                neighbor_transforms=self.reference_grid.point_neighbor_transforms[0],
            )
        return self._atom_edges

    @property
    def atom_contact_surface_areas(self) -> NDArray[np.float64]:
        """

        Returns
        -------
        NDArray[np.float64]
            A 2D array with indices i, j where i is the atom index, j is the neighboring
            atom index, and the entry at i, j is the total area in contact between
            these labels. One extra index is added that stores the number of connections
            to the vacuum.

            This value is calculated using voronoi cells of the voxels to
            approximate the shared area between a voxel point and a neighbor in
            another atom.

        """
        if self._atom_contact_surface_areas is None:
            neighbor_transforms, _, neighbor_areas, _ = (
                self.reference_grid.point_neighbor_voronoi_transforms
            )
            self._atom_contact_surface_areas = get_neighboring_basin_surface_area(
                labeled_array=self.atom_labels,
                neighbor_transforms=neighbor_transforms,
                neighbor_areas=neighbor_areas,
                vacuum_mask=self.vacuum_mask,
                label_num=len(self.structure),
            )
        return self._atom_contact_surface_areas.round(8)

    @property
    def atom_surface_areas(self) -> NDArray[np.float64]:
        """

        Returns
        -------
        NDArray[np.float64]
            The approximate surface area of each atom.

            This value is calculated using voronoi cells of the voxels to
            approximate the shared area between a voxel point and a neighbor in
            another atom.

        """
        if self._atom_surface_areas is None:
            # get the contact surface area of each atom
            contact_surfaces = self.atom_contact_surface_areas
            # sum across axis 0 to get the total
            self._atom_surface_areas = np.sum(contact_surfaces, axis=1)
        return self._atom_surface_areas.round(8)

    @property
    def oxidation_states(self) -> NDArray[np.float64]:
        oxi_state_data = []
        for site, site_charge in zip(self.structure, self.atom_charges):
            element_str = site.specie.name
            oxi_state = self.valence_counts.get(element_str, 0.0) - site_charge
            oxi_state_data.append(oxi_state)

        return np.array(oxi_state_data)

    ###########################################################################
    # Other Properties
    ###########################################################################

    @property
    def total_electron_number(self) -> float:
        """

        Returns
        -------
        float
            The total number of electrons in the system calculated from the
            atom charges and vacuum charge. If this does not match the true
            total electron number within reasonable floating point error,
            there is a major problem.

        """

        return round(self.atom_charges.sum() + self.vacuum_charge, 10)

    @property
    def total_volume(self):
        """

        Returns
        -------
        float
            The total volume integrated in the system. This should match the
            volume of the structure. If it does not there may be a serious problem.

        """

        return round(self.atom_volumes.sum() + self.vacuum_volume, 10)

    ###########################################################################
    # Methods
    ###########################################################################

    @staticmethod
    def all_methods() -> list[str]:
        """

        Returns
        -------
        list[str]
            A list of the available methods.

        """

        return [i.value for i in Method]

    def _run_bader(self) -> None:
        """
        Runs the entire Bader process and saves results to class variables.

        """
        t0 = time.time()
        logging.info(f"Beginning Bader Algorithm Using '{self.method.name}' Method")
        # Normalize the method name to a module and class name
        module_name = self.method.replace(
            "-", "_"
        )  # 'pseudo-neargrid' -> 'pseudo_neargrid'
        class_name = (
            "".join(part.capitalize() for part in module_name.split("_")) + "Method"
        )

        # import method
        mod = importlib.import_module(f"baderkit.core.bader.methods.{module_name}")
        Method = getattr(mod, class_name)

        # Instantiate and run the selected method
        method = Method(
            charge_grid=self.charge_grid,
            reference_grid=self.reference_grid,
            vacuum_mask=self.vacuum_mask,
            num_vacuum=self.num_vacuum,
            persistence_tol=self.persistence_tol,
            use_minima=False,
        )
        if self._use_overdetermined:
            method._use_overdetermined = True
        results = method.run()

        for key, value in results.items():
            if "extrema" in key:
                new_key = key.replace("extrema", "maxima")
                setattr(self, f"_{new_key}", value)
            else:
                setattr(self, f"_{key}", value)

        t1 = time.time()
        logging.info("Bader Algorithm Complete")
        logging.info(f"Time: {round(t1-t0,2)}")

    def _run_minima_bader(self) -> None:
        """
        Runs the entire Bader process and saves results to class variables.

        """
        t0 = time.time()
        logging.info(
            f"Beginning Minima Bader Algorithm Using '{self.method.name}' Method"
        )
        # Normalize the method name to a module and class name
        module_name = self.method.replace(
            "-", "_"
        )  # 'pseudo-neargrid' -> 'pseudo_neargrid'
        class_name = (
            "".join(part.capitalize() for part in module_name.split("_")) + "Method"
        )

        # import method
        mod = importlib.import_module(f"baderkit.core.bader.methods.{module_name}")
        Method = getattr(mod, class_name)

        # Instantiate and run the selected method
        method = Method(
            charge_grid=self.charge_grid,
            reference_grid=self.reference_grid,
            vacuum_mask=self.vacuum_mask,
            num_vacuum=self.num_vacuum,
            use_minima=True,
            persistence_tol=self.persistence_tol,
        )
        if self._use_overdetermined:
            method._use_overdetermined = True
        results = method.run()

        # set related properties
        for key, value in results.items():
            if "extrema" in key or "saddle" in key:
                new_key = key.replace("extrema", "minima")
                setattr(self, f"_{new_key}", value)

        t1 = time.time()
        logging.info("Bader Algorithm Complete")
        logging.info(f"Time: {round(t1-t0,2)}")

    def assign_basins_to_structure(
        self, structure: Structure, nna_cutoff: bool | float = False
    ):
        """
        Gets atom assignments for the provided structure.

        Parameters
        ----------
        structure : Structure
            The structure to assign basins to.
        nna_cutoff : bool | float, optional
            A distance cutoff. Any basins with maxima further from an atom than
            this value (in Angstroms) will be counted as its own species. Dummy
            atoms will be added to the structure. The default is False.

        Returns
        -------
        atom_labels : NDArray
            A 3D array with the same shape as the grid where each entry represents
            the atom that point belongs to.
        atom_charges : NDArray
            The charge assigned to each atom.
        atom_volumes : NDArray
            The volume assigned to each atom.
        basin_atoms : NDArray
            The atom each basin was assigned to.
        basin_atom_dists : NDArray
            The distance from each basin to the nearest atom.

        """
        if nna_cutoff is True:
            nna_cutoff = 1.0

        # Get basin and atom frac coords
        basins = self.maxima_frac  # (N_basins, 3)
        atoms = structure.frac_coords  # (N_atoms, 3)

        # get lattice matrix and number of atoms/basins
        L = structure.lattice.matrix  # (3, 3)
        N_basins = len(basins)

        def get_atom_basins(atoms, basins):
            # Vectorized deltas, minimum‑image wrapping
            diffs = atoms[None, :, :] - basins[:, None, :]
            diffs += np.where(diffs <= -0.5, 1, 0)
            diffs -= np.where(diffs >= 0.5, 1, 0)

            # Cartesian diffs & distances
            cart = np.einsum("bij,jk->bik", diffs, L)
            dists = np.linalg.norm(cart, axis=2)

            # Basin→atom assignment & distances
            basin_atoms = np.argmin(dists, axis=1)  # (N_basins,)
            basin_atom_dists = dists[np.arange(N_basins), basin_atoms]  # (N_basins,)
            return basin_atoms, basin_atom_dists

        basin_atoms, basin_atom_dists = get_atom_basins(atoms, basins)

        if nna_cutoff:
            # add dummy atoms at basin maxima far from atoms
            for coords, dist in zip(basins, basin_atom_dists):
                if dist > nna_cutoff:
                    # add a dummy atom to the structure
                    structure.append("X", coords)
            # recalculate distances
            atoms = structure.frac_coords
            basin_atoms, basin_atom_dists = get_atom_basins(atoms, basins)

        # vacuum is represented by an index one above the highest label. we add
        # that to our basin atoms temporarily
        basin_atoms = np.insert(basin_atoms, len(basin_atoms), len(structure))

        # Atom labels per grid point
        atom_labels = basin_atoms[self.maxima_basin_labels]

        # remove vacuum pointer in basin atoms
        basin_atoms = basin_atoms[:-1]

        atom_charges = np.bincount(
            basin_atoms, weights=self.basin_charges, minlength=len(structure)
        )
        atom_volumes = np.bincount(
            basin_atoms, weights=self.basin_volumes, minlength=len(structure)
        )

        return (
            atom_labels,
            atom_charges,
            atom_volumes,
            basin_atoms,
            basin_atom_dists,
        )

    def run_atom_assignment(self):
        """
        Assigns bader basins to this Bader objects structure.

        """
        # ensure bader has run (otherwise our time will include the bader time)
        self.maxima_frac

        # Default structure
        structure = self.structure

        t0 = time.time()
        logging.info("Assigning Atom Properties")
        # get basin assignments for this bader objects structure
        (
            atom_labels,
            atom_charges,
            atom_volumes,
            basin_atoms,
            basin_atom_dists,
        ) = self.assign_basins_to_structure(structure, self.nna_cutoff)

        # Store everything
        self._basin_atoms = basin_atoms
        self._basin_atom_dists = basin_atom_dists
        self._atom_labels = atom_labels
        self._atom_charges = atom_charges
        self._atom_volumes = atom_volumes
        logging.info("Atom Assignment Finished")
        t1 = time.time()
        logging.info(f"Time: {round(t1-t0, 2)}")

    def get_persistence_groups(self):
        """
        Gets the groups of voxels for each maximum and minimum that are within
        the extrema's basin and above/below the persistence value for that basin.
        The persistence value is defined as the value at which all voxelated
        maxima/minima (see ongrid_maxima_groups/ongrid_minima_groups) are connected

        Returns
        -------
        maxima_groups : list[NDArray[int64]]
            A list of Nx3 arrays where each array represents the grid indices of voxels
            that are within each maximas persistence threshold.
        minima_groups : list[NDArray[int64]]
            A list of Nx3 arrays where each array represents the grid indices of voxels
            that are within each minimas persistence threshold.

        """

        maxima_groups = get_persistence_groups(
            labels=self.maxima_basin_labels,
            data=self.reference_grid.total,
            persistence_cutoffs=self.maxima_persistence_values,
            extrema_vox=self.maxima_vox,
            use_minima=False,
        )

        minima_groups = get_persistence_groups(
            labels=self.minima_basin_labels,
            data=self.reference_grid.total,
            persistence_cutoffs=self.minima_persistence_values,
            extrema_vox=self.minima_vox,
            use_minima=True,
        )

        return maxima_groups, minima_groups

    def get_betti_numbers(
        self,
        return_values: bool = False,
        return_groups: bool = False,
    ) -> tuple:
        """
        The approximate betti numbers for an maxima and minima persistence
        groups. This is obtained by scanning through a persistence group's
        values from high to low and recording the betti numbers throughout.
        If a cage (1,0,1) or ring (1,1,0) is found at any point, the extremum
        is marked with this set. Otherwise, it is returned as a point (1,0,0).
        While other betti numbers are possible, we believe these are the
        only reasonable ones that should show up for very flat extrema in the
        ELF, ELI-D, LOL or other localization functions.

        Parameters
        ----------
        return_values : bool, optional
            Whether or not to return the values at which the resulting betti
            numbers exist. The default is False.
        return_groups : bool, optional
            Whether or not to return the voxel coordinates that result in the
            returned betti numbers. The default is False.

        Returns
        -------
        tuple
            The betti numbers for maxima and minima. If return_values
            is selected, the values at which the extrema form these betti numbers
            will be appended. If return_gorups is selected, the voxels making up
            these betti shapes are appended.

        """

        maxima_groups, minima_groups = self.get_persistence_groups()
        base_maxima = self.maxima_vox
        maxima_base_vals = self.reference_grid.total[
            base_maxima[:, 0], base_maxima[:, 1], base_maxima[:, 2]
        ]
        maxima_betti_numbers, maxima_betti_vals = get_all_betti_numbers_scanning(
            maxima_groups,
            maxima_base_vals,
            self.reference_grid.total,
            use_minima=False,
        )

        base_minima = self.minima_vox
        minima_base_vals = self.reference_grid.total[
            base_minima[:, 0], base_minima[:, 1], base_minima[:, 2]
        ]
        minima_betti_numbers, minima_betti_vals = get_all_betti_numbers_scanning(
            minima_groups,
            minima_base_vals,
            self.reference_grid.total,
            use_minima=True,
        )

        results = [maxima_betti_numbers, minima_betti_numbers]

        if return_values:
            results.append(maxima_betti_vals)
            results.append(minima_betti_vals)

        if return_groups:
            maxima_groups = get_persistence_groups(
                labels=self.maxima_basin_labels,
                data=self.reference_grid.total,
                persistence_cutoffs=maxima_betti_vals,
                extrema_vox=self.maxima_vox,
                use_minima=False,
            )

            minima_groups = get_persistence_groups(
                labels=self.minima_basin_labels,
                data=self.reference_grid.total,
                persistence_cutoffs=minima_betti_vals,
                extrema_vox=self.minima_vox,
                use_minima=True,
            )
            results.append(maxima_groups)
            results.append(minima_groups)

        return tuple(results)

    def _get_atom_surface_distances(self):
        """
        Calculates the distance from each atom to the nearest surface. This is
        automatically called during the atom assignment and generally should
        not be called manually.

        """
        self._atom_min_surface_distances, self._atom_avg_surface_distances = (
            get_min_avg_surface_dists(
                labels=self.atom_labels,
                frac_coords=self.structure.frac_coords,
                edge_mask=self.atom_edges,
                matrix=self.reference_grid.matrix,
                max_value=np.max(self.structure.lattice.abc) * 2,
            )
        )

    def _get_basin_surface_distances(self):
        """
        Calculates the distance from each basin maxima to the nearest surface.
        This is automatically called during the atom assignment and generally
        should not be called manually.

        """
        # get the minimum distances
        (
            self._basin_min_surface_distances,
            self._basin_avg_surface_distances,
        ) = get_min_avg_surface_dists(
            labels=self.maxima_basin_labels,
            frac_coords=self.maxima_frac,
            edge_mask=self.basin_edges,
            matrix=self.reference_grid.matrix,
            max_value=np.max(self.structure.lattice.abc) * 2,
        )

    ###########################################################################
    # Write Methods
    ###########################################################################

    def write_basin_volumes(
        self,
        basin_indices: NDArray[int],
        **kwargs,
    ):
        """
        Writes bader basins to vasp-like files. Points belonging to the basin
        will have values from the charge or reference grid, and all other points
        will be 0.

        Parameters
        ----------
        basin_indices : NDArray
            The list of basin indices to write

        """
        for basin in basin_indices:
            # get a mask everywhere but the requested basin
            mask = self.maxima_basin_labels == basin
            kwargs["suffix"] = f"_b{basin}"

            self._write_volume(volume_mask=mask, **kwargs)

    def write_all_basin_volumes(
        self,
        basin_tol: float = 1e-03,
        **kwargs,
    ):
        """
        Writes all bader basins to vasp-like files. Points belonging to the basin
        will have values from the charge or reference grid, and all other points
        will be 0.

        Parameters
        ----------
        basin_tol : float, optional
            The total charge value below which a basin will not be considered written

        """
        basin_indices = np.where(self.basin_charges > basin_tol)[0]
        self.write_basin_volumes(
            basin_indices=basin_indices,
            **kwargs,
        )

    def write_basin_volumes_sum(
        self,
        basin_indices: NDArray[int],
        **kwargs,
    ):
        """
        Writes the union of the provided bader basins to vasp-like files.
        Points belonging to the basins will have values from the charge or
        reference grid, and all other points will be 0.

        Parameters
        ----------
        basin_indices : NDArray
            The list of basin indices to sum and write

        """
        # create a mask including each of the requested basins
        mask = np.isin(self.maxima_basin_labels, basin_indices)
        # write
        kwargs["suffix"] = "_bsum"
        self._write_volume(volume_mask=mask, **kwargs)

    def write_atom_volumes(
        self,
        atom_indices: NDArray,
        **kwargs,
    ):
        """
        Writes atomic basins to vasp-like files. Points belonging to the atom
        will have values from the charge or reference grid, and all other points
        will be 0.

        Parameters
        ----------
        atom_indices : NDArray
            The list of atom indices to write

        """

        for atom_index in atom_indices:
            # get a mask at the requested atoms
            mask = self.atom_labels == atom_index
            kwargs["suffix"] = f"_a{atom_index}"
            self._write_volume(volume_mask=mask, **kwargs)

    def write_all_atom_volumes(
        self,
        **kwargs,
    ):
        """
        Writes all atomic basins to vasp-like files. Points belonging to the atom
        will have values from the charge or reference grid, and all other points
        will be 0.

        """
        atom_indices = np.array(range(len(self.structure)))
        self.write_atom_volumes(
            atom_indices=atom_indices,
            **kwargs,
        )

    def write_atom_volumes_sum(
        self,
        atom_indices: NDArray,
        **kwargs,
    ):
        """
        Writes the union of the provided atom basins to vasp-like files.
        Points belonging to the atoms will have values from the charge or
        reference grid, and all other points will be 0.

        Parameters
        ----------
        atom_indices : NDArray
            The list of atom indices to sum and write

        """

        mask = np.isin(self.atom_labels, atom_indices)
        # write
        kwargs["suffix"] = "_asum"
        self._write_volume(volume_mask=mask, **kwargs)

    def write_species_volume(
        self,
        species: str,
        **kwargs,
    ):
        """
        Writes the charge density or reference file for all atoms of the given
        species to a single file.

        Parameters
        ----------
        species : str, optional
            The species to write.

        """

        # add dummy atoms if desired
        indices = self.structure.indices_from_symbol(species)

        # Get mask where the grid belongs to requested species
        mask = np.isin(self.atom_labels, indices)
        kwargs["suffix"] = f"_{species}"
        self._write_volume(volume_mask=mask, **kwargs)

    def get_atom_results_dataframe(self) -> pd.DataFrame:
        """
        Collects a summary of results for the atoms in a pandas DataFrame.

        Returns
        -------
        atoms_df : pd.DataFrame
            A table summarizing the atomic basins.

        """
        # Get atom results summary
        atom_frac_coords = self.structure.frac_coords
        atoms_df = pd.DataFrame(
            {
                "label": self.structure.labels,
                "x": atom_frac_coords[:, 0],
                "y": atom_frac_coords[:, 1],
                "z": atom_frac_coords[:, 2],
                "charge": self.atom_charges,
                "volume": self.atom_volumes,
                "surface_dist": self.atom_min_surface_distances,
            }
        )
        return atoms_df

    def get_basin_results_dataframe(self, basin_tol: float):
        """
        Collects a summary of results for the basins in a pandas DataFrame.

        Returns
        -------
        basin_df : pd.DataFrame
            A table summarizing the basins.
        basin_tol : float, optional
            The total charge value below which a basin will not be considered significant.

        """
        subset = self.basin_charges > basin_tol
        basin_frac_coords = self.maxima_frac[subset]
        basin_df = pd.DataFrame(
            {
                "atoms": np.array(self.structure.labels)[self.basin_atoms[subset]],
                "x": basin_frac_coords[:, 0],
                "y": basin_frac_coords[:, 1],
                "z": basin_frac_coords[:, 2],
                "charge": self.basin_charges[subset],
                "volume": self.basin_volumes[subset],
                "surface_dist": self.basin_min_surface_distances[subset],
                "atom_dist": self.basin_atom_dists[subset],
            }
        )
        return basin_df

    def write_atom_tsv(self, filepath: Path | str = "bader_atoms.tsv"):
        """
        Writes a summary of atom results to .tsv files.

        Parameters
        ----------
        filepath : str | Path
            The Path to write the results to. The default is "bader_atoms.tsv".


        """
        filepath = Path(filepath)

        # Get atom results summary
        atoms_df = self.get_atom_results_dataframe()
        formatted_atoms_df = atoms_df.copy()
        numeric_cols = formatted_atoms_df.select_dtypes(include="number").columns
        formatted_atoms_df[numeric_cols] = formatted_atoms_df[numeric_cols].map(
            lambda x: f"{x:.5f}"
        )

        # Determine max width per column including header
        col_widths = {
            col: max(len(col), formatted_atoms_df[col].map(len).max())
            for col in atoms_df.columns
        }

        # Note what we're writing in log
        logging.info(f"Writing Atom Summary to {filepath}")

        # write output summaries
        with open(filepath, "w") as f:
            # Write header
            header = "\t".join(
                f"{col:<{col_widths[col]}}" for col in formatted_atoms_df.columns
            )
            f.write(header + "\n")

            # Write rows
            for _, row in formatted_atoms_df.iterrows():
                line = "\t".join(
                    f"{val:<{col_widths[col]}}" for col, val in row.items()
                )
                f.write(line + "\n")
            # write vacuum summary to atom file
            f.write("\n")
            f.write(f"Vacuum Charge:\t\t{self.vacuum_charge:.5f}\n")
            f.write(f"Vacuum Volume:\t\t{self.vacuum_volume:.5f}\n")
            f.write(f"Total Electrons:\t{self.total_electron_number:.5f}\n")
            f.write(f"Total Volume:\t{self.total_volume:.5f}\n")

    def write_basin_tsv(self, filepath: Path | str = "bader_basins.tsv"):
        """
        Writes a summary of basin results to .tsv files.

        Parameters
        ----------
        filepath : str | Path
            The Path to write the results to. The default is "bader_basins.tsv".

        """
        filepath = Path(filepath)

        # Get basin results summary
        basin_df = self.get_basin_results_dataframe(0.01)
        formatted_basin_df = basin_df.copy()
        numeric_cols = formatted_basin_df.select_dtypes(include="number").columns
        formatted_basin_df[numeric_cols] = formatted_basin_df[numeric_cols].map(
            lambda x: f"{x:.5f}"
        )

        # Determine max width per column including header
        col_widths = {
            col: max(len(col), formatted_basin_df[col].map(len).max())
            for col in basin_df.columns
        }

        # Write to file with aligned columns using tab as separator

        # Note what we're writing in log

        logging.info(f"Writing Basin Summary to {filepath}")

        # write output summaries
        with open(filepath, "w") as f:
            # Write header
            header = "\t".join(f"{col:<{col_widths[col]}}" for col in basin_df.columns)
            f.write(header + "\n")

            # Write rows
            for _, row in formatted_basin_df.iterrows():
                line = "\t".join(
                    f"{val:<{col_widths[col]}}" for col, val in row.items()
                )
                f.write(line + "\n")

    def to_dict(self, include_minima: bool = False) -> dict:
        """
        Converts the Bader object to a dictionary.

        Returns
        -------
        dict
            A dictionary representation of the Bader object.

        """
        results = super().to_dict()
        if include_minima:
            results["minima_results"] = self._to_dict(self._minima_results)
            results["saddle_results"] = self._to_dict(self._saddle_results)
        return results

atom_avg_surface_distances property

Returns:

Type Description
NDArray[float]

The avg distance from each atom to the edges of its basin

atom_charges property

Returns:

Type Description
NDArray[float]

The charge assigned to each atom

atom_contact_surface_areas property

Returns:

Type Description
NDArray[float64]

A 2D array with indices i, j where i is the atom index, j is the neighboring atom index, and the entry at i, j is the total area in contact between these labels. One extra index is added that stores the number of connections to the vacuum.

This value is calculated using voronoi cells of the voxels to approximate the shared area between a voxel point and a neighbor in another atom.

atom_edges property

Returns:

Type Description
NDArray[bool_]

A mask with the same shape as the input grids that is True at points on atom edges.

atom_labels property

Returns:

Type Description
NDArray[float]

A 3D array of the same shape as the reference grid with entries representing the atoms the voxel belongs to.

Note that for some methods (e.g. weight) some voxels have fractional assignments for each basin and this will not represent exactly how charges are assigned.

atom_min_surface_distances property

Returns:

Type Description
NDArray[float]

The distance from each atom to the nearest point on the atoms surface.

atom_surface_areas property

Returns:

Type Description
NDArray[float64]

The approximate surface area of each atom.

This value is calculated using voronoi cells of the voxels to approximate the shared area between a voxel point and a neighbor in another atom.

atom_volumes property

Returns:

Type Description
NDArray[float]

The volume assigned to each atom

basin_atom_dists property

Returns:

Type Description
NDArray[float]

The distance from each attractor to the nearest atom

basin_atoms property

Returns:

Type Description
NDArray[float]

The atom index of each basin is assigned to.

basin_avg_surface_distances property

Returns:

Type Description
NDArray[float]

The avg distance from each basin maxima to the edges of its basin

basin_charges property

Returns:

Type Description
NDArray[float]

The charges assigned to each attractor.

basin_contact_surface_areas property

Returns:

Type Description
NDArray[float64]

A 2D array with indices i, j where i is the basin index, j is the neighboring basin index, and the entry at i, j is the total area in contact between these labels. One extra index is added that stores the number of connections to the vacuum.

This value is calculated using voronoi cells of the voxels to approximate the shared area between a voxel point and a neighbor in another basin.

basin_edges property

Returns:

Type Description
NDArray[bool_]

A mask with the same shape as the input grids that is True at points on basin edges.

basin_min_surface_distances property

Returns:

Type Description
NDArray[float]

The distance from each basin maxima to the nearest point on the basins surface

basin_surface_areas property

Returns:

Type Description
NDArray[float64]

The approximate surface area of each basin.

This value is calculated using voronoi cells of the voxels to approximate the shared area between a voxel point and a neighbor in another basin.

basin_volumes property

Returns:

Type Description
NDArray[float]

The volume assigned to each attractor.

maxima_basin_images property

Returns:

Type Description
NDArray[int]

a 3D array of the same shape as the reference grid with entries representing which periodic neighbor each point is assigned to. For example, a point may be assigned to atom 0, but following the gradient leads to atom zero in the unit cell at (1, 0, 0). Images are represented by integers to save memory and follow the values created by itertools: 0: [-1, -1, -1] 1: [-1, -1, 0] 2: [-1, -1, 1] 3: [-1, 0, -1] 4: [-1, 0, 0] 5: [-1, 0, 1] 6: [-1, 1, -1] 7: [-1, 1, 0] 8: [-1, 1, 1] 9: [ 0, -1, -1] 10: [ 0, -1, 0] 11: [ 0, -1, 1] 12: [ 0, 0, -1] 13: [ 0, 0, 0] 14: [ 0, 0, 1] 15: [ 0, 1, -1] 16: [ 0, 1, 0] 17: [ 0, 1, 1] 18: [ 1, -1, -1] 19: [ 1, -1, 0] 20: [ 1, -1, 1] 21: [ 1, 0, -1] 22: [ 1, 0, 0] 23: [ 1, 0, 1] 24: [ 1, 1, -1] 25: [ 1, 1, 0] 26: [ 1, 1, 1]

maxima_basin_labels property

Returns:

Type Description
NDArray[float]

A 3D array of the same shape as the reference grid with entries representing the basin the voxel belongs to.

maxima_cart property

Returns:

Type Description
NDArray[int]

The cartesian coordinates of each attractor.

maxima_charge_values property

Returns:

Type Description
NDArray[float]

The charge data value at each maximum.

maxima_frac property

Returns:

Type Description
NDArray[float]

The fractional coordinates of each attractor.

maxima_persistence_values property

Returns:

Type Description
NDArray[int]

Each maxima may have been combined with several voxelated maxima (see ongrid_maxima_groups). For each maxima group, this is the lowest value at which all of the maxima in the group are topologically connected if one takes the all voxels at or above that value

maxima_ref_values property

Returns:

Type Description
NDArray[float]

The reference data value at each maximum. If the maximum is off grid, this value will be interpolated.

maxima_vox property

Returns:

Type Description
NDArray[float]

The grid coordinates of each attractor.

method property writable

Returns:

Type Description
str

The algorithm to use for generating bader basins. If None, defaults to neargrid.

minima_basin_images property

Returns:

Type Description
NDArray[float]

The equivalent of the basin_images property for minima basins.

minima_basin_labels property

Returns:

Type Description
NDArray[float]

The equivalent of bader basins for the desending gradient to local minima. This is each minima's ascending manifold and can be used in combination with the bader basins to locate important topological features.

minima_cart property

Returns:

Type Description
NDArray[int]

The cartesian coordinates of each attractor.

minima_charge_values property

Returns:

Type Description
NDArray[float]

The charge data value at each maximum. If the maximum is off grid, this value will be interpolated.

minima_frac property

Returns:

Type Description
NDArray[float]

The fractional coordinates of each local minimum.

minima_persistence_values property

Returns:

Type Description
NDArray[int]

Each minima may have been combined with several voxelated minima (see ongrid_minima_groups). For each minima group, this is the highest value at which all of the minima in the group are topologically connected if one takes the all voxels at or below that value

minima_ref_values property

Returns:

Type Description
NDArray[float]

The reference data value at each maximum. If the maximum is off grid, this value will be interpolated.

minima_vox property

Returns:

Type Description
NDArray[float]

The grid coordinates of each local minimum.

nna_cutoff property writable

Returns:

Type Description
float

The distance cutoff in angstroms above which a basin will be considered a non-nuclear attractor.

If a float is provided, any basins found at a distance in Angstroms greater than this cutoff will be considered non-nuclear attractors. If any are found, dummy atoms will be appended to the structure and regarded as separate species. If a bool is provided, NNAs will be assigned to the nearest atom on False or a default value (1 Ang) will be used on True.

ongrid_maxima_groups property

Returns:

Type Description
NDArray[int]

In many systems multiple nearby points will be found to be maxima usually due to voxelation. We combine these maxima into one with a persistence metric. This property provides all of the "false" maxima that are associated with the final maxima list.

For scalar fields like the ELF, LOL, or ELI-D, there may also be ring and cage-like maxima that are not well described by a single point. This also provides some indication of these maxima.

ongrid_minima_groups property

Returns:

Type Description
NDArray[int]

In many systems multiple nearby points will be found to be minima usually due to voxelation. We combine these minima into one with a persistence metric. This property provides all of the "false" minima that are associated with the final minima list.

For scalar fields like the ELF, LOL, or ELI-D, there may also be ring and cage-like minima that are not well described by a single point. This also provides some indication of these minima.

persistence_tol property writable

Returns:

Type Description
float

It is common for false maxima to be found using only nearest neighbor points. To deal with this we combine pairs of basins that have low topological persistence.

The persistence score is calculated as:

score = (lower_maximum - connection_value) / connection_value

saddle1_cart property

Returns:

Type Description
NDArray[int]

Cartesian coordinates of the type 1 saddles found in the system

saddle1_connections property

Returns:

Type Description
NDArray[int]

An Nx3 array where the first two entries of each row represent the two minima the corresponding saddle connects to and the third entry represents the image the second minimum sits in. The first minima sits inside the cell.

saddle1_frac property

Returns:

Type Description
NDArray[int]

Fractional coordinates of the type 1 saddles found in the system

saddle1_ref_values property

Returns:

Type Description
NDArray[float]

The reference data value at each saddle1.

saddle1_vox property

Returns:

Type Description
NDArray[int]

Grid coordinates of the type 1 saddles found in the system

saddle2_cart property

Returns:

Type Description
NDArray[int]

Cartesian coordinates of the type 2 saddles found in the system

saddle2_connections property

Returns:

Type Description
NDArray[int]

An Nx3 array where the first two entries of each row represent the two maxima the corresponding saddle connects to and the third entry represents the image the second maximum sits in. The first maxima sits inside the cell.

saddle2_frac property

Returns:

Type Description
NDArray[int]

Fractional coordinates of the type 2 saddles found in the system

saddle2_ref_values property

Returns:

Type Description
NDArray[float]

The reference data value at each saddle2.

saddle2_vox property

Returns:

Type Description
NDArray[int]

Voxel coordinates of the type 2 saddles found in the system

total_electron_number property

Returns:

Type Description
float

The total number of electrons in the system calculated from the atom charges and vacuum charge. If this does not match the true total electron number within reasonable floating point error, there is a major problem.

total_volume property

Returns:

Type Description
float

The total volume integrated in the system. This should match the volume of the structure. If it does not there may be a serious problem.

all_methods() staticmethod

Returns:

Type Description
list[str]

A list of the available methods.

Source code in src/baderkit/core/bader/bader.py
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
@staticmethod
def all_methods() -> list[str]:
    """

    Returns
    -------
    list[str]
        A list of the available methods.

    """

    return [i.value for i in Method]

assign_basins_to_structure(structure, nna_cutoff=False)

Gets atom assignments for the provided structure.

Parameters:

Name Type Description Default
structure Structure

The structure to assign basins to.

required
nna_cutoff bool | float

A distance cutoff. Any basins with maxima further from an atom than this value (in Angstroms) will be counted as its own species. Dummy atoms will be added to the structure. The default is False.

False

Returns:

Name Type Description
atom_labels NDArray

A 3D array with the same shape as the grid where each entry represents the atom that point belongs to.

atom_charges NDArray

The charge assigned to each atom.

atom_volumes NDArray

The volume assigned to each atom.

basin_atoms NDArray

The atom each basin was assigned to.

basin_atom_dists NDArray

The distance from each basin to the nearest atom.

Source code in src/baderkit/core/bader/bader.py
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
def assign_basins_to_structure(
    self, structure: Structure, nna_cutoff: bool | float = False
):
    """
    Gets atom assignments for the provided structure.

    Parameters
    ----------
    structure : Structure
        The structure to assign basins to.
    nna_cutoff : bool | float, optional
        A distance cutoff. Any basins with maxima further from an atom than
        this value (in Angstroms) will be counted as its own species. Dummy
        atoms will be added to the structure. The default is False.

    Returns
    -------
    atom_labels : NDArray
        A 3D array with the same shape as the grid where each entry represents
        the atom that point belongs to.
    atom_charges : NDArray
        The charge assigned to each atom.
    atom_volumes : NDArray
        The volume assigned to each atom.
    basin_atoms : NDArray
        The atom each basin was assigned to.
    basin_atom_dists : NDArray
        The distance from each basin to the nearest atom.

    """
    if nna_cutoff is True:
        nna_cutoff = 1.0

    # Get basin and atom frac coords
    basins = self.maxima_frac  # (N_basins, 3)
    atoms = structure.frac_coords  # (N_atoms, 3)

    # get lattice matrix and number of atoms/basins
    L = structure.lattice.matrix  # (3, 3)
    N_basins = len(basins)

    def get_atom_basins(atoms, basins):
        # Vectorized deltas, minimum‑image wrapping
        diffs = atoms[None, :, :] - basins[:, None, :]
        diffs += np.where(diffs <= -0.5, 1, 0)
        diffs -= np.where(diffs >= 0.5, 1, 0)

        # Cartesian diffs & distances
        cart = np.einsum("bij,jk->bik", diffs, L)
        dists = np.linalg.norm(cart, axis=2)

        # Basin→atom assignment & distances
        basin_atoms = np.argmin(dists, axis=1)  # (N_basins,)
        basin_atom_dists = dists[np.arange(N_basins), basin_atoms]  # (N_basins,)
        return basin_atoms, basin_atom_dists

    basin_atoms, basin_atom_dists = get_atom_basins(atoms, basins)

    if nna_cutoff:
        # add dummy atoms at basin maxima far from atoms
        for coords, dist in zip(basins, basin_atom_dists):
            if dist > nna_cutoff:
                # add a dummy atom to the structure
                structure.append("X", coords)
        # recalculate distances
        atoms = structure.frac_coords
        basin_atoms, basin_atom_dists = get_atom_basins(atoms, basins)

    # vacuum is represented by an index one above the highest label. we add
    # that to our basin atoms temporarily
    basin_atoms = np.insert(basin_atoms, len(basin_atoms), len(structure))

    # Atom labels per grid point
    atom_labels = basin_atoms[self.maxima_basin_labels]

    # remove vacuum pointer in basin atoms
    basin_atoms = basin_atoms[:-1]

    atom_charges = np.bincount(
        basin_atoms, weights=self.basin_charges, minlength=len(structure)
    )
    atom_volumes = np.bincount(
        basin_atoms, weights=self.basin_volumes, minlength=len(structure)
    )

    return (
        atom_labels,
        atom_charges,
        atom_volumes,
        basin_atoms,
        basin_atom_dists,
    )

get_atom_results_dataframe()

Collects a summary of results for the atoms in a pandas DataFrame.

Returns:

Name Type Description
atoms_df DataFrame

A table summarizing the atomic basins.

Source code in src/baderkit/core/bader/bader.py
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
def get_atom_results_dataframe(self) -> pd.DataFrame:
    """
    Collects a summary of results for the atoms in a pandas DataFrame.

    Returns
    -------
    atoms_df : pd.DataFrame
        A table summarizing the atomic basins.

    """
    # Get atom results summary
    atom_frac_coords = self.structure.frac_coords
    atoms_df = pd.DataFrame(
        {
            "label": self.structure.labels,
            "x": atom_frac_coords[:, 0],
            "y": atom_frac_coords[:, 1],
            "z": atom_frac_coords[:, 2],
            "charge": self.atom_charges,
            "volume": self.atom_volumes,
            "surface_dist": self.atom_min_surface_distances,
        }
    )
    return atoms_df

get_basin_results_dataframe(basin_tol)

Collects a summary of results for the basins in a pandas DataFrame.

Returns:

Name Type Description
basin_df DataFrame

A table summarizing the basins.

basin_tol (float, optional)

The total charge value below which a basin will not be considered significant.

Source code in src/baderkit/core/bader/bader.py
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
def get_basin_results_dataframe(self, basin_tol: float):
    """
    Collects a summary of results for the basins in a pandas DataFrame.

    Returns
    -------
    basin_df : pd.DataFrame
        A table summarizing the basins.
    basin_tol : float, optional
        The total charge value below which a basin will not be considered significant.

    """
    subset = self.basin_charges > basin_tol
    basin_frac_coords = self.maxima_frac[subset]
    basin_df = pd.DataFrame(
        {
            "atoms": np.array(self.structure.labels)[self.basin_atoms[subset]],
            "x": basin_frac_coords[:, 0],
            "y": basin_frac_coords[:, 1],
            "z": basin_frac_coords[:, 2],
            "charge": self.basin_charges[subset],
            "volume": self.basin_volumes[subset],
            "surface_dist": self.basin_min_surface_distances[subset],
            "atom_dist": self.basin_atom_dists[subset],
        }
    )
    return basin_df

get_betti_numbers(return_values=False, return_groups=False)

The approximate betti numbers for an maxima and minima persistence groups. This is obtained by scanning through a persistence group's values from high to low and recording the betti numbers throughout. If a cage (1,0,1) or ring (1,1,0) is found at any point, the extremum is marked with this set. Otherwise, it is returned as a point (1,0,0). While other betti numbers are possible, we believe these are the only reasonable ones that should show up for very flat extrema in the ELF, ELI-D, LOL or other localization functions.

Parameters:

Name Type Description Default
return_values bool

Whether or not to return the values at which the resulting betti numbers exist. The default is False.

False
return_groups bool

Whether or not to return the voxel coordinates that result in the returned betti numbers. The default is False.

False

Returns:

Type Description
tuple

The betti numbers for maxima and minima. If return_values is selected, the values at which the extrema form these betti numbers will be appended. If return_gorups is selected, the voxels making up these betti shapes are appended.

Source code in src/baderkit/core/bader/bader.py
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
def get_betti_numbers(
    self,
    return_values: bool = False,
    return_groups: bool = False,
) -> tuple:
    """
    The approximate betti numbers for an maxima and minima persistence
    groups. This is obtained by scanning through a persistence group's
    values from high to low and recording the betti numbers throughout.
    If a cage (1,0,1) or ring (1,1,0) is found at any point, the extremum
    is marked with this set. Otherwise, it is returned as a point (1,0,0).
    While other betti numbers are possible, we believe these are the
    only reasonable ones that should show up for very flat extrema in the
    ELF, ELI-D, LOL or other localization functions.

    Parameters
    ----------
    return_values : bool, optional
        Whether or not to return the values at which the resulting betti
        numbers exist. The default is False.
    return_groups : bool, optional
        Whether or not to return the voxel coordinates that result in the
        returned betti numbers. The default is False.

    Returns
    -------
    tuple
        The betti numbers for maxima and minima. If return_values
        is selected, the values at which the extrema form these betti numbers
        will be appended. If return_gorups is selected, the voxels making up
        these betti shapes are appended.

    """

    maxima_groups, minima_groups = self.get_persistence_groups()
    base_maxima = self.maxima_vox
    maxima_base_vals = self.reference_grid.total[
        base_maxima[:, 0], base_maxima[:, 1], base_maxima[:, 2]
    ]
    maxima_betti_numbers, maxima_betti_vals = get_all_betti_numbers_scanning(
        maxima_groups,
        maxima_base_vals,
        self.reference_grid.total,
        use_minima=False,
    )

    base_minima = self.minima_vox
    minima_base_vals = self.reference_grid.total[
        base_minima[:, 0], base_minima[:, 1], base_minima[:, 2]
    ]
    minima_betti_numbers, minima_betti_vals = get_all_betti_numbers_scanning(
        minima_groups,
        minima_base_vals,
        self.reference_grid.total,
        use_minima=True,
    )

    results = [maxima_betti_numbers, minima_betti_numbers]

    if return_values:
        results.append(maxima_betti_vals)
        results.append(minima_betti_vals)

    if return_groups:
        maxima_groups = get_persistence_groups(
            labels=self.maxima_basin_labels,
            data=self.reference_grid.total,
            persistence_cutoffs=maxima_betti_vals,
            extrema_vox=self.maxima_vox,
            use_minima=False,
        )

        minima_groups = get_persistence_groups(
            labels=self.minima_basin_labels,
            data=self.reference_grid.total,
            persistence_cutoffs=minima_betti_vals,
            extrema_vox=self.minima_vox,
            use_minima=True,
        )
        results.append(maxima_groups)
        results.append(minima_groups)

    return tuple(results)

get_persistence_groups()

Gets the groups of voxels for each maximum and minimum that are within the extrema's basin and above/below the persistence value for that basin. The persistence value is defined as the value at which all voxelated maxima/minima (see ongrid_maxima_groups/ongrid_minima_groups) are connected

Returns:

Name Type Description
maxima_groups list[NDArray[int64]]

A list of Nx3 arrays where each array represents the grid indices of voxels that are within each maximas persistence threshold.

minima_groups list[NDArray[int64]]

A list of Nx3 arrays where each array represents the grid indices of voxels that are within each minimas persistence threshold.

Source code in src/baderkit/core/bader/bader.py
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
def get_persistence_groups(self):
    """
    Gets the groups of voxels for each maximum and minimum that are within
    the extrema's basin and above/below the persistence value for that basin.
    The persistence value is defined as the value at which all voxelated
    maxima/minima (see ongrid_maxima_groups/ongrid_minima_groups) are connected

    Returns
    -------
    maxima_groups : list[NDArray[int64]]
        A list of Nx3 arrays where each array represents the grid indices of voxels
        that are within each maximas persistence threshold.
    minima_groups : list[NDArray[int64]]
        A list of Nx3 arrays where each array represents the grid indices of voxels
        that are within each minimas persistence threshold.

    """

    maxima_groups = get_persistence_groups(
        labels=self.maxima_basin_labels,
        data=self.reference_grid.total,
        persistence_cutoffs=self.maxima_persistence_values,
        extrema_vox=self.maxima_vox,
        use_minima=False,
    )

    minima_groups = get_persistence_groups(
        labels=self.minima_basin_labels,
        data=self.reference_grid.total,
        persistence_cutoffs=self.minima_persistence_values,
        extrema_vox=self.minima_vox,
        use_minima=True,
    )

    return maxima_groups, minima_groups

run_atom_assignment()

Assigns bader basins to this Bader objects structure.

Source code in src/baderkit/core/bader/bader.py
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
def run_atom_assignment(self):
    """
    Assigns bader basins to this Bader objects structure.

    """
    # ensure bader has run (otherwise our time will include the bader time)
    self.maxima_frac

    # Default structure
    structure = self.structure

    t0 = time.time()
    logging.info("Assigning Atom Properties")
    # get basin assignments for this bader objects structure
    (
        atom_labels,
        atom_charges,
        atom_volumes,
        basin_atoms,
        basin_atom_dists,
    ) = self.assign_basins_to_structure(structure, self.nna_cutoff)

    # Store everything
    self._basin_atoms = basin_atoms
    self._basin_atom_dists = basin_atom_dists
    self._atom_labels = atom_labels
    self._atom_charges = atom_charges
    self._atom_volumes = atom_volumes
    logging.info("Atom Assignment Finished")
    t1 = time.time()
    logging.info(f"Time: {round(t1-t0, 2)}")

to_dict(include_minima=False)

Converts the Bader object to a dictionary.

Returns:

Type Description
dict

A dictionary representation of the Bader object.

Source code in src/baderkit/core/bader/bader.py
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
def to_dict(self, include_minima: bool = False) -> dict:
    """
    Converts the Bader object to a dictionary.

    Returns
    -------
    dict
        A dictionary representation of the Bader object.

    """
    results = super().to_dict()
    if include_minima:
        results["minima_results"] = self._to_dict(self._minima_results)
        results["saddle_results"] = self._to_dict(self._saddle_results)
    return results

write_all_atom_volumes(**kwargs)

Writes all atomic basins to vasp-like files. Points belonging to the atom will have values from the charge or reference grid, and all other points will be 0.

Source code in src/baderkit/core/bader/bader.py
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
def write_all_atom_volumes(
    self,
    **kwargs,
):
    """
    Writes all atomic basins to vasp-like files. Points belonging to the atom
    will have values from the charge or reference grid, and all other points
    will be 0.

    """
    atom_indices = np.array(range(len(self.structure)))
    self.write_atom_volumes(
        atom_indices=atom_indices,
        **kwargs,
    )

write_all_basin_volumes(basin_tol=0.001, **kwargs)

Writes all bader basins to vasp-like files. Points belonging to the basin will have values from the charge or reference grid, and all other points will be 0.

Parameters:

Name Type Description Default
basin_tol float

The total charge value below which a basin will not be considered written

0.001
Source code in src/baderkit/core/bader/bader.py
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
def write_all_basin_volumes(
    self,
    basin_tol: float = 1e-03,
    **kwargs,
):
    """
    Writes all bader basins to vasp-like files. Points belonging to the basin
    will have values from the charge or reference grid, and all other points
    will be 0.

    Parameters
    ----------
    basin_tol : float, optional
        The total charge value below which a basin will not be considered written

    """
    basin_indices = np.where(self.basin_charges > basin_tol)[0]
    self.write_basin_volumes(
        basin_indices=basin_indices,
        **kwargs,
    )

write_atom_tsv(filepath='bader_atoms.tsv')

Writes a summary of atom results to .tsv files.

Parameters:

Name Type Description Default
filepath str | Path

The Path to write the results to. The default is "bader_atoms.tsv".

'bader_atoms.tsv'
Source code in src/baderkit/core/bader/bader.py
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
def write_atom_tsv(self, filepath: Path | str = "bader_atoms.tsv"):
    """
    Writes a summary of atom results to .tsv files.

    Parameters
    ----------
    filepath : str | Path
        The Path to write the results to. The default is "bader_atoms.tsv".


    """
    filepath = Path(filepath)

    # Get atom results summary
    atoms_df = self.get_atom_results_dataframe()
    formatted_atoms_df = atoms_df.copy()
    numeric_cols = formatted_atoms_df.select_dtypes(include="number").columns
    formatted_atoms_df[numeric_cols] = formatted_atoms_df[numeric_cols].map(
        lambda x: f"{x:.5f}"
    )

    # Determine max width per column including header
    col_widths = {
        col: max(len(col), formatted_atoms_df[col].map(len).max())
        for col in atoms_df.columns
    }

    # Note what we're writing in log
    logging.info(f"Writing Atom Summary to {filepath}")

    # write output summaries
    with open(filepath, "w") as f:
        # Write header
        header = "\t".join(
            f"{col:<{col_widths[col]}}" for col in formatted_atoms_df.columns
        )
        f.write(header + "\n")

        # Write rows
        for _, row in formatted_atoms_df.iterrows():
            line = "\t".join(
                f"{val:<{col_widths[col]}}" for col, val in row.items()
            )
            f.write(line + "\n")
        # write vacuum summary to atom file
        f.write("\n")
        f.write(f"Vacuum Charge:\t\t{self.vacuum_charge:.5f}\n")
        f.write(f"Vacuum Volume:\t\t{self.vacuum_volume:.5f}\n")
        f.write(f"Total Electrons:\t{self.total_electron_number:.5f}\n")
        f.write(f"Total Volume:\t{self.total_volume:.5f}\n")

write_atom_volumes(atom_indices, **kwargs)

Writes atomic basins to vasp-like files. Points belonging to the atom will have values from the charge or reference grid, and all other points will be 0.

Parameters:

Name Type Description Default
atom_indices NDArray

The list of atom indices to write

required
Source code in src/baderkit/core/bader/bader.py
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
def write_atom_volumes(
    self,
    atom_indices: NDArray,
    **kwargs,
):
    """
    Writes atomic basins to vasp-like files. Points belonging to the atom
    will have values from the charge or reference grid, and all other points
    will be 0.

    Parameters
    ----------
    atom_indices : NDArray
        The list of atom indices to write

    """

    for atom_index in atom_indices:
        # get a mask at the requested atoms
        mask = self.atom_labels == atom_index
        kwargs["suffix"] = f"_a{atom_index}"
        self._write_volume(volume_mask=mask, **kwargs)

write_atom_volumes_sum(atom_indices, **kwargs)

Writes the union of the provided atom basins to vasp-like files. Points belonging to the atoms will have values from the charge or reference grid, and all other points will be 0.

Parameters:

Name Type Description Default
atom_indices NDArray

The list of atom indices to sum and write

required
Source code in src/baderkit/core/bader/bader.py
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
def write_atom_volumes_sum(
    self,
    atom_indices: NDArray,
    **kwargs,
):
    """
    Writes the union of the provided atom basins to vasp-like files.
    Points belonging to the atoms will have values from the charge or
    reference grid, and all other points will be 0.

    Parameters
    ----------
    atom_indices : NDArray
        The list of atom indices to sum and write

    """

    mask = np.isin(self.atom_labels, atom_indices)
    # write
    kwargs["suffix"] = "_asum"
    self._write_volume(volume_mask=mask, **kwargs)

write_basin_tsv(filepath='bader_basins.tsv')

Writes a summary of basin results to .tsv files.

Parameters:

Name Type Description Default
filepath str | Path

The Path to write the results to. The default is "bader_basins.tsv".

'bader_basins.tsv'
Source code in src/baderkit/core/bader/bader.py
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
def write_basin_tsv(self, filepath: Path | str = "bader_basins.tsv"):
    """
    Writes a summary of basin results to .tsv files.

    Parameters
    ----------
    filepath : str | Path
        The Path to write the results to. The default is "bader_basins.tsv".

    """
    filepath = Path(filepath)

    # Get basin results summary
    basin_df = self.get_basin_results_dataframe(0.01)
    formatted_basin_df = basin_df.copy()
    numeric_cols = formatted_basin_df.select_dtypes(include="number").columns
    formatted_basin_df[numeric_cols] = formatted_basin_df[numeric_cols].map(
        lambda x: f"{x:.5f}"
    )

    # Determine max width per column including header
    col_widths = {
        col: max(len(col), formatted_basin_df[col].map(len).max())
        for col in basin_df.columns
    }

    # Write to file with aligned columns using tab as separator

    # Note what we're writing in log

    logging.info(f"Writing Basin Summary to {filepath}")

    # write output summaries
    with open(filepath, "w") as f:
        # Write header
        header = "\t".join(f"{col:<{col_widths[col]}}" for col in basin_df.columns)
        f.write(header + "\n")

        # Write rows
        for _, row in formatted_basin_df.iterrows():
            line = "\t".join(
                f"{val:<{col_widths[col]}}" for col, val in row.items()
            )
            f.write(line + "\n")

write_basin_volumes(basin_indices, **kwargs)

Writes bader basins to vasp-like files. Points belonging to the basin will have values from the charge or reference grid, and all other points will be 0.

Parameters:

Name Type Description Default
basin_indices NDArray

The list of basin indices to write

required
Source code in src/baderkit/core/bader/bader.py
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
def write_basin_volumes(
    self,
    basin_indices: NDArray[int],
    **kwargs,
):
    """
    Writes bader basins to vasp-like files. Points belonging to the basin
    will have values from the charge or reference grid, and all other points
    will be 0.

    Parameters
    ----------
    basin_indices : NDArray
        The list of basin indices to write

    """
    for basin in basin_indices:
        # get a mask everywhere but the requested basin
        mask = self.maxima_basin_labels == basin
        kwargs["suffix"] = f"_b{basin}"

        self._write_volume(volume_mask=mask, **kwargs)

write_basin_volumes_sum(basin_indices, **kwargs)

Writes the union of the provided bader basins to vasp-like files. Points belonging to the basins will have values from the charge or reference grid, and all other points will be 0.

Parameters:

Name Type Description Default
basin_indices NDArray

The list of basin indices to sum and write

required
Source code in src/baderkit/core/bader/bader.py
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
def write_basin_volumes_sum(
    self,
    basin_indices: NDArray[int],
    **kwargs,
):
    """
    Writes the union of the provided bader basins to vasp-like files.
    Points belonging to the basins will have values from the charge or
    reference grid, and all other points will be 0.

    Parameters
    ----------
    basin_indices : NDArray
        The list of basin indices to sum and write

    """
    # create a mask including each of the requested basins
    mask = np.isin(self.maxima_basin_labels, basin_indices)
    # write
    kwargs["suffix"] = "_bsum"
    self._write_volume(volume_mask=mask, **kwargs)

write_species_volume(species, **kwargs)

Writes the charge density or reference file for all atoms of the given species to a single file.

Parameters:

Name Type Description Default
species str

The species to write.

required
Source code in src/baderkit/core/bader/bader.py
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
def write_species_volume(
    self,
    species: str,
    **kwargs,
):
    """
    Writes the charge density or reference file for all atoms of the given
    species to a single file.

    Parameters
    ----------
    species : str, optional
        The species to write.

    """

    # add dummy atoms if desired
    indices = self.structure.indices_from_symbol(species)

    # Get mask where the grid belongs to requested species
    mask = np.isin(self.atom_labels, indices)
    kwargs["suffix"] = f"_{species}"
    self._write_volume(volume_mask=mask, **kwargs)