Skip to content

Documentation for Linker object methods related to QA

The Linker object manages the data linkage process and holds the data linkage model.

Most of Splink's functionality can be accessed by calling methods (functions) on the linker, such as linker.predict(), linker.profile_columns() etc.

The Linker class is intended for subclassing for specific backends, e.g. a DuckDBLinker.

Source code in splink/linker.py
 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
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
class Linker:
    """The Linker object manages the data linkage process and holds the data linkage
    model.

    Most of Splink's functionality can  be accessed by calling methods (functions)
    on the linker, such as `linker.predict()`, `linker.profile_columns()` etc.

    The Linker class is intended for subclassing for specific backends, e.g.
    a `DuckDBLinker`.
    """

    def __init__(
        self,
        input_table_or_tables: str | list,
        settings_dict: dict | Path,
        accepted_df_dtypes,
        set_up_basic_logging: bool = True,
        input_table_aliases: str | list = None,
    ):
        """Initialise the linker object, which manages the data linkage process and
        holds the data linkage model.

        Examples:
            === "DuckDB"
                Dedupe
                ```py
                df = pd.read_csv("data_to_dedupe.csv")
                linker = DuckDBLinker(df, settings_dict)
                ```
                Link
                ```py
                df_1 = pd.read_parquet("table_1/")
                df_2 = pd.read_parquet("table_2/")
                linker = DuckDBLinker(
                    [df_1, df_2],
                    settings_dict,
                    input_table_aliases=["customers", "contact_center_callers"]
                    )
                ```
                Dedupe with a pre-trained model read from a json file
                ```py
                df = pd.read_csv("data_to_dedupe.csv")
                linker = DuckDBLinker(df, "model.json")
                ```
            === "Spark"
                Dedupe
                ```py
                df = spark.read.csv("data_to_dedupe.csv")
                linker = SparkLinker(df, settings_dict)
                ```
                Link
                ```py
                df_1 = spark.read.parquet("table_1/")
                df_2 = spark.read.parquet("table_2/")
                linker = SparkLinker(
                    [df_1, df_2],
                    settings_dict,
                    input_table_aliases=["customers", "contact_center_callers"]
                    )
                ```
                Dedupe with a pre-trained model read from a json file
                ```py
                df = spark.read.csv("data_to_dedupe.csv")
                linker = SparkLinker(df, "model.json")
                ```

        Args:
            input_table_or_tables (Union[str, list]): Input data into the linkage model.
                Either a single string (the name of a table in a database) for
                deduplication jobs, or a list of strings  (the name of tables in a
                database) for link_only or link_and_dedupe.  For some linkers, such as
                the DuckDBLinker and the SparkLinker, it's also possible to pass in
                dataframes (Pandas and Spark respectively) rather than strings.
            settings_dict (dict | Path, optional): A Splink settings dictionary, or a
                path to a json defining a settingss dictionary or pre-trained model.
                If not provided when the object is created, can later be added using
                `linker.load_settings()` or `linker.load_model()` Defaults to None.
            set_up_basic_logging (bool, optional): If true, sets ups up basic logging
                so that Splink sends messages at INFO level to stdout. Defaults to True.
            input_table_aliases (Union[str, list], optional): Labels assigned to
                input tables in Splink outputs.  If the names of the tables in the
                input database are long or unspecific, this argument can be used
                to attach more easily readable/interpretable names. Defaults to None.
        """

        if set_up_basic_logging:
            logging.basicConfig(
                format="%(message)s",
            )
            splink_logger = logging.getLogger("splink")
            splink_logger.setLevel(logging.INFO)

        self._pipeline = SQLPipeline()

        self._names_of_tables_created_by_splink: set = set()
        self._intermediate_table_cache: dict = CacheDictWithLogging()

        if not isinstance(settings_dict, (dict, type(None))):
            # Run if you've entered a filepath
            # feed it a blank settings dictionary
            self._setup_settings_objs(None)
            self.load_settings(settings_dict)
        else:
            settings_dict = deepcopy(settings_dict)
            self._setup_settings_objs(settings_dict)

        homogenised_tables, homogenised_aliases = self._register_input_tables(
            input_table_or_tables,
            input_table_aliases,
            accepted_df_dtypes,
        )

        self._input_tables_dict = self._get_input_tables_dict(
            homogenised_tables, homogenised_aliases
        )

        self._validate_input_dfs()
        self._em_training_sessions = []

        self._find_new_matches_mode = False
        self._train_u_using_random_sample_mode = False
        self._compare_two_records_mode = False
        self._self_link_mode = False
        self._analyse_blocking_mode = False
        self._deterministic_link_mode = False

        self.debug_mode = False

    @property
    def _cache_uid(self):
        if self._settings_dict:
            return self._settings_obj._cache_uid
        else:
            return self._cache_uid_no_settings

    @_cache_uid.setter
    def _cache_uid(self, value):
        if self._settings_dict:
            self._settings_obj._cache_uid = value
        else:
            self._cache_uid_no_settings = value

    @property
    def _settings_obj(self) -> Settings:
        if self._settings_obj_ is None:
            raise ValueError(
                "You did not provide a settings dictionary when you "
                "created the linker.  To continue, you need to provide a settings "
                "dictionary using the `load_settings()` method on your linker "
                "object. i.e. linker.load_settings(settings_dict)"
            )
        return self._settings_obj_

    @property
    def _input_tablename_l(self):
        if self._find_new_matches_mode:
            return "__splink__df_concat_with_tf"

        if self._self_link_mode:
            return "__splink__df_concat_with_tf"

        if self._compare_two_records_mode:
            return "__splink__compare_two_records_left_with_tf"

        if self._train_u_using_random_sample_mode:
            return "__splink__df_concat_with_tf_sample"

        if self._analyse_blocking_mode:
            return "__splink__df_concat"

        if self._two_dataset_link_only:
            return "__splink__df_concat_with_tf_left"

        return "__splink__df_concat_with_tf"

    @property
    def _input_tablename_r(self):
        if self._find_new_matches_mode:
            return "__splink__df_new_records_with_tf"

        if self._self_link_mode:
            return "__splink__df_concat_with_tf"

        if self._compare_two_records_mode:
            return "__splink__compare_two_records_right_with_tf"

        if self._train_u_using_random_sample_mode:
            return "__splink__df_concat_with_tf_sample"

        if self._analyse_blocking_mode:
            return "__splink__df_concat"

        if self._two_dataset_link_only:
            return "__splink_df_concat_with_tf_right"
        return "__splink__df_concat_with_tf"

    @property
    def _source_dataset_column_name(self):
        if self._settings_obj_ is None:
            return None

        # Used throughout the scripts to feed our SQL
        if self._settings_obj._source_dataset_column_name_is_required:
            df_obj = next(iter(self._input_tables_dict.values()))
            columns = df_obj.columns_escaped

            input_column, src_ds_col = self._settings_obj_._source_dataset_col
            return "__splink_source_dataset" if src_ds_col in columns else input_column
        else:
            return None

    @property
    def _two_dataset_link_only(self):
        # Two dataset link only join is a special case where an inner join of the
        # two datasets is much more efficient than self-joining the vertically
        # concatenation of all input datasets
        if self._find_new_matches_mode:
            return True

        if self._compare_two_records_mode:
            return True

        # in u-train sample mode we are joining the concatenated table mixing
        # both data sets - hence if we inner join on True we will end up with
        # samples which both originate from the same dataset
        if self._train_u_using_random_sample_mode:
            return False

        if self._analyse_blocking_mode:
            return False

        if (
            len(self._input_tables_dict) == 2
            and self._settings_obj._link_type == "link_only"
        ):
            return True
        else:
            return False

    @property
    def _sql_dialect(self):
        if self._sql_dialect_ is None:
            raise NotImplementedError(
                f"No SQL dialect set on object of type {type(self)}. "
                "Did you make sure to create a dialect-specific Linker?"
            )
        return self._sql_dialect_

    @property
    def _infinity_expression(self):
        raise NotImplementedError(
            f"infinity sql expression not available for {type(self)}"
        )

    @property
    def _verify_link_only_job(self):
        cache = self._intermediate_table_cache
        if "__splink__df_concat_with_tf" not in cache:
            return

        if self._settings_obj._link_type == "link_only":
            # if input datasets > 1 then skip
            if len(self._input_tables_dict) > 1:
                return

            # else, check if source dataset column is populated...
            src_ds = self._source_dataset_column_name
            if src_ds == "__splink_source_dataset":
                _, src_ds = self._settings_obj_._source_dataset_col

            sql = find_unique_source_dataset(src_ds)
            self._enqueue_sql(sql, "source_ds_distinct")
            src_ds_distinct = self._execute_sql_pipeline(
                [cache["__splink__df_concat_with_tf"]]
            )
            if len(src_ds_distinct.as_record_dict()) == 1:
                raise SplinkException(
                    "if `link_type` is `link_only`, it should have at least two "
                    "input dataframes, or one dataframe with a `source_dataset` "
                    "column outlining which dataset each record belongs to."
                )

    def _register_input_tables(self, input_tables, input_aliases, accepted_df_dtypes):
        # 'homogenised' means all entries are strings representing tables
        homogenised_tables = []
        homogenised_aliases = []
        accepted_df_dtypes = ensure_is_tuple(accepted_df_dtypes)

        existing_tables = []
        for alias in input_aliases:
            # Check if alias is a string (indicating a table name) and that it is not
            # a file path.
            if not isinstance(alias, str) or re.match(pattern=r".*", string=alias):
                continue
            exists = self._table_exists_in_database(alias)
            if exists:
                existing_tables.append(f"'{alias}'")
        if existing_tables:
            input_tables = ", ".join(existing_tables)
            raise ValueError(
                f"Table(s): {input_tables} already exists in database. "
                "Please remove or rename it/them before retrying"
            )

        for i, (table, alias) in enumerate(zip(input_tables, input_aliases)):
            if isinstance(alias, accepted_df_dtypes):
                alias = f"__splink__input_table_{i}"

            if isinstance(table, accepted_df_dtypes):
                self._table_registration(table, alias)
                table = alias

            homogenised_tables.append(table)
            homogenised_aliases.append(alias)

        return homogenised_tables, homogenised_aliases

    def _setup_settings_objs(self, settings_dict):
        # Setup the linker class's required settings
        self._settings_dict = settings_dict

        # if settings_dict is passed, set sql_dialect on it if missing, and make sure
        # incompatible dialect not passed
        if settings_dict is not None and settings_dict.get("sql_dialect", None) is None:
            settings_dict["sql_dialect"] = self._sql_dialect

        if settings_dict is None:
            self._cache_uid_no_settings = ascii_uid(8)
        else:
            uid = settings_dict.get("linker_uid", ascii_uid(8))
            settings_dict["linker_uid"] = uid

        if settings_dict is None:
            self._settings_obj_ = None
        else:
            self._settings_obj_ = Settings(settings_dict)

            self._validate_dialect()

    def _initialise_df_concat(self, materialise=False):
        cache = self._intermediate_table_cache
        concat_df = None
        if "__splink__df_concat" in cache:
            concat_df = cache["__splink__df_concat"]
        elif "__splink__df_concat_with_tf" in cache:
            concat_df = cache["__splink__df_concat_with_tf"]
            concat_df.templated_name = "__splink__df_concat"
        else:
            if materialise:
                # Clear the pipeline if we are materialising
                # There's no reason not to do this, since when
                # we execute the pipeline, it'll get cleared anyway
                self._pipeline.reset()
            sql = vertically_concatenate_sql(self)
            self._enqueue_sql(sql, "__splink__df_concat")
            if materialise:
                concat_df = self._execute_sql_pipeline()
                cache["__splink__df_concat"] = concat_df

        return concat_df

    def _initialise_df_concat_with_tf(self, materialise=True):
        cache = self._intermediate_table_cache
        nodes_with_tf = None
        if "__splink__df_concat_with_tf" in cache:
            nodes_with_tf = cache["__splink__df_concat_with_tf"]

        else:
            if materialise:
                # Clear the pipeline if we are materialising
                # There's no reason not to do this, since when
                # we execute the pipeline, it'll get cleared anyway
                self._pipeline.reset()

            sql = vertically_concatenate_sql(self)
            self._enqueue_sql(sql, "__splink__df_concat")

            sqls = compute_all_term_frequencies_sqls(self)
            for sql in sqls:
                self._enqueue_sql(sql["sql"], sql["output_table_name"])

            if materialise:
                nodes_with_tf = self._execute_sql_pipeline()
                cache["__splink__df_concat_with_tf"] = nodes_with_tf

        # verify the link job
        if self._settings_obj_ is not None:
            self._verify_link_only_job

        return nodes_with_tf

    def _table_to_splink_dataframe(
        self, templated_name, physical_name
    ) -> SplinkDataFrame:
        """Create a SplinkDataframe from a table in the underlying database called
        `physical_name`.

        Associate a `templated_name` with this table, which signifies the purpose
        or 'meaning' of this table to splink. (e.g. `__splink__df_blocked`)

        Args:
            templated_name (str): The purpose of the table to Splink
            physical_name (str): The name of the table in the underlying databse
        """
        raise NotImplementedError(
            "_table_to_splink_dataframe not implemented on this linker"
        )

    def _enqueue_sql(self, sql, output_table_name):
        """Add sql to the current pipeline, but do not execute the pipeline."""
        self._pipeline.enqueue_sql(sql, output_table_name)

    def _execute_sql_pipeline(
        self,
        input_dataframes: list[SplinkDataFrame] = [],
        materialise_as_hash=True,
        use_cache=True,
    ) -> SplinkDataFrame:
        """Execute the SQL queued in the current pipeline as a single statement
        e.g. `with a as (), b as , c as (), select ... from c`, then execute the
        pipeline, returning the resultant table as a SplinkDataFrame

        Args:
            input_dataframes (List[SplinkDataFrame], optional): A 'starting point' of
                SplinkDataFrames if needed. Defaults to [].
            materialise_as_hash (bool, optional): If true, the output tablename will end
                in a unique identifer. Defaults to True.
            use_cache (bool, optional): If true, look at whether the SQL pipeline has
                been executed before, and if so, use the existing result. Defaults to
                True.

        Returns:
            SplinkDataFrame: An abstraction representing the table created by the sql
                pipeline
        """

        if not self.debug_mode:
            sql_gen = self._pipeline._generate_pipeline(input_dataframes)

            output_tablename_templated = self._pipeline.queue[-1].output_table_name

            try:
                dataframe = self._sql_to_splink_dataframe_checking_cache(
                    sql_gen,
                    output_tablename_templated,
                    materialise_as_hash,
                    use_cache,
                )
            except Exception as e:
                raise e
            finally:
                self._pipeline.reset()

            return dataframe
        else:
            # In debug mode, we do not pipeline the sql and print the
            # results of each part of the pipeline
            for task in self._pipeline._generate_pipeline_parts(input_dataframes):
                output_tablename = task.output_table_name
                sql = task.sql
                print("------")
                print(f"--------Creating table: {output_tablename}--------")

                dataframe = self._sql_to_splink_dataframe_checking_cache(
                    sql,
                    output_tablename,
                    materialise_as_hash=False,
                    use_cache=False,
                )
            self._pipeline.reset()
            return dataframe

    def _execute_sql_against_backend(
        self, sql: str, templated_name: str, physical_name: str
    ) -> SplinkDataFrame:
        """Execute a single sql SELECT statement, returning a SplinkDataFrame.

        Subclasses should implement this, using _log_and_run_sql_execution() within
        their implementation, maybe doing some SQL translation or other prep/cleanup
        work before/after.
        """
        raise NotImplementedError(
            f"_execute_sql_against_backend not implemented for {type(self)}"
        )

    def _run_sql_execution(
        self, final_sql: str, templated_name: str, physical_name: str
    ) -> SplinkDataFrame:
        """**Actually** execute the sql against the backend database.

        This is intended to be implemented by a subclass, but not actually called
        directly. Instead, call _log_and_run_sql_execution, and that will call
        this method.

        This could return something, or not. It's up to the Linker subclass to decide.
        """
        raise NotImplementedError(
            f"_run_sql_execution not implemented for {type(self)}"
        )

    def _log_and_run_sql_execution(
        self, final_sql: str, templated_name: str, physical_name: str
    ) -> SplinkDataFrame:
        """Log the sql, then call _run_sql_execution(), wrapping any errors"""
        logger.debug(execute_sql_logging_message_info(templated_name, physical_name))
        logger.log(5, log_sql(final_sql))
        try:
            return self._run_sql_execution(final_sql, templated_name, physical_name)
        except Exception as e:
            # Parse our SQL through sqlglot to pretty print
            try:
                final_sql = sqlglot.parse_one(
                    final_sql,
                    read=self._sql_dialect,
                ).sql(pretty=True)
                # if sqlglot produces any errors, just report the raw SQL
            except Exception:
                pass

            raise SplinkException(
                f"Error executing the following sql for table "
                f"`{templated_name}` ({physical_name}):\n{final_sql}"
            ) from e

    def register_table(self, input, table_name, overwrite=False):
        """
        Register a table to your backend database, to be used in one of the
        splink methods, or simply to allow querying.

        Tables can be of type: dictionary, record level dictionary,
        pandas dataframe, pyarrow table and in the spark case, a spark df.

        Examples:
            ```py
            test_dict = {"a": [666,777,888],"b": [4,5,6]}
            linker.register_table(test_dict, "test_dict")
            linker.query_sql("select * from test_dict")
            ```

        Args:
            input: The data you wish to register. This can be either a dictionary,
                pandas dataframe, pyarrow table or a spark dataframe.
            table_name (str): The name you wish to assign to the table.
            overwrite (bool): Overwrite the table in the underlying database if it
                exists

        Returns:
            SplinkDataFrame: An abstraction representing the table created by the sql
                pipeline
        """

        raise NotImplementedError(f"register_table not implemented for {type(self)}")

    def _table_registration(self, input, table_name):
        """
        Register a table to your backend database, to be used in one of the
        splink methods, or simply to allow querying.

        Tables can be of type: dictionary, record level dictionary,
        pandas dataframe, pyarrow table and in the spark case, a spark df.

        This function is contains no overwrite functionality, so it can be used
        where we don't want to allow for overwriting.

        Args:
            input: The data you wish to register. This can be either a dictionary,
                pandas dataframe, pyarrow table or a spark dataframe.
            table_name (str): The name you wish to assign to the table.

        Returns:
            None
        """

        raise NotImplementedError(
            f"_table_registration not implemented for {type(self)}"
        )

    def query_sql(self, sql, output_type="pandas"):
        """
        Run a SQL query against your backend database and return
        the resulting output.

        Examples:
            === "DuckDB"
                ```py
                linker = DuckDBLinker(df, settings)
                df_predict = linker.predict()
                linker.query_sql(f"select * from {df_predict.physical_name} limit 10")
                ```
            === "Spark"
                ```py
                linker = SparkLinker(df, settings)
                df_predict = linker.predict()
                linker.query_sql(f"select * from {df_predict.physical_name} limit 10")
                ```
            === "Athena"
                ```py
                linker = AthenaLinker(df, settings)
                df_predict = linker.predict()
                linker.query_sql(f"select * from {df_predict.physical_name} limit 10")
                ```
            === "SQLite"
                ```py
                linker = SQLiteLinker(df, settings)
                df_predict = linker.predict()
                linker.query_sql(f"select * from {df_predict.physical_name} limit 10")
            ```

        Args:
            sql (str): The SQL to be queried.
            output_type (str): One of splink_df/splinkdf or pandas.
                This determines the type of table that your results are output in.
        """

        output_tablename_templated = "__splink__df_sql_query"

        splink_dataframe = self._sql_to_splink_dataframe_checking_cache(
            sql,
            output_tablename_templated,
            materialise_as_hash=False,
            use_cache=False,
        )

        if output_type in ("splink_df", "splinkdf"):
            return splink_dataframe
        elif output_type == "pandas":
            out = splink_dataframe.as_pandas_dataframe()
            # If pandas, drop the table to cleanup the db
            splink_dataframe.drop_table_from_database()
            return out
        else:
            raise ValueError(
                f"output_type '{output_type}' is not supported.",
                "Must be one of 'splink_df'/'splinkdf' or 'pandas'",
            )

    def _sql_to_splink_dataframe_checking_cache(
        self,
        sql,
        output_tablename_templated,
        materialise_as_hash=True,
        use_cache=True,
    ) -> SplinkDataFrame:
        """Execute sql, or if identical sql has been run before, return cached results.

        This function
            - is used by _execute_sql_pipeline to to execute SQL
            - or can be used directly if you have a single SQL statement that's
              not in a pipeline

        Return a SplinkDataFrame representing the results of the SQL
        """

        to_hash = (sql + self._cache_uid).encode("utf-8")
        hash = hashlib.sha256(to_hash).hexdigest()[:9]
        # Ensure hash is valid sql table name
        table_name_hash = f"{output_tablename_templated}_{hash}"

        if use_cache:
            if self._table_exists_in_database(output_tablename_templated):
                logger.debug(f"Using existing table {output_tablename_templated}")
                return self._table_to_splink_dataframe(
                    output_tablename_templated, output_tablename_templated
                )

            if self._table_exists_in_database(table_name_hash):
                logger.debug(
                    f"Using cache for {output_tablename_templated}"
                    f" with physical name {table_name_hash}"
                )
                return self._table_to_splink_dataframe(
                    output_tablename_templated, table_name_hash
                )

        if self.debug_mode:
            print(sql)

        if materialise_as_hash:
            splink_dataframe = self._execute_sql_against_backend(
                sql, output_tablename_templated, table_name_hash
            )
        else:
            splink_dataframe = self._execute_sql_against_backend(
                sql,
                output_tablename_templated,
                output_tablename_templated,
            )

        self._names_of_tables_created_by_splink.add(splink_dataframe.physical_name)

        if self.debug_mode:
            df_pd = splink_dataframe.as_pandas_dataframe()
            try:
                from IPython.display import display

                display(df_pd)
            except ModuleNotFoundError:
                print(df_pd)

        return splink_dataframe

    def __deepcopy__(self, memo):
        """When we do EM training, we need a copy of the linker which is independent
        of the main linker e.g. setting parameters on the copy will not affect the
        main linker.  This method implements ensures linker can be deepcopied.
        """
        new_linker = copy(self)
        new_linker._em_training_sessions = []
        new_settings = deepcopy(self._settings_obj_)
        new_linker._settings_obj_ = new_settings
        return new_linker

    def _ensure_aliases_populated_and_is_list(
        self, input_table_or_tables, input_table_aliases
    ):
        if input_table_aliases is None:
            input_table_aliases = input_table_or_tables

        input_table_aliases = ensure_is_list(input_table_aliases)

        return input_table_aliases

    def _get_input_tables_dict(self, input_table_or_tables, input_table_aliases):
        input_table_or_tables = ensure_is_list(input_table_or_tables)

        input_table_aliases = self._ensure_aliases_populated_and_is_list(
            input_table_or_tables, input_table_aliases
        )

        d = {}
        for table_name, table_alias in zip(input_table_or_tables, input_table_aliases):
            d[table_alias] = self._table_to_splink_dataframe(table_alias, table_name)
        return d

    def _get_input_tf_dict(self, df_dict):
        d = {}
        for df_name, df_value in df_dict.items():
            renamed = colname_to_tf_tablename(df_name)
            d[renamed] = self._table_to_splink_dataframe(renamed, df_value)
        return d

    def _predict_warning(self):
        if not self._settings_obj._is_fully_trained:
            msg = (
                "\n -- WARNING --\n"
                "You have called predict(), but there are some parameter "
                "estimates which have neither been estimated or specified in your "
                "settings dictionary.  To produce predictions the following"
                " untrained trained parameters will use default values."
            )
            messages = self._settings_obj._not_trained_messages()

            warn_message = "\n".join([msg] + messages)

            logger.warning(warn_message)

    def _table_exists_in_database(self, table_name):
        raise NotImplementedError(
            f"table_exists_in_database not implemented for {type(self)}"
        )

    def _validate_input_dfs(self):
        if not hasattr(self, "_input_tables_dict"):
            # This is only triggered where a user loads a settings dict from a
            # given file path.
            return

        for df in self._input_tables_dict.values():
            df.validate()

        if self._settings_obj_ is not None:
            if self._settings_obj._link_type == "dedupe_only":
                if len(self._input_tables_dict) > 1:
                    raise ValueError(
                        'If link_type = "dedupe only" then input tables must contain '
                        "only a single input table",
                    )

    def _validate_dialect(self):
        settings_dialect = self._settings_obj._sql_dialect
        if settings_dialect != self._sql_dialect:
            raise ValueError(
                f"Incompatible SQL dialect! `settings` dictionary uses "
                f"dialect {settings_dialect}, but expecting "
                f"'{self._sql_dialect}' for Linker of type {type(self)}"
            )

    def _populate_probability_two_random_records_match_from_trained_values(self):
        recip_prop_matches_estimates = []

        logger.log(
            15,
            (
                "---- Using training sessions to compute "
                "probability two random records match ----"
            ),
        )
        for em_training_session in self._em_training_sessions:
            training_lambda = (
                em_training_session._settings_obj._probability_two_random_records_match
            )
            training_lambda_bf = prob_to_bayes_factor(training_lambda)
            reverse_levels = (
                em_training_session._comparison_levels_to_reverse_blocking_rule
            )

            logger.log(
                15,
                "\n"
                f"Probability two random records match from trained model blocking on "
                f"{em_training_session._blocking_rule_for_training.blocking_rule}: "
                f"{training_lambda:,.3f}",
            )

            for reverse_level in reverse_levels:
                # Get comparison level on current settings obj
                cc = self._settings_obj._get_comparison_by_output_column_name(
                    reverse_level.comparison._output_column_name
                )

                cl = cc._get_comparison_level_by_comparison_vector_value(
                    reverse_level._comparison_vector_value
                )

                if cl._has_estimated_values:
                    bf = cl._trained_m_median / cl._trained_u_median
                else:
                    bf = cl._bayes_factor

                logger.log(
                    15,
                    f"Reversing comparison level {cc._output_column_name}"
                    f" using bayes factor {bf:,.3f}",
                )

                training_lambda_bf = training_lambda_bf / bf

                as_prob = bayes_factor_to_prob(training_lambda_bf)

                logger.log(
                    15,
                    (
                        "This estimate of probability two random records match now: "
                        f" {as_prob:,.3f} "
                        f"with reciprocal {(1/as_prob):,.3f}"
                    ),
                )
            logger.log(15, "\n---------")
            p = bayes_factor_to_prob(training_lambda_bf)
            recip_prop_matches_estimates.append(1 / p)

        prop_matches_estimate = 1 / median(recip_prop_matches_estimates)

        self._settings_obj._probability_two_random_records_match = prop_matches_estimate
        logger.log(
            15,
            "\nMedian of prop of matches estimates: "
            f"{self._settings_obj._probability_two_random_records_match:,.3f} "
            "reciprocal "
            f"{1/self._settings_obj._probability_two_random_records_match:,.3f}",
        )

    def _populate_m_u_from_trained_values(self):
        ccs = self._settings_obj.comparisons

        for cc in ccs:
            for cl in cc._comparison_levels_excluding_null:
                if cl._has_estimated_u_values:
                    cl.u_probability = cl._trained_u_median
                if cl._has_estimated_m_values:
                    cl.m_probability = cl._trained_m_median

    def _delete_tables_created_by_splink_from_db(
        self, retain_term_frequency=True, retain_df_concat_with_tf=True
    ):
        to_remove = set()
        for name in self._names_of_tables_created_by_splink:
            # Only delete tables explicitly marked as having been created by splink
            if "__splink__" not in name:
                continue
            if name == "__splink__df_concat_with_tf":
                if not retain_df_concat_with_tf:
                    self._delete_table_from_database(name)
                    to_remove.add(name)
            elif name.startswith("__splink__df_tf_"):
                if not retain_term_frequency:
                    self._delete_table_from_database(name)
                    to_remove.add(name)
            else:
                self._delete_table_from_database(name)
                to_remove.add(name)

        self._names_of_tables_created_by_splink = (
            self._names_of_tables_created_by_splink - to_remove
        )

    def _raise_error_if_necessary_waterfall_columns_not_computed(self):
        ricc = self._settings_obj._retain_intermediate_calculation_columns
        rmc = self._settings_obj._retain_matching_columns
        if not (ricc and rmc):
            raise ValueError(
                "retain_intermediate_calculation_columns and "
                "retain_matching_columns must both be set to True in your settings"
                " dictionary to use this function, because otherwise the necessary "
                "columns will not be available in the input records."
                f" Their current values are {ricc} and {rmc}, respectively. "
                "Please re-run your linkage with them both set to True."
            )

    def _raise_error_if_necessary_accuracy_columns_not_computed(self):
        rmc = self._settings_obj._retain_matching_columns
        if not (rmc):
            raise ValueError(
                "retain_matching_columns must be set to True in your settings"
                " dictionary to use this function, because otherwise the necessary "
                "columns will not be available in the input records."
                f" Its current value is {rmc}. "
                "Please re-run your linkage with it set to True."
            )

    def load_settings(self, settings_dict: dict | str | Path):
        """Initialise settings for the linker.  To be used if settings were
        not passed to the linker on creation. This can either be in the form
        of a settings dictionary or a filepath to a json file containing a
        valid settings dictionary.

        Examples:
            ```py
            linker = DuckDBLinker(df)
            linker.profile_columns(["first_name", "surname"])
            linker.load_settings(settings_dict)
            ```

        Args:
            settings_dict (dict | str | Path): A Splink settings dictionary or
                the path to your settings json file.
        """

        if not isinstance(settings_dict, dict):
            p = Path(settings_dict)
            if not p.is_file():  # check if it's a valid file/filepath
                raise FileNotFoundError(
                    "The filepath you have provided is either not a valid file "
                    "or doesn't exist along the path provided."
                )
            settings_dict = json.loads(p.read_text())

        # Store the cache ID so it can be reloaded after cache invalidation
        cache_id = self._cache_uid
        # So we don't run into any issues with generated tables having
        # invalid columns as settings have been tweaked, invalidate
        # the cache and allow these tables to be recomputed.

        # This is less efficient, but triggers infrequently and ensures we don't
        # run into issues where the defaults used conflict with the actual values
        # supplied in settings.

        # This is particularly relevant with `source_dataset`, which appears within
        # concat_with_tf.
        self.invalidate_cache()

        # If a uid already exists in your settings object, prioritise this
        settings_dict["linker_uid"] = settings_dict.get("linker_uid", cache_id)
        settings_dict["sql_dialect"] = settings_dict.get(
            "sql_dialect", self._sql_dialect
        )
        self._settings_dict = settings_dict
        self._settings_obj_ = Settings(settings_dict)
        self._validate_input_dfs()
        self._validate_dialect()

    def load_model(self, model_path: Path):
        """
        Load a pre-defined model from a json file into the linker.
        This is intended to be used with the output of
        `save_model_to_json()`.

        Examples:
            ```py
            linker.load_model("my_settings.json")
            ```

        Args:
            model_path (Path): A path to your model settings json file.
        """

        return self.load_settings(model_path)

    def initialise_settings(self, settings_dict: dict):
        """*This method is now deprecated. Please use `load_settings`
        when loading existing settings or `load_model` when loading
         a pre-trained model.*

        Initialise settings for the linker.  To be used if settings were
        not passed to the linker on creation.
        Examples:
            === "DuckDB"
                ```py
                linker = DuckDBLinker(df")
                linker.profile_columns(["first_name", "surname"])
                linker.initialise_settings(settings_dict)
                ```
            === "Spark"
                ```py
                linker = SparkLinker(df")
                linker.profile_columns(["first_name", "surname"])
                linker.initialise_settings(settings_dict)
                ```
            === "Athena"
                ```py
                linker = AthenaLinker(df")
                linker.profile_columns(["first_name", "surname"])
                linker.initialise_settings(settings_dict)
                ```
            === "SQLite"
                ```py
                linker = SQLiteLinker(df")
                linker.profile_columns(["first_name", "surname"])
                linker.initialise_settings(settings_dict)
                ```
        Args:
            settings_dict (dict): A Splink settings dictionary
        """
        # If a uid already exists in your settings object, prioritise this
        settings_dict["linker_uid"] = settings_dict.get("linker_uid", self._cache_uid)
        settings_dict["sql_dialect"] = settings_dict.get(
            "sql_dialect", self._sql_dialect
        )
        self._settings_dict = settings_dict
        self._settings_obj_ = Settings(settings_dict)
        self._validate_input_dfs()
        self._validate_dialect()

        warnings.warn(
            "`initialise_settings` is deprecated. We advise you use "
            "`linker.load_settings()` when loading in your settings or a previously "
            "trained model.",
            DeprecationWarning,
            stacklevel=2,
        )

    def load_settings_from_json(self, in_path: str | Path):
        """*This method is now deprecated. Please use `load_settings`
        when loading existing settings or `load_model` when loading
         a pre-trained model.*

        Load settings from a `.json` file.
        This `.json` file would usually be the output of
        `linker.save_model_to_json()`
        Examples:
            ```py
            linker.load_settings_from_json("my_settings.json")
            ```
        Args:
            in_path (str): Path to settings json file
        """
        self.load_settings(in_path)

        warnings.warn(
            "`load_settings_from_json` is deprecated. We advise you use "
            "`linker.load_settings()` when loading in your settings or a previously "
            "trained model.",
            DeprecationWarning,
            stacklevel=2,
        )

    def compute_tf_table(self, column_name: str) -> SplinkDataFrame:
        """Compute a term frequency table for a given column and persist to the database

        This method is useful if you want to pre-compute term frequency tables e.g.
        so that real time linkage executes faster, or so that you can estimate
        various models without having to recompute term frequency tables each time

        Examples:
            === "DuckDB"
                Real time linkage
                ```py
                linker = DuckDBLinker(df)
                linker.load_settings("saved_settings.json")
                linker.compute_tf_table("surname")
                linker.compare_two_records(record_left, record_right)
                ```
                Pre-computed term frequency tables
                ```py
                linker = DuckDBLinker(df)
                df_first_name_tf = linker.compute_tf_table("first_name")
                df_first_name_tf.write.parquet("folder/first_name_tf")
                >>>
                # On subsequent data linking job, read this table rather than recompute
                df_first_name_tf = pd.read_parquet("folder/first_name_tf")
                df_first_name_tf.createOrReplaceTempView("__splink__df_tf_first_name")
                ```
            === "Spark"
                Real time linkage
                ```py
                linker = SparkLinker(df)
                linker.load_settings("saved_settings.json")
                linker.compute_tf_table("surname")
                linker.compare_two_records(record_left, record_right)
                ```
                Pre-computed term frequency tables
                ```py
                linker = SparkLinker(df)
                df_first_name_tf = linker.compute_tf_table("first_name")
                df_first_name_tf.write.parquet("folder/first_name_tf")
                >>>
                # On subsequent data linking job, read this table rather than recompute
                df_first_name_tf = spark.read.parquet("folder/first_name_tf")
                df_first_name_tf.createOrReplaceTempView("__splink__df_tf_first_name")
                ```

        Args:
            column_name (str): The column name in the input table

        Returns:
            SplinkDataFrame: The resultant table as a splink data frame
        """

        input_col = InputColumn(column_name, settings_obj=self._settings_obj)
        tf_tablename = colname_to_tf_tablename(input_col)
        cache = self._intermediate_table_cache
        concat_tf_tables = [
            remove_quotes_from_identifiers(tf_col.input_name_as_tree).sql()
            for tf_col in self._settings_obj._term_frequency_columns
        ]

        if tf_tablename in cache:
            tf_df = cache[tf_tablename]
        elif "__splink__df_concat_with_tf" in cache and column_name in concat_tf_tables:
            self._pipeline.reset()
            # If our df_concat_with_tf table already exists, use backwards inference to
            # find a given tf table
            colname = InputColumn(column_name)
            sql = term_frequencies_from_concat_with_tf(colname)
            self._enqueue_sql(sql, colname_to_tf_tablename(colname))
            tf_df = self._execute_sql_pipeline(
                [cache["__splink__df_concat_with_tf"]], materialise_as_hash=True
            )
            self._intermediate_table_cache[tf_tablename] = tf_df
        else:
            # Clear the pipeline if we are materialising
            self._pipeline.reset()
            df_concat = self._initialise_df_concat()
            input_dfs = []
            if df_concat:
                input_dfs.append(df_concat)
            sql = term_frequencies_for_single_column_sql(input_col)
            self._enqueue_sql(sql, tf_tablename)
            tf_df = self._execute_sql_pipeline(input_dfs, materialise_as_hash=True)
            self._intermediate_table_cache[tf_tablename] = tf_df

        return tf_df

    def deterministic_link(self) -> SplinkDataFrame:
        """Uses the blocking rules specified by
        `blocking_rules_to_generate_predictions` in the settings dictionary to
        generate pairwise record comparisons.

        For deterministic linkage, this should be a list of blocking rules which
        are strict enough to generate only true links.

        Deterministic linkage, however, is likely to result in missed links
        (false negatives).

        Examples:
            === "DuckDB"
            ```py
            from splink.duckdb.duckdb_linker import DuckDBLinker

            settings = {
                "link_type": "dedupe_only",
                "blocking_rules_to_generate_predictions": [
                    "l.first_name = r.first_name",
                    "l.surname = r.surname",
                ],
                "comparisons": []
            }
            >>>
            linker = DuckDBLinker(df, settings)
            df = linker.deterministic_link()
            ```
            === "Spark"
            ```py
            from splink.spark.spark_linker import SparkLinker

            settings = {
                "link_type": "dedupe_only",
                "blocking_rules_to_generate_predictions": [
                    "l.first_name = r.first_name",
                    "l.surname = r.surname",
                ],
                "comparisons": []
            }
            >>>
            linker = SparkLinker(df, settings)
            df = linker.deterministic_link()
            ```
            === "Athena"
            ```py
            from splink.athena.athena_linker import AthenaLinker

            settings = {
                "link_type": "dedupe_only",
                "blocking_rules_to_generate_predictions": [
                    "l.first_name = r.first_name",
                    "l.surname = r.surname",
                ],
                "comparisons": []
            }
            >>>
            linker = AthenaLinker(df, settings)
            df = linker.deterministic_link()
            ```
            === "SQLite"
            ```py
            from splink.sqlite.sqlite_linker import SQLiteLinker

            settings = {
                "link_type": "dedupe_only",
                "blocking_rules_to_generate_predictions": [
                    "l.first_name = r.first_name",
                    "l.surname = r.surname",
                ],
                "comparisons": []
            }
            >>>
            linker = SQLiteLinker(df, settings)
            df = linker.deterministic_link()
            ```

        Returns:
            SplinkDataFrame: A SplinkDataFrame of the pairwise comparisons.  This
                represents a table materialised in the database. Methods on the
                SplinkDataFrame allow you to access the underlying data.
        """

        # Allows clustering during a deterministic linkage.
        # This is used in `cluster_pairwise_predictions_at_threshold`
        # to set the cluster threshold to 1
        self._deterministic_link_mode = True

        concat_with_tf = self._initialise_df_concat_with_tf()
        sql = block_using_rules_sql(self)
        self._enqueue_sql(sql, "__splink__df_blocked")
        return self._execute_sql_pipeline([concat_with_tf])

    def estimate_u_using_random_sampling(
        self, max_pairs: int = None, seed: int = None, *, target_rows=None
    ):
        """Estimate the u parameters of the linkage model using random sampling.

        The u parameters represent the proportion of record comparisons that fall
        into each comparison level amongst truly non-matching records.

        This procedure takes a sample of the data and generates the cartesian
        product of pairwise record comparisons amongst the sampled records.
        The validity of the u values rests on the assumption that the resultant
        pairwise comparisons are non-matches (or at least, they are very unlikely to be
        matches). For large datasets, this is typically true.

        The results of estimate_u_using_random_sampling, and therefore an entire splink
        model, can be made reproducible by setting the seed parameter. Setting the seed
        will have performance implications as additional processing is required.

        Args:
            max_pairs (int): The maximum number of pairwise record comparisons to
            sample. Larger will give more accurate estimates
            but lead to longer runtimes.  In our experience at least 1e9 (one billion)
            gives best results but can take a long time to compute. 1e7 (ten million)
            is often adequate whilst testing different model specifications, before
            the final model is estimated.
            seed (int): Seed for random sampling. Assign to get reproducible u
            probabilities. Note, seed for random sampling is only supported for
            DuckDB and Spark, for Athena and SQLite set to None.

        Examples:
            ```py
            linker.estimate_u_using_random_sampling(1e8)
            ```

        Returns:
            None: Updates the estimated u parameters within the linker object
            and returns nothing.
        """
        # TODO: Remove this compatibility code in a future release once we drop
        # support for "target_rows". Deprecation warning added in 3.7.0
        if max_pairs is not None and target_rows is not None:
            # user supplied both
            raise TypeError("Just use max_pairs")
        elif max_pairs is not None:
            # user is doing it correctly
            pass
        elif target_rows is not None:
            # user is using deprecated argument
            warnings.warn(
                "target_rows is deprecated; use max_pairs",
                DeprecationWarning,
                stacklevel=2,
            )
            max_pairs = target_rows
        else:
            raise TypeError("Missing argument max_pairs")

        estimate_u_values(self, max_pairs, seed)
        self._populate_m_u_from_trained_values()

        self._settings_obj._columns_without_estimated_parameters_message()

    def estimate_m_from_label_column(self, label_colname: str):
        """Estimate the m parameters of the linkage model from a label (ground truth)
        column in the input dataframe(s).

        The m parameters represent the proportion of record comparisons that fall
        into each comparison level amongst truly matching records.

        The ground truth column is used to generate pairwise record comparisons
        which are then assumed to be matches.

        For example, if the entity being matched is persons, and your input dataset(s)
        contain social security number, this could be used to estimate the m values
        for the model.

        Note that this column does not need to be fully populated.  A common case is
        where a unique identifier such as social security number is only partially
        populated.

        Args:
            label_colname (str): The name of the column containing the ground truth
                label in the input data.

        Examples:
            ```py
            linker.estimate_m_from_label_column("social_security_number")
            ```

        Returns:
            Updates the estimated m parameters within the linker object
            and returns nothing.
        """

        # Ensure this has been run on the main linker so that it can be used by
        # training linked when it checks the cache
        self._initialise_df_concat_with_tf()
        estimate_m_values_from_label_column(
            self,
            self._input_tables_dict,
            label_colname,
        )
        self._populate_m_u_from_trained_values()

        self._settings_obj._columns_without_estimated_parameters_message()

    def estimate_parameters_using_expectation_maximisation(
        self,
        blocking_rule: str,
        comparisons_to_deactivate: list[str | Comparison] = None,
        comparison_levels_to_reverse_blocking_rule: list[ComparisonLevel] = None,
        fix_probability_two_random_records_match: bool = False,
        fix_m_probabilities=False,
        fix_u_probabilities=True,
        populate_probability_two_random_records_match_from_trained_values=False,
    ) -> EMTrainingSession:
        """Estimate the parameters of the linkage model using expectation maximisation.

        By default, the m probabilities are estimated, but not the u probabilities,
        because good estimates for the u probabilities can be obtained from
        `linker.estimate_u_using_random_sampling()`.  You can change this by setting
        `fix_u_probabilities` to False.

        The blocking rule provided is used to generate pairwise record comparisons.
        Usually, this should be a blocking rule that results in a dataframe where
        matches are between about 1% and 99% of the comparisons.

        By default, m parameters are estimated for all comparisons except those which
        are included in the blocking rule.

        For example, if the blocking rule is `l.first_name = r.first_name`, then
        parameter esimates will be made for all comparison except those which use
        `first_name` in their sql_condition

        By default, the probability two random records match is estimated for the
        blocked data, and then the m and u parameters for the columns specified in the
        blocking rules are used to estiamte the global probability two random records
        match.

        To control which comparisons should have their parameter estimated, and the
        process of 'reversing out' the global probability two random records match, the
        user may specify `comparisons_to_deactivate` and
        `comparison_levels_to_reverse_blocking_rule`.   This is useful, for example
        if you block on the dmetaphone of a column but match on the original column.

        Examples:
            Default behaviour
            ```py
            br_training = "l.first_name = r.first_name and l.dob = r.dob"
            linker.estimate_parameters_using_expectation_maximisation(br_training)
            ```
            Specify which comparisons to deactivate
            ```py
            br_training = "l.dmeta_first_name = r.dmeta_first_name"
            settings_obj = linker._settings_obj
            comp = settings_obj._get_comparison_by_output_column_name("first_name")
            dmeta_level = comp._get_comparison_level_by_comparison_vector_value(1)
            linker.estimate_parameters_using_expectation_maximisation(
                br_training,
                comparisons_to_deactivate=["first_name"],
                comparison_levels_to_reverse_blocking_rule=[dmeta_level],
            )
            ```

        Args:
            blocking_rule (str): The blocking rule used to generate pairwise record
                comparisons.
            comparisons_to_deactivate (list, optional): By default, splink will
                analyse the blocking rule provided and estimate the m parameters for
                all comaprisons except those included in the blocking rule.  If
                comparisons_to_deactivate are provided, spink will instead
                estimate m parameters for all comparison except those specified
                in the comparisons_to_deactivate list.  This list can either contain
                the output_column_name of the Comparison as a string, or Comparison
                objects.  Defaults to None.
            comparison_levels_to_reverse_blocking_rule (list, optional): By default,
                splink will analyse the blocking rule provided and adjust the
                global probability two random records match to account for the matches
                specified in the blocking rule. If provided, this argument will overrule
                this default behaviour. The user must provide a list of ComparisonLevel
                objects.  Defaults to None.
            fix_probability_two_random_records_match (bool, optional): If True, do not
                update the probability two random records match after each iteration.
                Defaults to False.
            fix_m_probabilities (bool, optional): If True, do not update the m
                probabilities after each iteration. Defaults to False.
            fix_u_probabilities (bool, optional): If True, do not update the u
                probabilities after each iteration. Defaults to True.
            populate_probability_two_random_records_match_from_trained_values
                (bool, optional): If True, derive this parameter from
                the blocked value. Defaults to False.

        Examples:
            ```py
            blocking_rule = "l.first_name = r.first_name and l.dob = r.dob"
            linker.estimate_parameters_using_expectation_maximisation(blocking_rule)
            ```

        Returns:
            EMTrainingSession:  An object containing information about the training
                session such as how parameters changed during the iteration history

        """
        # Ensure this has been run on the main linker so that it's in the cache
        # to be used by the training linkers
        self._initialise_df_concat_with_tf()

        if comparisons_to_deactivate:
            # If user provided a string, convert to Comparison object
            comparisons_to_deactivate = [
                self._settings_obj._get_comparison_by_output_column_name(n)
                if isinstance(n, str)
                else n
                for n in comparisons_to_deactivate
            ]
            if comparison_levels_to_reverse_blocking_rule is None:
                logger.warning(
                    "\nWARNING: \n"
                    "You have provided comparisons_to_deactivate but not "
                    "comparison_levels_to_reverse_blocking_rule.\n"
                    "If comparisons_to_deactivate is provided, then "
                    "you usually need to provide corresponding "
                    "comparison_levels_to_reverse_blocking_rule "
                    "because each comparison to deactivate is effectively treated "
                    "as an exact match."
                )

        em_training_session = EMTrainingSession(
            self,
            blocking_rule,
            fix_u_probabilities=fix_u_probabilities,
            fix_m_probabilities=fix_m_probabilities,
            fix_probability_two_random_records_match=fix_probability_two_random_records_match,  # noqa 501
            comparisons_to_deactivate=comparisons_to_deactivate,
            comparison_levels_to_reverse_blocking_rule=comparison_levels_to_reverse_blocking_rule,  # noqa 501
        )

        em_training_session._train()

        self._populate_m_u_from_trained_values()

        if populate_probability_two_random_records_match_from_trained_values:
            self._populate_probability_two_random_records_match_from_trained_values()

        self._settings_obj._columns_without_estimated_parameters_message()

        return em_training_session

    def predict(
        self,
        threshold_match_probability: float = None,
        threshold_match_weight: float = None,
        materialise_after_computing_term_frequencies=True,
    ) -> SplinkDataFrame:
        """Create a dataframe of scored pairwise comparisons using the parameters
        of the linkage model.

        Uses the blocking rules specified in the
        `blocking_rules_to_generate_predictions` of the settings dictionary to
        generate the pairwise comparisons.

        Args:
            threshold_match_probability (float, optional): If specified,
                filter the results to include only pairwise comparisons with a
                match_probability above this threshold. Defaults to None.
            threshold_match_weight (float, optional): If specified,
                filter the results to include only pairwise comparisons with a
                match_weight above this threshold. Defaults to None.
            materialise_after_computing_term_frequencies (bool): If true, Splink
                will materialise the table containing the input nodes (rows)
                joined to any term frequencies which have been asked
                for in the settings object.  If False, this will be
                computed as part of one possibly gigantic CTE
                pipeline.   Defaults to True

        Examples:
            ```py
            linker = DuckDBLinker(df)
            linker.load_settings("saved_settings.json")
            df = linker.predict(threshold_match_probability=0.95)
            df.as_pandas_dataframe(limit=5)
            ```
        Returns:
            SplinkDataFrame: A SplinkDataFrame of the pairwise comparisons.  This
                represents a table materialised in the database. Methods on the
                SplinkDataFrame allow you to access the underlying data.

        """

        # If materialise_after_computing_term_frequencies=False and the user only
        # calls predict, it runs as a single pipeline with no materialisation
        # of anything.

        # _initialise_df_concat_with_tf returns None if the table doesn't exist
        # and only SQL is queued in this step.
        nodes_with_tf = self._initialise_df_concat_with_tf(
            materialise=materialise_after_computing_term_frequencies
        )

        input_dataframes = []
        if nodes_with_tf:
            input_dataframes.append(nodes_with_tf)

        sql = block_using_rules_sql(self)
        self._enqueue_sql(sql, "__splink__df_blocked")

        repartition_after_blocking = getattr(self, "repartition_after_blocking", False)

        # repartition after blocking only exists on the SparkLinker
        if repartition_after_blocking:
            df_blocked = self._execute_sql_pipeline(input_dataframes)
            input_dataframes.append(df_blocked)

        sql = compute_comparison_vector_values_sql(self._settings_obj)
        self._enqueue_sql(sql, "__splink__df_comparison_vectors")

        sqls = predict_from_comparison_vectors_sqls(
            self._settings_obj,
            threshold_match_probability,
            threshold_match_weight,
            sql_infinity_expression=self._infinity_expression,
        )
        for sql in sqls:
            self._enqueue_sql(sql["sql"], sql["output_table_name"])

        predictions = self._execute_sql_pipeline(input_dataframes)
        self._predict_warning()
        return predictions

    def find_matches_to_new_records(
        self,
        records_or_tablename,
        blocking_rules=[],
        match_weight_threshold=-4,
    ) -> SplinkDataFrame:
        """Given one or more records, find records in the input dataset(s) which match
        and return in order of the splink prediction score.

        This effectively provides a way of searching the input datasets
        for given record(s)

        Args:
            records_or_tablename (List[dict]): Input search record(s) as list of dict,
                or a table registered to the database.
            blocking_rules (list, optional): Blocking rules to select
                which records to find and score. If [], do not use a blocking
                rule - meaning the input records will be compared to all records
                provided to the linker when it was instantiated. Defaults to [].
            match_weight_threshold (int, optional): Return matches with a match weight
                above this threshold. Defaults to -4.

        Examples:
            ```py
            linker = DuckDBLinker(df)
            linker.load_settings("saved_settings.json")
            # Pre-compute tf tables for any tables with
            # term frequency adjustments
            linker.compute_tf_table("first_name")
            record = {'unique_id': 1,
                'first_name': "John",
                'surname': "Smith",
                'dob': "1971-05-24",
                'city': "London",
                'email': "john@smith.net"
                }
            df = linker.find_matches_to_new_records([record], blocking_rules=[])
            ```

        Returns:
            SplinkDataFrame: The pairwise comparisons.
        """

        original_blocking_rules = (
            self._settings_obj._blocking_rules_to_generate_predictions
        )
        original_link_type = self._settings_obj._link_type

        if not isinstance(records_or_tablename, str):
            uid = ascii_uid(8)
            self.register_table(
                records_or_tablename, f"__splink__df_new_records_{uid}", overwrite=True
            )
            new_records_tablename = f"__splink__df_new_records_{uid}"
        else:
            new_records_tablename = records_or_tablename

        cache = self._intermediate_table_cache
        input_dfs = []
        # If our df_concat_with_tf table already exists, use backwards inference to
        # find all underlying term frequency tables.
        if "__splink__df_concat_with_tf" in cache:
            concat_with_tf = cache["__splink__df_concat_with_tf"]
            tf_tables = compute_term_frequencies_from_concat_with_tf(self)
            # This queues up our tf tables, rather materialising them
            for tf in tf_tables:
                # if tf is a SplinkDataFrame, then the table already exists
                if isinstance(tf, SplinkDataFrame):
                    input_dfs.append(tf)
                else:
                    self._enqueue_sql(tf["sql"], tf["output_table_name"])
        else:
            # This queues up our cols_with_tf and df_concat_with_tf tables.
            concat_with_tf = self._initialise_df_concat_with_tf(materialise=False)

        if concat_with_tf:
            input_dfs.append(concat_with_tf)

        rules = []
        for r in blocking_rules:
            br_as_obj = BlockingRule(r) if not isinstance(r, BlockingRule) else r
            br_as_obj.preceding_rules = rules.copy()
            rules.append(br_as_obj)
        blocking_rules = rules

        self._settings_obj._blocking_rules_to_generate_predictions = blocking_rules

        self._settings_obj._link_type = "link_only_find_matches_to_new_records"
        self._find_new_matches_mode = True

        sql = _join_tf_to_input_df_sql(self)
        sql = sql.replace("__splink__df_concat", new_records_tablename)
        self._enqueue_sql(sql, "__splink__df_new_records_with_tf")

        sql = block_using_rules_sql(self)
        self._enqueue_sql(sql, "__splink__df_blocked")

        sql = compute_comparison_vector_values_sql(self._settings_obj)
        self._enqueue_sql(sql, "__splink__df_comparison_vectors")

        sqls = predict_from_comparison_vectors_sqls(
            self._settings_obj,
            sql_infinity_expression=self._infinity_expression,
        )
        for sql in sqls:
            self._enqueue_sql(sql["sql"], sql["output_table_name"])

        sql = f"""
        select * from __splink__df_predict
        where match_weight > {match_weight_threshold}
        """

        self._enqueue_sql(sql, "__splink__find_matches_predictions")

        predictions = self._execute_sql_pipeline(
            input_dataframes=input_dfs, use_cache=False
        )

        self._settings_obj._blocking_rules_to_generate_predictions = (
            original_blocking_rules
        )
        self._settings_obj._link_type = original_link_type
        self._find_new_matches_mode = False

        return predictions

    def compare_two_records(self, record_1: dict, record_2: dict):
        """Use the linkage model to compare and score a pairwise record comparison
        based on the two input records provided

        Args:
            record_1 (dict): dictionary representing the first record.  Columns names
                and data types must be the same as the columns in the settings object
            record_2 (dict): dictionary representing the second record.  Columns names
                and data types must be the same as the columns in the settings object

        Examples:
            ```py
            linker = DuckDBLinker(df)
            linker.load_settings("saved_settings.json")
            linker.compare_two_records(record_left, record_right)
            ```

        Returns:
            SplinkDataFrame: Pairwise comparison with scored prediction
        """
        original_blocking_rules = (
            self._settings_obj._blocking_rules_to_generate_predictions
        )
        original_link_type = self._settings_obj._link_type

        self._compare_two_records_mode = True
        self._settings_obj._blocking_rules_to_generate_predictions = []

        uid = ascii_uid(8)
        df_records_left = self.register_table(
            [record_1], f"__splink__compare_two_records_left_{uid}", overwrite=True
        )
        df_records_left.templated_name = "__splink__compare_two_records_left"

        df_records_right = self.register_table(
            [record_2], f"__splink__compare_two_records_right_{uid}", overwrite=True
        )
        df_records_right.templated_name = "__splink__compare_two_records_right"

        sql_join_tf = _join_tf_to_input_df_sql(self)

        sql_join_tf = sql_join_tf.replace(
            "__splink__df_concat", "__splink__compare_two_records_left"
        )
        self._enqueue_sql(sql_join_tf, "__splink__compare_two_records_left_with_tf")

        sql_join_tf = sql_join_tf.replace(
            "__splink__compare_two_records_left", "__splink__compare_two_records_right"
        )

        self._enqueue_sql(sql_join_tf, "__splink__compare_two_records_right_with_tf")

        sql = block_using_rules_sql(self)
        self._enqueue_sql(sql, "__splink__df_blocked")

        sql = compute_comparison_vector_values_sql(self._settings_obj)
        self._enqueue_sql(sql, "__splink__df_comparison_vectors")

        sqls = predict_from_comparison_vectors_sqls(
            self._settings_obj,
            sql_infinity_expression=self._infinity_expression,
        )
        for sql in sqls:
            self._enqueue_sql(sql["sql"], sql["output_table_name"])

        predictions = self._execute_sql_pipeline(
            [df_records_left, df_records_right], use_cache=False
        )

        self._settings_obj._blocking_rules_to_generate_predictions = (
            original_blocking_rules
        )
        self._settings_obj._link_type = original_link_type
        self._compare_two_records_mode = False

        return predictions

    def _self_link(self) -> SplinkDataFrame:
        """Use the linkage model to compare and score all records in our input df with
            themselves.

        Returns:
            SplinkDataFrame: Scored pairwise comparisons of the input records to
                themselves.
        """

        original_blocking_rules = (
            self._settings_obj._blocking_rules_to_generate_predictions
        )
        original_link_type = self._settings_obj._link_type

        # Changes our sql to allow for a self link.
        # This is used in `_sql_gen_where_condition` in blocking.py
        # to remove any 'where' clauses when blocking (normally when blocking
        # we want to *remove* self links!)
        self._self_link_mode = True

        # Block on uid i.e. create pairwise record comparisons where the uid matches
        uid_cols = self._settings_obj._unique_id_input_columns
        uid_l = _composite_unique_id_from_edges_sql(uid_cols, None, "l")
        uid_r = _composite_unique_id_from_edges_sql(uid_cols, None, "r")

        self._settings_obj._blocking_rules_to_generate_predictions = [
            BlockingRule(f"{uid_l} = {uid_r}")
        ]

        nodes_with_tf = self._initialise_df_concat_with_tf()

        sql = block_using_rules_sql(self)

        self._enqueue_sql(sql, "__splink__df_blocked")

        sql = compute_comparison_vector_values_sql(self._settings_obj)

        self._enqueue_sql(sql, "__splink__df_comparison_vectors")

        sqls = predict_from_comparison_vectors_sqls(
            self._settings_obj,
            sql_infinity_expression=self._infinity_expression,
        )
        for sql in sqls:
            output_table_name = sql["output_table_name"]
            output_table_name = output_table_name.replace("predict", "self_link")
            self._enqueue_sql(sql["sql"], output_table_name)

        predictions = self._execute_sql_pipeline(
            input_dataframes=[nodes_with_tf], use_cache=False
        )

        self._settings_obj._blocking_rules_to_generate_predictions = (
            original_blocking_rules
        )
        self._settings_obj._link_type = original_link_type
        self._self_link_mode = False

        return predictions

    def cluster_pairwise_predictions_at_threshold(
        self,
        df_predict: SplinkDataFrame,
        threshold_match_probability: float = None,
        pairwise_formatting: bool = False,
        filter_pairwise_format_for_clusters: bool = True,
    ) -> SplinkDataFrame:
        """Clusters the pairwise match predictions that result from `linker.predict()`
        into groups of connected record using the connected components graph clustering
        algorithm

        Records with an estimated `match_probability` above
        `threshold_match_probability` are considered to be a match (i.e. they represent
        the same entity).

        Args:
            df_predict (SplinkDataFrame): The results of `linker.predict()`
            threshold_match_probability (float): Filter the pairwise match predictions
                to include only pairwise comparisons with a match_probability above this
                threshold. This dataframe is then fed into the clustering
                algorithm.
            pairwise_formatting (bool): Whether to output the pairwise match predictions
                from linker.predict() with cluster IDs.
                If this is set to false, the output will be a list of all IDs, clustered
                into groups based on the desired match threshold.
            filter_pairwise_format_for_clusters (bool): If pairwise formatting has been
                selected, whether to output all columns found within linker.predict(),
                or just return clusters.

        Returns:
            SplinkDataFrame: A SplinkDataFrame containing a list of all IDs, clustered
                into groups based on the desired match threshold.

        """

        # Feeding in df_predict forces materiailisation, if it exists in your database
        concat_with_tf = self._initialise_df_concat_with_tf(df_predict)

        edges_table = _cc_create_unique_id_cols(
            self,
            concat_with_tf.physical_name,
            df_predict.physical_name,
            threshold_match_probability,
        )

        cc = solve_connected_components(
            self,
            edges_table,
            df_predict,
            concat_with_tf,
            pairwise_formatting,
            filter_pairwise_format_for_clusters,
        )

        return cc

    def profile_columns(
        self, column_expressions: str | list[str], top_n=10, bottom_n=10
    ):
        return profile_columns(self, column_expressions, top_n=top_n, bottom_n=bottom_n)

    def _get_labels_tablename_from_input(
        self, labels_splinkdataframe_or_table_name: str | SplinkDataFrame
    ):
        if isinstance(labels_splinkdataframe_or_table_name, SplinkDataFrame):
            labels_tablename = labels_splinkdataframe_or_table_name.physical_name
        elif isinstance(labels_splinkdataframe_or_table_name, str):
            labels_tablename = labels_splinkdataframe_or_table_name
        else:
            raise ValueError(
                "The 'labels_splinkdataframe_or_table_name' argument"
                " must be of type SplinkDataframe or a string representing a tablename"
                " in the input database"
            )
        return labels_tablename

    def estimate_m_from_pairwise_labels(self, labels_splinkdataframe_or_table_name):
        """Estimate the m parameters of the linkage model from a dataframe of pairwise
        labels.

        The table of labels should be in the following format, and should
        be registered with your database:
        |source_dataset_l|unique_id_l|source_dataset_r|unique_id_r|
        |----------------|-----------|----------------|-----------|
        |df_1            |1          |df_2            |2          |
        |df_1            |1          |df_2            |3          |

        Note that `source_dataset` and `unique_id` should correspond to the
        values specified in the settings dict, and the `input_table_aliases`
        passed to the `linker` object. Note that at the moment, this method does
        not respect values in a `clerical_match_score` column.  If provided, these
        are ignored and it is assumed that every row in the table of labels is a score
        of 1, i.e. a perfect match.

        Args:
          labels_splinkdataframe_or_table_name (str): Name of table containing labels
            in the database or SplinkDataframe

        Examples:
            ```py
            pairwise_labels = pd.read_csv("./data/pairwise_labels_to_estimate_m.csv")
            linker.register_table(pairwise_labels, "labels", overwrite=True)
            linker.estimate_m_from_pairwise_labels("labels")
            ```
        """
        labels_tablename = self._get_labels_tablename_from_input(
            labels_splinkdataframe_or_table_name
        )
        estimate_m_from_pairwise_labels(self, labels_tablename)

    def truth_space_table_from_labels_table(
        self,
        labels_splinkdataframe_or_table_name,
        threshold_actual=0.5,
        match_weight_round_to_nearest: float = None,
    ) -> SplinkDataFrame:
        """Generate truth statistics (false positive etc.) for each threshold value of
        match_probability, suitable for plotting a ROC chart.

        The table of labels should be in the following format, and should be registered
        with your database:

        |source_dataset_l|unique_id_l|source_dataset_r|unique_id_r|clerical_match_score|
        |----------------|-----------|----------------|-----------|--------------------|
        |df_1            |1          |df_2            |2          |0.99                |
        |df_1            |1          |df_2            |3          |0.2                 |

        Note that `source_dataset` and `unique_id` should correspond to the values
        specified in the settings dict, and the `input_table_aliases` passed to the
        `linker` object.

        For `dedupe_only` links, the `source_dataset` columns can be ommitted.

        Args:
            labels_splinkdataframe_or_table_name (str | SplinkDataFrame): Name of table
                containing labels in the database
            threshold_actual (float, optional): Where the `clerical_match_score`
                provided by the user is a probability rather than binary, this value
                is used as the threshold to classify `clerical_match_score`s as binary
                matches or non matches. Defaults to 0.5.
            match_weight_round_to_nearest (float, optional): When provided, thresholds
                are rounded.  When large numbers of labels are provided, this is
                sometimes necessary to reduce the size of the ROC table, and therefore
                the number of points plotted on the ROC chart. Defaults to None.

        Examples:
            === "DuckDB"
                ```py
                labels = pd.read_csv("my_labels.csv")
                linker.register_table(labels, "labels")
                linker.truth_space_table_from_labels_table("labels")
                ```
            === "Spark"
                ```py
                labels = spark.read.csv("my_labels.csv", header=True)
                labels.createDataFrame("labels")
                linker.truth_space_table_from_labels_table("labels")
                ```
        Returns:
            SplinkDataFrame:  Table of truth statistics
        """
        labels_tablename = self._get_labels_tablename_from_input(
            labels_splinkdataframe_or_table_name
        )

        self._raise_error_if_necessary_accuracy_columns_not_computed()
        return truth_space_table_from_labels_table(
            self,
            labels_tablename,
            threshold_actual=threshold_actual,
            match_weight_round_to_nearest=match_weight_round_to_nearest,
        )

    def roc_chart_from_labels_table(
        self,
        labels_splinkdataframe_or_table_name: str | SplinkDataFrame,
        threshold_actual=0.5,
        match_weight_round_to_nearest: float = None,
    ):
        """Generate a ROC chart from labelled (ground truth) data.

        The table of labels should be in the following format, and should be registered
        with your database:

        |source_dataset_l|unique_id_l|source_dataset_r|unique_id_r|clerical_match_score|
        |----------------|-----------|----------------|-----------|--------------------|
        |df_1            |1          |df_2            |2          |0.99                |
        |df_1            |1          |df_2            |3          |0.2                 |

        Note that `source_dataset` and `unique_id` should correspond to the values
        specified in the settings dict, and the `input_table_aliases` passed to the
        `linker` object.

        For `dedupe_only` links, the `source_dataset` columns can be ommitted.

        Args:
            labels_splinkdataframe_or_table_name (str | SplinkDataFrame): Name of table
                containing labels in the database
            threshold_actual (float, optional): Where the `clerical_match_score`
                provided by the user is a probability rather than binary, this value
                is used as the threshold to classify `clerical_match_score`s as binary
                matches or non matches. Defaults to 0.5.
            match_weight_round_to_nearest (float, optional): When provided, thresholds
                are rounded.  When large numbers of labels are provided, this is
                sometimes necessary to reduce the size of the ROC table, and therefore
                the number of points plotted on the ROC chart. Defaults to None.

        Examples:
            === "DuckDB"
                ```py
                labels = pd.read_csv("my_labels.csv")
                linker.register_table(labels, "labels")
                linker.roc_chart_from_labels_table("labels")
                ```
            === "Spark"
                ```py
                labels = spark.read.csv("my_labels.csv", header=True)
                labels.createDataFrame("labels")
                linker.roc_chart_from_labels_table("labels")
                ```

        Returns:
            VegaLite: A VegaLite chart object. See altair.vegalite.v4.display.VegaLite.
                The vegalite spec is available as a dictionary using the `spec`
                attribute.
        """
        labels_tablename = self._get_labels_tablename_from_input(
            labels_splinkdataframe_or_table_name
        )

        self._raise_error_if_necessary_accuracy_columns_not_computed()
        df_truth_space = truth_space_table_from_labels_table(
            self,
            labels_tablename,
            threshold_actual=threshold_actual,
            match_weight_round_to_nearest=match_weight_round_to_nearest,
        )
        recs = df_truth_space.as_record_dict()
        return roc_chart(recs)

    def precision_recall_chart_from_labels_table(
        self,
        labels_splinkdataframe_or_table_name,
        threshold_actual=0.5,
        match_weight_round_to_nearest: float = None,
    ):
        """Generate a precision-recall chart from labelled (ground truth) data.

        The table of labels should be in the following format, and should be registered
        as a table with your database:

        |source_dataset_l|unique_id_l|source_dataset_r|unique_id_r|clerical_match_score|
        |----------------|-----------|----------------|-----------|--------------------|
        |df_1            |1          |df_2            |2          |0.99                |
        |df_1            |1          |df_2            |3          |0.2                 |

        Note that `source_dataset` and `unique_id` should correspond to the values
        specified in the settings dict, and the `input_table_aliases` passed to the
        `linker` object.

        For `dedupe_only` links, the `source_dataset` columns can be ommitted.

        Args:
            labels_splinkdataframe_or_table_name (str | SplinkDataFrame): Name of table
                containing labels in the database
            threshold_actual (float, optional): Where the `clerical_match_score`
                provided by the user is a probability rather than binary, this value
                is used as the threshold to classify `clerical_match_score`s as binary
                matches or non matches. Defaults to 0.5.
            match_weight_round_to_nearest (float, optional): When provided, thresholds
                are rounded.  When large numbers of labels are provided, this is
                sometimes necessary to reduce the size of the ROC table, and therefore
                the number of points plotted on the ROC chart. Defaults to None.
        Examples:
            === "DuckDB"
                ```py
                labels = pd.read_csv("my_labels.csv")
                linker.register_table(labels, "labels")
                linker.precision_recall_chart_from_labels_table("labels")
                ```
            === "Spark"
                ```py
                labels = spark.read.csv("my_labels.csv", header=True)
                labels.createDataFrame("labels")
                linker.precision_recall_chart_from_labels_table("labels")
                ```

        Returns:
            VegaLite: A VegaLite chart object. See altair.vegalite.v4.display.VegaLite.
                The vegalite spec is available as a dictionary using the `spec`
                attribute.
        """
        labels_tablename = self._get_labels_tablename_from_input(
            labels_splinkdataframe_or_table_name
        )
        self._raise_error_if_necessary_accuracy_columns_not_computed()
        df_truth_space = truth_space_table_from_labels_table(
            self,
            labels_tablename,
            threshold_actual=threshold_actual,
            match_weight_round_to_nearest=match_weight_round_to_nearest,
        )
        recs = df_truth_space.as_record_dict()
        return precision_recall_chart(recs)

    def prediction_errors_from_labels_table(
        self,
        labels_splinkdataframe_or_table_name,
        include_false_positives=True,
        include_false_negatives=True,
        threshold=0.5,
    ):
        """Generate a dataframe containing false positives and false negatives
        based on the comparison between the clerical_match_score in the labels
        table compared with the splink predicted match probability

        Args:
            labels_splinkdataframe_or_table_name (str | SplinkDataFrame): Name of table
                containing labels in the database
            include_false_positives (bool, optional): Defaults to True.
            include_false_negatives (bool, optional): Defaults to True.
            threshold (float, optional): Threshold above which a score is considered
                to be a match. Defaults to 0.5.

        Returns:
            SplinkDataFrame:  Table containing false positives and negatives
        """
        labels_tablename = self._get_labels_tablename_from_input(
            labels_splinkdataframe_or_table_name
        )
        return prediction_errors_from_labels_table(
            self,
            labels_tablename,
            include_false_positives,
            include_false_negatives,
            threshold,
        )

    def truth_space_table_from_labels_column(
        self,
        labels_column_name,
        threshold_actual=0.5,
        match_weight_round_to_nearest: float = None,
    ):
        """Generate truth statistics (false positive etc.) for each threshold value of
        match_probability, suitable for plotting a ROC chart.

        Your labels_column_name should include the ground truth cluster (unique
        identifier) that groups entities which are the same

        Args:
            labels_tablename (str): Name of table containing labels in the database
            threshold_actual (float, optional): Where the `clerical_match_score`
                provided by the user is a probability rather than binary, this value
                is used as the threshold to classify `clerical_match_score`s as binary
                matches or non matches. Defaults to 0.5.
            match_weight_round_to_nearest (float, optional): When provided, thresholds
                are rounded.  When large numbers of labels are provided, this is
                sometimes necessary to reduce the size of the ROC table, and therefore
                the number of points plotted on the ROC chart. Defaults to None.

        Examples:
            ```py
            linker.truth_space_table_from_labels_column("cluster")
            ```

        Returns:
            SplinkDataFrame:  Table of truth statistics
        """

        return truth_space_table_from_labels_column(
            self, labels_column_name, threshold_actual, match_weight_round_to_nearest
        )

    def roc_chart_from_labels_column(
        self,
        labels_column_name,
        threshold_actual=0.5,
        match_weight_round_to_nearest: float = None,
    ):
        """Generate a ROC chart from ground truth data, whereby the ground truth
        is in a column in the input dataset called `labels_column_name`

        Args:
            labels_column_name (str): Column name containing labels in the input table
            threshold_actual (float, optional): Where the `clerical_match_score`
                provided by the user is a probability rather than binary, this value
                is used as the threshold to classify `clerical_match_score`s as binary
                matches or non matches. Defaults to 0.5.
            match_weight_round_to_nearest (float, optional): When provided, thresholds
                are rounded.  When large numbers of labels are provided, this is
                sometimes necessary to reduce the size of the ROC table, and therefore
                the number of points plotted on the ROC chart. Defaults to None.

        Examples:
            ```py
            linker.roc_chart_from_labels_column("labels")
            ```

        Returns:
            VegaLite: A VegaLite chart object. See altair.vegalite.v4.display.VegaLite.
                The vegalite spec is available as a dictionary using the `spec`
                attribute.
        """

        df_truth_space = truth_space_table_from_labels_column(
            self,
            labels_column_name,
            threshold_actual=threshold_actual,
            match_weight_round_to_nearest=match_weight_round_to_nearest,
        )
        recs = df_truth_space.as_record_dict()
        return roc_chart(recs)

    def precision_recall_chart_from_labels_column(
        self,
        labels_column_name,
        threshold_actual=0.5,
        match_weight_round_to_nearest: float = None,
    ):
        """Generate a precision-recall chart from ground truth data, whereby the ground
        truth is in a column in the input dataset called `labels_column_name`

        Args:
            labels_column_name (str): Column name containing labels in the input table
            threshold_actual (float, optional): Where the `clerical_match_score`
                provided by the user is a probability rather than binary, this value
                is used as the threshold to classify `clerical_match_score`s as binary
                matches or non matches. Defaults to 0.5.
            match_weight_round_to_nearest (float, optional): When provided, thresholds
                are rounded.  When large numbers of labels are provided, this is
                sometimes necessary to reduce the size of the ROC table, and therefore
                the number of points plotted on the ROC chart. Defaults to None.
        Examples:
            ```py
            linker.precision_recall_chart_from_labels_column("ground_truth")
            ```

        Returns:
            VegaLite: A VegaLite chart object. See altair.vegalite.v4.display.VegaLite.
                The vegalite spec is available as a dictionary using the `spec`
                attribute.
        """

        df_truth_space = truth_space_table_from_labels_column(
            self,
            labels_column_name,
            threshold_actual=threshold_actual,
            match_weight_round_to_nearest=match_weight_round_to_nearest,
        )
        recs = df_truth_space.as_record_dict()
        return precision_recall_chart(recs)

    def prediction_errors_from_labels_column(
        self,
        label_colname,
        include_false_positives=True,
        include_false_negatives=True,
        threshold=0.5,
    ):
        """Generate a dataframe containing false positives and false negatives
        based on the comparison between the splink match probability and the
        labels column.  A label column is a column in the input dataset that contains
        the 'ground truth' cluster to which the record belongs

        Args:
            label_colname (str): Name of labels column in input data
            include_false_positives (bool, optional): Defaults to True.
            include_false_negatives (bool, optional): Defaults to True.
            threshold (float, optional): Threshold above which a score is considered
                to be a match. Defaults to 0.5.

        Returns:
            SplinkDataFrame:  Table containing false positives and negatives
        """
        return prediction_errors_from_label_column(
            self,
            label_colname,
            include_false_positives,
            include_false_negatives,
            threshold,
        )

    def match_weights_histogram(
        self, df_predict: SplinkDataFrame, target_bins: int = 30, width=600, height=250
    ):
        """Generate a histogram that shows the distribution of match weights in
        `df_predict`

        Args:
            df_predict (SplinkDataFrame): Output of `linker.predict()`
            target_bins (int, optional): Target number of bins in histogram. Defaults to
                30.
            width (int, optional): Width of output. Defaults to 600.
            height (int, optional): Height of output chart. Defaults to 250.


        Returns:
            VegaLite: A VegaLite chart object. See altair.vegalite.v4.display.VegaLite.
                The vegalite spec is available as a dictionary using the `spec`
                attribute.

        """
        df = histogram_data(self, df_predict, target_bins)
        recs = df.as_record_dict()
        return match_weights_histogram(recs, width=width, height=height)

    def waterfall_chart(self, records: list[dict], filter_nulls=True):
        """Visualise how the final match weight is computed for the provided pairwise
        record comparisons.

        Records must be provided as a list of dictionaries. This would usually be
        obtained from `df.as_record_dict(limit=n)` where `df` is a SplinkDataFrame.

        Examples:
            ```py
            df = linker.predict(threshold_match_weight=2)
            records = df.as_record_dict(limit=10)
            linker.waterfall_chart(records)
            ```

        Args:
            records (List[dict]): Usually be obtained from `df.as_record_dict(limit=n)`
                where `df` is a SplinkDataFrame.
            filter_nulls (bool, optional): Whether the visualiation shows null
                comparisons, which have no effect on final match weight. Defaults to
                True.


        Returns:
            VegaLite: A VegaLite chart object. See altair.vegalite.v4.display.VegaLite.
                The vegalite spec is available as a dictionary using the `spec`
                attribute.

        """
        self._raise_error_if_necessary_waterfall_columns_not_computed()

        return waterfall_chart(records, self._settings_obj, filter_nulls)

    def unlinkables_chart(
        self,
        x_col="match_weight",
        source_dataset=None,
        as_dict=False,
    ):
        """Generate an interactive chart displaying the proportion of records that
        are "unlinkable" for a given splink score threshold and model parameters.

        Unlinkable records are those that, even when compared with themselves, do not
        contain enough information to confirm a match.

        Args:
            x_col (str, optional): Column to use for the x-axis.
                Defaults to "match_weight".
            source_dataset (str, optional): Name of the source dataset to use for
                the title of the output chart.
            as_dict (bool, optional): If True, return a dict version of the chart.

        Examples:
            For the simplest code pipeline, load a pre-trained model
            and run this against the test data.
            ```py
            df = pd.read_csv("./tests/datasets/fake_1000_from_splink_demos.csv")
            linker = DuckDBLinker(df)
            linker.load_settings("saved_settings.json")
            linker.unlinkables_chart()
            ```
            For more complex code pipelines, you can run an entire pipeline
            that estimates your m and u values, before `unlinkables_chart().

        Returns:
            VegaLite: A VegaLite chart object. See altair.vegalite.v4.display.VegaLite.
                The vegalite spec is available as a dictionary using the `spec`
                attribute.
        """

        # Link our initial df on itself and calculate the % of unlinkable entries
        records = unlinkables_data(self)
        return unlinkables_chart(records, x_col, source_dataset, as_dict)

    def comparison_viewer_dashboard(
        self,
        df_predict: SplinkDataFrame,
        out_path: str,
        overwrite=False,
        num_example_rows=2,
        return_html_as_string=False,
    ):
        """Generate an interactive html visualization of the linker's predictions and
        save to `out_path`.  For more information see
        [this video](https://www.youtube.com/watch?v=DNvCMqjipis)


        Args:
            df_predict (SplinkDataFrame): The outputs of `linker.predict()`
            out_path (str): The path (including filename) to save the html file to.
            overwrite (bool, optional): Overwrite the html file if it already exists?
                Defaults to False.
            num_example_rows (int, optional): Number of example rows per comparison
                vector. Defaults to 2.
            return_html_as_string: If True, return the html as a string

        Examples:
            ```py
            df_predictions = linker.predict()
            linker.comparison_viewer_dashboard(df_predictions, "scv.html", True, 2)
            ```

            Optionally, in Jupyter, you can display the results inline
            Otherwise you can just load the html file in your browser
            ```py
            from IPython.display import IFrame
            IFrame(src="./scv.html", width="100%", height=1200)
            ```

        """
        self._raise_error_if_necessary_waterfall_columns_not_computed()

        sql = comparison_vector_distribution_sql(self)
        self._enqueue_sql(sql, "__splink__df_comparison_vector_distribution")

        sqls = comparison_viewer_table_sqls(self, num_example_rows)
        for sql in sqls:
            self._enqueue_sql(sql["sql"], sql["output_table_name"])

        df = self._execute_sql_pipeline([df_predict])

        rendered = render_splink_comparison_viewer_html(
            df.as_record_dict(),
            self._settings_obj._as_completed_dict(),
            out_path,
            overwrite,
        )
        if return_html_as_string:
            return rendered

    def parameter_estimate_comparisons_chart(self, include_m=True, include_u=True):
        """Show a chart that shows how parameter estimates have differed across
        the different estimation methods you have used.

        For example, if you have run two EM estimation sessions, blocking on
        different variables, and both result in parameter estimates for
        first_name, this chart will enable easy comparison of the different
        estimates

        Args:
            include_m (bool, optional): Show different estimates of m values. Defaults
                to True.
            include_u (bool, optional): Show different estimates of u values. Defaults
                to True.

        """
        records = self._settings_obj._parameter_estimates_as_records

        to_retain = []
        if include_m:
            to_retain.append("m")
        if include_u:
            to_retain.append("u")

        records = [r for r in records if r["m_or_u"] in to_retain]

        return parameter_estimate_comparisons(records)

    def missingness_chart(self, input_dataset: str = None):
        """Generate a summary chart of the missingness (prevalence of nulls) of
        columns in the input datasets.  By default, missingness is assessed across
        all input datasets

        Args:
            input_dataset (str, optional): Name of one of the input tables in the
            database.  If provided, missingness will be computed for this table alone.
            Defaults to None.

        Examples:
            ```py
            linker.missingness_chart()
            ```
            To view offline (if you don't have an internet connection):
            ```py
            from splink.charts import save_offline_chart
            c = linker.missingness_chart()
            save_offline_chart(c.spec, "test_chart.html")
            ```
            View resultant html file in Jupyter (or just load it in your browser)
            ```py
            from IPython.display import IFrame
            IFrame(src="./test_chart.html", width=1000, height=500
            ```
        """
        records = missingness_data(self, input_dataset)
        return missingness_chart(records)

    def completeness_chart(self, input_dataset: str = None, cols: list[str] = None):
        """Generate a summary chart of the completeness (proportion of non-nulls) of
        columns in each of the input datasets. By default, completeness is assessed for
        all column in the input data.

        Args:
            input_dataset (str, optional): Name of one of the input tables in the
                database.  If provided, completeness will be computed for this table
                alone. Defaults to None.
            cols (List[str], optional): List of column names to calculate completeness.
                Default to None.

        Examples:
            ```py
            linker.completeness_chart()
            ```
            To view offline (if you don't have an internet connection):
            ```py
            from splink.charts import save_offline_chart
            c = linker.completeness_chart()
            save_offline_chart(c.spec, "test_chart.html")
            ```
            View resultant html file in Jupyter (or just load it in your browser)
            ```py
            from IPython.display import IFrame
            IFrame(src="./test_chart.html", width=1000, height=500
            ```
        """
        records = completeness_data(self, input_dataset, cols)
        return completeness_chart(records)

    def count_num_comparisons_from_blocking_rule(
        self,
        blocking_rule: str,
    ) -> int:
        """Compute the number of pairwise record comparisons that would be generated by
        a blocking rule

        Args:
            blocking_rule (str): The blocking rule to analyse
            link_type (str, optional): The link type.  This is needed only if the
                linker has not yet been provided with a settings dictionary.  Defaults
                to None.
            unique_id_column_name (str, optional):  This is needed only if the
                linker has not yet been provided with a settings dictionary.  Defaults
                to None.

        Examples:
            ```py
            br = "l.first_name = r.first_name"
            linker.count_num_comparisons_from_blocking_rule(br)
            ```
            > 19387
            ```py
            br = "l.name = r.name and substr(l.dob,1,4) = substr(r.dob,1,4)"
            linker.count_num_comparisons_from_blocking_rule(br)
            ```
            > 394

        Returns:
            int: The number of comparisons generated by the blocking rule
        """

        sql = vertically_concatenate_sql(self)
        self._enqueue_sql(sql, "__splink__df_concat")

        sql = number_of_comparisons_generated_by_blocking_rule_sql(self, blocking_rule)
        self._enqueue_sql(sql, "__splink__analyse_blocking_rule")
        res = self._execute_sql_pipeline().as_record_dict()[0]
        return res["count_of_pairwise_comparisons_generated"]

    def cumulative_comparisons_from_blocking_rules_records(
        self,
        blocking_rules: str or list = None,
    ):
        """Output the number of comparisons generated by each successive blocking rule.

        This is equivalent to the output size of df_predict and details how many
        comparisons each of your individual blocking rules will contribute to the
        total.

        Args:
            blocking_rules (str or list): The blocking rule(s) to compute comparisons
                for. If null, the rules set out in your settings object will be used.

        Examples:
            ```py
            linker_settings = DuckDBLinker(df, settings)
            # Compute the cumulative number of comparisons generated by the rules
            # in your settings object.
            linker_settings.cumulative_comparisons_from_blocking_rules_records()
            >>>
            # Generate total comparisons with custom blocking rules.
            blocking_rules = [
               "l.surname = r.surname",
               "l.first_name = r.first_name
                and substr(l.dob,1,4) = substr(r.dob,1,4)"
            ]
            >>>
            linker_settings.cumulative_comparisons_from_blocking_rules_records(
                blocking_rules
             )
            ```

        Returns:
            List: A list of blocking rules and the corresponding number of
                comparisons it is forecast to generate.
        """
        if blocking_rules:
            blocking_rules = ensure_is_list(blocking_rules)

        records = cumulative_comparisons_generated_by_blocking_rules(
            self, blocking_rules, output_chart=False
        )

        return records

    def cumulative_num_comparisons_from_blocking_rules_chart(
        self,
        blocking_rules: str or list = None,
    ):
        """Display a chart with the cumulative number of comparisons generated by a
        selection of blocking rules.

        This is equivalent to the output size of df_predict and details how many
        comparisons each of your individual blocking rules will contribute to the
        total.

        Args:
            blocking_rules (str or list): The blocking rule(s) to compute comparisons
                for. If null, the rules set out in your settings object will be used.

        Examples:
            ```py
            linker_settings = DuckDBLinker(df, settings)
            # Compute the cumulative number of comparisons generated by the rules
            # in your settings object.
            linker_settings.cumulative_num_comparisons_from_blocking_rules_chart()
            >>>
            # Generate total comparisons with custom blocking rules.
            blocking_rules = [
               "l.surname = r.surname",
               "l.first_name = r.first_name
                and substr(l.dob,1,4) = substr(r.dob,1,4)"
            ]
            >>>
            linker_settings.cumulative_num_comparisons_from_blocking_rules_chart(
                blocking_rules
             )
            ```

        Returns:
            VegaLite: A VegaLite chart object. See altair.vegalite.v4.display.VegaLite.
                The vegalite spec is available as a dictionary using the `spec`
                attribute.
        """

        if blocking_rules:
            blocking_rules = ensure_is_list(blocking_rules)

        records = cumulative_comparisons_generated_by_blocking_rules(
            self, blocking_rules, output_chart=True
        )

        return cumulative_blocking_rule_comparisons_generated(records)

    def count_num_comparisons_from_blocking_rules_for_prediction(self, df_predict):
        """Counts the maginal number of edges created from each of the blocking rules
        in `blocking_rules_to_generate_predictions`

        This is different to `count_num_comparisons_from_blocking_rule`
        because it (a) analyses multiple blocking rules rather than a single rule, and
        (b) deduplicates any comparisons that are generated, to tell you the
        marginal effect of each entry in `blocking_rules_to_generate_predictions`

        Args:
            df_predict (SplinkDataFrame): SplinkDataFrame with match weights
            and probabilities of rows matching

        Examples:
            ```py
            linker = DuckDBLinker(df, connection=":memory:")
            linker.load_settings("saved_settings.json")
            df_predict = linker.predict(threshold_match_probability=0.95)
            count_pairwise = linker.count_num_comparisons_from_blocking_rules_for_prediction(df_predict)
            count_pairwise.as_pandas_dataframe(limit=5)
            ```

        Returns:
            SplinkDataFrame: A SplinkDataFrame of the pairwise comparisons and
                estimated pairwise comparisons generated by the blocking rules.
        """  # noqa: E501
        sql = count_num_comparisons_from_blocking_rules_for_prediction_sql(
            self, df_predict
        )
        match_key_analysis = self._sql_to_splink_dataframe_checking_cache(
            sql, "__splink__match_key_analysis"
        )
        return match_key_analysis

    def match_weights_chart(self):
        """Display a chart of the (partial) match weights of the linkage model

        Examples:
            ```py
            linker.match_weights_chart()
            ```
            To view offline (if you don't have an internet connection):
            ```py
            from splink.charts import save_offline_chart
            c = linker.match_weights_chart()
            save_offline_chart(c.spec, "test_chart.html")
            ```
            View resultant html file in Jupyter (or just load it in your browser)
            ```py
            from IPython.display import IFrame
            IFrame(src="./test_chart.html", width=1000, height=500)
            ```

        Returns:
            VegaLite: A VegaLite chart object. See altair.vegalite.v4.display.VegaLite.
                The vegalite spec is available as a dictionary using the `spec`
                attribute.
        """
        return self._settings_obj.match_weights_chart()

    def tf_adjustment_chart(
        self,
        output_column_name: str,
        n_most_freq: int = 10,
        n_least_freq: int = 10,
        vals_to_include: str | list = None,
        as_dict: bool = False,
    ):
        """Display a chart showing the impact of term frequency adjustments on a
        specific comparison level.
        Each value

        Args:
            output_column_name (str): Name of an output column for which term frequency
                 adjustment has been applied.
            n_most_freq (int, optional): Number of most frequent values to show. If this
                 or `n_least_freq` set to None, all values will be shown.
                Default to 10.
            n_least_freq (int, optional): Number of least frequent values to show. If
                this or `n_most_freq` set to None, all values will be shown.
                Default to 10.
            vals_to_include (list, optional): Specific values for which to show term
                sfrequency adjustments.
                Defaults to None.

        Returns:
            VegaLite: A VegaLite chart object. See altair.vegalite.v4.display.VegaLite.
                The vegalite spec is available as a dictionary using the `spec`
                attribute.
        """

        # Comparisons with TF adjustments
        tf_comparisons = [
            c._output_column_name
            for c in self._settings_obj.comparisons
            if any([cl._has_tf_adjustments for cl in c.comparison_levels])
        ]
        if output_column_name not in tf_comparisons:
            raise ValueError(
                f"{output_column_name} is not a valid comparison column, or does not"
                f" have term frequency adjustment activated"
            )

        vals_to_include = ensure_is_list(vals_to_include)

        return tf_adjustment_chart(
            self,
            output_column_name,
            n_most_freq,
            n_least_freq,
            vals_to_include,
            as_dict,
        )

    def m_u_parameters_chart(self):
        """Display a chart of the m and u parameters of the linkage model

        Examples:
            ```py
            linker.m_u_parameters_chart()
            ```
            To view offline (if you don't have an internet connection):
            ```py
            from splink.charts import save_offline_chart
            c = linker.match_weights_chart()
            save_offline_chart(c.spec, "test_chart.html")
            ```
            View resultant html file in Jupyter (or just load it in your browser)
            ```py
            from IPython.display import IFrame
            IFrame(src="./test_chart.html", width=1000, height=500)
            ```

        Returns:
            VegaLite: A VegaLite chart object. See altair.vegalite.v4.display.VegaLite.
                The vegalite spec is available as a dictionary using the `spec`
                attribute.
        """

        return self._settings_obj.m_u_parameters_chart()

    def cluster_studio_dashboard(
        self,
        df_predict: SplinkDataFrame,
        df_clustered: SplinkDataFrame,
        out_path: str,
        sampling_method="random",
        sample_size: int = 10,
        cluster_ids: list = None,
        cluster_names: list = None,
        overwrite: bool = False,
        return_html_as_string=False,
    ):
        """Generate an interactive html visualization of the predicted cluster and
        save to `out_path`.

        Args:
            df_predict (SplinkDataFrame): The outputs of `linker.predict()`
            df_clustered (SplinkDataFrame): The outputs of
                `linker.cluster_pairwise_predictions_at_threshold()`
            out_path (str): The path (including filename) to save the html file to.
            sampling_method (str, optional): `random` or `by_cluster_size`. Defaults to
                `random`.
            sample_size (int, optional): Number of clusters to show in the dahboard.
                Defaults to 10.
            cluster_ids (list): The IDs of the clusters that will be displayed in the
                dashboard.  If provided, ignore the `sampling_method` and `sample_size`
                arguments. Defaults to None.
            overwrite (bool, optional): Overwrite the html file if it already exists?
                Defaults to False.
            cluster_names (list, optional): If provided, the dashboard will display
                these names in the selection box. Ony works in conjunction with
                `cluster_ids`.  Defaults to None.
            return_html_as_string: If True, return the html as a string

        Examples:
            ```py
            df_p = linker.predict()
            df_c = linker.cluster_pairwise_predictions_at_threshold(df_p, 0.5)
            linker.cluster_studio_dashboard(
                df_p, df_c, [0, 4, 7], "cluster_studio.html"
            )
            ```
            Optionally, in Jupyter, you can display the results inline
            Otherwise you can just load the html file in your browser
            ```py
            from IPython.display import IFrame
            IFrame(src="./cluster_studio.html", width="100%", height=1200)
            ```
        """
        self._raise_error_if_necessary_waterfall_columns_not_computed()

        rendered = render_splink_cluster_studio_html(
            self,
            df_predict,
            df_clustered,
            out_path,
            sampling_method=sampling_method,
            sample_size=sample_size,
            cluster_ids=cluster_ids,
            overwrite=overwrite,
            cluster_names=cluster_names,
        )

        if return_html_as_string:
            return rendered

    def save_model_to_json(
        self, out_path: str | None = None, overwrite: bool = False
    ) -> dict:
        """Save the configuration and parameters of the linkage model to a `.json` file.

        The model can later be loaded back in using `linker.load_model()`.
        The settings dict is also returned in case you want to save it a different way.

        Examples:
            ```py
            linker.save_model_to_json("my_settings.json", overwrite=True)
            ```
        Args:
            out_path (str, optional): File path for json file. If None, don't save to
                file. Defaults to None.
            overwrite (bool, optional): Overwrite if already exists? Defaults to False.

        Returns:
            dict: The settings as a dictionary.
        """
        model_dict = self._settings_obj.as_dict()
        if out_path:
            if os.path.isfile(out_path) and not overwrite:
                raise ValueError(
                    f"The path {out_path} already exists. Please provide a different "
                    "path or set overwrite=True"
                )
            with open(out_path, "w", encoding="utf-8") as f:
                json.dump(model_dict, f, indent=4)
        return model_dict

    def save_settings_to_json(
        self, out_path: str | None = None, overwrite: bool = False
    ) -> dict:
        """
        This function is deprecated. Use save_model_to_json() instead.
        """
        warnings.warn(
            "This function is deprecated. Use save_model_to_json() instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        return self.save_model_to_json(out_path, overwrite)

    def estimate_probability_two_random_records_match(
        self, deterministic_matching_rules, recall
    ):
        """Estimate the model parameter `probability_two_random_records_match` using
        a direct estimation approach.

        See [here](https://github.com/moj-analytical-services/splink/issues/462)
        for discussion of methodology

        Args:
            deterministic_matching_rules (list): A list of deterministic matching
                rules that should be designed to admit very few (none if possible)
                false positives
            recall (float): A guess at the recall the deterministic matching rules
                will attain.  i.e. what proportion of true matches will be recovered
                by these deterministic rules
        """

        if (recall > 1) or (recall <= 0):
            raise ValueError(
                f"Estimated recall must be greater than 0 "
                f"and no more than 1. Supplied value {recall}."
            )

        # If user, by error, provides a single rule as a string
        if isinstance(deterministic_matching_rules, str):
            deterministic_matching_rules = [deterministic_matching_rules]

        records = cumulative_comparisons_generated_by_blocking_rules(
            self,
            deterministic_matching_rules,
        )

        summary_record = records[-1]
        num_observed_matches = summary_record["cumulative_rows"]
        num_total_comparisons = summary_record["cartesian"]

        if num_observed_matches > num_total_comparisons * recall:
            raise ValueError(
                f"Deterministic matching rules led to more "
                f"observed matches than is consistent with supplied recall. "
                f"With these rules, recall must be at least "
                f"{num_observed_matches/num_total_comparisons:,.2f}."
            )

        num_expected_matches = num_observed_matches / recall
        prob = num_expected_matches / num_total_comparisons

        # warn about boundary values, as these will usually be in error
        if num_observed_matches == 0:
            logger.warning(
                f"WARNING: Deterministic matching rules led to no observed matches! "
                f"This means that no possible record pairs are matches, "
                f"and no records are linked to one another.\n"
                f"If this is truly the case then you do not need "
                f"to run the linkage model.\n"
                f"However this is usually in error; "
                f"expected rules to have recall of {100*recall:,.0f}%. "
                f"Consider revising rules as they may have an error."
            )
        if prob == 1:
            logger.warning(
                "WARNING: Probability two random records match is estimated to be 1.\n"
                "This means that all possible record pairs are matches, "
                "and all records are linked to one another.\n"
                "If this is truly the case then you do not need "
                "to run the linkage model.\n"
                "However, it is more likely that this estimate is faulty. "
                "Perhaps your deterministic matching rules include "
                "too many false positives?"
            )

        self._settings_obj._probability_two_random_records_match = prob

        reciprocal_prob = "Infinity" if prob == 0 else f"{1/prob:,.2f}"
        logger.info(
            f"Probability two random records match is estimated to be  {prob:.3g}.\n"
            f"This means that amongst all possible pairwise record comparisons, one in "
            f"{reciprocal_prob} are expected to match.  "
            f"With {num_total_comparisons:,.0f} total"
            " possible comparisons, we expect a total of around "
            f"{num_expected_matches:,.2f} matching pairs"
        )

    def invalidate_cache(self):
        """Invalidate the Splink cache.  Any previously-computed tables
        will be recomputed.
        This is useful, for example, if the input data tables have changed.
        """
        # Before Splink executes a SQL command, it checks the cache to see
        # whether a table already exists with the name of the output table

        # This function has the effect of changing the names of the output tables
        # to include a different unique id

        # As a result, any previously cached tables will not be found
        self._cache_uid = ascii_uid(8)

        # As a result, any previously cached tables will not be found
        self._intermediate_table_cache.invalidate_cache()

        # Also drop any existing splink tables from the database
        # Note, this is not actually necessary, it's just good housekeeping
        self._delete_tables_created_by_splink_from_db()

    def register_table_input_nodes_concat_with_tf(self, input_data, overwrite=False):
        """Register a pre-computed version of the input_nodes_concat_with_tf table that
        you want to re-use e.g. that you created in a previous run

        This method allowed you to register this table in the Splink cache
        so it will be used rather than Splink computing this table anew.

        Args:
            input_data: The data you wish to register. This can be either a dictionary,
                pandas dataframe, pyarrow table or a spark dataframe.
            overwrite (bool): Overwrite the table in the underlying database if it
                exists
        """

        table_name_physical = "__splink__df_concat_with_tf_" + self._cache_uid
        splink_dataframe = self.register_table(
            input_data, table_name_physical, overwrite=overwrite
        )
        self._intermediate_table_cache["__splink__df_concat_with_tf"] = splink_dataframe
        return splink_dataframe

    def register_table_predict(self, input_data, overwrite=False):
        table_name_physical = "__splink__df_predict_" + self._cache_uid
        splink_dataframe = self.register_table(
            input_data, table_name_physical, overwrite=overwrite
        )
        self._intermediate_table_cache["__splink__df_predict"] = splink_dataframe
        return splink_dataframe

    def register_term_frequency_lookup(self, input_data, col_name, overwrite=False):
        input_col = InputColumn(col_name, settings_obj=self._settings_obj)
        table_name_templated = colname_to_tf_tablename(input_col)
        table_name_physical = f"{table_name_templated}_{self._cache_uid}"
        splink_dataframe = self.register_table(
            input_data, table_name_physical, overwrite=overwrite
        )
        self._intermediate_table_cache[table_name_templated] = splink_dataframe
        return splink_dataframe

    def register_labels_table(self, input_data, overwrite=False):
        table_name_physical = "__splink__df_labels_" + ascii_uid(8)
        splink_dataframe = self.register_table(
            input_data, table_name_physical, overwrite=overwrite
        )
        return splink_dataframe

cluster_studio_dashboard(df_predict, df_clustered, out_path, sampling_method='random', sample_size=10, cluster_ids=None, cluster_names=None, overwrite=False, return_html_as_string=False)

Generate an interactive html visualization of the predicted cluster and save to out_path.

Parameters:

Name Type Description Default
df_predict SplinkDataFrame

The outputs of linker.predict()

required
df_clustered SplinkDataFrame

The outputs of linker.cluster_pairwise_predictions_at_threshold()

required
out_path str

The path (including filename) to save the html file to.

required
sampling_method str

random or by_cluster_size. Defaults to random.

'random'
sample_size int

Number of clusters to show in the dahboard. Defaults to 10.

10
cluster_ids list

The IDs of the clusters that will be displayed in the dashboard. If provided, ignore the sampling_method and sample_size arguments. Defaults to None.

None
overwrite bool

Overwrite the html file if it already exists? Defaults to False.

False
cluster_names list

If provided, the dashboard will display these names in the selection box. Ony works in conjunction with cluster_ids. Defaults to None.

None
return_html_as_string

If True, return the html as a string

False

Examples:

df_p = linker.predict()
df_c = linker.cluster_pairwise_predictions_at_threshold(df_p, 0.5)
linker.cluster_studio_dashboard(
    df_p, df_c, [0, 4, 7], "cluster_studio.html"
)
Optionally, in Jupyter, you can display the results inline Otherwise you can just load the html file in your browser
from IPython.display import IFrame
IFrame(src="./cluster_studio.html", width="100%", height=1200)

Source code in splink/linker.py
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
def cluster_studio_dashboard(
    self,
    df_predict: SplinkDataFrame,
    df_clustered: SplinkDataFrame,
    out_path: str,
    sampling_method="random",
    sample_size: int = 10,
    cluster_ids: list = None,
    cluster_names: list = None,
    overwrite: bool = False,
    return_html_as_string=False,
):
    """Generate an interactive html visualization of the predicted cluster and
    save to `out_path`.

    Args:
        df_predict (SplinkDataFrame): The outputs of `linker.predict()`
        df_clustered (SplinkDataFrame): The outputs of
            `linker.cluster_pairwise_predictions_at_threshold()`
        out_path (str): The path (including filename) to save the html file to.
        sampling_method (str, optional): `random` or `by_cluster_size`. Defaults to
            `random`.
        sample_size (int, optional): Number of clusters to show in the dahboard.
            Defaults to 10.
        cluster_ids (list): The IDs of the clusters that will be displayed in the
            dashboard.  If provided, ignore the `sampling_method` and `sample_size`
            arguments. Defaults to None.
        overwrite (bool, optional): Overwrite the html file if it already exists?
            Defaults to False.
        cluster_names (list, optional): If provided, the dashboard will display
            these names in the selection box. Ony works in conjunction with
            `cluster_ids`.  Defaults to None.
        return_html_as_string: If True, return the html as a string

    Examples:
        ```py
        df_p = linker.predict()
        df_c = linker.cluster_pairwise_predictions_at_threshold(df_p, 0.5)
        linker.cluster_studio_dashboard(
            df_p, df_c, [0, 4, 7], "cluster_studio.html"
        )
        ```
        Optionally, in Jupyter, you can display the results inline
        Otherwise you can just load the html file in your browser
        ```py
        from IPython.display import IFrame
        IFrame(src="./cluster_studio.html", width="100%", height=1200)
        ```
    """
    self._raise_error_if_necessary_waterfall_columns_not_computed()

    rendered = render_splink_cluster_studio_html(
        self,
        df_predict,
        df_clustered,
        out_path,
        sampling_method=sampling_method,
        sample_size=sample_size,
        cluster_ids=cluster_ids,
        overwrite=overwrite,
        cluster_names=cluster_names,
    )

    if return_html_as_string:
        return rendered

comparison_viewer_dashboard(df_predict, out_path, overwrite=False, num_example_rows=2, return_html_as_string=False)

Generate an interactive html visualization of the linker's predictions and save to out_path. For more information see this video

Parameters:

Name Type Description Default
df_predict SplinkDataFrame

The outputs of linker.predict()

required
out_path str

The path (including filename) to save the html file to.

required
overwrite bool

Overwrite the html file if it already exists? Defaults to False.

False
num_example_rows int

Number of example rows per comparison vector. Defaults to 2.

2
return_html_as_string

If True, return the html as a string

False

Examples:

df_predictions = linker.predict()
linker.comparison_viewer_dashboard(df_predictions, "scv.html", True, 2)

Optionally, in Jupyter, you can display the results inline Otherwise you can just load the html file in your browser

from IPython.display import IFrame
IFrame(src="./scv.html", width="100%", height=1200)

Source code in splink/linker.py
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
def comparison_viewer_dashboard(
    self,
    df_predict: SplinkDataFrame,
    out_path: str,
    overwrite=False,
    num_example_rows=2,
    return_html_as_string=False,
):
    """Generate an interactive html visualization of the linker's predictions and
    save to `out_path`.  For more information see
    [this video](https://www.youtube.com/watch?v=DNvCMqjipis)


    Args:
        df_predict (SplinkDataFrame): The outputs of `linker.predict()`
        out_path (str): The path (including filename) to save the html file to.
        overwrite (bool, optional): Overwrite the html file if it already exists?
            Defaults to False.
        num_example_rows (int, optional): Number of example rows per comparison
            vector. Defaults to 2.
        return_html_as_string: If True, return the html as a string

    Examples:
        ```py
        df_predictions = linker.predict()
        linker.comparison_viewer_dashboard(df_predictions, "scv.html", True, 2)
        ```

        Optionally, in Jupyter, you can display the results inline
        Otherwise you can just load the html file in your browser
        ```py
        from IPython.display import IFrame
        IFrame(src="./scv.html", width="100%", height=1200)
        ```

    """
    self._raise_error_if_necessary_waterfall_columns_not_computed()

    sql = comparison_vector_distribution_sql(self)
    self._enqueue_sql(sql, "__splink__df_comparison_vector_distribution")

    sqls = comparison_viewer_table_sqls(self, num_example_rows)
    for sql in sqls:
        self._enqueue_sql(sql["sql"], sql["output_table_name"])

    df = self._execute_sql_pipeline([df_predict])

    rendered = render_splink_comparison_viewer_html(
        df.as_record_dict(),
        self._settings_obj._as_completed_dict(),
        out_path,
        overwrite,
    )
    if return_html_as_string:
        return rendered

m_u_parameters_chart()

Display a chart of the m and u parameters of the linkage model

Examples:

linker.m_u_parameters_chart()
To view offline (if you don't have an internet connection):
from splink.charts import save_offline_chart
c = linker.match_weights_chart()
save_offline_chart(c.spec, "test_chart.html")
View resultant html file in Jupyter (or just load it in your browser)
from IPython.display import IFrame
IFrame(src="./test_chart.html", width=1000, height=500)

Returns:

Name Type Description
VegaLite

A VegaLite chart object. See altair.vegalite.v4.display.VegaLite. The vegalite spec is available as a dictionary using the spec attribute.

Source code in splink/linker.py
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
def m_u_parameters_chart(self):
    """Display a chart of the m and u parameters of the linkage model

    Examples:
        ```py
        linker.m_u_parameters_chart()
        ```
        To view offline (if you don't have an internet connection):
        ```py
        from splink.charts import save_offline_chart
        c = linker.match_weights_chart()
        save_offline_chart(c.spec, "test_chart.html")
        ```
        View resultant html file in Jupyter (or just load it in your browser)
        ```py
        from IPython.display import IFrame
        IFrame(src="./test_chart.html", width=1000, height=500)
        ```

    Returns:
        VegaLite: A VegaLite chart object. See altair.vegalite.v4.display.VegaLite.
            The vegalite spec is available as a dictionary using the `spec`
            attribute.
    """

    return self._settings_obj.m_u_parameters_chart()

match_weights_chart()

Display a chart of the (partial) match weights of the linkage model

Examples:

linker.match_weights_chart()
To view offline (if you don't have an internet connection):
from splink.charts import save_offline_chart
c = linker.match_weights_chart()
save_offline_chart(c.spec, "test_chart.html")
View resultant html file in Jupyter (or just load it in your browser)
from IPython.display import IFrame
IFrame(src="./test_chart.html", width=1000, height=500)

Returns:

Name Type Description
VegaLite

A VegaLite chart object. See altair.vegalite.v4.display.VegaLite. The vegalite spec is available as a dictionary using the spec attribute.

Source code in splink/linker.py
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
def match_weights_chart(self):
    """Display a chart of the (partial) match weights of the linkage model

    Examples:
        ```py
        linker.match_weights_chart()
        ```
        To view offline (if you don't have an internet connection):
        ```py
        from splink.charts import save_offline_chart
        c = linker.match_weights_chart()
        save_offline_chart(c.spec, "test_chart.html")
        ```
        View resultant html file in Jupyter (or just load it in your browser)
        ```py
        from IPython.display import IFrame
        IFrame(src="./test_chart.html", width=1000, height=500)
        ```

    Returns:
        VegaLite: A VegaLite chart object. See altair.vegalite.v4.display.VegaLite.
            The vegalite spec is available as a dictionary using the `spec`
            attribute.
    """
    return self._settings_obj.match_weights_chart()

parameter_estimate_comparisons_chart(include_m=True, include_u=True)

Show a chart that shows how parameter estimates have differed across the different estimation methods you have used.

For example, if you have run two EM estimation sessions, blocking on different variables, and both result in parameter estimates for first_name, this chart will enable easy comparison of the different estimates

Parameters:

Name Type Description Default
include_m bool

Show different estimates of m values. Defaults to True.

True
include_u bool

Show different estimates of u values. Defaults to True.

True
Source code in splink/linker.py
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
def parameter_estimate_comparisons_chart(self, include_m=True, include_u=True):
    """Show a chart that shows how parameter estimates have differed across
    the different estimation methods you have used.

    For example, if you have run two EM estimation sessions, blocking on
    different variables, and both result in parameter estimates for
    first_name, this chart will enable easy comparison of the different
    estimates

    Args:
        include_m (bool, optional): Show different estimates of m values. Defaults
            to True.
        include_u (bool, optional): Show different estimates of u values. Defaults
            to True.

    """
    records = self._settings_obj._parameter_estimates_as_records

    to_retain = []
    if include_m:
        to_retain.append("m")
    if include_u:
        to_retain.append("u")

    records = [r for r in records if r["m_or_u"] in to_retain]

    return parameter_estimate_comparisons(records)

precision_recall_chart_from_labels_column(labels_column_name, threshold_actual=0.5, match_weight_round_to_nearest=None)

Generate a precision-recall chart from ground truth data, whereby the ground truth is in a column in the input dataset called labels_column_name

Parameters:

Name Type Description Default
labels_column_name str

Column name containing labels in the input table

required
threshold_actual float

Where the clerical_match_score provided by the user is a probability rather than binary, this value is used as the threshold to classify clerical_match_scores as binary matches or non matches. Defaults to 0.5.

0.5
match_weight_round_to_nearest float

When provided, thresholds are rounded. When large numbers of labels are provided, this is sometimes necessary to reduce the size of the ROC table, and therefore the number of points plotted on the ROC chart. Defaults to None.

None

Examples:

linker.precision_recall_chart_from_labels_column("ground_truth")

Returns:

Name Type Description
VegaLite

A VegaLite chart object. See altair.vegalite.v4.display.VegaLite. The vegalite spec is available as a dictionary using the spec attribute.

Source code in splink/linker.py
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
def precision_recall_chart_from_labels_column(
    self,
    labels_column_name,
    threshold_actual=0.5,
    match_weight_round_to_nearest: float = None,
):
    """Generate a precision-recall chart from ground truth data, whereby the ground
    truth is in a column in the input dataset called `labels_column_name`

    Args:
        labels_column_name (str): Column name containing labels in the input table
        threshold_actual (float, optional): Where the `clerical_match_score`
            provided by the user is a probability rather than binary, this value
            is used as the threshold to classify `clerical_match_score`s as binary
            matches or non matches. Defaults to 0.5.
        match_weight_round_to_nearest (float, optional): When provided, thresholds
            are rounded.  When large numbers of labels are provided, this is
            sometimes necessary to reduce the size of the ROC table, and therefore
            the number of points plotted on the ROC chart. Defaults to None.
    Examples:
        ```py
        linker.precision_recall_chart_from_labels_column("ground_truth")
        ```

    Returns:
        VegaLite: A VegaLite chart object. See altair.vegalite.v4.display.VegaLite.
            The vegalite spec is available as a dictionary using the `spec`
            attribute.
    """

    df_truth_space = truth_space_table_from_labels_column(
        self,
        labels_column_name,
        threshold_actual=threshold_actual,
        match_weight_round_to_nearest=match_weight_round_to_nearest,
    )
    recs = df_truth_space.as_record_dict()
    return precision_recall_chart(recs)

precision_recall_chart_from_labels_table(labels_splinkdataframe_or_table_name, threshold_actual=0.5, match_weight_round_to_nearest=None)

Generate a precision-recall chart from labelled (ground truth) data.

The table of labels should be in the following format, and should be registered as a table with your database:

source_dataset_l unique_id_l source_dataset_r unique_id_r clerical_match_score
df_1 1 df_2 2 0.99
df_1 1 df_2 3 0.2

Note that source_dataset and unique_id should correspond to the values specified in the settings dict, and the input_table_aliases passed to the linker object.

For dedupe_only links, the source_dataset columns can be ommitted.

Parameters:

Name Type Description Default
labels_splinkdataframe_or_table_name str | SplinkDataFrame

Name of table containing labels in the database

required
threshold_actual float

Where the clerical_match_score provided by the user is a probability rather than binary, this value is used as the threshold to classify clerical_match_scores as binary matches or non matches. Defaults to 0.5.

0.5
match_weight_round_to_nearest float

When provided, thresholds are rounded. When large numbers of labels are provided, this is sometimes necessary to reduce the size of the ROC table, and therefore the number of points plotted on the ROC chart. Defaults to None.

None

Examples:

labels = pd.read_csv("my_labels.csv")
linker.register_table(labels, "labels")
linker.precision_recall_chart_from_labels_table("labels")
labels = spark.read.csv("my_labels.csv", header=True)
labels.createDataFrame("labels")
linker.precision_recall_chart_from_labels_table("labels")

Returns:

Name Type Description
VegaLite

A VegaLite chart object. See altair.vegalite.v4.display.VegaLite. The vegalite spec is available as a dictionary using the spec attribute.

Source code in splink/linker.py
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
def precision_recall_chart_from_labels_table(
    self,
    labels_splinkdataframe_or_table_name,
    threshold_actual=0.5,
    match_weight_round_to_nearest: float = None,
):
    """Generate a precision-recall chart from labelled (ground truth) data.

    The table of labels should be in the following format, and should be registered
    as a table with your database:

    |source_dataset_l|unique_id_l|source_dataset_r|unique_id_r|clerical_match_score|
    |----------------|-----------|----------------|-----------|--------------------|
    |df_1            |1          |df_2            |2          |0.99                |
    |df_1            |1          |df_2            |3          |0.2                 |

    Note that `source_dataset` and `unique_id` should correspond to the values
    specified in the settings dict, and the `input_table_aliases` passed to the
    `linker` object.

    For `dedupe_only` links, the `source_dataset` columns can be ommitted.

    Args:
        labels_splinkdataframe_or_table_name (str | SplinkDataFrame): Name of table
            containing labels in the database
        threshold_actual (float, optional): Where the `clerical_match_score`
            provided by the user is a probability rather than binary, this value
            is used as the threshold to classify `clerical_match_score`s as binary
            matches or non matches. Defaults to 0.5.
        match_weight_round_to_nearest (float, optional): When provided, thresholds
            are rounded.  When large numbers of labels are provided, this is
            sometimes necessary to reduce the size of the ROC table, and therefore
            the number of points plotted on the ROC chart. Defaults to None.
    Examples:
        === "DuckDB"
            ```py
            labels = pd.read_csv("my_labels.csv")
            linker.register_table(labels, "labels")
            linker.precision_recall_chart_from_labels_table("labels")
            ```
        === "Spark"
            ```py
            labels = spark.read.csv("my_labels.csv", header=True)
            labels.createDataFrame("labels")
            linker.precision_recall_chart_from_labels_table("labels")
            ```

    Returns:
        VegaLite: A VegaLite chart object. See altair.vegalite.v4.display.VegaLite.
            The vegalite spec is available as a dictionary using the `spec`
            attribute.
    """
    labels_tablename = self._get_labels_tablename_from_input(
        labels_splinkdataframe_or_table_name
    )
    self._raise_error_if_necessary_accuracy_columns_not_computed()
    df_truth_space = truth_space_table_from_labels_table(
        self,
        labels_tablename,
        threshold_actual=threshold_actual,
        match_weight_round_to_nearest=match_weight_round_to_nearest,
    )
    recs = df_truth_space.as_record_dict()
    return precision_recall_chart(recs)

prediction_errors_from_labels_table(labels_splinkdataframe_or_table_name, include_false_positives=True, include_false_negatives=True, threshold=0.5)

Generate a dataframe containing false positives and false negatives based on the comparison between the clerical_match_score in the labels table compared with the splink predicted match probability

Parameters:

Name Type Description Default
labels_splinkdataframe_or_table_name str | SplinkDataFrame

Name of table containing labels in the database

required
include_false_positives bool

Defaults to True.

True
include_false_negatives bool

Defaults to True.

True
threshold float

Threshold above which a score is considered to be a match. Defaults to 0.5.

0.5

Returns:

Name Type Description
SplinkDataFrame

Table containing false positives and negatives

Source code in splink/linker.py
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
def prediction_errors_from_labels_table(
    self,
    labels_splinkdataframe_or_table_name,
    include_false_positives=True,
    include_false_negatives=True,
    threshold=0.5,
):
    """Generate a dataframe containing false positives and false negatives
    based on the comparison between the clerical_match_score in the labels
    table compared with the splink predicted match probability

    Args:
        labels_splinkdataframe_or_table_name (str | SplinkDataFrame): Name of table
            containing labels in the database
        include_false_positives (bool, optional): Defaults to True.
        include_false_negatives (bool, optional): Defaults to True.
        threshold (float, optional): Threshold above which a score is considered
            to be a match. Defaults to 0.5.

    Returns:
        SplinkDataFrame:  Table containing false positives and negatives
    """
    labels_tablename = self._get_labels_tablename_from_input(
        labels_splinkdataframe_or_table_name
    )
    return prediction_errors_from_labels_table(
        self,
        labels_tablename,
        include_false_positives,
        include_false_negatives,
        threshold,
    )

roc_chart_from_labels_column(labels_column_name, threshold_actual=0.5, match_weight_round_to_nearest=None)

Generate a ROC chart from ground truth data, whereby the ground truth is in a column in the input dataset called labels_column_name

Parameters:

Name Type Description Default
labels_column_name str

Column name containing labels in the input table

required
threshold_actual float

Where the clerical_match_score provided by the user is a probability rather than binary, this value is used as the threshold to classify clerical_match_scores as binary matches or non matches. Defaults to 0.5.

0.5
match_weight_round_to_nearest float

When provided, thresholds are rounded. When large numbers of labels are provided, this is sometimes necessary to reduce the size of the ROC table, and therefore the number of points plotted on the ROC chart. Defaults to None.

None

Examples:

linker.roc_chart_from_labels_column("labels")

Returns:

Name Type Description
VegaLite

A VegaLite chart object. See altair.vegalite.v4.display.VegaLite. The vegalite spec is available as a dictionary using the spec attribute.

Source code in splink/linker.py
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
def roc_chart_from_labels_column(
    self,
    labels_column_name,
    threshold_actual=0.5,
    match_weight_round_to_nearest: float = None,
):
    """Generate a ROC chart from ground truth data, whereby the ground truth
    is in a column in the input dataset called `labels_column_name`

    Args:
        labels_column_name (str): Column name containing labels in the input table
        threshold_actual (float, optional): Where the `clerical_match_score`
            provided by the user is a probability rather than binary, this value
            is used as the threshold to classify `clerical_match_score`s as binary
            matches or non matches. Defaults to 0.5.
        match_weight_round_to_nearest (float, optional): When provided, thresholds
            are rounded.  When large numbers of labels are provided, this is
            sometimes necessary to reduce the size of the ROC table, and therefore
            the number of points plotted on the ROC chart. Defaults to None.

    Examples:
        ```py
        linker.roc_chart_from_labels_column("labels")
        ```

    Returns:
        VegaLite: A VegaLite chart object. See altair.vegalite.v4.display.VegaLite.
            The vegalite spec is available as a dictionary using the `spec`
            attribute.
    """

    df_truth_space = truth_space_table_from_labels_column(
        self,
        labels_column_name,
        threshold_actual=threshold_actual,
        match_weight_round_to_nearest=match_weight_round_to_nearest,
    )
    recs = df_truth_space.as_record_dict()
    return roc_chart(recs)

roc_chart_from_labels_table(labels_splinkdataframe_or_table_name, threshold_actual=0.5, match_weight_round_to_nearest=None)

Generate a ROC chart from labelled (ground truth) data.

The table of labels should be in the following format, and should be registered with your database:

source_dataset_l unique_id_l source_dataset_r unique_id_r clerical_match_score
df_1 1 df_2 2 0.99
df_1 1 df_2 3 0.2

Note that source_dataset and unique_id should correspond to the values specified in the settings dict, and the input_table_aliases passed to the linker object.

For dedupe_only links, the source_dataset columns can be ommitted.

Parameters:

Name Type Description Default
labels_splinkdataframe_or_table_name str | SplinkDataFrame

Name of table containing labels in the database

required
threshold_actual float

Where the clerical_match_score provided by the user is a probability rather than binary, this value is used as the threshold to classify clerical_match_scores as binary matches or non matches. Defaults to 0.5.

0.5
match_weight_round_to_nearest float

When provided, thresholds are rounded. When large numbers of labels are provided, this is sometimes necessary to reduce the size of the ROC table, and therefore the number of points plotted on the ROC chart. Defaults to None.

None

Examples:

labels = pd.read_csv("my_labels.csv")
linker.register_table(labels, "labels")
linker.roc_chart_from_labels_table("labels")
labels = spark.read.csv("my_labels.csv", header=True)
labels.createDataFrame("labels")
linker.roc_chart_from_labels_table("labels")

Returns:

Name Type Description
VegaLite

A VegaLite chart object. See altair.vegalite.v4.display.VegaLite. The vegalite spec is available as a dictionary using the spec attribute.

Source code in splink/linker.py
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
def roc_chart_from_labels_table(
    self,
    labels_splinkdataframe_or_table_name: str | SplinkDataFrame,
    threshold_actual=0.5,
    match_weight_round_to_nearest: float = None,
):
    """Generate a ROC chart from labelled (ground truth) data.

    The table of labels should be in the following format, and should be registered
    with your database:

    |source_dataset_l|unique_id_l|source_dataset_r|unique_id_r|clerical_match_score|
    |----------------|-----------|----------------|-----------|--------------------|
    |df_1            |1          |df_2            |2          |0.99                |
    |df_1            |1          |df_2            |3          |0.2                 |

    Note that `source_dataset` and `unique_id` should correspond to the values
    specified in the settings dict, and the `input_table_aliases` passed to the
    `linker` object.

    For `dedupe_only` links, the `source_dataset` columns can be ommitted.

    Args:
        labels_splinkdataframe_or_table_name (str | SplinkDataFrame): Name of table
            containing labels in the database
        threshold_actual (float, optional): Where the `clerical_match_score`
            provided by the user is a probability rather than binary, this value
            is used as the threshold to classify `clerical_match_score`s as binary
            matches or non matches. Defaults to 0.5.
        match_weight_round_to_nearest (float, optional): When provided, thresholds
            are rounded.  When large numbers of labels are provided, this is
            sometimes necessary to reduce the size of the ROC table, and therefore
            the number of points plotted on the ROC chart. Defaults to None.

    Examples:
        === "DuckDB"
            ```py
            labels = pd.read_csv("my_labels.csv")
            linker.register_table(labels, "labels")
            linker.roc_chart_from_labels_table("labels")
            ```
        === "Spark"
            ```py
            labels = spark.read.csv("my_labels.csv", header=True)
            labels.createDataFrame("labels")
            linker.roc_chart_from_labels_table("labels")
            ```

    Returns:
        VegaLite: A VegaLite chart object. See altair.vegalite.v4.display.VegaLite.
            The vegalite spec is available as a dictionary using the `spec`
            attribute.
    """
    labels_tablename = self._get_labels_tablename_from_input(
        labels_splinkdataframe_or_table_name
    )

    self._raise_error_if_necessary_accuracy_columns_not_computed()
    df_truth_space = truth_space_table_from_labels_table(
        self,
        labels_tablename,
        threshold_actual=threshold_actual,
        match_weight_round_to_nearest=match_weight_round_to_nearest,
    )
    recs = df_truth_space.as_record_dict()
    return roc_chart(recs)

truth_space_table_from_labels_column(labels_column_name, threshold_actual=0.5, match_weight_round_to_nearest=None)

Generate truth statistics (false positive etc.) for each threshold value of match_probability, suitable for plotting a ROC chart.

Your labels_column_name should include the ground truth cluster (unique identifier) that groups entities which are the same

Parameters:

Name Type Description Default
labels_tablename str

Name of table containing labels in the database

required
threshold_actual float

Where the clerical_match_score provided by the user is a probability rather than binary, this value is used as the threshold to classify clerical_match_scores as binary matches or non matches. Defaults to 0.5.

0.5
match_weight_round_to_nearest float

When provided, thresholds are rounded. When large numbers of labels are provided, this is sometimes necessary to reduce the size of the ROC table, and therefore the number of points plotted on the ROC chart. Defaults to None.

None

Examples:

linker.truth_space_table_from_labels_column("cluster")

Returns:

Name Type Description
SplinkDataFrame

Table of truth statistics

Source code in splink/linker.py
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
def truth_space_table_from_labels_column(
    self,
    labels_column_name,
    threshold_actual=0.5,
    match_weight_round_to_nearest: float = None,
):
    """Generate truth statistics (false positive etc.) for each threshold value of
    match_probability, suitable for plotting a ROC chart.

    Your labels_column_name should include the ground truth cluster (unique
    identifier) that groups entities which are the same

    Args:
        labels_tablename (str): Name of table containing labels in the database
        threshold_actual (float, optional): Where the `clerical_match_score`
            provided by the user is a probability rather than binary, this value
            is used as the threshold to classify `clerical_match_score`s as binary
            matches or non matches. Defaults to 0.5.
        match_weight_round_to_nearest (float, optional): When provided, thresholds
            are rounded.  When large numbers of labels are provided, this is
            sometimes necessary to reduce the size of the ROC table, and therefore
            the number of points plotted on the ROC chart. Defaults to None.

    Examples:
        ```py
        linker.truth_space_table_from_labels_column("cluster")
        ```

    Returns:
        SplinkDataFrame:  Table of truth statistics
    """

    return truth_space_table_from_labels_column(
        self, labels_column_name, threshold_actual, match_weight_round_to_nearest
    )

truth_space_table_from_labels_table(labels_splinkdataframe_or_table_name, threshold_actual=0.5, match_weight_round_to_nearest=None)

Generate truth statistics (false positive etc.) for each threshold value of match_probability, suitable for plotting a ROC chart.

The table of labels should be in the following format, and should be registered with your database:

source_dataset_l unique_id_l source_dataset_r unique_id_r clerical_match_score
df_1 1 df_2 2 0.99
df_1 1 df_2 3 0.2

Note that source_dataset and unique_id should correspond to the values specified in the settings dict, and the input_table_aliases passed to the linker object.

For dedupe_only links, the source_dataset columns can be ommitted.

Parameters:

Name Type Description Default
labels_splinkdataframe_or_table_name str | SplinkDataFrame

Name of table containing labels in the database

required
threshold_actual float

Where the clerical_match_score provided by the user is a probability rather than binary, this value is used as the threshold to classify clerical_match_scores as binary matches or non matches. Defaults to 0.5.

0.5
match_weight_round_to_nearest float

When provided, thresholds are rounded. When large numbers of labels are provided, this is sometimes necessary to reduce the size of the ROC table, and therefore the number of points plotted on the ROC chart. Defaults to None.

None

Examples:

labels = pd.read_csv("my_labels.csv")
linker.register_table(labels, "labels")
linker.truth_space_table_from_labels_table("labels")
labels = spark.read.csv("my_labels.csv", header=True)
labels.createDataFrame("labels")
linker.truth_space_table_from_labels_table("labels")

Returns:

Name Type Description
SplinkDataFrame SplinkDataFrame

Table of truth statistics

Source code in splink/linker.py
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
def truth_space_table_from_labels_table(
    self,
    labels_splinkdataframe_or_table_name,
    threshold_actual=0.5,
    match_weight_round_to_nearest: float = None,
) -> SplinkDataFrame:
    """Generate truth statistics (false positive etc.) for each threshold value of
    match_probability, suitable for plotting a ROC chart.

    The table of labels should be in the following format, and should be registered
    with your database:

    |source_dataset_l|unique_id_l|source_dataset_r|unique_id_r|clerical_match_score|
    |----------------|-----------|----------------|-----------|--------------------|
    |df_1            |1          |df_2            |2          |0.99                |
    |df_1            |1          |df_2            |3          |0.2                 |

    Note that `source_dataset` and `unique_id` should correspond to the values
    specified in the settings dict, and the `input_table_aliases` passed to the
    `linker` object.

    For `dedupe_only` links, the `source_dataset` columns can be ommitted.

    Args:
        labels_splinkdataframe_or_table_name (str | SplinkDataFrame): Name of table
            containing labels in the database
        threshold_actual (float, optional): Where the `clerical_match_score`
            provided by the user is a probability rather than binary, this value
            is used as the threshold to classify `clerical_match_score`s as binary
            matches or non matches. Defaults to 0.5.
        match_weight_round_to_nearest (float, optional): When provided, thresholds
            are rounded.  When large numbers of labels are provided, this is
            sometimes necessary to reduce the size of the ROC table, and therefore
            the number of points plotted on the ROC chart. Defaults to None.

    Examples:
        === "DuckDB"
            ```py
            labels = pd.read_csv("my_labels.csv")
            linker.register_table(labels, "labels")
            linker.truth_space_table_from_labels_table("labels")
            ```
        === "Spark"
            ```py
            labels = spark.read.csv("my_labels.csv", header=True)
            labels.createDataFrame("labels")
            linker.truth_space_table_from_labels_table("labels")
            ```
    Returns:
        SplinkDataFrame:  Table of truth statistics
    """
    labels_tablename = self._get_labels_tablename_from_input(
        labels_splinkdataframe_or_table_name
    )

    self._raise_error_if_necessary_accuracy_columns_not_computed()
    return truth_space_table_from_labels_table(
        self,
        labels_tablename,
        threshold_actual=threshold_actual,
        match_weight_round_to_nearest=match_weight_round_to_nearest,
    )

unlinkables_chart(x_col='match_weight', source_dataset=None, as_dict=False)

Generate an interactive chart displaying the proportion of records that are "unlinkable" for a given splink score threshold and model parameters.

Unlinkable records are those that, even when compared with themselves, do not contain enough information to confirm a match.

Parameters:

Name Type Description Default
x_col str

Column to use for the x-axis. Defaults to "match_weight".

'match_weight'
source_dataset str

Name of the source dataset to use for the title of the output chart.

None
as_dict bool

If True, return a dict version of the chart.

False

Examples:

For the simplest code pipeline, load a pre-trained model and run this against the test data.

df = pd.read_csv("./tests/datasets/fake_1000_from_splink_demos.csv")
linker = DuckDBLinker(df)
linker.load_settings("saved_settings.json")
linker.unlinkables_chart()
For more complex code pipelines, you can run an entire pipeline that estimates your m and u values, before `unlinkables_chart().

Returns:

Name Type Description
VegaLite

A VegaLite chart object. See altair.vegalite.v4.display.VegaLite. The vegalite spec is available as a dictionary using the spec attribute.

Source code in splink/linker.py
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
def unlinkables_chart(
    self,
    x_col="match_weight",
    source_dataset=None,
    as_dict=False,
):
    """Generate an interactive chart displaying the proportion of records that
    are "unlinkable" for a given splink score threshold and model parameters.

    Unlinkable records are those that, even when compared with themselves, do not
    contain enough information to confirm a match.

    Args:
        x_col (str, optional): Column to use for the x-axis.
            Defaults to "match_weight".
        source_dataset (str, optional): Name of the source dataset to use for
            the title of the output chart.
        as_dict (bool, optional): If True, return a dict version of the chart.

    Examples:
        For the simplest code pipeline, load a pre-trained model
        and run this against the test data.
        ```py
        df = pd.read_csv("./tests/datasets/fake_1000_from_splink_demos.csv")
        linker = DuckDBLinker(df)
        linker.load_settings("saved_settings.json")
        linker.unlinkables_chart()
        ```
        For more complex code pipelines, you can run an entire pipeline
        that estimates your m and u values, before `unlinkables_chart().

    Returns:
        VegaLite: A VegaLite chart object. See altair.vegalite.v4.display.VegaLite.
            The vegalite spec is available as a dictionary using the `spec`
            attribute.
    """

    # Link our initial df on itself and calculate the % of unlinkable entries
    records = unlinkables_data(self)
    return unlinkables_chart(records, x_col, source_dataset, as_dict)

waterfall_chart(records, filter_nulls=True)

Visualise how the final match weight is computed for the provided pairwise record comparisons.

Records must be provided as a list of dictionaries. This would usually be obtained from df.as_record_dict(limit=n) where df is a SplinkDataFrame.

Examples:

df = linker.predict(threshold_match_weight=2)
records = df.as_record_dict(limit=10)
linker.waterfall_chart(records)

Parameters:

Name Type Description Default
records List[dict]

Usually be obtained from df.as_record_dict(limit=n) where df is a SplinkDataFrame.

required
filter_nulls bool

Whether the visualiation shows null comparisons, which have no effect on final match weight. Defaults to True.

True

Returns:

Name Type Description
VegaLite

A VegaLite chart object. See altair.vegalite.v4.display.VegaLite. The vegalite spec is available as a dictionary using the spec attribute.

Source code in splink/linker.py
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
def waterfall_chart(self, records: list[dict], filter_nulls=True):
    """Visualise how the final match weight is computed for the provided pairwise
    record comparisons.

    Records must be provided as a list of dictionaries. This would usually be
    obtained from `df.as_record_dict(limit=n)` where `df` is a SplinkDataFrame.

    Examples:
        ```py
        df = linker.predict(threshold_match_weight=2)
        records = df.as_record_dict(limit=10)
        linker.waterfall_chart(records)
        ```

    Args:
        records (List[dict]): Usually be obtained from `df.as_record_dict(limit=n)`
            where `df` is a SplinkDataFrame.
        filter_nulls (bool, optional): Whether the visualiation shows null
            comparisons, which have no effect on final match weight. Defaults to
            True.


    Returns:
        VegaLite: A VegaLite chart object. See altair.vegalite.v4.display.VegaLite.
            The vegalite spec is available as a dictionary using the `spec`
            attribute.

    """
    self._raise_error_if_necessary_waterfall_columns_not_computed()

    return waterfall_chart(records, self._settings_obj, filter_nulls)