-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalysis_utils.py
More file actions
4114 lines (3377 loc) · 150 KB
/
Copy pathanalysis_utils.py
File metadata and controls
4114 lines (3377 loc) · 150 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
import glob
import hashlib
import json
import math
import os
from typing import Any, Callable, Optional
import numpy as np
import pandas as pd
from localizer.plugins.google_timeline.parser import ( # noqa: F401
_WHERE_WHEN_COLUMNS,
_parse_latlng,
load_google_timeline,
)
def _get_ruptures() -> Optional[Any]:
"""Lazily import ruptures (pulls in scipy) only when changepoint detection runs."""
try:
import ruptures as _r
return _r
except (ImportError, Exception):
return None
def get_cache_key(
lastfm_file: str,
swarm_dir: Optional[str] = None,
assumptions_file: Optional[str] = None,
timeline_path: str = "",
) -> str:
"""Generate a unique cache key based on input files and their modification times."""
if not os.path.exists(lastfm_file):
return "none"
lastfm_mtime = os.path.getmtime(lastfm_file)
key_parts = [lastfm_file, str(lastfm_mtime)]
if swarm_dir and os.path.isdir(swarm_dir):
# Sort files to ensure deterministic key
swarm_files = sorted(glob.glob(os.path.join(swarm_dir, "checkins*.json")))
for f in swarm_files:
key_parts.append(f)
key_parts.append(str(os.path.getmtime(f)))
if assumptions_file and os.path.exists(assumptions_file):
key_parts.append(assumptions_file)
key_parts.append(str(os.path.getmtime(assumptions_file)))
if timeline_path and os.path.exists(timeline_path):
key_parts.append(timeline_path)
key_parts.append(str(os.path.getmtime(timeline_path)))
# Include version to invalidate cache if logic changes
key_parts.append("v1.6")
return hashlib.md5("".join(key_parts).encode(), usedforsecurity=False).hexdigest() # noqa: S324
def get_cached_data(cache_key: str, cache_dir: str = "data/cache") -> Optional[pd.DataFrame]:
"""Retrieve processed data from cache if it exists."""
if cache_key == "none":
return None
cache_path = os.path.join(cache_dir, f"{cache_key}.csv.gz")
if os.path.exists(cache_path):
try:
df = pd.read_csv(cache_path, compression="gzip")
if "date_text" in df.columns:
df["date_text"] = pd.to_datetime(df["date_text"])
return df
except Exception as e:
print(f"Warning: failed to read cache at {cache_path}: {e}")
return None
def save_to_cache(df: pd.DataFrame, cache_key: str, cache_dir: str = "data/cache") -> None:
"""Save processed data to cache."""
if cache_key == "none":
return
if not os.path.exists(cache_dir):
os.makedirs(cache_dir, exist_ok=True)
cache_path = os.path.join(cache_dir, f"{cache_key}.csv.gz")
try:
df.to_csv(cache_path, index=False, compression="gzip")
except Exception as e:
print(f"Error saving to cache: {e}")
def load_assumptions(assumptions_file: Optional[str]) -> dict[str, Any]:
"""Load location assumptions from a JSON file."""
default_data = {
"defaults": {
"city": "Reykjavik, IS",
"state": "IS",
"country": "Iceland",
"lat": 64.1265,
"lng": -21.8174,
"timezone": "Atlantic/Reykjavik",
},
"holidays": [],
"trips": [],
"residency": [],
}
if not assumptions_file or not os.path.exists(assumptions_file):
return default_data
try:
with open(assumptions_file) as f:
user_data = json.load(f)
# Merge with defaults to ensure all keys exist
for key in default_data:
if key not in user_data:
user_data[key] = default_data[key]
return user_data # type: ignore[no-any-return]
except Exception as e:
print(f"Error loading assumptions: {e}")
return default_data
def load_listening_data(file_path: str) -> Optional[pd.DataFrame]:
"""Load and preprocess listening history from CSV."""
if not os.path.exists(file_path):
return None
try:
df = pd.read_csv(file_path)
if "date_text" in df.columns:
df["date_text"] = pd.to_datetime(df["date_text"])
# Ensure we have a unix timestamp for lookup (Last.fm 'uts')
if "timestamp" not in df.columns and "date_text" in df.columns:
df["timestamp"] = df["date_text"].astype("int64") // 10**9
return df
except Exception:
return None
def load_swarm_data(swarm_dir: str) -> pd.DataFrame:
"""Load and parse Swarm checkin data from JSON files."""
all_checkins = []
if not swarm_dir or not os.path.exists(swarm_dir):
return pd.DataFrame(
columns=[
"timestamp",
"offset",
"city",
"state",
"country",
"venue",
"venue_category",
"lat",
"lng",
"event_category",
"shout",
]
)
json_files = glob.glob(os.path.join(swarm_dir, "checkins*.json"))
for file_path in json_files:
try:
with open(file_path, encoding="utf-8") as f:
data = json.load(f)
items = data.get("items", [])
for item in items:
raw_created_at = item.get("createdAt")
if raw_created_at is None:
continue
try:
if isinstance(raw_created_at, (int, float)):
created_at = pd.to_datetime(raw_created_at, unit="s", utc=True)
else:
created_at = pd.to_datetime(raw_created_at, utc=True)
ts = int(created_at.timestamp())
except (ValueError, TypeError):
continue
offset = item.get("timeZoneOffset", 0)
venue = item.get("venue") or {}
location = venue.get("location") or {}
city = location.get("city")
state = location.get("state")
country = location.get("country")
# Track whether this item has no geographic text at all so
# we can batch-reverse-geocode from lat/lng after the loop.
needs_geocode = not (city or state or country)
if not city:
city = state or country or venue.get("name", "Unknown")
if not state:
state = country or "Unknown"
if not country:
country = "Unknown"
lat = item.get("lat") or location.get("lat")
lng = item.get("lng") or location.get("lng")
categories = venue.get("categories", [])
venue_category = categories[0].get("name", "") if categories else ""
event_cats = item.get("event", {}).get("categories", [])
event_category = event_cats[0].get("name", "") if event_cats else ""
shout = item.get("shout", "") or ""
all_checkins.append(
{
"timestamp": ts,
"offset": offset,
"city": city,
"state": state,
"country": country,
"venue": venue.get("name", "Unknown"),
"venue_category": venue_category,
"lat": lat,
"lng": lng,
"_needs_geocode": needs_geocode and lat is not None and lng is not None,
"event_category": event_category,
"shout": shout,
}
)
except Exception as e:
print(f"Error loading {file_path}: {e}")
if not all_checkins:
return pd.DataFrame(
columns=[
"timestamp",
"offset",
"city",
"state",
"country",
"venue",
"venue_category",
"lat",
"lng",
"event_category",
"shout",
]
)
df = pd.DataFrame(all_checkins)
# Reverse-geocode rows that had no city/state/country in the export but do
# have coordinates (common in newer Foursquare GDPR exports which omit
# venue.location entirely).
geo_mask = df["_needs_geocode"].astype(bool)
if geo_mask.any():
try:
import reverse_geocoder as rg # optional dependency
coords = list(zip(df.loc[geo_mask, "lat"], df.loc[geo_mask, "lng"]))
results = rg.search(coords, verbose=False)
df.loc[geo_mask, "city"] = [r["name"] for r in results]
df.loc[geo_mask, "state"] = [r.get("admin1", r["cc"]) for r in results]
df.loc[geo_mask, "country"] = [r["cc"] for r in results]
except ImportError:
pass # degrade to venue-name / "Unknown" fallbacks already set
df = df.drop(columns=["_needs_geocode"])
df = df.sort_values("timestamp").drop_duplicates("timestamp")
return df
def infer_residency_periods(
swarm_df: pd.DataFrame,
radius_km: float = 48.0,
min_months: int = 3,
) -> list[dict[str, str]]:
"""Infer home-base residency periods from Swarm check-in coordinates.
Applies a five-step algorithm:
1. Greedy haversine radius merge to cluster coordinates into metro areas.
2. Monthly plurality vote to assign each calendar month to a cluster.
3. Forward-fill sparse months (no back-fill for leading gaps).
4. Stability filter: only keep runs of >= min_months consecutive months.
5. Collapse qualifying runs into period dicts with city, start, end.
Args:
swarm_df: DataFrame with columns timestamp (int unix seconds),
lat (float), lng (float), city (str).
radius_km: Merge radius in kilometres for greedy clustering.
min_months: Minimum consecutive months required to declare a residency.
Returns:
List of dicts with keys ``city``, ``start``, ``end`` (ISO date strings),
sorted by start date. Returns ``[]`` on edge-case inputs.
"""
# --- Guard: required columns ---
if swarm_df is None or swarm_df.empty:
return []
if "lat" not in swarm_df.columns or "lng" not in swarm_df.columns:
return []
# --- Drop rows with null lat/lng ---
df = swarm_df.dropna(subset=["lat", "lng"]).copy()
if df.empty:
return []
# Ensure city column exists; fill missing/None with empty string
if "city" not in df.columns:
df["city"] = ""
df["city"] = df["city"].fillna("").astype(str)
# --- Step 1: Greedy haversine radius merge ---
# Collect unique (lat, lng) pairs and their city labels
unique_coords = df[["lat", "lng", "city"]].copy()
unique_coords["lat"] = unique_coords["lat"].astype(float)
unique_coords["lng"] = unique_coords["lng"].astype(float)
# cluster_centroids: list of [mean_lat, mean_lng, total_count]
# cluster_city_counts: list of dict {city: count}
cluster_centroids: list[list[float]] = []
cluster_city_counts: list[dict[str, int]] = []
# Maps row index to cluster index
coord_cluster: list[int] = []
def _haversine(lat1: float, lng1: float, lat2: float, lng2: float) -> float:
"""Return haversine distance in km between two coordinate pairs."""
r = 6371.0
dlat = math.radians(lat2 - lat1)
dlng = math.radians(lng2 - lng1)
a = (
math.sin(dlat / 2) ** 2
+ math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlng / 2) ** 2
)
return r * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
for _, row in unique_coords.iterrows():
lat, lng, city = float(row["lat"]), float(row["lng"]), str(row["city"])
best_idx = -1
best_dist = float("inf")
for ci, centroid in enumerate(cluster_centroids):
d = _haversine(lat, lng, centroid[0], centroid[1])
if d < best_dist:
best_dist = d
best_idx = ci
if best_idx >= 0 and best_dist <= radius_km:
# Assign to existing cluster and recompute centroid
count = cluster_centroids[best_idx][2]
cluster_centroids[best_idx][0] = (cluster_centroids[best_idx][0] * count + lat) / (
count + 1
)
cluster_centroids[best_idx][1] = (cluster_centroids[best_idx][1] * count + lng) / (
count + 1
)
cluster_centroids[best_idx][2] = count + 1
coord_cluster.append(best_idx)
if city:
cluster_city_counts[best_idx][city] = cluster_city_counts[best_idx].get(city, 0) + 1
else:
# Start a new cluster
new_idx = len(cluster_centroids)
cluster_centroids.append([lat, lng, 1.0])
city_counts: dict[str, int] = {}
if city:
city_counts[city] = 1
cluster_city_counts.append(city_counts)
coord_cluster.append(new_idx)
# Label each cluster by most-frequent city name
cluster_labels: list[str] = []
for city_counts in cluster_city_counts:
if city_counts:
cluster_labels.append(max(city_counts, key=lambda k: city_counts[k]))
else:
cluster_labels.append("Unknown")
# Assign cluster index to every row in df by matching (lat, lng)
# Build a lookup: (lat, lng) -> cluster index
coord_to_cluster: dict[tuple[float, float], int] = {}
for i, row in enumerate(unique_coords.itertuples(index=False)):
coord_to_cluster[(float(row.lat), float(row.lng))] = coord_cluster[i]
df["_cluster"] = df.apply(
lambda r: coord_to_cluster.get((float(r["lat"]), float(r["lng"])), 0), axis=1
)
df["_cluster_label"] = df["_cluster"].apply(lambda c: cluster_labels[c])
# --- Step 2: Monthly plurality vote ---
df["_month"] = pd.to_datetime(df["timestamp"], unit="s").dt.to_period("M")
month_clusters = df.groupby(["_month", "_cluster"]).size().reset_index(name="count")
# For each month, pick the cluster with the highest count (ties: lowest cluster index)
idx = month_clusters.groupby("_month")["count"].idxmax()
month_winner = month_clusters.loc[idx].set_index("_month")["_cluster"]
# Convert cluster index to label
month_label: pd.Series = month_winner.map(lambda c: cluster_labels[c])
# --- Step 3: Forward-fill sparse months ---
all_months = pd.period_range(month_label.index.min(), month_label.index.max(), freq="M")
month_label = month_label.reindex(all_months)
month_label = month_label.ffill()
# Drop leading NaN (months before first check-in — no back-fill)
month_label = month_label.dropna()
if month_label.empty:
return []
# --- Step 4: Stability filter ---
# Identify runs and mark months in runs of length >= min_months
labels_list = month_label.tolist()
months_list = month_label.index.tolist()
n = len(labels_list)
# Compute run lengths
qualifying: list[bool] = [False] * n
i = 0
while i < n:
j = i
while j < n and labels_list[j] == labels_list[i]:
j += 1
run_len = j - i
if run_len >= min_months:
for k in range(i, j):
qualifying[k] = True
i = j
# --- Step 5: Collapse qualifying months into period dicts ---
# Build a list of (city_label, month_period) for qualifying months only,
# then merge consecutive entries with the same label — even if there were
# non-qualifying months between two same-label qualifying runs (blip eaten).
qualifying_entries: list[tuple[str, Any]] = [
(labels_list[k], months_list[k]) for k in range(n) if qualifying[k]
]
periods: list[dict[str, str]] = []
ei = 0
while ei < len(qualifying_entries):
city_label, run_start_period = qualifying_entries[ei]
run_end_period = run_start_period
ei += 1
while ei < len(qualifying_entries) and qualifying_entries[ei][0] == city_label:
run_end_period = qualifying_entries[ei][1]
ei += 1
start_str = run_start_period.to_timestamp("D", how="start").strftime("%Y-%m-%d")
end_str = run_end_period.to_timestamp("D", how="end").strftime("%Y-%m-%d")
periods.append({"city": city_label, "start": start_str, "end": end_str})
return sorted(periods, key=lambda d: d["start"])
def get_assumption_location(ts: int, assumptions: dict[str, Any]) -> Optional[dict[str, Any]]:
"""
Get location and offset based on runtime assumptions (Issue #39).
This is a non-vectorized version mainly used for tests and single lookups.
"""
dt_utc = pd.to_datetime([ts], unit="s", utc=True)
# Recurring holiday check — skip placeholder holidays (lat=0, lng=0) used
# only for analytics, not for location assignment.
for holiday in assumptions.get("holidays", []):
if holiday.get("lat", 0) == 0 and holiday.get("lng", 0) == 0:
continue
tz = holiday.get("timezone", "UTC")
local_time = dt_utc.tz_convert(tz)[0]
month = holiday.get("month")
day_range = holiday.get("day_range", [])
if local_time.month == month and day_range[0] <= local_time.day <= day_range[1]:
return {
"offset": int(local_time.utcoffset().total_seconds() / 60),
"city": holiday.get("city"),
"state": holiday.get("state", holiday.get("city")),
"country": holiday.get("country", "Unknown"),
"lat": holiday.get("lat"),
"lng": holiday.get("lng"),
}
# Trip check
for trip in assumptions.get("trips", []):
start = pd.to_datetime(trip.get("start")).date()
end = pd.to_datetime(trip.get("end")).date()
tz = trip.get("timezone", "UTC")
local_time = dt_utc.tz_convert(tz)[0]
if start <= local_time.date() <= end:
return {
"offset": int(local_time.utcoffset().total_seconds() / 60),
"city": trip.get("city"),
"state": trip.get("state", trip.get("city")),
"country": trip.get("country", "Unknown"),
"lat": trip.get("lat"),
"lng": trip.get("lng"),
}
# Residency check
dt_naive = dt_utc[0].replace(tzinfo=None)
for res in assumptions.get("residency", []):
start = pd.to_datetime(res.get("start")).replace(tzinfo=None)
end = pd.to_datetime(res.get("end")).replace(tzinfo=None)
if start <= dt_naive <= end:
for rule in res.get("sub_rules", []):
tz = rule.get("timezone", "UTC")
local_time = dt_utc.tz_convert(tz)[0]
cond = rule.get("condition")
if cond == "work_hours":
if local_time.weekday() < 5 and (
(local_time.hour == 8 and local_time.minute >= 30)
or (9 <= local_time.hour < 16)
or (local_time.hour == 16 and local_time.minute <= 30)
):
return {
"offset": int(local_time.utcoffset().total_seconds() / 60),
"city": rule.get("city"),
"state": rule.get("state", rule.get("city")),
"country": rule.get("country", "Unknown"),
"lat": rule.get("lat"),
"lng": rule.get("lng"),
}
elif cond == "home_logic":
home_1_end = pd.to_datetime(rule.get("home_1_end")).replace(tzinfo=None)
use_home_1 = dt_naive <= home_1_end
return {
"offset": int(local_time.utcoffset().total_seconds() / 60),
"city": rule.get("city_1") if use_home_1 else rule.get("city_2"),
"state": (rule.get("state_1") if use_home_1 else rule.get("state_2"))
or (rule.get("city_1") if use_home_1 else rule.get("city_2")),
"country": rule.get("country", "Unknown"),
"lat": rule.get("lat_1") if use_home_1 else rule.get("lat_2"),
"lng": rule.get("lng_1") if use_home_1 else rule.get("lng_2"),
}
return {
"offset": 0,
"city": res.get("city"),
"state": res.get("state", res.get("city")),
"country": res.get("country", "Unknown"),
"lat": res.get("lat"),
"lng": res.get("lng"),
}
return None
def apply_location_context(
lastfm_df: pd.DataFrame,
swarm_df: pd.DataFrame,
assumptions: dict[str, Any],
max_age_days: int = 30,
) -> pd.DataFrame:
"""
Adjust Last.fm track timestamps and locations based on location-source checkins
(Swarm, Google Location History, Google Timeline, etc. — any ``places``-shaped
frame, regardless of ``source_id``) or runtime assumptions.
Highly optimized vectorized implementation (Issue #39 optimization; renamed
from ``apply_swarm_offsets`` in Issue #110 once it became source-agnostic).
"""
if lastfm_df.empty:
return lastfm_df
df = lastfm_df.copy()
defaults = assumptions.get("defaults", {})
DEFAULT_CITY = defaults.get("city", "Reykjavik")
DEFAULT_STATE = defaults.get("state", "IS")
DEFAULT_COUNTRY = defaults.get("country", "Iceland")
DEFAULT_LAT = defaults.get("lat", 64.1265)
DEFAULT_LNG = defaults.get("lng", -21.8174)
DEFAULT_TZ = defaults.get("timezone", "Atlantic/Reykjavik")
# 1. Pre-calculate UTC timestamps and local variants for checks
dt_utc = pd.to_datetime(df["timestamp"], unit="s", utc=True)
# Initialize result columns with defaults
df["tz_offset_min"] = 0
df["city"] = DEFAULT_CITY
df["state"] = DEFAULT_STATE
df["country"] = DEFAULT_COUNTRY
df["lat"] = DEFAULT_LAT
df["lng"] = DEFAULT_LNG
# Track which rows have been geocoded to avoid overwriting
geocoded_mask: np.ndarray = np.zeros(len(df), dtype=bool)
# 2. Try Swarm Data (Fastest Lookup)
if not swarm_df.empty:
swarm_ts = swarm_df["timestamp"].values
max_age_sec = max_age_days * 24 * 60 * 60
# Use binary search to find the most recent checkin for every track
indices = np.searchsorted(swarm_ts, df["timestamp"].values, side="right") - 1
# Filter indices that are within range and not too old
valid_indices_mask = indices >= 0
if valid_indices_mask.any():
checkin_ts = swarm_ts[indices[valid_indices_mask]]
age_mask = (df["timestamp"].values[valid_indices_mask] - checkin_ts) <= max_age_sec
final_swarm_mask = valid_indices_mask.copy()
final_swarm_mask[valid_indices_mask] = age_mask
if final_swarm_mask.any():
match_indices = indices[final_swarm_mask]
df.loc[final_swarm_mask, "tz_offset_min"] = swarm_df["offset"].values[match_indices]
df.loc[final_swarm_mask, "city"] = swarm_df["city"].values[match_indices]
df.loc[final_swarm_mask, "state"] = swarm_df["state"].values[match_indices]
df.loc[final_swarm_mask, "country"] = swarm_df["country"].values[match_indices]
df.loc[final_swarm_mask, "lat"] = swarm_df["lat"].values[match_indices]
df.loc[final_swarm_mask, "lng"] = swarm_df["lng"].values[match_indices]
geocoded_mask[final_swarm_mask] = True
# 3. Apply Runtime Assumptions (Residency, Trips, Holidays)
remaining_mask = ~geocoded_mask
if remaining_mask.any():
# Pre-process trips and residency into datetime objects
processed_trips = []
for t in assumptions.get("trips", []):
t_copy = t.copy()
t_copy["_start"] = pd.to_datetime(t.get("start")).date()
t_copy["_end"] = pd.to_datetime(t.get("end")).date()
processed_trips.append(t_copy)
processed_residency = []
for r in assumptions.get("residency", []):
r_copy = r.copy()
r_copy["_start"] = pd.to_datetime(r.get("start")).replace(tzinfo=None)
r_copy["_end"] = pd.to_datetime(r.get("end")).replace(tzinfo=None)
processed_residency.append(r_copy)
# For efficiency, compute local time once per unique timezone used in assumptions
tz_to_local = {}
# Apply Holidays (recurring) — skip placeholder entries (lat=0, lng=0)
# that are used only for analytics, not for location assignment.
for holiday in assumptions.get("holidays", []):
if not remaining_mask.any():
break
if holiday.get("lat", 0) == 0 and holiday.get("lng", 0) == 0:
continue
tz = holiday.get("timezone", "UTC")
if tz not in tz_to_local:
tz_to_local[tz] = dt_utc.dt.tz_convert(tz)
local_time = tz_to_local[tz]
month = holiday.get("month")
day_range = holiday.get("day_range", [])
holiday_mask = (
remaining_mask
& (local_time.dt.month == month)
& (local_time.dt.day >= day_range[0])
& (local_time.dt.day <= day_range[1])
)
if holiday_mask.any():
holiday_offsets = (
local_time[holiday_mask].dt.tz_localize(None)
- dt_utc[holiday_mask].dt.tz_localize(None)
).dt.total_seconds() / 60
df.loc[holiday_mask, "tz_offset_min"] = holiday_offsets
df.loc[holiday_mask, "city"] = holiday.get("city")
df.loc[holiday_mask, "state"] = holiday.get("state", holiday.get("city"))
df.loc[holiday_mask, "country"] = holiday.get("country", "Unknown")
df.loc[holiday_mask, "lat"] = holiday.get("lat")
df.loc[holiday_mask, "lng"] = holiday.get("lng")
geocoded_mask[holiday_mask] = True
remaining_mask = ~geocoded_mask
# Apply Trips
for trip in processed_trips:
if not remaining_mask.any():
break
tz = trip.get("timezone", "UTC")
if tz not in tz_to_local:
tz_to_local[tz] = dt_utc.dt.tz_convert(tz)
local_time = tz_to_local[tz]
local_date = local_time.dt.date
trip_mask = (
remaining_mask & (local_date >= trip["_start"]) & (local_date <= trip["_end"])
)
if trip_mask.any():
trip_offsets = (
local_time[trip_mask].dt.tz_localize(None)
- dt_utc[trip_mask].dt.tz_localize(None)
).dt.total_seconds() / 60
df.loc[trip_mask, "tz_offset_min"] = trip_offsets
df.loc[trip_mask, "city"] = trip.get("city")
df.loc[trip_mask, "state"] = trip.get("state", trip.get("city"))
df.loc[trip_mask, "country"] = trip.get("country", "Unknown")
df.loc[trip_mask, "lat"] = trip.get("lat")
df.loc[trip_mask, "lng"] = trip.get("lng")
geocoded_mask[trip_mask] = True
remaining_mask = ~geocoded_mask
# Apply Residency (with sub-rules)
dt_naive = dt_utc.dt.tz_localize(None)
for res in processed_residency:
if not remaining_mask.any():
break
res_mask = remaining_mask & (dt_naive >= res["_start"]) & (dt_naive <= res["_end"])
if res_mask.any():
# Apply sub-rules within this residency period
res_remaining = res_mask.copy()
for rule in res.get("sub_rules", []):
if not res_remaining.any():
break
tz = rule.get("timezone", "UTC")
if tz not in tz_to_local:
tz_to_local[tz] = dt_utc.dt.tz_convert(tz)
local_time = tz_to_local[tz]
cond = rule.get("condition")
if cond == "work_hours":
# Mon-Fri, 8:30 - 16:30
work_mask = (
res_remaining
& (local_time.dt.weekday < 5)
& (
((local_time.dt.hour == 8) & (local_time.dt.minute >= 30))
| ((local_time.dt.hour >= 9) & (local_time.dt.hour < 16))
| ((local_time.dt.hour == 16) & (local_time.dt.minute <= 30))
)
)
if work_mask.any():
work_offsets = (
local_time[work_mask].dt.tz_localize(None)
- dt_utc[work_mask].dt.tz_localize(None)
).dt.total_seconds() / 60
df.loc[work_mask, "tz_offset_min"] = work_offsets
df.loc[work_mask, "city"] = rule.get("city")
df.loc[work_mask, "state"] = rule.get("state", rule.get("city"))
df.loc[work_mask, "country"] = rule.get("country", "Unknown")
df.loc[work_mask, "lat"] = rule.get("lat")
df.loc[work_mask, "lng"] = rule.get("lng")
geocoded_mask[work_mask] = True
res_remaining &= ~work_mask
elif cond == "home_logic":
home_1_end = pd.to_datetime(rule.get("home_1_end")).replace(tzinfo=None)
h1_mask = res_remaining & (dt_naive <= home_1_end)
h2_mask = res_remaining & (dt_naive > home_1_end)
if h1_mask.any():
h1_offsets = (
local_time[h1_mask].dt.tz_localize(None)
- dt_utc[h1_mask].dt.tz_localize(None)
).dt.total_seconds() / 60
df.loc[h1_mask, "tz_offset_min"] = h1_offsets
df.loc[h1_mask, "city"] = rule.get("city_1")
df.loc[h1_mask, "state"] = rule.get("state_1", rule.get("city_1"))
df.loc[h1_mask, "country"] = rule.get("country", "Unknown")
df.loc[h1_mask, "lat"] = rule.get("lat_1")
df.loc[h1_mask, "lng"] = rule.get("lng_1")
geocoded_mask[h1_mask] = True
if h2_mask.any():
h2_offsets = (
local_time[h2_mask].dt.tz_localize(None)
- dt_utc[h2_mask].dt.tz_localize(None)
).dt.total_seconds() / 60
df.loc[h2_mask, "tz_offset_min"] = h2_offsets
df.loc[h2_mask, "city"] = rule.get("city_2")
df.loc[h2_mask, "state"] = rule.get("state_2", rule.get("city_2"))
df.loc[h2_mask, "country"] = rule.get("country", "Unknown")
df.loc[h2_mask, "lat"] = rule.get("lat_2")
df.loc[h2_mask, "lng"] = rule.get("lng_2")
geocoded_mask[h2_mask] = True
res_remaining &= ~(h1_mask | h2_mask)
# Final fallback for residency if no sub-rules matched
if res_remaining.any():
df.loc[res_remaining, "tz_offset_min"] = 0 # Default offset
df.loc[res_remaining, "city"] = res.get("city")
df.loc[res_remaining, "state"] = res.get("state", res.get("city"))
df.loc[res_remaining, "country"] = res.get("country", "Unknown")
df.loc[res_remaining, "lat"] = res.get("lat")
df.loc[res_remaining, "lng"] = res.get("lng")
geocoded_mask[res_remaining] = True
remaining_mask = ~geocoded_mask
# 4. Final Default (remaining tracks)
remaining_mask = ~geocoded_mask
if remaining_mask.any():
# Compute default timezone once for all remaining
default_local = dt_utc[remaining_mask].dt.tz_convert(DEFAULT_TZ)
default_offsets = (
default_local.dt.tz_localize(None) - dt_utc[remaining_mask].dt.tz_localize(None)
).dt.total_seconds() / 60
df.loc[remaining_mask, "tz_offset_min"] = default_offsets
df.loc[remaining_mask, "city"] = DEFAULT_CITY
df.loc[remaining_mask, "state"] = DEFAULT_STATE
df.loc[remaining_mask, "country"] = DEFAULT_COUNTRY
df.loc[remaining_mask, "lat"] = DEFAULT_LAT
df.loc[remaining_mask, "lng"] = DEFAULT_LNG
# Apply the computed offsets to date_text
df["local_date"] = pd.to_datetime(df["timestamp"], unit="s") + pd.to_timedelta(
df["tz_offset_min"], unit="m"
)
df["original_date_text"] = df["date_text"]
df["date_text"] = df["local_date"]
return df
def get_top_entities(df: pd.DataFrame, entity: str = "artist", limit: int = 10) -> pd.DataFrame:
"""Get the top n most played entities (artist, album, track)."""
if entity not in df.columns:
return pd.DataFrame()
top = df[entity].value_counts().head(limit).reset_index()
top.columns = [entity, "Plays"]
return top
def get_unique_entities(
subset_df: pd.DataFrame, full_df: pd.DataFrame, entity: str = "artist", limit: int = 10
) -> pd.DataFrame:
"""
Identify entities that are uniquely prominent in the subset compared to the full dataset.
Uses a simple 'Over-representation' score: (Subset Frequency / Total Frequency).
"""
if subset_df.empty or full_df.empty or entity not in full_df.columns:
return pd.DataFrame()
subset_counts = subset_df[entity].value_counts()
full_counts = full_df[entity].value_counts()
# Filter to only entities present in subset
relevant_full = full_counts[subset_counts.index]
# Score = (subset count) / (total count)
# This favors entities that appear ONLY in this subset
scores = subset_counts / relevant_full
unique_data = (
pd.DataFrame(
{entity: scores.index, "Uniqueness": scores.values, "Plays": subset_counts.values}
)
.sort_values("Uniqueness", ascending=False)
.head(limit)
)
return unique_data
def get_listening_intensity(df: pd.DataFrame, freq: str = "D") -> pd.DataFrame:
"""Calculate play counts per specified frequency ('D' for day, 'W' for week, 'ME' for month)."""
if "date_text" not in df.columns or df.empty:
return pd.DataFrame()
# pandas Period uses 'M' for month-end; resample uses the newer 'ME' alias.
period_freq = "M" if freq == "ME" else freq
return (
df.assign(date_group=df["date_text"].dt.to_period(period_freq).dt.to_timestamp())
.groupby("date_group")
.size()
.reset_index(name="Plays")
.rename(columns={"date_group": "date"})
)
def get_milestones(df: pd.DataFrame, intervals: Optional[list[int]] = None) -> pd.DataFrame:
"""Find tracks that hit specific volume milestones."""
if intervals is None:
intervals = [1000, 5000, 10000, 50000]
if df.empty:
return pd.DataFrame()
df_sorted = df.sort_values("date_text").reset_index(drop=True)
milestones = []
for interval in intervals:
if len(df_sorted) >= interval:
track = df_sorted.iloc[interval - 1]
milestones.append(
{
"Milestone": f"{interval:,} Tracks",
"Artist": track["artist"],
"Track": track["track"],
"Date": track["date_text"],
}
)
return pd.DataFrame(milestones)
def get_listening_streaks(df: pd.DataFrame) -> dict:
"""Find the longest streak of consecutive days with at least one play."""
if df.empty:
return {"longest_streak": 0, "current_streak": 0}
dates_series = pd.to_datetime(df["date_text"]).dt.normalize().drop_duplicates().sort_values()
if dates_series.empty:
return {"longest_streak": 0, "current_streak": 0}
# Each gap > 1 day starts a new streak group.
gap = dates_series.diff().dt.days.fillna(1)
group_ids = (gap != 1).cumsum()
streak_lengths = group_ids.value_counts()
longest = int(streak_lengths.max())
last_group = group_ids.iloc[-1]
current = int(streak_lengths[last_group])
if (pd.Timestamp.now().normalize() - dates_series.iloc[-1]).days > 1:
current = 0
return {
"longest_streak": longest,
"current_streak": current,
"last_active": dates_series.iloc[-1].date(),
}
def get_forgotten_favorites(
df: pd.DataFrame, top_n: int = 10, months_threshold: int = 6
) -> pd.DataFrame:
"""Identify artists that were once favorites but haven't been heard recently."""
if df.empty:
return pd.DataFrame()
latest_date = df["date_text"].max()
threshold_date = latest_date - pd.DateOffset(months=months_threshold)
past_df = df[df["date_text"] < threshold_date]
recent_df = df[df["date_text"] >= threshold_date]
if past_df.empty:
return pd.DataFrame()
past_top = past_df["artist"].value_counts().head(top_n * 2)
recent_artists = recent_df["artist"].unique()
forgotten_series = past_top[~past_top.index.isin(recent_artists)].head(top_n)
return pd.DataFrame({"Artist": forgotten_series.index, "Past Plays": forgotten_series.values})
def get_cumulative_plays(df: pd.DataFrame) -> pd.DataFrame:
"""Calculate cumulative plays over time."""
if "date_text" not in df.columns or df.empty:
return pd.DataFrame()
df_copy = df.sort_values("date_text")
df_copy["date"] = df_copy["date_text"].dt.date
daily = df_copy.groupby("date").size().reset_index(name="DailyPlays")
daily["CumulativePlays"] = daily["DailyPlays"].cumsum()
return daily
def get_hourly_distribution(df: pd.DataFrame) -> pd.DataFrame:
"""Calculate the distribution of plays throughout the hours of the day."""
if "date_text" not in df.columns:
return pd.DataFrame()
return df.assign(hour=df["date_text"].dt.hour).groupby("hour").size().reset_index(name="Plays")
def get_day_hour_heatmap(df: pd.DataFrame) -> pd.DataFrame:
"""Return a pivot table of play counts by day-of-week and hour of day.
Args:
df: Listening history with a ``date_text`` column.
Returns:
DataFrame indexed by day name (Monday–Sunday, ordered) with hour-of-day
columns 0–23 and integer play counts as values. Empty if no data.
"""
if "date_text" not in df.columns or df.empty:
return pd.DataFrame()
days_order = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
data = (
df.assign(day_of_week=df["date_text"].dt.day_name(), hour=df["date_text"].dt.hour)
.groupby(["day_of_week", "hour"])
.size()
.reset_index(name="Plays")
)
data["day_of_week"] = pd.Categorical(data["day_of_week"], categories=days_order, ordered=True)
return data.pivot(index="day_of_week", columns="hour", values="Plays").fillna(0)
def get_daily_activity(
df: Optional[pd.DataFrame],
swarm_df: Optional[pd.DataFrame] = None,
source: str = "all",
) -> pd.DataFrame:
"""Prepare zero-filled per-day activity counts for the activity calendar heatmap.
Args:
df: Listening history with a ``date_text`` column (Last.fm), or None.
swarm_df: Check-in history with a ``timestamp`` column (Unix seconds,
Swarm/Foursquare), or None.
source: Which source(s) to include in the counts. One of ``"all"``,
``"music"``, or ``"checkins"``.
Returns:
A two-column DataFrame (``date``: datetime64[ns], tz-naive midnight;
``value``: int activity count), sorted ascending by ``date`` and
zero-filled across the full contiguous date range covered by the
selected source(s). Empty (0 rows, correct columns/dtypes) when the
input(s) relevant to ``source`` are None/empty.
Raises:
ValueError: If ``source`` is not one of ``"all"``, ``"music"``,
``"checkins"``.
"""
valid_sources = {"all", "music", "checkins"}
if source not in valid_sources:
raise ValueError(f"Invalid source {source!r}; expected one of {sorted(valid_sources)}")
empty_result = pd.DataFrame(
{"date": pd.Series(dtype="datetime64[ns]"), "value": pd.Series(dtype="int64")}
)