Skip to content

Bader

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

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

required
reference_grid Grid | None

A grid object whose values will be used to construct the basins. If None, defaults to the charge_grid.

None
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 will be used on True.

0.001
normalize_vacuum bool | None

Whether or not the reference data needs to be converted to real space units for vacuum tolerance comparison. This should be True for charge densities and False for the ELF. If None, the setting will be guessed from the reference grid's data type.

None
basin_tol float

The value below which a basin will not be considered significant. This is used only used to avoid writing out data that is likely not valuable.

0.001
Source code in src/baderkit/core/bader.py
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 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
class Bader:
    """
    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
        A Grid object with the charge density that will be integrated.
    reference_grid : Grid | None
        A grid object whose values will be used to construct the basins. If
        None, defaults to the charge_grid.
    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 will be used on True.
    normalize_vacuum: bool, optional
        Whether or not the reference data needs to be converted to real space
        units for vacuum tolerance comparison. This should be True for charge
        densities and False for the ELF. If None, the setting will be guessed
        from the reference grid's data type.
    basin_tol: float, optional
        The value below which a basin will not be considered significant. This
        is used only used to avoid writing out data that is likely not valuable.

    """

    def __init__(
        self,
        charge_grid: Grid,
        reference_grid: Grid | None = None,
        method: str | Method = Method.weight,
        vacuum_tol: float | bool = 1.0e-3,
        normalize_vacuum: bool | None = None,
        basin_tol: float = 1.0e-3,
    ):

        # ensure th method is valid
        if method not in {m.value for m in Method}:
            raise ValueError(
                f"Invalid method '{method}'. Available options are: {[i.value for i in Method]}"
            )

        self._charge_grid = charge_grid

        # if no reference is provided, use the base charge grid
        if reference_grid is None:
            reference_grid = charge_grid.copy()
        self._reference_grid = reference_grid

        # guess whether the reference should be scaled for vacuum tolerance comparison
        if normalize_vacuum is None:
            if reference_grid.data_type == "elf":
                normalize_vacuum = False
            else:
                normalize_vacuum = True

        self._method = method

        # if vacuum tolerance is True, set it to the same default as above
        if vacuum_tol is True:
            self._vacuum_tol = 1.0e-3
        else:
            self._vacuum_tol = vacuum_tol
        self._normalize_vacuum = normalize_vacuum
        self._basin_tol = basin_tol

        # set hidden class variables. This allows us to cache properties and
        # still be able to recalculate them if needed, though that should only
        # be done by advanced users
        self._reset_properties()
        self._use_overdetermined = False

    ###########################################################################
    # Set Properties
    ###########################################################################
    def _reset_properties(
        self,
        include_properties: list[str] = None,
        exclude_properties: list[str] = [],
    ):
        # if include properties is not provided, we wnat to reset everything
        if include_properties is None:
            include_properties = [
                # assigned by run_bader
                "basin_labels",
                "basin_maxima_frac",
                "basin_maxima_values",
                "basin_maxima_vox",
                "basin_charges",
                "basin_volumes",
                "vacuum_charge",
                "vacuum_volume",
                "significant_basins",
                "vacuum_mask",
                "num_vacuum",
                # Assigned by calling the property
                "basin_surface_distances",
                "basin_edges",
                "atom_edges",
                "structure",
                # Assigned by run_atom_assignment
                "basin_atoms",
                "basin_atom_dists",
                "atom_labels",
                "atom_charges",
                "atom_volumes",
                "atom_surface_distances",
                "total_electron_number",
            ]
        # get our final list of properties
        reset_properties = [
            i for i in include_properties if i not in exclude_properties
        ]
        # set corresponding hidden variable to None
        for prop in reset_properties:
            setattr(self, f"_{prop}", None)

    @property
    def charge_grid(self) -> Grid:
        """

        Returns
        -------
        Grid
            A Grid object with the charge density that will be integrated.

        """
        return self._charge_grid

    @charge_grid.setter
    def charge_grid(self, value: Grid):
        self._charge_grid = value
        self._reset_properties()

    @property
    def reference_grid(self) -> Grid:
        """

        Returns
        -------
        Grid
            A grid object whose values will be used to construct the basins.

        """
        return self._reference_grid

    @reference_grid.setter
    def reference_grid(self, value: Grid):
        self._reference_grid = value
        self._reset_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):
        assert (
            value in Method
        ), f"Invalid method '{value}'. Available options are: {[i.value for i in Method]}"
        self._method = value
        self._reset_properties(exclude_properties=["vacuum_mask", "num_vacuum"])

    @property
    def vacuum_tol(self) -> float | bool:
        """

        Returns
        -------
        float
            The value below which a point will be considered part of the vacuum.
            The default is 0.001.

        """
        return self._vacuum_tol

    @vacuum_tol.setter
    def vacuum_tol(self, value: float | bool):
        self._vacuum_tol = value
        self._reset_properties()
        # TODO: only reset everything if the vacuum actually changes

    @property
    def normalize_vacuum(self) -> bool:
        """

        Returns
        -------
        bool
            Whether or not the reference data needs to be converted to real space
            units for vacuum tolerance comparison. This should be set to True if
            the data follows VASP's CHGCAR standards, but False if the data should
            be compared as is (e.g. in ELFCARs)

        """
        return self._normalize_vacuum

    @normalize_vacuum.setter
    def normalize_vacuum(self, value: bool) -> bool:
        self._normalize_vacuum = value
        self._reset_properties()
        # TODO: only reset everything if the vacuum actually changes

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

        Returns
        -------
        float
            The value below which a basin will not be considered significant. This
            is used to avoid writing out data that is likely not valuable.
            The default is 0.001.

        """
        return self._basin_tol

    @basin_tol.setter
    def basin_tol(self, value: float):
        self._basin_tol = value
        self._reset_properties(include_properties=["significant_basins"])

    ###########################################################################
    # Calculated Properties
    ###########################################################################

    @property
    def 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. Note that for some
            methods (e.g. weight) the voxels have weights for each basin.
            These will be stored in the basin_weights property.

        """
        if self._basin_labels is None:
            self.run_bader()
        return self._basin_labels

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

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

        """
        if self._basin_maxima_frac is None:
            self.run_bader()
        return self._basin_maxima_frac

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

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

        """
        if self._basin_maxima_values is None:
            self.run_bader()
        return self._basin_maxima_values

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

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

        """

        # get the voxel coordinates for reduced maxima
        voxel_coords = np.round(
            self.charge_grid.frac_to_grid(self.basin_maxima_frac)
        ).astype(int)
        return self.charge_grid.total[
            voxel_coords[:, 0], voxel_coords[:, 1], voxel_coords[:, 2]
        ]

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

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

        """

        # get the voxel coordinates for reduced maxima
        voxel_coords = np.round(
            self.reference_grid.frac_to_grid(self.basin_maxima_frac)
        ).astype(int)
        return self.reference_grid.total[
            voxel_coords[:, 0], voxel_coords[:, 1], voxel_coords[:, 2]
        ]

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

        Returns
        -------
        NDArray[int]
            The voxel coordinates of each attractor. There may be more of these
            than the fractional coordinates, as some maxima sit exactly between
            several voxels.

        """
        if self._basin_maxima_vox is None:
            self.run_bader()
        return self._basin_maxima_vox

    @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

    @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

    @property
    def basin_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_surface_distances is None:
            self._basin_surface_distances = self._get_basin_surface_distances()
        return self._basin_surface_distances

    @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

    @property
    def significant_basins(self) -> NDArray[bool]:
        """

        Returns
        -------
        NDArray[bool]
            A 1D mask with an entry for each basin that is True where basins
            are significant.

        """
        if self._significant_basins is None:
            self._significant_basins = self.basin_charges > self.basin_tol
        return self._significant_basins

    @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

    @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

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

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

        """
        if self._atom_surface_distances is None:
            self._atom_surface_distances = self._get_atom_surface_distances()
        return self._atom_surface_distances

    @property
    def structure(self) -> Structure:
        """

        Returns
        -------
        Structure
            The pymatgen structure basins are assigned to.

        """
        if self._structure is None:
            self._structure = self.reference_grid.structure.copy()
            self._structure.relabel_sites(ignore_uniq=True)
        return self._structure

    @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(
                labeled_array=self.basin_labels,
                vacuum_mask=np.zeros(self.basin_labels.shape, dtype=np.bool_),
                neighbor_transforms=self.reference_grid.point_neighbor_transforms[0],
            )
        return self._basin_edges

    @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(
                labeled_array=self.atom_labels,
                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 vacuum_charge(self) -> float:
        """

        Returns
        -------
        float
            The charge assigned to the vacuum.

        """
        if self._vacuum_charge is None:
            self.run_bader()
        return self._vacuum_charge

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

        Returns
        -------
        float
            The total volume assigned to the vacuum.

        """
        if self._vacuum_volume is None:
            self.run_bader()
        return self._vacuum_volume

    @property
    def vacuum_mask(self) -> NDArray[bool]:
        """

        Returns
        -------
        NDArray[bool]
            A mask representing the voxels that belong to the vacuum.

        """
        if self._vacuum_mask is None:
            # if vacuum tolerance is set to False, ignore vacuum
            if self.vacuum_tol is False:
                self._vacuum_mask = np.zeros_like(
                    self.reference_grid.total, dtype=np.bool_
                )
            else:
                if self.normalize_vacuum:
                    self._vacuum_mask = self.reference_grid.total < (
                        self.vacuum_tol * self.structure.volume
                    )
                else:
                    self._vacuum_mask = self.reference_grid.total < self.vacuum_tol
        return self._vacuum_mask

    @property
    def num_vacuum(self) -> int:
        """

        Returns
        -------
        int
            The number of vacuum points in the array

        """
        if self._num_vacuum is None:
            self._num_vacuum = np.count_nonzero(self.vacuum_mask)
        return self._num_vacuum

    @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 self.atom_charges.sum() + self.vacuum_charge

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

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

        """

        return [i.value for i in Method]

    @property
    def results_summary(self) -> dict:
        """

        Returns
        -------
        results_dict : dict
            A dictionary summary of all results

        """
        results_dict = {
            "method": self.method,
            "basin_maxima_frac": self.basin_maxima_frac,
            "basin_maxima_vox": self.basin_maxima_vox,
            "basin_charges": self.basin_charges,
            "basin_volumes": self.basin_volumes,
            "basin_surface_distances": self.basin_surface_distances,
            "basin_atoms": self.basin_atoms,
            "basin_atom_dists": self.basin_atom_dists,
            "atom_charges": self.atom_charges,
            "atom_volumes": self.atom_volumes,
            "atom_surface_distances": self.atom_surface_distances,
            "structure": self.structure,
            "vacuum_charge": self.vacuum_charge,
            "vacuum_volume": self.vacuum_volume,
            "significant_basins": self.significant_basins,
            "total_electron_num": self.total_electron_number,
        }
        return results_dict

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

        Returns
        -------
        None

        """
        t0 = time.time()
        logging.info(f"Beginning Bader Algorithm Using '{self.method}' 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.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,
        )
        if self._use_overdetermined:
            method._use_overdetermined = True
        results = method.run()

        for key, value in results.items():
            setattr(self, f"_{key}", value)
        t1 = time.time()
        logging.info("Bader Algorithm Complete")
        logging.info(f"Time: {round(t1-t0,2)}")

    def run_atom_assignment(self, structure: Structure = None):
        """
        Assigns bader basins to the atoms in the provided structure.

        Parameters
        ----------
        structure : Structure, optional
            If provided, basins will be assigned to the atoms in this structure.
            The default is None.

        Returns
        -------
        None.

        """
        # Default structure
        structure = structure or self.structure
        self._structure = structure

        # Shorthand access
        basins = self.basin_maxima_frac  # (N_basins, 3)
        t0 = time.time()
        logging.info("Assigning Atom Properties")
        atoms = structure.frac_coords  # (N_atoms, 3)
        L = structure.lattice.matrix  # (3, 3)
        N_basins, N_atoms = len(basins), len(atoms)

        # 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,)

        # Atom labels per grid point
        # NOTE: append -1 so that vacuum gets assigned to -1 in the atom_labels
        # array
        basin_atoms = np.insert(basin_atoms, len(basin_atoms), -1)
        atom_labels = basin_atoms[self.basin_labels]

        # Sum up charges/volumes per atom in one shot. slice with -1 is necessary
        # to prevent no negative value error
        try:
            atom_charges = np.bincount(
                basin_atoms[:-1], weights=self.basin_charges, minlength=N_atoms
            )
            atom_volumes = np.bincount(
                basin_atoms[:-1], weights=self.basin_volumes, minlength=N_atoms
            )
        except:
            breakpoint()
        # Store everything
        self._basin_atoms = basin_atoms[:-1]
        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_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.

    #     Returns
    #     -------
    #     None.

    #     """
    #     atom_labeled_voxels = self.atom_labels
    #     atom_radii = []
    #     # NOTE: We don't use the atom_edges property because its usually not
    #     # needed by users and takes up more space in memory
    #     edge_mask = self.atom_edges
    #     for atom_index in track(
    #         range(len(self.structure)), description="Calculating atom radii"
    #     ):
    #         # get the voxels corresponding to the interior edge of this basin
    #         atom_edge_mask = (atom_labeled_voxels == atom_index) & edge_mask
    #         edge_vox_coords = np.argwhere(atom_edge_mask)
    #         # convert to frac coords
    #         edge_frac_coords = self.reference_grid.grid_to_frac(edge_vox_coords)
    #         atom_frac_coord = self.structure.frac_coords[atom_index]
    #         # Get the difference in coords between atom and edges
    #         coord_diff = atom_frac_coord - edge_frac_coords
    #         # Wrap any coords that are more than 0.5 or less than -0.5
    #         coord_diff -= np.round(coord_diff)
    #         # Convert to cartesian coordinates
    #         cart_coords = self.reference_grid.frac_to_cart(coord_diff)
    #         # Calculate distance of each
    #         norm = np.linalg.norm(cart_coords, axis=1)
    #         if len(norm) == 0:
    #             logging.warning(f"No volume assigned to atom at site {atom_index}.")
    #             atom_radii.append(0)
    #         else:
    #             atom_radii.append(norm.min())
    #     atom_radii = np.array(atom_radii)
    #     self._atom_surface_distances = atom_radii

    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.

        Returns
        -------
        None.

        """
        return get_min_dists(
            labels=self.atom_labels,
            frac_coords=self.structure.frac_coords,
            edge_indices=np.argwhere(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.

        Returns
        -------
        None.

        """
        # get the minimum distances
        return get_min_dists(
            labels=self.basin_labels,
            frac_coords=self.basin_maxima_frac,
            edge_indices=np.argwhere(self.basin_edges),
            matrix=self.reference_grid.matrix,
            max_value=np.max(self.structure.lattice.abc) * 2,
        )

    @classmethod
    def from_vasp(
        cls,
        charge_filename: Path | str = "CHGCAR",
        reference_filename: Path | None | str = None,
        total_only: bool = True,
        **kwargs,
    ) -> Self:
        """
        Creates a Bader class object from VASP files.

        Parameters
        ----------
        charge_filename : Path | str, optional
            The path to the CHGCAR like file that will be used for summing charge.
            The default is "CHGCAR".
        reference_filename : Path | None | str, optional
            The path to CHGCAR like file that will be used for partitioning.
            If None, the charge file will be used for partitioning.
        total_only: bool
            If true, only the first set of data in the file will be read. This
            increases speed and reduced memory usage as the other data is typically
            not used.
            Defaults to True.
        **kwargs : dict
            Keyword arguments to pass to the Bader class.

        Returns
        -------
        Self
            A Bader class object.

        """
        charge_grid = Grid.from_vasp(charge_filename, total_only=total_only)
        if reference_filename is None:
            reference_grid = None
        else:
            reference_grid = Grid.from_vasp(reference_filename, total_only=total_only)

        return cls(charge_grid=charge_grid, reference_grid=reference_grid, **kwargs)

    @classmethod
    def from_cube(
        cls,
        charge_filename: Path | str,
        reference_filename: Path | None | str = None,
        **kwargs,
    ) -> Self:
        """
        Creates a Bader class object from .cube files.

        Parameters
        ----------
        charge_filename : Path | str, optional
            The path to the .cube file that will be used for summing charge.
        reference_filename : Path | None | str, optional
            The path to .cube file that will be used for partitioning.
            If None, the charge file will be used for partitioning.
        **kwargs : dict
            Keyword arguments to pass to the Bader class.

        Returns
        -------
        Self
            A Bader class object.

        """
        charge_grid = Grid.from_cube(charge_filename)
        if reference_filename is None:
            reference_grid = None
        else:
            reference_grid = Grid.from_cube(reference_filename)
        return cls(charge_grid=charge_grid, reference_grid=reference_grid, **kwargs)

    @classmethod
    def from_dynamic(
        cls,
        charge_filename: Path | str,
        reference_filename: Path | None | str = None,
        format: Literal["vasp", "cube", None] = None,
        total_only: bool = True,
        **kwargs,
    ) -> Self:
        """
        Creates a Bader class object from VASP or .cube files. If no format is
        provided the method will automatically try and determine the file type
        from the name

        Parameters
        ----------
        charge_filename : Path | str
            The path to the file containing the charge density that will be
            integrated.
        reference_filename : Path | None | str, optional
            The path to the file that will be used for partitioning.
            If None, the charge file will be used for partitioning.
        format : Literal["vasp", "cube", None], optional
            The format of the grids to read in. If None, the formats will be
            guessed from the file names.
        total_only: bool
            If true, only the first set of data in the file will be read. This
            increases speed and reduced memory usage as the other data is typically
            not used. This is only used if the file format is determined to be
            VASP, as cube files are assumed to contain only one set of data.
            Defaults to True.
        **kwargs : dict
            Keyword arguments to pass to the Bader class.

        Returns
        -------
        Self
            A Bader class object.

        """

        charge_grid = Grid.from_dynamic(
            charge_filename, format=format, total_only=total_only
        )
        if reference_filename is None:
            reference_grid = None
        else:
            reference_grid = Grid.from_dynamic(
                reference_filename, format=format, total_only=total_only
            )
        return cls(charge_grid=charge_grid, reference_grid=reference_grid, **kwargs)

    def copy(self) -> Self:
        """

        Returns
        -------
        Self
            A deep copy of this Bader object.

        """
        return copy.deepcopy(self)

    def write_basin_volumes(
        self,
        basin_indices: NDArray,
        directory: str | Path = None,
        write_reference: bool = False,
        output_format: str | Format = None,
        **writer_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
        directory : str | Path
            The directory to write the files in. If None, the active directory
            is used.
        write_reference : bool, optional
            Whether or not to write the reference data rather than the charge data.
            Default is False.
        output_format : str | Format, optional
            The format to write with. If None, writes to source format stored in
            the Grid objects metadata.
            Defaults to None.

        Returns
        -------
        None.

        """
        # get the data to use
        if write_reference:
            data_array = self.reference_grid.total
        else:
            data_array = self.charge_grid.total

        if directory is None:
            directory = Path(".")
        for basin in basin_indices:
            # get a mask everywhere but the requested basin
            mask = self.basin_labels != basin
            # copy data to avoid overwriting. Set data off of basin to 0
            data_array_copy = data_array.copy()
            data_array_copy[mask] = 0.0
            grid = Grid(structure=self.structure, data={"total": data_array_copy})
            file_path = directory / f"{grid.data_type.prefix}_b{basin}"
            # write file
            grid.write(filename=file_path, output_format=output_format, **writer_kwargs)

    def write_all_basin_volumes(
        self,
        directory: str | Path = None,
        write_reference: bool = False,
        output_format: str | Format = None,
        **writer_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
        ----------
        directory : str | Path
            The directory to write the files in. If None, the active directory
            is used.
        write_reference : bool, optional
            Whether or not to write the reference data rather than the charge data.
            Default is False.
        output_format : str | Format, optional
            The format to write with. If None, writes to source format stored in
            the Grid objects metadata.
            Defaults to None.

        Returns
        -------
        None.

        """
        basin_indices = np.where(self.significant_basins)[0]
        self.write_basin_volumes(
            basin_indices=basin_indices,
            directory=directory,
            write_reference=write_reference,
            output_format=output_format,
            **writer_kwargs,
        )

    def write_basin_volumes_sum(
        self,
        basin_indices: NDArray,
        directory: str | Path = None,
        write_reference: bool = False,
        output_format: str | Format = None,
        **writer_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
        directory : str | Path
            The directory to write the files in. If None, the active directory
            is used.
        write_reference : bool, optional
            Whether or not to write the reference data rather than the charge data.
            Default is False.
        output_format : str | Format, optional
            The format to write with. If None, writes to source format stored in
            the Grid objects metadata.
            Defaults to None.

        Returns
        -------
        None.

        """
        # get the data to use
        if write_reference:
            data_array = self.reference_grid.total
        else:
            data_array = self.charge_grid.total

        if directory is None:
            directory = Path(".")
        # create a mask including each of the requested basins
        mask = np.isin(self.basin_labels, basin_indices)
        # copy data to avoid overwriting. Set data off of basin to 0
        data_array_copy = data_array.copy()
        data_array_copy[~mask] = 0.0
        grid = Grid(structure=self.structure, data={"total": data_array_copy})
        file_path = directory / f"{grid.data_type.prefix}_bsum"
        # write file
        grid.write(filename=file_path, output_format=output_format, **writer_kwargs)

    def write_atom_volumes(
        self,
        atom_indices: NDArray,
        directory: str | Path = None,
        write_reference: bool = False,
        output_format: str | Format = None,
        **writer_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
        directory : str | Path
            The directory to write the files in. If None, the active directory
            is used.
        write_reference : bool, optional
            Whether or not to write the reference data rather than the charge data.
            Default is False.
        output_format : str | Format, optional
            The format to write with. If None, writes to source format stored in
            the Grid objects metadata.
            Defaults to None.

        Returns
        -------
        None.

        """
        # get the data to use
        if write_reference:
            data_array = self.reference_grid.total
        else:
            data_array = self.charge_grid.total

        if directory is None:
            directory = Path(".")
        for atom_index in atom_indices:
            # get a mask everywhere but the requested basin
            mask = self.atom_labels != atom_index
            # copy data to avoid overwriting. Set data off of basin to 0
            data_array_copy = data_array.copy()
            data_array_copy[mask] = 0.0
            grid = Grid(structure=self.structure, data={"total": data_array_copy})
            file_path = directory / f"{grid.data_type.prefix}_a{atom_index}"
            # write file
            grid.write(filename=file_path, output_format=output_format, **writer_kwargs)

    def write_all_atom_volumes(
        self,
        directory: str | Path = None,
        write_reference: bool = False,
        output_format: str | Format = None,
        **writer_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.

        Parameters
        ----------
        directory : str | Path
            The directory to write the files in. If None, the active directory
            is used.
        directory : str | Path
            The directory to write the files in. If None, the active directory
            is used.
        write_reference : bool, optional
            Whether or not to write the reference data rather than the charge data.
            Default is False.
        output_format : str | Format, optional
            The format to write with. If None, writes to source format stored in
            the Grid objects metadata.
            Defaults to None.

        Returns
        -------
        None.

        """
        atom_indices = np.array(range(len(self.structure)))
        self.write_atom_volumes(
            atom_indices=atom_indices,
            directory=directory,
            write_reference=write_reference,
            output_format=output_format,
            **writer_kwargs,
        )

    def write_atom_volumes_sum(
        self,
        atom_indices: NDArray,
        directory: str | Path = None,
        write_reference: bool = False,
        output_format: str | Format = None,
        **writer_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
        directory : str | Path
            The directory to write the files in. If None, the active directory
            is used.
        write_reference : bool, optional
            Whether or not to write the reference data rather than the charge data.
            Default is False.
        output_format : str | Format, optional
            The format to write with. If None, writes to source format stored in
            the Grid objects metadata.
            Defaults to None.

        Returns
        -------
        None.

        """
        # get the data to use
        if write_reference:
            data_array = self.reference_grid.total
        else:
            data_array = self.charge_grid.total

        if directory is None:
            directory = Path(".")
        mask = np.isin(self.atom_labels, atom_indices)
        data_array_copy = data_array.copy()
        data_array_copy[~mask] = 0.0
        grid = Grid(structure=self.structure, data={"total": data_array_copy})
        file_path = directory / f"{grid.data_type.prefix}_asum"
        # write file
        grid.write(filename=file_path, output_format=output_format, **writer_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_surface_distances,
            }
        )
        return atoms_df

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

        Returns
        -------
        basin_df : pd.DataFrame
            A table summarizing the basins.

        """
        subset = self.significant_basins
        basin_frac_coords = self.basin_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_surface_distances[subset],
                "atom_dist": self.basin_atom_dists[subset],
            }
        )
        return basin_df

    def write_results_summary(
        self,
        directory: Path | str | None = None,
    ):
        """
        Writes a summary of atom and basin results to .tsv files.

        Parameters
        ----------
        directory : str | Path
            The directory to write the files in. If None, the active directory
            is used.

        Returns
        -------
        None.

        """
        if directory is None:
            directory = Path(".")

        # 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}"
        )

        # Get basin results summary
        basin_df = self.get_basin_results_dataframe()
        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
        atom_col_widths = {
            col: max(len(col), formatted_atoms_df[col].map(len).max())
            for col in atoms_df.columns
        }
        basin_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
        for df, col_widths, name in zip(
            [formatted_atoms_df, formatted_basin_df],
            [atom_col_widths, basin_col_widths],
            ["bader_atom_summary.tsv", "bader_basin_summary.tsv"],
        ):
            # Note what we're writing in log
            if "atom" in name:
                logging.info(f"Writing Atom Summary to {name}")
            else:
                logging.info(f"Writing Basin Summary to {name}")

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

                # Write rows
                for _, row in 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
                if name == "bader_atom_summary.tsv":
                    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")

atom_charges property

Returns:

Type Description
NDArray[float]

The charge assigned to each 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_surface_distances property

Returns:

Type Description
NDArray[float]

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

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_charges property

Returns:

Type Description
NDArray[float]

The charges assigned to each attractor.

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_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. Note that for some methods (e.g. weight) the voxels have weights for each basin. These will be stored in the basin_weights property.

basin_maxima_charge_values property

Returns:

Type Description
NDArray[float]

The charge data value at each maximum

basin_maxima_frac property

Returns:

Type Description
NDArray[float]

The fractional coordinates of each attractor.

basin_maxima_ref_values property

Returns:

Type Description
NDArray[float]

The reference data value at each maximum

basin_maxima_values property

Returns:

Type Description
NDArray[float]

The fractional coordinates of each attractor.

basin_maxima_vox property

Returns:

Type Description
NDArray[int]

The voxel coordinates of each attractor. There may be more of these than the fractional coordinates, as some maxima sit exactly between several voxels.

basin_surface_distances property

Returns:

Type Description
NDArray[float]

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

basin_tol property writable

Returns:

Type Description
float

The value below which a basin will not be considered significant. This is used to avoid writing out data that is likely not valuable. The default is 0.001.

basin_volumes property

Returns:

Type Description
NDArray[float]

The volume assigned to each attractor.

charge_grid property writable

Returns:

Type Description
Grid

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

method property writable

Returns:

Type Description
str

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

normalize_vacuum property writable

Returns:

Type Description
bool

Whether or not the reference data needs to be converted to real space units for vacuum tolerance comparison. This should be set to True if the data follows VASP's CHGCAR standards, but False if the data should be compared as is (e.g. in ELFCARs)

num_vacuum property

Returns:

Type Description
int

The number of vacuum points in the array

reference_grid property writable

Returns:

Type Description
Grid

A grid object whose values will be used to construct the basins.

results_summary property

Returns:

Name Type Description
results_dict dict

A dictionary summary of all results

significant_basins property

Returns:

Type Description
NDArray[bool]

A 1D mask with an entry for each basin that is True where basins are significant.

structure property

Returns:

Type Description
Structure

The pymatgen structure basins are assigned to.

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.

vacuum_charge property

Returns:

Type Description
float

The charge assigned to the vacuum.

vacuum_mask property

Returns:

Type Description
NDArray[bool]

A mask representing the voxels that belong to the vacuum.

vacuum_tol property writable

Returns:

Type Description
float

The value below which a point will be considered part of the vacuum. The default is 0.001.

vacuum_volume property

Returns:

Type Description
float

The total volume assigned to the vacuum.

all_methods() staticmethod

Returns:

Type Description
list[str]

A list of the available methods.

Source code in src/baderkit/core/bader.py
642
643
644
645
646
647
648
649
650
651
652
653
@staticmethod
def all_methods() -> list[str]:
    """

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

    """

    return [i.value for i in Method]

copy()

Returns:

Type Description
Self

A deep copy of this Bader object.

Source code in src/baderkit/core/bader.py
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
def copy(self) -> Self:
    """

    Returns
    -------
    Self
        A deep copy of this Bader object.

    """
    return copy.deepcopy(self)

from_cube(charge_filename, reference_filename=None, **kwargs) classmethod

Creates a Bader class object from .cube files.

Parameters:

Name Type Description Default
charge_filename Path | str

The path to the .cube file that will be used for summing charge.

required
reference_filename Path | None | str

The path to .cube file that will be used for partitioning. If None, the charge file will be used for partitioning.

None
**kwargs dict

Keyword arguments to pass to the Bader class.

{}

Returns:

Type Description
Self

A Bader class object.

Source code in src/baderkit/core/bader.py
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
@classmethod
def from_cube(
    cls,
    charge_filename: Path | str,
    reference_filename: Path | None | str = None,
    **kwargs,
) -> Self:
    """
    Creates a Bader class object from .cube files.

    Parameters
    ----------
    charge_filename : Path | str, optional
        The path to the .cube file that will be used for summing charge.
    reference_filename : Path | None | str, optional
        The path to .cube file that will be used for partitioning.
        If None, the charge file will be used for partitioning.
    **kwargs : dict
        Keyword arguments to pass to the Bader class.

    Returns
    -------
    Self
        A Bader class object.

    """
    charge_grid = Grid.from_cube(charge_filename)
    if reference_filename is None:
        reference_grid = None
    else:
        reference_grid = Grid.from_cube(reference_filename)
    return cls(charge_grid=charge_grid, reference_grid=reference_grid, **kwargs)

from_dynamic(charge_filename, reference_filename=None, format=None, total_only=True, **kwargs) classmethod

Creates a Bader class object from VASP or .cube files. If no format is provided the method will automatically try and determine the file type from the name

Parameters:

Name Type Description Default
charge_filename Path | str

The path to the file containing the charge density that will be integrated.

required
reference_filename Path | None | str

The path to the file that will be used for partitioning. If None, the charge file will be used for partitioning.

None
format Literal['vasp', 'cube', None]

The format of the grids to read in. If None, the formats will be guessed from the file names.

None
total_only bool

If true, only the first set of data in the file will be read. This increases speed and reduced memory usage as the other data is typically not used. This is only used if the file format is determined to be VASP, as cube files are assumed to contain only one set of data. Defaults to True.

True
**kwargs dict

Keyword arguments to pass to the Bader class.

{}

Returns:

Type Description
Self

A Bader class object.

Source code in src/baderkit/core/bader.py
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
@classmethod
def from_dynamic(
    cls,
    charge_filename: Path | str,
    reference_filename: Path | None | str = None,
    format: Literal["vasp", "cube", None] = None,
    total_only: bool = True,
    **kwargs,
) -> Self:
    """
    Creates a Bader class object from VASP or .cube files. If no format is
    provided the method will automatically try and determine the file type
    from the name

    Parameters
    ----------
    charge_filename : Path | str
        The path to the file containing the charge density that will be
        integrated.
    reference_filename : Path | None | str, optional
        The path to the file that will be used for partitioning.
        If None, the charge file will be used for partitioning.
    format : Literal["vasp", "cube", None], optional
        The format of the grids to read in. If None, the formats will be
        guessed from the file names.
    total_only: bool
        If true, only the first set of data in the file will be read. This
        increases speed and reduced memory usage as the other data is typically
        not used. This is only used if the file format is determined to be
        VASP, as cube files are assumed to contain only one set of data.
        Defaults to True.
    **kwargs : dict
        Keyword arguments to pass to the Bader class.

    Returns
    -------
    Self
        A Bader class object.

    """

    charge_grid = Grid.from_dynamic(
        charge_filename, format=format, total_only=total_only
    )
    if reference_filename is None:
        reference_grid = None
    else:
        reference_grid = Grid.from_dynamic(
            reference_filename, format=format, total_only=total_only
        )
    return cls(charge_grid=charge_grid, reference_grid=reference_grid, **kwargs)

from_vasp(charge_filename='CHGCAR', reference_filename=None, total_only=True, **kwargs) classmethod

Creates a Bader class object from VASP files.

Parameters:

Name Type Description Default
charge_filename Path | str

The path to the CHGCAR like file that will be used for summing charge. The default is "CHGCAR".

'CHGCAR'
reference_filename Path | None | str

The path to CHGCAR like file that will be used for partitioning. If None, the charge file will be used for partitioning.

None
total_only bool

If true, only the first set of data in the file will be read. This increases speed and reduced memory usage as the other data is typically not used. Defaults to True.

True
**kwargs dict

Keyword arguments to pass to the Bader class.

{}

Returns:

Type Description
Self

A Bader class object.

Source code in src/baderkit/core/bader.py
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
@classmethod
def from_vasp(
    cls,
    charge_filename: Path | str = "CHGCAR",
    reference_filename: Path | None | str = None,
    total_only: bool = True,
    **kwargs,
) -> Self:
    """
    Creates a Bader class object from VASP files.

    Parameters
    ----------
    charge_filename : Path | str, optional
        The path to the CHGCAR like file that will be used for summing charge.
        The default is "CHGCAR".
    reference_filename : Path | None | str, optional
        The path to CHGCAR like file that will be used for partitioning.
        If None, the charge file will be used for partitioning.
    total_only: bool
        If true, only the first set of data in the file will be read. This
        increases speed and reduced memory usage as the other data is typically
        not used.
        Defaults to True.
    **kwargs : dict
        Keyword arguments to pass to the Bader class.

    Returns
    -------
    Self
        A Bader class object.

    """
    charge_grid = Grid.from_vasp(charge_filename, total_only=total_only)
    if reference_filename is None:
        reference_grid = None
    else:
        reference_grid = Grid.from_vasp(reference_filename, total_only=total_only)

    return cls(charge_grid=charge_grid, reference_grid=reference_grid, **kwargs)

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.py
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
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_surface_distances,
        }
    )
    return atoms_df

get_basin_results_dataframe()

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

Returns:

Name Type Description
basin_df DataFrame

A table summarizing the basins.

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

    Returns
    -------
    basin_df : pd.DataFrame
        A table summarizing the basins.

    """
    subset = self.significant_basins
    basin_frac_coords = self.basin_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_surface_distances[subset],
            "atom_dist": self.basin_atom_dists[subset],
        }
    )
    return basin_df

run_atom_assignment(structure=None)

Assigns bader basins to the atoms in the provided structure.

Parameters:

Name Type Description Default
structure Structure

If provided, basins will be assigned to the atoms in this structure. The default is None.

None

Returns:

Type Description
None.
Source code in src/baderkit/core/bader.py
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
def run_atom_assignment(self, structure: Structure = None):
    """
    Assigns bader basins to the atoms in the provided structure.

    Parameters
    ----------
    structure : Structure, optional
        If provided, basins will be assigned to the atoms in this structure.
        The default is None.

    Returns
    -------
    None.

    """
    # Default structure
    structure = structure or self.structure
    self._structure = structure

    # Shorthand access
    basins = self.basin_maxima_frac  # (N_basins, 3)
    t0 = time.time()
    logging.info("Assigning Atom Properties")
    atoms = structure.frac_coords  # (N_atoms, 3)
    L = structure.lattice.matrix  # (3, 3)
    N_basins, N_atoms = len(basins), len(atoms)

    # 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,)

    # Atom labels per grid point
    # NOTE: append -1 so that vacuum gets assigned to -1 in the atom_labels
    # array
    basin_atoms = np.insert(basin_atoms, len(basin_atoms), -1)
    atom_labels = basin_atoms[self.basin_labels]

    # Sum up charges/volumes per atom in one shot. slice with -1 is necessary
    # to prevent no negative value error
    try:
        atom_charges = np.bincount(
            basin_atoms[:-1], weights=self.basin_charges, minlength=N_atoms
        )
        atom_volumes = np.bincount(
            basin_atoms[:-1], weights=self.basin_volumes, minlength=N_atoms
        )
    except:
        breakpoint()
    # Store everything
    self._basin_atoms = basin_atoms[:-1]
    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)}")

