-
Notifications
You must be signed in to change notification settings - Fork 130
/
linker.py
3662 lines (3124 loc) · 150 KB
/
linker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
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
from __future__ import annotations # noqa: I001
import json
import logging
import os
import warnings
from copy import copy, deepcopy
from pathlib import Path
from statistics import median
from typing import Dict, Optional, Union
from splink.input_column import InputColumn
from splink.settings_validation.log_invalid_columns import (
InvalidColumnsLogger,
SettingsColumnCleaner,
)
from splink.settings_validation.valid_types import (
_validate_dialect,
log_comparison_errors,
)
from .accuracy import (
prediction_errors_from_label_column,
prediction_errors_from_labels_table,
truth_space_table_from_labels_column,
truth_space_table_from_labels_table,
)
from .analyse_blocking import (
count_comparisons_from_blocking_rule_pre_filter_conditions_sqls,
cumulative_comparisons_generated_by_blocking_rules,
number_of_comparisons_generated_by_blocking_rule_post_filters_sql,
)
from .blocking import (
BlockingRule,
SaltedBlockingRule,
block_using_rules_sqls,
blocking_rule_to_obj,
materialise_exploded_id_tables,
)
from .blocking_rule_creator import BlockingRuleCreator
from .cache_dict_with_logging import CacheDictWithLogging
from .charts import (
accuracy_chart,
completeness_chart,
cumulative_blocking_rule_comparisons_generated,
match_weights_histogram,
missingness_chart,
parameter_estimate_comparisons,
precision_recall_chart,
roc_chart,
threshold_selection_tool,
unlinkables_chart,
waterfall_chart,
)
from .cluster_studio import render_splink_cluster_studio_html
from .comparison import Comparison
from .comparison_level import ComparisonLevel
from .comparison_vector_distribution import (
comparison_vector_distribution_sql,
)
from .comparison_vector_values import compute_comparison_vector_values_sql
from .connected_components import (
_cc_create_unique_id_cols,
solve_connected_components,
)
from .edge_metrics import compute_edge_metrics
from .database_api import DatabaseAPI
from .em_training_session import EMTrainingSession
from .estimate_u import estimate_u_values
from .exceptions import SplinkDeprecated, SplinkException
from .find_brs_with_comparison_counts_below_threshold import (
find_blocking_rules_below_threshold_comparison_count,
)
from .find_matches_to_new_records import add_unique_id_and_source_dataset_cols_if_needed
from .graph_metrics import (
GraphMetricsResults,
_node_degree_sql,
_size_density_centralisation_sql,
)
from .labelling_tool import (
generate_labelling_tool_comparisons,
render_labelling_tool_html,
)
from .m_from_labels import estimate_m_from_pairwise_labels
from .m_training import estimate_m_values_from_label_column
from .match_key_analysis import (
count_num_comparisons_from_blocking_rules_for_prediction_sql,
)
from .match_weights_histogram import histogram_data
from .misc import (
ascii_uid,
bayes_factor_to_prob,
ensure_is_list,
prob_to_bayes_factor,
)
from .missingness import completeness_data, missingness_data
from .optimise_cost_of_brs import suggest_blocking_rules
from .pipeline import SQLPipeline
from .predict import (
predict_from_comparison_vectors_sqls_using_settings,
predict_from_comparison_vectors_sqls,
)
from .profile_data import profile_columns
from .settings_creator import SettingsCreator
from .splink_comparison_viewer import (
comparison_viewer_table_sqls,
render_splink_comparison_viewer_html,
)
from .splink_dataframe import SplinkDataFrame
from .term_frequencies import (
_join_tf_to_input_df_sql,
colname_to_tf_tablename,
compute_all_term_frequencies_sqls,
compute_term_frequencies_from_concat_with_tf,
term_frequencies_for_single_column_sql,
term_frequencies_from_concat_with_tf,
tf_adjustment_chart,
)
from .unique_id_concat import (
_composite_unique_id_from_edges_sql,
_composite_unique_id_from_nodes_sql,
)
from .unlinkables import unlinkables_data
from .vertically_concatenate import vertically_concatenate_sql
logger = logging.getLogger(__name__)
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: SettingsCreator | dict | Path | str,
database_api: DatabaseAPI,
set_up_basic_logging: bool = True,
input_table_aliases: str | list = None,
validate_settings: bool = True,
):
"""Initialise the linker object, which manages the data linkage process and
holds the data linkage model.
Examples:
Dedupe
```py
linker = Linker(df, settings_dict, db_api)
```
Link
```py
df_1 = pd.read_parquet("table_1/")
df_2 = pd.read_parquet("table_2/")
linker = Linker(
[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 = Linker(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.
validate_settings (bool, optional): When True, check your settings
dictionary for any potential errors that may cause splink to fail.
"""
self._db_schema = "splink"
if set_up_basic_logging:
logging.basicConfig(
format="%(message)s",
)
splink_logger = logging.getLogger("splink")
splink_logger.setLevel(logging.INFO)
self._pipeline = SQLPipeline()
self.db_api = database_api
# TODO: temp hack for compat
self._intermediate_table_cache: CacheDictWithLogging = (
self.db_api._intermediate_table_cache
)
# Turn into a creator
if not isinstance(settings, SettingsCreator):
settings_creator = SettingsCreator.from_path_or_dict(settings)
else:
settings_creator = settings
# Deal with uuid
if settings_creator.linker_uid is None:
settings_creator.linker_uid = ascii_uid(8)
# Do we trust the dialect set in the settings dict
# or overwrite it with the db api dialect?
# Maybe overwrite it here and incompatibilities have to be dealt with
# by comparisons/ blocking rules etc??
self._settings_obj = settings_creator.get_settings(
database_api.sql_dialect.name
)
# TODO: Add test of what happens if the db_api is for a different backend
# to the sql_dialect set in the settings dict
input_tables = ensure_is_list(input_table_or_tables)
input_tables = self.db_api.process_input_tables(input_tables)
self._input_tables_dict = self._register_input_tables(
input_tables,
input_table_aliases,
)
self._validate_input_dfs()
self._validate_settings(validate_settings)
self._em_training_sessions: list[EMTrainingSession] = []
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
def _input_columns(
self,
include_unique_id_col_names=True,
include_additional_columns_to_retain=True,
) -> list[InputColumn]:
"""Retrieve the column names from the input dataset(s) as InputColumns
Args:
include_unique_id_col_names (bool, optional): Whether to include unique ID
column names. Defaults to True.
include_additional_columns_to_retain (bool, optional): Whether to include
additional columns to retain. Defaults to True.
Raises:
SplinkException: If the input frames have different sets of columns.
Returns:
list[InputColumn]
"""
input_dfs = self._input_tables_dict.values()
# get a list of the column names for each input frame
# sort it for consistent ordering, and give each frame's
# columns as a tuple so we can hash it
column_names_by_input_df = [
tuple(sorted([col.name for col in input_df.columns]))
for input_df in input_dfs
]
# check that the set of input columns is the same for each frame,
# fail if the sets are different
if len(set(column_names_by_input_df)) > 1:
common_cols = set.intersection(
*(set(col_names) for col_names in column_names_by_input_df)
)
problem_names = {
col
for frame_col_names in column_names_by_input_df
for col in frame_col_names
if col not in common_cols
}
raise SplinkException(
"All linker input frames must have the same set of columns. "
"The following columns were not found in all input frames: "
+ ", ".join(problem_names)
)
columns = next(iter(input_dfs)).columns
remove_columns = []
if not include_unique_id_col_names:
remove_columns.extend(
self._settings_obj.column_info_settings.unique_id_input_columns
)
if not include_additional_columns_to_retain:
remove_columns.extend(self._settings_obj._additional_columns_to_retain)
remove_id_cols = [c.unquote().name for c in remove_columns]
columns = [col for col in columns if col.unquote().name not in remove_id_cols]
return columns
@property
def _source_dataset_column_already_exists(self):
input_cols = [c.unquote().name for c in self._input_columns()]
return (
self._settings_obj.column_info_settings.source_dataset_column_name
in input_cols
)
@property
def _cache_uid(self):
return self._settings_obj._cache_uid
@_cache_uid.setter
def _cache_uid(self, value):
self._settings_obj._cache_uid = value
@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:
if self._two_dataset_link_only:
return "__splink__df_concat_with_tf_sample_left"
else:
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:
if self._two_dataset_link_only:
return "__splink__df_concat_with_tf_sample_right"
else:
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 _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
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
# convenience wrappers:
@property
def debug_mode(self):
return self.db_api.debug_mode
@debug_mode.setter
def debug_mode(self, value: bool):
self.db_api.debug_mode = value
# TODO: rename these!
@property
def _sql_dialect(self):
return self.db_api.sql_dialect.name
@property
def _sql_dialect_object(self):
return self.db_api.sql_dialect
@property
def _infinity_expression(self):
return self._sql_dialect_object.infinity_expression
def _random_sample_sql(
self, proportion, sample_size, seed=None, table=None, unique_id=None
):
return self._sql_dialect_object.random_sample_sql(
proportion, sample_size, seed=seed, table=table, unique_id=unique_id
)
def _register_input_tables(
self, input_tables, input_aliases
) -> Dict[str, SplinkDataFrame]:
if input_aliases is None:
input_table_aliases = [
f"__splink__input_table_{i}" for i, _ in enumerate(input_tables)
]
overwrite = True
else:
input_table_aliases = ensure_is_list(input_aliases)
overwrite = False
return self.db_api.register_multiple_tables(
input_tables, input_table_aliases, overwrite
)
def _check_for_valid_settings(self):
# raw tables don't yet exist in db
return hasattr(self, "_input_tables_dict")
def _validate_settings_components(self, settings_dict):
# Vaidate our settings after plugging them through
# `Settings(<settings>)`
log_comparison_errors(
# null if not in dict - check using value is ignored
settings_dict.get("comparisons", None),
self._sql_dialect,
)
def _validate_settings(self, validate_settings):
# TODO: restore logic
return
# Vaidate our settings after plugging them through
# `Settings(<settings>)`
if not self._check_for_valid_settings():
return
self._validate_input_dfs()
# Run miscellaneous checks on our settings dictionary.
_validate_dialect(
settings_dialect=self._settings_obj._sql_dialect,
linker_dialect=self._sql_dialect,
linker_type=self.__class__.__name__,
)
# Constructs output logs for our various settings inputs
cleaned_settings = SettingsColumnCleaner(
settings_object=self._settings_obj,
input_columns=self._input_tables_dict,
)
InvalidColumnsLogger(cleaned_settings).construct_output_logs(validate_settings)
def _initialise_df_concat(self, materialise=False):
cache = self._intermediate_table_cache
concat_df = None
if "__splink__df_concat" in cache:
concat_df = cache.get_with_logging("__splink__df_concat")
elif "__splink__df_concat_with_tf" in cache:
concat_df = cache.get_with_logging("__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.get_with_logging("__splink__df_concat_with_tf")
else:
# In duckdb, calls to random() in a CTE pipeline cause problems:
# https://gist.github.com/RobinL/d329e7004998503ce91b68479aa41139
if self._settings_obj.salting_required:
materialise = True
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
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
"""
return self.db_api.table_to_splink_dataframe(templated_name, physical_name)
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] = [],
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 [].
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
"""
try:
dataframe = self.db_api.sql_pipeline_to_splink_dataframe(
self._pipeline,
input_dataframes,
use_cache,
)
except Exception as e:
raise e
finally:
self._pipeline.reset()
return dataframe
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
"""
return self.db_api.register_table(input, table_name, overwrite)
def query_sql(self, sql, output_type="pandas"):
"""
Run a SQL query against your backend database and return
the resulting output.
Examples:
```py
linker = Linker(df, settings, db_api)
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,
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_and_remove_from_cache()
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,
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
"""
return self.db_api.sql_to_splink_dataframe_checking_cache(
sql,
output_tablename_templated,
use_cache=use_cache,
)
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 _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 _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._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 _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.core_model_settings.probability_two_random_records_match
)
training_lambda_bf = prob_to_bayes_factor(training_lambda)
reverse_level_infos = (
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_sql}: "
f"{training_lambda:,.3f}",
)
for reverse_level_info in reverse_level_infos:
# Get comparison level on current settings obj
# TODO: do we need this dance? We already have the level + comparison
# maybe they are different copies with different values?
reverse_level = reverse_level_info["level"]
cc = self._settings_obj._get_comparison_by_output_column_name(
reverse_level_info["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):
self.db_api.delete_tables_created_by_splink_from_db()
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 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:
Real time linkage
```py
linker = Linker(df, db_api)
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 = Linker(df, db_api)
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")
```
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,
column_info_settings=self._settings_obj.column_info_settings,
sql_dialect=self._settings_obj._sql_dialect,
)
tf_tablename = colname_to_tf_tablename(input_col)
cache = self._intermediate_table_cache
concat_tf_tables = [
tf_col.unquote().name
for tf_col in self._settings_obj._term_frequency_columns
]
if tf_tablename in cache:
tf_df = cache.get_with_logging(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"]])
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)
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:
```py
from splink.linker import Linker
from splink.duckdb.database_api import DuckDBAPI
db_api = DuckDBAPI()
settings = {
"link_type": "dedupe_only",
"blocking_rules_to_generate_predictions": [
"l.first_name = r.first_name",
"l.surname = r.surname",
],
"comparisons": []
}
>>>
linker = Linker(df, settings, db_api)
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()
exploding_br_with_id_tables = materialise_exploded_id_tables(self)
sqls = block_using_rules_sqls(self)
for sql in sqls:
self._enqueue_sql(sql["sql"], sql["output_table_name"])
deterministic_link_df = self._execute_sql_pipeline([concat_with_tf])
[b.drop_materialised_id_pairs_dataframe() for b in exploding_br_with_id_tables]
return deterministic_link_df
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