-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathvalidator.py
More file actions
1273 lines (1113 loc) · 50.7 KB
/
Copy pathvalidator.py
File metadata and controls
1273 lines (1113 loc) · 50.7 KB
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
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Module for the Validator class."""
import duckdb
import pandas as pd
import os
import sys
_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(_SCRIPT_DIR)
_DATA_DIR = os.path.dirname(os.path.dirname(_SCRIPT_DIR))
sys.path.append(os.path.join(_DATA_DIR, 'util'))
from result import ValidationResult, ValidationStatus
from counters import Counters
import validator_goldens
class Validator:
"""
Contains the core logic for all validation rules.
This class is stateless and does not interact with the filesystem.
"""
def validate_sql(self, stats_df: pd.DataFrame, differ_df: pd.DataFrame,
params: dict) -> ValidationResult:
"""Runs a SQL query to validate the data.
Args:
stats_df: A DataFrame containing the summary statistics.
differ_df: A DataFrame containing the differ output.
params: A dictionary containing the validation parameters, which must
have 'query' and 'condition' keys.
Returns:
A ValidationResult object.
"""
if 'query' not in params or 'condition' not in params:
return ValidationResult(
ValidationStatus.CONFIG_ERROR,
'SQL_VALIDATOR',
message=
"Configuration error: 'query' and 'condition' must be specified for SQL_VALIDATOR."
)
try:
con = duckdb.connect(database=':memory:', read_only=False)
con.register('stats', stats_df)
con.register('differ', differ_df)
final_query = f"""
WITH data_to_validate AS (
{params['query']}
)
SELECT *
FROM data_to_validate
WHERE NOT ({params['condition']})
"""
failing_df = con.execute(final_query).fetchdf()
if failing_df.empty:
return ValidationResult(ValidationStatus.PASSED,
'SQL_VALIDATOR')
return ValidationResult(
ValidationStatus.FAILED,
'SQL_VALIDATOR',
message=f"{len(failing_df)} rows failed the SQL validation.",
details={'failing_rows': failing_df.to_dict('records')})
except duckdb.Error as e:
return ValidationResult(ValidationStatus.CONFIG_ERROR,
'SQL_VALIDATOR',
message=f"SQL Error: {e}")
def validate_max_date_latest(self, stats_df: pd.DataFrame,
params: dict) -> ValidationResult:
"""Checks that the MaxDate in the stats summary is from the current year.
Args:
stats_df: A DataFrame containing the summary statistics, expected to have
a 'MaxDate' column.
params: A dictionary containing the validation parameters.
Returns:
A ValidationResult object.
"""
if 'MaxDate' not in stats_df.columns:
return ValidationResult(
ValidationStatus.DATA_ERROR,
'MAX_DATE_LATEST',
message="Input data is missing required column: 'MaxDate'.")
rows_processed = len(stats_df)
if stats_df.empty:
return ValidationResult(ValidationStatus.PASSED,
'MAX_DATE_LATEST',
details={
'rows_processed': 0,
'rows_succeeded': 0,
'rows_failed': 0
})
stats_df['MaxDate'] = pd.to_datetime(stats_df['MaxDate'])
max_date_year = stats_df['MaxDate'].dt.year.max()
current_year = pd.to_datetime('today').year
if max_date_year < current_year:
return ValidationResult(
ValidationStatus.FAILED,
'MAX_DATE_LATEST',
message=
f"Latest date found was {max_date_year}, expected {current_year}.",
details={
'latest_date_found': int(max_date_year),
'expected_latest_date': int(current_year),
'rows_processed': rows_processed,
'rows_succeeded': 0,
'rows_failed': rows_processed
})
return ValidationResult(ValidationStatus.PASSED,
'MAX_DATE_LATEST',
details={
'rows_processed': rows_processed,
'rows_succeeded': rows_processed,
'rows_failed': 0
})
def validate_deleted_records_count(self, differ_df: pd.DataFrame,
params: dict) -> ValidationResult:
"""Checks if the total number of deleted points is within a threshold.
Args:
differ_df: A DataFrame containing the differ output, expected to have a
'DELETED' column.
params: A dictionary containing the validation parameters, which may
have a 'threshold' key.
Returns:
A ValidationResult object.
"""
if differ_df.empty:
deleted_records_count = 0
threshold = params.get('threshold', 0)
if deleted_records_count > threshold:
return ValidationResult(
ValidationStatus.FAILED,
'DELETED_RECORDS_COUNT',
message=
f"Found {deleted_records_count} deleted points, which is over the threshold of {threshold}.",
details={
'deleted_records_count': int(deleted_records_count),
'threshold': threshold,
'rows_processed': 0,
'rows_succeeded': 0,
'rows_failed': 0
})
return ValidationResult(ValidationStatus.PASSED,
'DELETED_RECORDS_COUNT',
details={
'rows_processed': 0,
'rows_succeeded': 0,
'rows_failed': 0
})
if 'DELETED' not in differ_df.columns:
return ValidationResult(
ValidationStatus.DATA_ERROR,
'DELETED_RECORDS_COUNT',
message="Input data is missing required column: 'DELETED'.")
rows_processed = len(differ_df)
threshold = params.get('threshold', 0)
deleted_records_count = differ_df['DELETED'].sum()
if deleted_records_count > threshold:
return ValidationResult(
ValidationStatus.FAILED,
'DELETED_RECORDS_COUNT',
message=
f"Found {deleted_records_count} deleted points, which is over the threshold of {threshold}.",
details={
'deleted_records_count': int(deleted_records_count),
'threshold': threshold,
'rows_processed': rows_processed,
'rows_succeeded': 0,
'rows_failed': rows_processed
})
return ValidationResult(ValidationStatus.PASSED,
'DELETED_RECORDS_COUNT',
details={
'rows_processed': rows_processed,
'rows_succeeded': rows_processed,
'rows_failed': 0
})
def validate_deleted_records_percent(self, differ_df: pd.DataFrame,
summary: dict,
params: dict) -> ValidationResult:
"""Checks if the percentage of deleted records is within a threshold.
Args:
differ_df: A DataFrame containing the differ output.
summary: A dictionary containing the differ summary.
params: A dictionary containing the validation parameters, which may
have a 'threshold' key.
Returns:
A ValidationResult object.
"""
if differ_df is None:
return ValidationResult(ValidationStatus.DATA_ERROR,
'DELETED_RECORDS_PERCENT',
message="Differ DataFrame is missing.")
if summary is None:
return ValidationResult(ValidationStatus.DATA_ERROR,
'DELETED_RECORDS_PERCENT',
message="Differ summary is missing.")
if 'previous_obs_size' not in summary:
return ValidationResult(
ValidationStatus.DATA_ERROR,
'DELETED_RECORDS_PERCENT',
message=
"Differ summary is missing required field: 'previous_obs_size'."
)
previous_obs_size = summary['previous_obs_size']
if differ_df.empty:
deleted_records_count = 0
elif 'DELETED' not in differ_df.columns:
return ValidationResult(
ValidationStatus.DATA_ERROR,
'DELETED_RECORDS_PERCENT',
message="Input data is missing required column: 'DELETED'.")
else:
deleted_records_count = differ_df['DELETED'].sum()
if previous_obs_size == 0:
if deleted_records_count > 0:
percent = 100.0
else:
percent = 0.0
else:
percent = (deleted_records_count / previous_obs_size) * 100
threshold = params.get('threshold', 0)
if percent > threshold:
return ValidationResult(
ValidationStatus.FAILED,
'DELETED_RECORDS_PERCENT',
message=
f"Found {percent:.2f}% deleted records, which is over the threshold of {threshold}%.",
details={
'deleted_records_count': int(deleted_records_count),
'previous_obs_size': int(previous_obs_size),
'percent': percent,
'threshold': threshold
})
return ValidationResult(
ValidationStatus.PASSED,
'DELETED_RECORDS_PERCENT',
details={
'deleted_records_count': int(deleted_records_count),
'previous_obs_size': int(previous_obs_size),
'percent': percent,
'threshold': threshold
})
def validate_empty_import(self, differ_df: pd.DataFrame, summary: dict,
params: dict) -> ValidationResult:
"""Checks if the import is empty (no observations and no schema).
Args:
differ_df: A DataFrame containing the differ output (unused but passed for consistency).
summary: A dictionary containing the differ summary.
params: A dictionary containing the validation parameters.
Returns:
A ValidationResult object.
"""
if summary is None:
return ValidationResult(ValidationStatus.DATA_ERROR,
'EMPTY_IMPORT_CHECK',
message="Differ summary is missing.")
current_obs_size = summary['current_obs_size']
current_schema_size = summary['current_schema_size']
if current_obs_size == 0 and current_schema_size == 0:
return ValidationResult(
ValidationStatus.FAILED,
'EMPTY_IMPORT_CHECK',
message=
"The import is empty: both current_obs_size and current_schema_size are 0.",
details={
'current_obs_size': int(current_obs_size),
'current_schema_size': int(current_schema_size)
})
return ValidationResult(
ValidationStatus.PASSED,
'EMPTY_IMPORT_CHECK',
details={
'current_obs_size': int(current_obs_size),
'current_schema_size': int(current_schema_size)
})
def validate_missing_refs_count(self, report: dict,
params: dict) -> ValidationResult:
"""Checks if the total number of missing references is within a threshold.
Args:
report: A json object containing the lint report
params: A dictionary containing the validation parameters, which may
have a 'threshold' key.
Returns:
A ValidationResult object.
"""
missing_refs_count = 0
if report:
counters = report.get('levelSummary',
{}).get('LEVEL_WARNING',
{}).get('counters', {})
missing_refs_count = sum(
int(value)
for key, value in counters.items()
if key.startswith('Existence_MissingReference'))
threshold = params.get('threshold', 0)
if missing_refs_count > threshold:
return ValidationResult(
ValidationStatus.FAILED,
'MISSING_REFS_COUNT',
message=
f"Found {missing_refs_count} missing references, which is over the threshold of {threshold}.",
details={'missing_refs_count': missing_refs_count})
return ValidationResult(
ValidationStatus.PASSED,
'MISSING_REFS_COUNT',
details={'missing_refs_count': missing_refs_count})
def validate_lint_error_count(self, report: dict,
params: dict) -> ValidationResult:
"""Checks if the total number of lint errors is within a threshold.
Args:
report: A json object containing the lint report
params: A dictionary containing the validation parameters, which may
have a 'threshold' key.
Returns:
A ValidationResult object.
"""
lint_error_count = 0
if report:
counters = report.get('levelSummary',
{}).get('LEVEL_ERROR',
{}).get('counters', {})
lint_error_count = sum(int(value) for value in counters.values())
threshold = params.get('threshold', 0)
if lint_error_count > threshold:
return ValidationResult(
ValidationStatus.FAILED,
'LINT_ERROR_COUNT',
message=
f"Found {lint_error_count} lint errors, which is over the threshold of {threshold}.",
details={'lint_error_count': lint_error_count})
return ValidationResult(ValidationStatus.PASSED,
'LINT_ERROR_COUNT',
details={'lint_error_count': lint_error_count})
def validate_modified_records_count(self, differ_df: pd.DataFrame,
params: dict) -> ValidationResult:
"""Checks if the number of modified points is the same for all StatVars.
Args:
differ_df: A DataFrame containing the differ output, expected to have a
'MODIFIED' column.
params: A dictionary containing the validation parameters.
Returns:
A ValidationResult object.
"""
if differ_df.empty:
return ValidationResult(ValidationStatus.PASSED,
'MODIFIED_RECORDS_COUNT',
details={
'rows_processed': 0,
'rows_succeeded': 0,
'rows_failed': 0
})
if 'MODIFIED' not in differ_df.columns:
return ValidationResult(
ValidationStatus.DATA_ERROR,
'MODIFIED_RECORDS_COUNT',
message="Input data is missing required column: 'MODIFIED'.")
rows_processed = len(differ_df)
unique_counts = differ_df['MODIFIED'].nunique()
if unique_counts > 1:
return ValidationResult(
ValidationStatus.FAILED,
'MODIFIED_RECORDS_COUNT',
message=
"The number of modified data points is not consistent across all StatVars",
details={
'distinct_statvar_count': differ_df['StatVar'].nunique(),
'distinct_modified_records_count': unique_counts,
'rows_processed': rows_processed,
'rows_succeeded': 0,
'rows_failed': rows_processed
})
return ValidationResult(ValidationStatus.PASSED,
'MODIFIED_RECORDS_COUNT',
details={
'rows_processed': rows_processed,
'rows_succeeded': rows_processed,
'rows_failed': 0
})
def validate_added_records_count(self, differ_df: pd.DataFrame,
params: dict) -> ValidationResult:
"""Checks if the number of added points is the same for all StatVars.
Args:
differ_df: A DataFrame containing the differ output, expected to have an
'ADDED' column.
params: A dictionary containing the validation parameters.
Returns:
A ValidationResult object.
"""
if differ_df.empty:
return ValidationResult(ValidationStatus.PASSED,
'ADDED_RECORDS_COUNT',
details={
'rows_processed': 0,
'rows_succeeded': 0,
'rows_failed': 0
})
if 'ADDED' not in differ_df.columns:
return ValidationResult(
ValidationStatus.DATA_ERROR,
'ADDED_RECORDS_COUNT',
message="Input data is missing required column: 'ADDED'.")
rows_processed = len(differ_df)
unique_counts = differ_df['ADDED'].nunique()
if unique_counts > 1:
return ValidationResult(
ValidationStatus.FAILED,
'ADDED_RECORDS_COUNT',
message=
"The number of added data points is not consistent across all StatVars.",
details={
'distinct_statvar_count': differ_df['StatVar'].nunique(),
'distinct_added_records_count': unique_counts,
'rows_processed': rows_processed,
'rows_succeeded': 0,
'rows_failed': rows_processed
})
return ValidationResult(ValidationStatus.PASSED,
'ADDED_RECORDS_COUNT',
details={
'rows_processed': rows_processed,
'rows_succeeded': rows_processed,
'rows_failed': 0
})
def validate_num_places_consistent(self, stats_df: pd.DataFrame,
params: dict) -> ValidationResult:
"""Checks if the number of places is the same for all StatVars.
Args:
stats_df: A DataFrame containing the summary statistics, expected to have
a 'NumPlaces' column.
params: A dictionary containing the validation parameters.
Returns:
A ValidationResult object.
"""
if 'NumPlaces' not in stats_df.columns:
return ValidationResult(
ValidationStatus.DATA_ERROR,
'NUM_PLACES_CONSISTENT',
message="Input data is missing required column: 'NumPlaces'.")
rows_processed = len(stats_df)
if stats_df.empty:
return ValidationResult(ValidationStatus.PASSED,
'NUM_PLACES_CONSISTENT',
details={
'rows_processed': 0,
'rows_succeeded': 0,
'rows_failed': 0
})
unique_counts = stats_df['NumPlaces'].nunique()
if unique_counts > 1:
return ValidationResult(
ValidationStatus.FAILED,
'NUM_PLACES_CONSISTENT',
message=
"The number of places is not consistent across all StatVars.",
details={
'distinct_statvar_count': stats_df['StatVar'].nunique(),
'distinct_place_count': unique_counts,
'rows_processed': rows_processed,
'rows_succeeded': 0,
'rows_failed': rows_processed
})
return ValidationResult(ValidationStatus.PASSED,
'NUM_PLACES_CONSISTENT',
details={
'rows_processed': rows_processed,
'rows_succeeded': rows_processed,
'rows_failed': 0
})
def validate_num_places_count(self, stats_df: pd.DataFrame,
params: dict) -> ValidationResult:
"""Checks if the number of places for each StatVar is within a defined range.
The range can be specified using 'minimum', 'maximum', or an exact 'value'
in the params.
Args:
stats_df: A DataFrame containing the summary statistics, expected to have
'NumPlaces' and 'StatVar' columns.
params: A dictionary containing the validation parameters.
Returns:
A ValidationResult object.
"""
if 'NumPlaces' not in stats_df.columns:
return ValidationResult(
ValidationStatus.DATA_ERROR,
'NUM_PLACES_COUNT',
message="Input data is missing required column: 'NumPlaces'.")
if stats_df.empty:
return ValidationResult(ValidationStatus.PASSED,
'NUM_PLACES_COUNT',
details={
'rows_processed': 0,
'rows_succeeded': 0,
'rows_failed': 0
})
min_val = params.get('minimum')
max_val = params.get('maximum')
exact_val = params.get('value')
rows_processed = len(stats_df)
rows_failed = 0
failed_rows_details = []
for _, row in stats_df.iterrows():
value = row['NumPlaces']
stat_var = row.get('StatVar', 'Unknown')
failed = False
if exact_val is not None and value != exact_val:
failed = True
failed_rows_details.append({
'stat_var': stat_var,
'actual_value': value,
'expected_value': exact_val,
'reason': f"Expected exactly {exact_val}"
})
elif min_val is not None and value < min_val:
failed = True
failed_rows_details.append({
'stat_var': stat_var,
'actual_value': value,
'minimum': min_val,
'reason': f"Below minimum of {min_val}"
})
elif max_val is not None and value > max_val:
failed = True
failed_rows_details.append({
'stat_var': stat_var,
'actual_value': value,
'maximum': max_val,
'reason': f"Above maximum of {max_val}"
})
if failed:
rows_failed += 1
rows_succeeded = rows_processed - rows_failed
if rows_failed > 0:
return ValidationResult(
ValidationStatus.FAILED,
'NUM_PLACES_COUNT',
message=
f"{rows_failed} out of {rows_processed} rows failed the range check.",
details={
'failed_rows': failed_rows_details,
'rows_processed': rows_processed,
'rows_succeeded': rows_succeeded,
'rows_failed': rows_failed
})
return ValidationResult(ValidationStatus.PASSED,
'NUM_PLACES_COUNT',
details={
'rows_processed': rows_processed,
'rows_succeeded': rows_succeeded,
'rows_failed': rows_failed
})
def validate_min_value_check(self, stats_df: pd.DataFrame,
params: dict) -> ValidationResult:
"""Checks if the MinValue for each StatVar is not below a defined minimum.
Args:
stats_df: A DataFrame containing the summary statistics, expected to have
'MinValue' and 'StatVar' columns.
params: A dictionary containing the validation parameters, which must
have a 'minimum' key.
Returns:
A ValidationResult object.
"""
if 'minimum' not in params:
return ValidationResult(
ValidationStatus.CONFIG_ERROR,
'MIN_VALUE_CHECK',
message="Configuration error: 'minimum' key not specified.")
if 'MinValue' not in stats_df.columns:
return ValidationResult(
ValidationStatus.DATA_ERROR,
'MIN_VALUE_CHECK',
message="Input data is missing required column: 'MinValue'.")
if stats_df.empty:
return ValidationResult(ValidationStatus.PASSED,
'MIN_VALUE_CHECK',
details={
'rows_processed': 0,
'rows_succeeded': 0,
'rows_failed': 0
})
min_val = params['minimum']
rows_processed = len(stats_df)
rows_failed = 0
failed_rows_details = []
for _, row in stats_df.iterrows():
min_value = row['MinValue']
stat_var = row.get('StatVar', 'Unknown')
if min_value < min_val:
rows_failed += 1
failed_rows_details.append({
'stat_var': stat_var,
'actual_min_value': min_value,
'minimum': min_val
})
rows_succeeded = rows_processed - rows_failed
if rows_failed > 0:
return ValidationResult(
ValidationStatus.FAILED,
'MIN_VALUE_CHECK',
message=
f"{rows_failed} out of {rows_processed} StatVars failed the minimum value check.",
details={
'failed_rows': failed_rows_details,
'rows_processed': rows_processed,
'rows_succeeded': rows_succeeded,
'rows_failed': rows_failed
})
return ValidationResult(ValidationStatus.PASSED,
'MIN_VALUE_CHECK',
details={
'rows_processed': rows_processed,
'rows_succeeded': rows_succeeded,
'rows_failed': rows_failed
})
def validate_max_date_consistent(self, stats_df: pd.DataFrame,
params: dict) -> ValidationResult:
"""Checks if the MaxDate is the same for all StatVars.
Args:
stats_df: A DataFrame containing the summary statistics, expected to have
a 'MaxDate' column.
params: A dictionary containing the validation parameters.
Returns:
A ValidationResult object.
"""
if 'MaxDate' not in stats_df.columns:
return ValidationResult(
ValidationStatus.DATA_ERROR,
'MAX_DATE_CONSISTENT',
message="Input data is missing required column: 'MaxDate'.")
rows_processed = len(stats_df)
if stats_df.empty:
return ValidationResult(ValidationStatus.PASSED,
'MAX_DATE_CONSISTENT',
details={
'rows_processed': 0,
'rows_succeeded': 0,
'rows_failed': 0
})
unique_dates = stats_df['MaxDate'].nunique()
if unique_dates > 1:
return ValidationResult(
ValidationStatus.FAILED,
'MAX_DATE_CONSISTENT',
message="The MaxDate is not consistent across all StatVars.",
details={
'distinct_statvar_count': stats_df['StatVar'].nunique(),
'distinct_max_date_count': unique_dates,
'rows_processed': rows_processed,
'rows_succeeded': 0,
'rows_failed': rows_processed
})
return ValidationResult(ValidationStatus.PASSED,
'MAX_DATE_CONSISTENT',
details={
'rows_processed': rows_processed,
'rows_succeeded': rows_processed,
'rows_failed': 0
})
def validate_num_observations_check(self, stats_df: pd.DataFrame,
params: dict) -> ValidationResult:
"""Checks if the number of observations for each StatVar is within a defined range.
The range can be specified using 'minimum', 'maximum', or an exact 'value'
in the params.
Args:
stats_df: A DataFrame containing the summary statistics, expected to have
'NumObservations' and 'StatVar' columns.
params: A dictionary containing the validation parameters.
Returns:
A ValidationResult object.
"""
if 'NumObservations' not in stats_df.columns:
return ValidationResult(
ValidationStatus.DATA_ERROR,
'NUM_OBSERVATIONS_CHECK',
message=
"Input data is missing required column: 'NumObservations'.")
if stats_df.empty:
return ValidationResult(ValidationStatus.PASSED,
'NUM_OBSERVATIONS_CHECK',
details={
'rows_processed': 0,
'rows_succeeded': 0,
'rows_failed': 0
})
min_val = params.get('minimum')
max_val = params.get('maximum')
exact_val = params.get('value')
rows_processed = len(stats_df)
rows_failed = 0
failed_rows_details = []
for _, row in stats_df.iterrows():
value = row['NumObservations']
stat_var = row.get('StatVar', 'Unknown')
failed = False
if exact_val is not None and value != exact_val:
failed = True
failed_rows_details.append({
'stat_var': stat_var,
'actual_value': value,
'expected_value': exact_val,
'reason': f"Expected exactly {exact_val}"
})
elif min_val is not None and value < min_val:
failed = True
failed_rows_details.append({
'stat_var': stat_var,
'actual_value': value,
'minimum': min_val,
'reason': f"Below minimum of {min_val}"
})
elif max_val is not None and value > max_val:
failed = True
failed_rows_details.append({
'stat_var': stat_var,
'actual_value': value,
'maximum': max_val,
'reason': f"Above maximum of {max_val}"
})
if failed:
rows_failed += 1
rows_succeeded = rows_processed - rows_failed
if rows_failed > 0:
return ValidationResult(
ValidationStatus.FAILED,
'NUM_OBSERVATIONS_CHECK',
message=
f"{rows_failed} out of {rows_processed} rows failed the range check.",
details={
'failed_rows': failed_rows_details,
'rows_processed': rows_processed,
'rows_succeeded': rows_succeeded,
'rows_failed': rows_failed
})
return ValidationResult(ValidationStatus.PASSED,
'NUM_OBSERVATIONS_CHECK',
details={
'rows_processed': rows_processed,
'rows_succeeded': rows_succeeded,
'rows_failed': rows_failed
})
def validate_unit_consistency(self, stats_df: pd.DataFrame,
params: dict) -> ValidationResult:
"""Checks if the unit is the same for all StatVars.
Args:
stats_df: A DataFrame containing the summary statistics, expected to have
a 'Units' column.
params: A dictionary containing the validation parameters.
Returns:
A ValidationResult object.
"""
if 'Units' not in stats_df.columns:
return ValidationResult(
ValidationStatus.DATA_ERROR,
'UNIT_CONSISTENCY_CHECK',
message="Input data is missing required column: 'Units'.")
rows_processed = len(stats_df)
if stats_df.empty:
return ValidationResult(ValidationStatus.PASSED,
'UNIT_CONSISTENCY_CHECK',
details={
'rows_processed': 0,
'rows_succeeded': 0,
'rows_failed': 0
})
unique_units = stats_df['Units'].nunique()
if unique_units > 1:
return ValidationResult(
ValidationStatus.FAILED,
'UNIT_CONSISTENCY_CHECK',
message="The unit is not consistent across all StatVars.",
details={
'distinct_statvar_count': stats_df['StatVar'].nunique(),
'distinct_unit_count': unique_units,
'rows_processed': rows_processed,
'rows_succeeded': 0,
'rows_failed': rows_processed
})
return ValidationResult(ValidationStatus.PASSED,
'UNIT_CONSISTENCY_CHECK',
details={
'rows_processed': rows_processed,
'rows_succeeded': rows_processed,
'rows_failed': 0
})
def validate_max_value_check(self, stats_df: pd.DataFrame,
params: dict) -> ValidationResult:
"""Checks if the MaxValue for each StatVar is not above a defined maximum.
Args:
stats_df: A DataFrame containing the summary statistics, expected to have
'MaxValue' and 'StatVar' columns.
params: A dictionary containing the validation parameters, which must
have a 'maximum' key.
Returns:
A ValidationResult object.
"""
if 'maximum' not in params:
return ValidationResult(
ValidationStatus.CONFIG_ERROR,
'MAX_VALUE_CHECK',
message="Configuration error: 'maximum' key not specified.")
if 'MaxValue' not in stats_df.columns:
return ValidationResult(
ValidationStatus.DATA_ERROR,
'MAX_VALUE_CHECK',
message="Input data is missing required column: 'MaxValue'.")
if stats_df.empty:
return ValidationResult(ValidationStatus.PASSED,
'MAX_VALUE_CHECK',
details={
'rows_processed': 0,
'rows_succeeded': 0,
'rows_failed': 0
})
max_val = params['maximum']
rows_processed = len(stats_df)
rows_failed = 0
failed_rows_details = []
for _, row in stats_df.iterrows():
max_value = row['MaxValue']
stat_var = row.get('StatVar', 'Unknown')
if max_value > max_val:
rows_failed += 1
failed_rows_details.append({
'stat_var': stat_var,
'actual_max_value': max_value,
'maximum': max_val
})
rows_succeeded = rows_processed - rows_failed
if rows_failed > 0:
return ValidationResult(
ValidationStatus.FAILED,
'MAX_VALUE_CHECK',
message=
f"{rows_failed} out of {rows_processed} StatVars failed the maximum value check.",
details={
'failed_rows': failed_rows_details,
'rows_processed': rows_processed,
'rows_succeeded': rows_succeeded,
'rows_failed': rows_failed
})
return ValidationResult(ValidationStatus.PASSED,
'MAX_VALUE_CHECK',
details={
'rows_processed': rows_processed,
'rows_succeeded': rows_succeeded,
'rows_failed': rows_failed
})
def validate_goldens(self, df: pd.DataFrame,
params: dict) -> ValidationResult:
"""Validates records against a golden set.
Args:
df: A DataFrame containing the data to validate (used if input_files
is not provided in params).
params: A dictionary containing:
'golden_files': Path(s) to golden MCF/CSV files.
'input_files': (Optional) Path(s) to input files. If not provided,
the 'df' will be used.
'output_path': (Optional) folder or output filename to save missing goldens.
And other optional validator_goldens config (e.g., goldens_key_property).
Returns:
A ValidationResult object.
"""
golden_files = params.get('golden_files')
if not golden_files:
return ValidationResult(
ValidationStatus.CONFIG_ERROR,
'GOLDENS_CHECK',
message=
"Configuration error: 'golden_files' must be specified for GOLDENS_CHECK validator."
)
try:
inputs = params.get('input_files')