run_bader()

Runs the entire Bader process and saves results to class variables.

Returns:

Type Description
None
Source code in src/baderkit/core/bader.py
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
def run_bader(self) -> None:
    """
    Runs the entire Bader process and saves results to class variables.

    Returns
    -------
    None

    """
    t0 = time.time()
    logging.info(f"Beginning Bader Algorithm Using '{self.method}' 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.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,
    )
    if self._use_overdetermined:
        method._use_overdetermined = True
    results = method.run()

    for key, value in results.items():
        setattr(self, f"_{key}", value)
    t1 = time.time()
    logging.info("Bader Algorithm Complete")
    logging.info(f"Time: {round(t1-t0,2)}")

write_all_atom_volumes(directory=None, write_reference=False, output_format=None, **writer_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.

Parameters:

Name Type Description Default
directory str | Path

The directory to write the files in. If None, the active directory is used.

None
directory str | Path

The directory to write the files in. If None, the active directory is used.

None
write_reference bool

Whether or not to write the reference data rather than the charge data. Default is False.

False
output_format str | Format

The format to write with. If None, writes to source format stored in the Grid objects metadata. Defaults to None.

None

Returns:

Type Description
None.
Source code in src/baderkit/core/bader.py
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
def write_all_atom_volumes(
    self,
    directory: str | Path = None,
    write_reference: bool = False,
    output_format: str | Format = None,
    **writer_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.

    Parameters
    ----------
    directory : str | Path
        The directory to write the files in. If None, the active directory
        is used.
    directory : str | Path
        The directory to write the files in. If None, the active directory
        is used.
    write_reference : bool, optional
        Whether or not to write the reference data rather than the charge data.
        Default is False.
    output_format : str | Format, optional
        The format to write with. If None, writes to source format stored in
        the Grid objects metadata.
        Defaults to None.

    Returns
    -------
    None.

    """
    atom_indices = np.array(range(len(self.structure)))
    self.write_atom_volumes(
        atom_indices=atom_indices,
        directory=directory,
        write_reference=write_reference,
        output_format=output_format,
        **writer_kwargs,
    )

write_all_basin_volumes(directory=None, write_reference=False, output_format=None, **writer_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
directory str | Path

The directory to write the files in. If None, the active directory is used.

None
write_reference bool

Whether or not to write the reference data rather than the charge data. Default is False.

False
output_format str | Format

The format to write with. If None, writes to source format stored in the Grid objects metadata. Defaults to None.

None

Returns:

Type Description
None.
Source code in src/baderkit/core/bader.py
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
def write_all_basin_volumes(
    self,
    directory: str | Path = None,
    write_reference: bool = False,
    output_format: str | Format = None,
    **writer_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
    ----------
    directory : str | Path
        The directory to write the files in. If None, the active directory
        is used.
    write_reference : bool, optional
        Whether or not to write the reference data rather than the charge data.
        Default is False.
    output_format : str | Format, optional
        The format to write with. If None, writes to source format stored in
        the Grid objects metadata.
        Defaults to None.

    Returns
    -------
    None.

    """
    basin_indices = np.where(self.significant_basins)[0]
    self.write_basin_volumes(
        basin_indices=basin_indices,
        directory=directory,
        write_reference=write_reference,
        output_format=output_format,
        **writer_kwargs,
    )

write_atom_volumes(atom_indices, directory=None, write_reference=False, output_format=None, **writer_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
directory str | Path

The directory to write the files in. If None, the active directory is used.

None
write_reference bool

Whether or not to write the reference data rather than the charge data. Default is False.

False
output_format str | Format

The format to write with. If None, writes to source format stored in the Grid objects metadata. Defaults to None.

None

Returns:

Type Description
None.
Source code in src/baderkit/core/bader.py
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
def write_atom_volumes(
    self,
    atom_indices: NDArray,
    directory: str | Path = None,
    write_reference: bool = False,
    output_format: str | Format = None,
    **writer_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
    directory : str | Path
        The directory to write the files in. If None, the active directory
        is used.
    write_reference : bool, optional
        Whether or not to write the reference data rather than the charge data.
        Default is False.
    output_format : str | Format, optional
        The format to write with. If None, writes to source format stored in
        the Grid objects metadata.
        Defaults to None.

    Returns
    -------
    None.

    """
    # get the data to use
    if write_reference:
        data_array = self.reference_grid.total
    else:
        data_array = self.charge_grid.total

    if directory is None:
        directory = Path(".")
    for atom_index in atom_indices:
        # get a mask everywhere but the requested basin
        mask = self.atom_labels != atom_index
        # copy data to avoid overwriting. Set data off of basin to 0
        data_array_copy = data_array.copy()
        data_array_copy[mask] = 0.0
        grid = Grid(structure=self.structure, data={"total": data_array_copy})
        file_path = directory / f"{grid.data_type.prefix}_a{atom_index}"
        # write file
        grid.write(filename=file_path, output_format=output_format, **writer_kwargs)

write_atom_volumes_sum(atom_indices, directory=None, write_reference=False, output_format=None, **writer_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
directory str | Path

The directory to write the files in. If None, the active directory is used.

None
write_reference bool

Whether or not to write the reference data rather than the charge data. Default is False.

False
output_format str | Format

The format to write with. If None, writes to source format stored in the Grid objects metadata. Defaults to None.

None

Returns:

Type Description
None.
Source code in src/baderkit/core/bader.py
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
def write_atom_volumes_sum(
    self,
    atom_indices: NDArray,
    directory: str | Path = None,
    write_reference: bool = False,
    output_format: str | Format = None,
    **writer_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
    directory : str | Path
        The directory to write the files in. If None, the active directory
        is used.
    write_reference : bool, optional
        Whether or not to write the reference data rather than the charge data.
        Default is False.
    output_format : str | Format, optional
        The format to write with. If None, writes to source format stored in
        the Grid objects metadata.
        Defaults to None.

    Returns
    -------
    None.

    """
    # get the data to use
    if write_reference:
        data_array = self.reference_grid.total
    else:
        data_array = self.charge_grid.total

    if directory is None:
        directory = Path(".")
    mask = np.isin(self.atom_labels, atom_indices)
    data_array_copy = data_array.copy()
    data_array_copy[~mask] = 0.0
    grid = Grid(structure=self.structure, data={"total": data_array_copy})
    file_path = directory / f"{grid.data_type.prefix}_asum"
    # write file
    grid.write(filename=file_path, output_format=output_format, **writer_kwargs)

write_basin_volumes(basin_indices, directory=None, write_reference=False, output_format=None, **writer_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
directory str | Path

The directory to write the files in. If None, the active directory is used.

None
write_reference bool

Whether or not to write the reference data rather than the charge data. Default is False.

False
output_format str | Format

The format to write with. If None, writes to source format stored in the Grid objects metadata. Defaults to None.

None

Returns:

Type Description
None.
Source code in src/baderkit/core/bader.py
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
def write_basin_volumes(
    self,
    basin_indices: NDArray,
    directory: str | Path = None,
    write_reference: bool = False,
    output_format: str | Format = None,
    **writer_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
    directory : str | Path
        The directory to write the files in. If None, the active directory
        is used.
    write_reference : bool, optional
        Whether or not to write the reference data rather than the charge data.
        Default is False.
    output_format : str | Format, optional
        The format to write with. If None, writes to source format stored in
        the Grid objects metadata.
        Defaults to None.

    Returns
    -------
    None.

    """
    # get the data to use
    if write_reference:
        data_array = self.reference_grid.total
    else:
        data_array = self.charge_grid.total

    if directory is None:
        directory = Path(".")
    for basin in basin_indices:
        # get a mask everywhere but the requested basin
        mask = self.basin_labels != basin
        # copy data to avoid overwriting. Set data off of basin to 0
        data_array_copy = data_array.copy()
        data_array_copy[mask] = 0.0
        grid = Grid(structure=self.structure, data={"total": data_array_copy})
        file_path = directory / f"{grid.data_type.prefix}_b{basin}"
        # write file
        grid.write(filename=file_path, output_format=output_format, **writer_kwargs)

write_basin_volumes_sum(basin_indices, directory=None, write_reference=False, output_format=None, **writer_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
directory str | Path

The directory to write the files in. If None, the active directory is used.

None
write_reference bool

Whether or not to write the reference data rather than the charge data. Default is False.

False
output_format str | Format

The format to write with. If None, writes to source format stored in the Grid objects metadata. Defaults to None.

None

Returns:

Type Description
None.
Source code in src/baderkit/core/bader.py
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
def write_basin_volumes_sum(
    self,
    basin_indices: NDArray,
    directory: str | Path = None,
    write_reference: bool = False,
    output_format: str | Format = None,
    **writer_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
    directory : str | Path
        The directory to write the files in. If None, the active directory
        is used.
    write_reference : bool, optional
        Whether or not to write the reference data rather than the charge data.
        Default is False.
    output_format : str | Format, optional
        The format to write with. If None, writes to source format stored in
        the Grid objects metadata.
        Defaults to None.

    Returns
    -------
    None.

    """
    # get the data to use
    if write_reference:
        data_array = self.reference_grid.total
    else:
        data_array = self.charge_grid.total

    if directory is None:
        directory = Path(".")
    # create a mask including each of the requested basins
    mask = np.isin(self.basin_labels, basin_indices)
    # copy data to avoid overwriting. Set data off of basin to 0
    data_array_copy = data_array.copy()
    data_array_copy[~mask] = 0.0
    grid = Grid(structure=self.structure, data={"total": data_array_copy})
    file_path = directory / f"{grid.data_type.prefix}_bsum"
    # write file
    grid.write(filename=file_path, output_format=output_format, **writer_kwargs)

write_results_summary(directory=None)

Writes a summary of atom and basin results to .tsv files.

Parameters:

Name Type Description Default
directory str | Path

The directory to write the files in. If None, the active directory is used.

None

Returns:

Type Description
None.
Source code in src/baderkit/core/bader.py
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
def write_results_summary(
    self,
    directory: Path | str | None = None,
):
    """
    Writes a summary of atom and basin results to .tsv files.

    Parameters
    ----------
    directory : str | Path
        The directory to write the files in. If None, the active directory
        is used.

    Returns
    -------
    None.

    """
    if directory is None:
        directory = Path(".")

    # 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}"
    )

    # Get basin results summary
    basin_df = self.get_basin_results_dataframe()
    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
    atom_col_widths = {
        col: max(len(col), formatted_atoms_df[col].map(len).max())
        for col in atoms_df.columns
    }
    basin_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
    for df, col_widths, name in zip(
        [formatted_atoms_df, formatted_basin_df],
        [atom_col_widths, basin_col_widths],
        ["bader_atom_summary.tsv", "bader_basin_summary.tsv"],
    ):
        # Note what we're writing in log
        if "atom" in name:
            logging.info(f"Writing Atom Summary to {name}")
        else:
            logging.info(f"Writing Basin Summary to {name}")

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

            # Write rows
            for _, row in 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
            if name == "bader_atom_summary.tsv":
                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")