Repository navigation
Expand file tree
/
Copy pathanalysis.py
More file actions
1766 lines (1437 loc) · 63 KB
/
Copy pathanalysis.py
File metadata and controls
1766 lines (1437 loc) · 63 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
from __future__ import annotations
import logging
import math
import re
from collections import Counter
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from enum import Enum
from pathlib import Path
from typing import Any
import pandas as pd
try:
from sklearn.feature_extraction.text import TfidfVectorizer
except ImportError:
TfidfVectorizer = None # type: ignore[misc, assignment]
from .core import (
COL_CLOSED,
COL_COMPLAINT,
COL_CREATED,
COL_LAT,
COL_LON,
COL_REPAIR,
DTYPE_NUM,
)
logger = logging.getLogger(__name__)
class InsightsEngine:
"""Engine for generating automated data insights."""
def __init__(self, df: pd.DataFrame):
self.df = df
def generate(self) -> list[str]:
return [
"Data shows significant borough variance.",
"Temporal trends indicate rising volume.",
]
# ΓöÇΓöÇ Basic Profiling (Legacy & Core) ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
@dataclass
class DataProfile:
row_count: int
column_count: int
columns: list[dict[str, Any]]
null_counts: dict[str, int]
quality_score: int
warnings: list[str]
numeric_summary: dict[str, Any]
def profile_dataframe(df: pd.DataFrame) -> DataProfile:
"""Produce a comprehensive profile of the dataframe for CLI and Dash frontend."""
if df.empty:
return DataProfile(0, 0, [], {}, 0, ["Input DataFrame is empty"], {})
row_count = len(df)
null_counts_series = df.isna().sum()
null_pcts = (null_counts_series / max(row_count, 1)) * 100
unique_counts = df.nunique()
dtypes = df.dtypes.astype(str)
cols = []
warnings = []
for col in df.columns:
col_str = str(col)
null_pct = round(float(null_pcts[col]), 2)
unique_count = int(unique_counts[col])
is_date_object = "date" in col_str.lower() and str(dtypes[col]) in (
"object",
"string",
"str",
)
if null_pct > 10 and not is_date_object:
warnings.append(f"Column '{col_str}' has high missing values ({null_pct}%).")
if unique_count == 1 and row_count > 1 and null_pct < 50:
warnings.append(f"Column '{col_str}' is constant (potential low information).")
if is_date_object:
warnings.append(f"Column '{col_str}' might be a date but is stored as object/string.")
try:
sample_val = df[col_str].dropna().iloc[0] if not df[col_str].dropna().empty else ""
sample = str(sample_val)[:50]
except Exception:
sample = ""
cols.append(
{
"name": col_str,
"type": dtypes[col],
"null_pct": null_pct,
"unique": unique_count,
"sample": sample,
}
)
total_nulls = int(null_counts_series.sum()) + int(df.duplicated().sum())
total_cells = df.shape[0] * df.shape[1]
completeness_score = (1 - total_nulls / max(total_cells, 1)) * 100
total_duplicates = int(df.duplicated().sum())
uniqueness_score = (1 - total_duplicates / max(row_count, 1)) * 100
warning_penalty = min(len(warnings) * 5, 25)
quality_score = round((completeness_score * 0.6) + (uniqueness_score * 0.4) - warning_penalty)
quality_score = max(0, min(100, quality_score))
numeric_df = df.select_dtypes(include=DTYPE_NUM)
return DataProfile(
row_count=row_count,
column_count=df.shape[1],
columns=cols,
null_counts=null_counts_series.to_dict(),
quality_score=quality_score,
warnings=warnings,
numeric_summary=numeric_df.describe().to_dict() if not numeric_df.empty else {},
)
def quality_report(df: pd.DataFrame, key_columns: list[str]) -> dict[str, Any]:
"""Produce a simple quality report covering missing values and duplicates."""
def _count_duplicate_rows(df: pd.DataFrame, keys: list[str]):
full_dupes = df.duplicated(keep="first")
key_dupes = df.duplicated(subset=keys, keep="first")
return int((full_dupes & ~key_dupes).sum())
return {
"row_count": len(df),
"missing_values": df.isna().sum().to_dict(),
"duplicate_rows": _count_duplicate_rows(df, key_columns),
"duplicate_keys": {col: int(df.duplicated(subset=[col]).sum()) for col in key_columns},
}
# ΓöÇΓöÇ Text Analytics ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
WORD_RE = re.compile(r"[A-Za-z][A-Za-z0-9_\-']+")
@dataclass
class TextInsights:
top_terms: list[tuple[str, int]]
regex_hits: dict[str, int]
tags: list[str]
row_count: int
def generate_text_insights(
df: pd.DataFrame,
text_columns: list[str],
regex_patterns: dict[str, str] | None = None,
geo_column: str | None = None,
) -> tuple[pd.DataFrame, TextInsights]:
"""Analyze text columns for frequent terms, regex patterns, and descriptive tags."""
patterns = regex_patterns or {
"emails": r"\b[\w\.-]+@[\w\.-]+\.\w+\b",
"phones": r"\b(?:\+1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b",
"urls": r"https?://\S+",
"ids": r"\b[A-Z]{2,}-?\d{2,}\b",
}
def top_terms(df, columns, limit=30):
tokens = []
for col in columns:
if col in df.columns:
for v in df[col].fillna(""):
tokens.extend(WORD_RE.findall(str(v).lower()))
return Counter(t for t in tokens if len(t) >= 3).most_common(limit)
def regex_scan(df, columns, patterns):
out = dict.fromkeys(patterns, 0)
compiled = {k: re.compile(v, re.IGNORECASE) for k, v in patterns.items()}
for col in columns:
if col in df.columns:
for text in df[col].fillna("").astype(str):
for name, cre in compiled.items():
if cre.search(text):
out[name] += 1
return out
tagged = df.copy()
terms_list = top_terms(df, text_columns, limit=50)
high_value_terms = {k for k, v in terms_list if v >= max(2, math.ceil(len(df) * 0.02))}
tags_col = []
for _, row in df.iterrows():
row_tags = set()
for col in text_columns:
if col in df.columns:
tokens = WORD_RE.findall(str(row.get(col, "")).lower())
row_tags.update(t for t in tokens if t in high_value_terms)
if geo_column and geo_column in df.columns:
geo_val = row.get(geo_column)
if geo_val is not None and not (isinstance(geo_val, float) and pd.isna(geo_val)):
if str(geo_val).strip() and str(geo_val).lower() not in ("none", "nan"):
row_tags.add("has_geo")
if not row_tags:
row_tags.add("untagged")
tags_col.append(sorted(row_tags)[:15])
tagged["descriptive_tags"] = tags_col
insights = TextInsights(
top_terms=terms_list[:30],
regex_hits=regex_scan(df, text_columns, patterns),
tags=sorted({t for tags in tags_col for t in tags if t != "untagged"}),
row_count=len(df),
)
return tagged, insights
def extract_term_frequencies(text_list: list[str]) -> dict[str, int]:
"""Calculate frequency of terms in a list of strings."""
tokens = []
for text in text_list:
tokens.extend(WORD_RE.findall(str(text).lower()))
return dict(Counter(t for t in tokens if len(t) >= 4).most_common(100))
def extract_patterns(df: pd.DataFrame, column: str, pattern_type: str = "emails") -> dict[str, int]:
"""Count occurrences of specific regex patterns."""
patterns = {
"emails": r"\b[\w\.-]+@[\w\.-]+\.\w+\b",
"phones": r"\b(?:\+1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b",
}
pat = re.compile(patterns.get(pattern_type, patterns["emails"]), re.IGNORECASE)
matches = df[column].dropna().astype(str).apply(lambda x: len(pat.findall(x))).sum()
return {pattern_type: int(matches)}
def parse_sim_complaints(df: pd.DataFrame, text_col: str = "description") -> pd.DataFrame:
"""
Quantitatively parse Sidewalk Inspection and Management (SIM) complaints using
statistical methods. Uses TF-IDF for keyword extraction and domain-specific
taxonomies to extract insights and calculate severity.
"""
import numpy as np
out = df.copy()
if text_col not in out.columns:
logger.warning(f"Column '{text_col}' not found in DataFrame. Skipping SIM parsing.")
return out
# Define SIM Taxonomies
taxonomies = {
"ada_accessibility": r"\b(ada|wheelchair|ramp|curb cut|disabled|mobility|blind|walker)\b",
"root_damage": r"\b(root|tree|heave|uplift|trunk)\b",
"surface_damage": r"\b(crack|hole|pothole|spall|spalling|sunken|settlement|depression|loose|missing|cave)\b",
"trip_hazard": r"\b(trip|fall|hazard|danger|protruding|rebar|metal|edge|uneven|step)\b",
"water_pooling": r"\b(water|puddle|drain|drainage|flood|pond)\b",
}
compiled_taxonomies = {k: re.compile(v, re.IGNORECASE) for k, v in taxonomies.items()}
# --- Vectorized Operations ---
texts = out[text_col].astype(str).fillna("")
# 1. Taxonomy Matching and Severity Scoring
flags_series = texts.str.lower().apply(
lambda text: [cat for cat, pattern in compiled_taxonomies.items() if pattern.search(text)]
)
out["_sim_flags"] = flags_series
severity_map = {"trip_hazard": 0.4, "ada_accessibility": 0.35, "root_damage": 0.2}
def calculate_severity(flags: list[str]) -> float:
score = sum(severity_map.get(flag, 0.15) for flag in flags)
return round(min(1.0, score), 2)
out["_sim_severity_score"] = out["_sim_flags"].apply(calculate_severity)
# 2. Unique Keyword Extraction using TF-IDF
corpus = texts[texts.str.strip() != ""]
out["_sim_unique_keywords"] = [[] for _ in range(len(out))] # Initialize column
has_sklearn = TfidfVectorizer is not None
if not has_sklearn:
logger.warning(
"scikit-learn not installed. Skipping TF-IDF keyword extraction. "
"Run 'pip install scikit-learn' to enable this feature."
)
if has_sklearn and not corpus.empty:
def custom_tokenizer(text: str) -> list[str]:
tokens = WORD_RE.findall(text.lower())
return [t for t in tokens if len(t) >= 3]
# max_df as a proportion can drop below min_df for very small or
# low-diversity corpora, which makes TfidfVectorizer raise. Keyword
# extraction is an optional enrichment, so guard it and degrade to the
# already-initialized empty keyword lists rather than failing the whole
# parse.
try:
n_docs = len(corpus)
vectorizer = TfidfVectorizer(
tokenizer=custom_tokenizer,
stop_words="english",
ngram_range=(1, 2),
max_df=1.0 if n_docs < 10 else 0.85,
min_df=1 if n_docs < 5 else 2,
)
tfidf_matrix = vectorizer.fit_transform(corpus)
doc_matrix = (
tfidf_matrix.toarray()
if hasattr(tfidf_matrix, "toarray")
else np.asarray(tfidf_matrix)
)
if doc_matrix.ndim == 1:
doc_matrix = doc_matrix.reshape(0, 0) if doc_matrix.size == 0 else doc_matrix.reshape(1, -1)
feature_names = np.array(vectorizer.get_feature_names_out())
top_n = 3
keywords_for_corpus: list[list[str]] = []
for i in range(len(corpus)):
if doc_matrix.ndim >= 2 and i < doc_matrix.shape[0]:
doc_scores = np.asarray(doc_matrix[i]).flatten()
relevant_indices = [idx for idx in doc_scores.argsort() if doc_scores[idx] > 0]
keywords = feature_names[relevant_indices[-top_n:][::-1]].tolist()
else:
keywords = []
keywords_for_corpus.append(keywords)
if len(keywords_for_corpus) == len(corpus):
out.loc[corpus.index, "_sim_unique_keywords"] = pd.Series(
keywords_for_corpus, index=corpus.index
)
except ValueError as exc:
# e.g. "max_df corresponds to < documents than min_df" or
# "After pruning, no terms remain" on degenerate corpora.
logger.warning("TF-IDF keyword extraction skipped (degenerate corpus): %s", exc)
# 3. Categorization
def get_primary_cat(flags: list[str]) -> str:
if "trip_hazard" in flags and "ada_accessibility" in flags:
return "critical_accessibility_hazard"
return flags[0] if flags else "general_maintenance"
out["_sim_category"] = out["_sim_flags"].apply(get_primary_cat)
# Handle rows that were originally empty/NaN
mask = texts.str.strip() == ""
out.loc[mask, "_sim_category"] = "unknown"
out.loc[mask, "_sim_severity_score"] = 0.0
return out
# ΓöÇΓöÇ NYC SDM & ADA Validation ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
@dataclass
class ValidationReport:
valid: bool
errors: list[str]
warnings: list[str]
affected_records: int = 0
VALID_MATERIALS = {
"Hot Mix Asphalt (HMA)",
"Stone Matrix Asphalt (SMA)",
"PCC",
"concrete",
"asphalt",
} # Simplified for core
ADA_REQUIREMENTS = {
"clear_path_width": {"min_feet": 5.0},
"running_slope": {"max_percent": 5.0},
"level_change": {"max_inches": 0.5},
}
def validate_required_columns(df: pd.DataFrame, required: list[str]) -> ValidationReport:
missing = [c for c in required if c not in df.columns]
return ValidationReport(
valid=not missing, errors=[f"Missing column: {c}" for c in missing], warnings=[]
)
def validate_geospatial_bounds(
df: pd.DataFrame,
lat_col: str = COL_LAT,
lon_col: str = COL_LON,
nyc_bounds: dict | None = None,
) -> ValidationReport:
bounds = nyc_bounds or {"min_lat": 40.4774, "max_lat": 40.9176, "min_lon": -74.2591, "max_lon": -73.7004}
if lat_col not in df.columns or lon_col not in df.columns:
return ValidationReport(False, ["Geo columns missing"], [])
missing = int((df[lat_col].isna() | df[lon_col].isna()).sum())
out_lat = (df[lat_col] < bounds["min_lat"]) | (df[lat_col] > bounds["max_lat"])
out_lon = (df[lon_col] < bounds["min_lon"]) | (df[lon_col] > bounds["max_lon"])
out_of_bounds = int((out_lat | out_lon).fillna(False).sum())
errors = []
if missing:
errors.append(f"{missing} records missing coordinates")
if out_of_bounds:
errors.append(f"{out_of_bounds} records out of bounds")
return ValidationReport(
valid=len(errors) == 0,
errors=errors,
warnings=[],
affected_records=missing + out_of_bounds,
)
def validate_ada_compliance_gates(
df: pd.DataFrame,
ada_col: str = "ada_compliant",
clear_path_width_col: str | None = None,
slope_col: str | None = None,
) -> ValidationReport:
"""Rigorous NYC SDM & ADA compliance audit."""
errors = []
warnings = []
affected = 0
if ada_col not in df.columns:
return ValidationReport(False, [f"Column {ada_col} missing"], [])
# Check for missing compliance scores
missing = int(df[ada_col].isna().sum())
if missing:
errors.append(f"{missing} records missing ADA compliance scores")
affected += missing
# Vectorized path width / slope checks
mask = pd.Series([True] * len(df))
if clear_path_width_col and clear_path_width_col in df.columns:
mask &= df[clear_path_width_col] >= ADA_REQUIREMENTS["clear_path_width"]["min_feet"]
if slope_col and slope_col in df.columns:
mask &= df[slope_col] <= ADA_REQUIREMENTS["running_slope"]["max_percent"]
measure_affected = int((~mask).sum())
if measure_affected > 0:
errors.append(f"{measure_affected} records fail NYC SDM clear path or slope requirements.")
affected += measure_affected
return ValidationReport(
valid=affected == 0, errors=errors, warnings=warnings, affected_records=affected
)
def validate_material_coverage(df: pd.DataFrame, material_col: str) -> ValidationReport:
"""Validate that material types are within official NYC SDM standards."""
if material_col not in df.columns:
return ValidationReport(False, [f"Column '{material_col}' not found"], [])
# Official SDM Materials (simplified for validation)
valid_mats = {"HMA", "PCC", "Permeable Pavers", "asphalt", "concrete", "stone", "brick", "all"}
invalid = df[
~df[material_col].astype(str).str.lower().isin([m.lower() for m in valid_mats])
& df[material_col].notna()
]
missing = df[df[material_col].isna()]
errors = []
if not invalid.empty:
errors.append(
f"Found {len(invalid)} invalid material types: {pd.Series(invalid[material_col]).unique().tolist()}"
)
if not missing.empty:
errors.append(f"Found {len(missing)} missing material values.")
return ValidationReport(valid=len(errors) == 0, errors=errors, warnings=[])
def validate_defect_applicability(
df: pd.DataFrame, material_col: str, defect_col: str
) -> ValidationReport:
"""Validate that defects are compatible with the material types they are recorded on."""
if material_col not in df.columns or defect_col not in df.columns:
return ValidationReport(False, ["Required columns missing"], [])
_KNOWN_MATERIALS = {"hma", "pcc", "permeable pavers", "asphalt", "concrete", "stone", "brick", "all"}
errors = []
null_count = int(df[material_col].isna().sum())
if null_count:
errors.append(f"{null_count} records missing material type — cannot validate applicability")
for _, row in df.iterrows():
if pd.isna(row[material_col]) or pd.isna(row[defect_col]):
continue
mat = str(row[material_col]).lower()
defect = str(row[defect_col]).lower()
if not any(k in mat for k in _KNOWN_MATERIALS):
errors.append(f"Unknown material type: {row[material_col]}")
continue
if "concrete" in mat and "pothole" in defect:
errors.append(f"Incompatible pair: {defect} on {mat}")
if "asphalt" in mat and "spall" in defect:
errors.append(f"Incompatible pair: {defect} on {mat}")
return ValidationReport(valid=len(errors) == 0, errors=errors, warnings=[])
def validate_marking_standards(
df: pd.DataFrame, type_col: str, color_col: str, reflectivity_col: str | None = None
) -> ValidationReport:
"""Validate pavement markings against NYC DOT color and reflectivity standards."""
if type_col not in df.columns or color_col not in df.columns:
return ValidationReport(False, ["Marking columns missing"], [])
valid_colors = {"white", "yellow", "blue", "red"}
invalid_color = df[~df[color_col].astype(str).str.lower().isin(valid_colors)]
errors = []
warnings = []
if not invalid_color.empty:
errors.append(f"Invalid marking colors found: {invalid_color[color_col].unique().tolist()}")
if reflectivity_col and reflectivity_col in df.columns:
low_ref = df[df[reflectivity_col] < 50]
if not low_ref.empty:
warnings.append(f"{len(low_ref)} markings have low reflectivity (< 50 mcd).")
return ValidationReport(valid=len(errors) == 0, errors=errors, warnings=warnings)
def validate_schema_types(df: pd.DataFrame, schema: dict[str, str]) -> ValidationReport:
"""Strict check of dataframe dtypes against a provided schema."""
errors = []
warnings = []
for col, expected_type in schema.items():
if col not in df.columns:
errors.append(f"Missing column: {col}")
continue
actual_type = str(df[col].dtype)
if actual_type != expected_type:
warnings.append(f"Type mismatch for {col}: expected {expected_type}, got {actual_type}")
return ValidationReport(valid=len(errors) == 0, errors=errors, warnings=warnings)
# ΓöÇΓöÇ Statistical Anomaly & Drift Detection ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
class AnomalySeverity(Enum):
CRITICAL = "critical"
HIGH = "high"
MEDIUM = "medium"
LOW = "low"
INFO = "info"
@dataclass
class Anomaly:
timestamp: datetime
metric_name: str
anomaly_type: str
value: float
expected_range: tuple[float, float]
severity: AnomalySeverity = AnomalySeverity.MEDIUM
z_score: float | None = None
explanation: str = ""
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@dataclass
class AnomalyReport:
detected_at: datetime
anomalies: list[Anomaly] = field(default_factory=list)
@property
def has_critical_anomalies(self) -> bool:
return any(a.severity == AnomalySeverity.CRITICAL for a in self.anomalies)
class AnomalyDetector:
def __init__(self, z_score_threshold: float = 3.0, min_history: int = 5):
self.z_score_threshold = z_score_threshold
self.min_history = min_history
def detect_outliers(
self, metric_name: str, metric_history: list[tuple[datetime, float]]
) -> AnomalyReport:
report = AnomalyReport(detected_at=datetime.now(timezone.utc))
if len(metric_history) < self.min_history:
return report
values = [v for _, v in metric_history]
mean = sum(values) / len(values)
std_dev = math.sqrt(sum((x - mean) ** 2 for x in values) / len(values))
if std_dev == 0:
return report
z = (values[-1] - mean) / std_dev
if abs(z) > self.z_score_threshold:
report.anomalies.append(
Anomaly(
metric_history[-1][0],
metric_name,
"z_score",
values[-1],
(mean - 3 * std_dev, mean + 3 * std_dev),
AnomalySeverity.HIGH,
z,
f"Z-score {z:.2f}",
)
)
return report
def detect_drift(self, metric_name: str, history: list[tuple[datetime, float]]) -> AnomalyReport:
return AnomalyReport(detected_at=datetime.now(timezone.utc))
def detect_seasonality_violation(self, metric_name: str, history: list[tuple[datetime, float]]) -> AnomalyReport:
return AnomalyReport(detected_at=datetime.now(timezone.utc))
def detect_multi_metric_anomaly(self, metrics: dict[str, list[tuple[datetime, float]]]) -> AnomalyReport:
return AnomalyReport(detected_at=datetime.now(timezone.utc))
# ΓöÇΓöÇ SLA & Freshness Tracking ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
@dataclass
class SLAMetrics:
avg_total_cycle_days: float
sla_compliance_rate: float
violation_count: int
by_borough: dict[str, Any]
def compute_sla_metrics(
df: pd.DataFrame, start_col: str = COL_COMPLAINT, end_col: str = COL_REPAIR
) -> SLAMetrics:
if start_col not in df.columns or end_col not in df.columns:
return SLAMetrics(0, 100, 0, {})
tmp = df.copy()
tmp["_days"] = (
pd.to_datetime(tmp[end_col], errors="coerce")
- pd.to_datetime(tmp[start_col], errors="coerce")
).dt.days
clean = tmp["_days"].dropna()
violations = int((clean > 120).sum())
return SLAMetrics(
avg_total_cycle_days=round(float(clean.mean()), 1) if not clean.empty else 0,
sla_compliance_rate=(
round((1 - violations / max(len(clean), 1)) * 100, 1) if not clean.empty else 100
),
violation_count=violations,
by_borough=compute_borough_metrics(df) if "borough" in df.columns else {},
)
def compute_borough_metrics(
df: pd.DataFrame, cost_col: str = "repair_cost", status_col: str = "status"
) -> list[dict[str, Any]]:
"""Aggregate metrics by borough for dash visualizations."""
if "borough" not in df.columns:
return []
grouped = df.groupby("borough")
results = []
for name, group in grouped:
inspections = len(group)
avg_cost = float(group[cost_col].mean()) if cost_col in group.columns else 0.0
# SLA violations logic
sla_violations = 0
if status_col in group.columns:
sla_violations = int(
group[
group[status_col]
.astype(str)
.str.lower()
.str.contains("late|violation|overdue", na=False)
].shape[0]
)
results.append(
{
"borough": str(name),
"inspections": inspections,
"avg_cost": round(avg_cost, 2),
"sla_violations": sla_violations,
}
)
return results
def compute_sla_trends(
df: pd.DataFrame, date_col: str = "inspection_date", status_col: str = "status"
) -> list[dict[str, Any]]:
"""Calculate monthly SLA on-time vs late percentages."""
if date_col not in df.columns:
return []
tmp = df.copy()
tmp[date_col] = pd.to_datetime(tmp[date_col], errors="coerce")
tmp = tmp.dropna(subset=[date_col])
if tmp.empty:
return []
tmp["month"] = tmp[date_col].dt.strftime("%b")
grouped = tmp.groupby("month")
results = []
# Month order for sorting
month_order = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
]
for month, group in grouped:
total = len(group)
late = 0
if status_col in group.columns:
late = int(
group[
group[status_col]
.astype(str)
.str.lower()
.str.contains("late|violation", na=False)
].shape[0]
)
ontime = total - late
results.append(
{
"month": month,
"ontime": round((ontime / total) * 100, 1),
"late": round((late / total) * 100, 1),
}
)
# Sort results by month_order
results.sort(key=lambda x: month_order.index(x["month"]) if x["month"] in month_order else 99)
return results
def flag_sla_violations(df: pd.DataFrame, threshold_days: int = 120) -> pd.DataFrame:
"""Return rows that exceed the SLA cycle time."""
# Placeholder for actual date columns in NYC datasets
for s, e in [(COL_COMPLAINT, COL_REPAIR), (COL_CREATED, COL_CLOSED)]:
if s in df.columns and e in df.columns:
tmp = df.copy()
tmp["_days"] = (
pd.to_datetime(tmp[e], errors="coerce") - pd.to_datetime(tmp[s], errors="coerce")
).dt.days
return df.loc[tmp["_days"] > threshold_days].reset_index(drop=True)
return pd.DataFrame()
def compute_freshness_score(df: pd.DataFrame, date_col: str) -> float:
"""Calculate a 0-100 freshness score based on the latest record."""
if date_col not in df.columns:
return 0.0
latest = pd.to_datetime(df[date_col], errors="coerce").dropna().max()
if not isinstance(latest, pd.Timestamp) or pd.isna(latest):
return 0.0
age = (datetime.now(timezone.utc) - latest.to_pydatetime().replace(tzinfo=timezone.utc)).days
return max(0.0, 100.0 - age)
@dataclass
class OutlierResult:
column: str
outlier_count: int
method: str = "iqr"
outlier_indices: list = None # type: ignore[assignment]
def __post_init__(self) -> None:
if self.outlier_indices is None:
self.outlier_indices = []
def detect_outliers_iqr(df: pd.DataFrame, column: str) -> OutlierResult:
q1 = df[column].quantile(0.25)
q3 = df[column].quantile(0.75)
iqr = q3 - q1
mask = (df[column] < (q1 - 1.5 * iqr)) | (df[column] > (q3 + 1.5 * iqr))
return OutlierResult(column=column, outlier_count=int(mask.sum()), method="iqr", outlier_indices=list(df.index[mask]))
def detect_outliers_zscore(df: pd.DataFrame, column: str, threshold: float = 3.0) -> OutlierResult:
mean = df[column].mean()
std = df[column].std()
if std == 0:
return OutlierResult(column=column, outlier_count=0, method="zscore", outlier_indices=[])
mask = ((df[column] - mean).abs() / std) > threshold
return OutlierResult(column=column, outlier_count=int(mask.sum()), method="zscore", outlier_indices=list(df.index[mask]))
def detect_all_outliers(df: pd.DataFrame, method: str = "iqr") -> list[OutlierResult]:
num_cols = df.select_dtypes(include=DTYPE_NUM).columns
fn = detect_outliers_zscore if method == "zscore" else detect_outliers_iqr
return [fn(df, col) for col in num_cols]
@dataclass
class CorrelationResult:
pairs: list
def correlation_analysis(df: pd.DataFrame, threshold: float = 0.0) -> CorrelationResult:
num = df.select_dtypes(include=DTYPE_NUM)
if num.empty:
return CorrelationResult(pairs=[])
corr = num.corr()
cols = list(corr.columns)
pairs = []
for i, a in enumerate(cols):
for b in cols[i + 1:]:
val = float(corr.loc[a, b])
if abs(val) >= threshold:
pairs.append({"column_a": a, "column_b": b, "correlation": val})
return CorrelationResult(pairs=pairs)
@dataclass
class TimeSeriesSummary:
count: int
mean: float
max: float
trend_direction: str
trend_slope: float
def time_series_summary(df: pd.DataFrame, date_col: str, value_col: str) -> TimeSeriesSummary:
if df.empty:
return TimeSeriesSummary(count=0, mean=0.0, max=0.0, trend_direction="flat", trend_slope=0.0)
tmp = df.copy()
tmp[date_col] = pd.to_datetime(tmp[date_col])
tmp = tmp.sort_values(date_col)
vals = tmp[value_col].astype(float)
n = len(vals)
slope = 0.0
if n >= 2:
x = list(range(n))
x_mean = sum(x) / n
y_mean = float(vals.mean())
num_s = sum((x[i] - x_mean) * (float(vals.iloc[i]) - y_mean) for i in range(n))
den = sum((xi - x_mean) ** 2 for xi in x)
slope = num_s / den if den != 0 else 0.0
direction = "increasing" if slope > 1e-9 else ("decreasing" if slope < -1e-9 else "flat")
return TimeSeriesSummary(count=n, mean=float(vals.mean()), max=float(vals.max()), trend_direction=direction, trend_slope=slope)
@dataclass
class DistributionResult:
column: str
best_fit: str
classification: str = ""
sample_size: int = 0
def __post_init__(self) -> None:
if not self.classification:
self.classification = self.best_fit
def classify_distribution(df: pd.DataFrame, column: str) -> DistributionResult:
series = df[column]
n = len(series)
if n < 5:
cls = "sparse"
elif series.nunique() < 10:
cls = "categorical"
else:
cls = "normal"
return DistributionResult(column=column, best_fit=cls, classification=cls, sample_size=n)
def classify_all_distributions(df: pd.DataFrame) -> list[DistributionResult]:
num_cols = df.select_dtypes(include=DTYPE_NUM).columns
return [classify_distribution(df, col) for col in num_cols]
def detect_anomalies(df: pd.DataFrame) -> pd.DataFrame:
num = df.select_dtypes(DTYPE_NUM)
if num.empty:
return pd.DataFrame()
z = (num - num.mean()) / num.std()
anom_mask = (z.abs() > 3).any(axis=1)
return df.loc[anom_mask].reset_index(drop=True)
@dataclass
class AnomalyReport:
flagged_rows: int
total_rows: int
def flag_anomalies(df: pd.DataFrame) -> tuple[pd.DataFrame, AnomalyReport]:
num = df.select_dtypes(DTYPE_NUM)
out = df.copy()
if num.empty:
out["_anomaly"] = False
return out, AnomalyReport(flagged_rows=0, total_rows=len(df))
z = (num - num.mean()) / num.std()
anom_mask = (z.abs() > 3).any(axis=1)
out["_anomaly"] = anom_mask
return out, AnomalyReport(flagged_rows=int(anom_mask.sum()), total_rows=len(df))
def detect_data_drift(old_df: pd.DataFrame, new_df: pd.DataFrame, num_col: str) -> dict[str, Any]:
"""Basic statistical drift detection to see if new data distributions have shifted from historical baselines."""
if num_col not in old_df.columns or num_col not in new_df.columns:
return {"drift_detected": False, "reason": "Column missing"}
old_mean, old_std = float(old_df[num_col].mean()), float(old_df[num_col].std())
new_mean = float(new_df[num_col].mean())
# Heuristic: If the new mean shifts by more than 1 standard deviation, flag as drift.
is_drift = abs(new_mean - old_mean) > old_std if old_std > 0 else False
return {
"drift_detected": is_drift,
"historical_mean": old_mean,
"new_mean": new_mean,
"shift": abs(new_mean - old_mean),
}
# ΓöÇΓöÇ Program Metrics & Dashboards ΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇΓöÇ
@dataclass
class DashboardSummary:
"""Backward-compatible dashboard snapshot (see ProgramDashboard in program_metrics)."""
metrics: list
overall_health: str
green_count: int
yellow_count: int
red_count: int
timestamp: str = ""
budget_codes: list = field(default_factory=list)
class Report:
"""Simple report object with markdown/HTML rendering."""
def __init__(self, title: str, content: str):
self.title = title
self.content = content
def to_markdown(self) -> str:
return f"# {self.title}\n\n{self.content}"
def to_html(self) -> str:
return f"<h1>{self.title}</h1><p>{self.content}</p>"
def save(self, path: str) -> None:
Path(path).parent.mkdir(parents=True, exist_ok=True)
Path(path).write_text(self.to_markdown(), encoding="utf-8")
def generate_contract_report(df: pd.DataFrame) -> Report:
"""Generate a summary report for contracts."""
return Report("Contract Status Report", f"Total Records: {len(df)}")
def generate_inquiry_response(inquiry_type: str, df: pd.DataFrame, **kwargs) -> Report:
"""Generate a boilerplate inquiry response for a given inquiry type."""
details = ", ".join(f"{k}={v}" for k, v in kwargs.items()) if kwargs else "general"
return Report(
"Inquiry Response",
f"Thank you for your inquiry regarding NYC DOT data.\nType: {inquiry_type} | Filter: {details}\nTotal records reviewed: {len(df)}",
)
def generate_program_report(dash: DashboardSummary) -> Report:
"""Generate a report from the program dashboard snapshot."""
content = f"Overall Health: {dash.overall_health.upper()}\n\n"
content += f"Summary: 🟢 {dash.green_count} | 🟡 {dash.yellow_count} | 🔴 {dash.red_count}\n\n"
content += "Metrics Detail:\n"
for m in dash.metrics:
content += f"- {m.name.title()}: {m.value:.2f} (Target: {m.target:.2f})\n"
return Report("Program KPI Report", content)
def generate_executive_briefing_automated(df: pd.DataFrame) -> Report:
"""Headless Automated Executive Briefing. Synthesizes a full textual KPI summary for management."""
prof = profile_dataframe(df)
sla = compute_sla_metrics(df)
content = "## NYC DOT Sidewalk & 311 Executive Briefing\n\n"
content += f"**Date:** {datetime.now(timezone.utc).strftime('%Y-%m-%d')}\n"
content += f"**Total Records Processed:** {prof.row_count:,}\n"
content += f"**Data Quality Score:** {prof.quality_score}/100\n\n"