"""Near-term movement projection: two honesty-first tiers. `heading` (default): estimate current bearing and speed from the last N fixes, project forward linearly, and grow an uncertainty cone whose width is grounded in that individual's own historical bearing/speed variance -- not an arbitrary constant. This is the credible baseline. `markov` (optional upgrade): discretize the individual's own historical bearing changes into direction bins, build a transition model from its own track, and simulate a small ensemble of forward paths. The output is a spread of plausible paths, not one line. Neither tier should be read as a forecast of certainty. Both are labeled "projected range of motion" by the callers in analysis.py/app.py. """ import numpy as np import pandas as pd from clean import haversine_km EARTH_RADIUS_KM = 6371.0088 def bearing_deg(lat1, lon1, lat2, lon2): """Initial great-circle bearing in degrees (0=north, 90=east) from point 1 to point 2.""" lat1, lat2 = np.radians(lat1), np.radians(lat2) dlon = np.radians(lon2 - lon1) x = np.sin(dlon) * np.cos(lat2) y = np.cos(lat1) * np.sin(lat2) - np.sin(lat1) * np.cos(lat2) * np.cos(dlon) return (np.degrees(np.arctan2(x, y)) + 360) % 360 def destination_point(lat, lon, bearing, distance_km): """Great-circle destination point given a start point, bearing (deg), and distance (km).""" lat1 = np.radians(lat) lon1 = np.radians(lon) brng = np.radians(bearing) d_r = distance_km / EARTH_RADIUS_KM lat2 = np.arcsin(np.sin(lat1) * np.cos(d_r) + np.cos(lat1) * np.sin(d_r) * np.cos(brng)) lon2 = lon1 + np.arctan2( np.sin(brng) * np.sin(d_r) * np.cos(lat1), np.cos(d_r) - np.sin(lat1) * np.sin(lat2), ) return np.degrees(lat2), (np.degrees(lon2) + 540) % 360 - 180 def circular_mean_deg(bearings): """Mean of a list of compass bearings (degrees), handling the 0/360 wraparound.""" radians = np.radians(bearings) return (np.degrees(np.arctan2(np.mean(np.sin(radians)), np.mean(np.cos(radians)))) + 360) % 360 def circular_std_deg(bearings): """Circular standard deviation of compass bearings (degrees), handling wraparound.""" radians = np.radians(bearings) r = np.hypot(np.mean(np.sin(radians)), np.mean(np.cos(radians))) r = min(r, 1.0) return np.degrees(np.sqrt(-2 * np.log(r))) if r > 0 else 180.0 def track_segments(individual_df): """Return per-consecutive-fix bearing (deg) and speed (km/h) for one individual's sorted track. Expects individual_df sorted by timestamp with location_lat/location_long columns. Returns a DataFrame of len(individual_df) - 1 rows with columns bearing, speed_kmh, dt_hours. """ df = individual_df.sort_values("timestamp").reset_index(drop=True) lat1, lon1 = df["location_lat"].values[:-1], df["location_long"].values[:-1] lat2, lon2 = df["location_lat"].values[1:], df["location_long"].values[1:] dt_hours = (df["timestamp"].values[1:] - df["timestamp"].values[:-1]) / np.timedelta64(1, "h") dt_hours = dt_hours.astype(float) bearings = bearing_deg(lat1, lon1, lat2, lon2) dist_km = haversine_km(lat1, lon1, lat2, lon2) with np.errstate(divide="ignore", invalid="ignore"): speed_kmh = np.where(dt_hours > 0, dist_km / dt_hours, np.nan) return pd.DataFrame({"bearing": bearings, "speed_kmh": speed_kmh, "dt_hours": dt_hours}) def _compass_direction(deg): directions = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"] idx = int((deg + 11.25) // 22.5) % 16 return directions[idx] def predict_heading(individual_df, window=10, horizon_hours=24, step_hours=1): """Linear heading/speed projection with a variance-grounded expanding uncertainty cone. Uses the last `window` segments to estimate current heading and speed, and the individual's *entire* track history to estimate bearing/speed variance (so the cone reflects how erratically this individual actually moves, not an arbitrary assumption). Returns a dict with: - centerline: list of (timestamp, lat, lon) for the projected path - cone_left / cone_right: matching boundary lat/lon lists - summary: short plain-language description - heading_deg, speed_kmh, bearing_std_deg, speed_std_deg (for transparency) """ segments = track_segments(individual_df) segments = segments[segments["speed_kmh"].notna()] if len(segments) < 2: raise ValueError("Need at least 2 valid track segments to predict.") recent = segments.tail(window) heading = circular_mean_deg(recent["bearing"].values) speed_kmh = float(recent["speed_kmh"].mean()) bearing_std = circular_std_deg(segments["bearing"].values) speed_std = float(segments["speed_kmh"].std(ddof=0)) if len(segments) > 1 else speed_kmh * 0.5 last_fix = individual_df.sort_values("timestamp").iloc[-1] start_lat, start_lon, start_time = last_fix["location_lat"], last_fix["location_long"], last_fix["timestamp"] steps = np.arange(step_hours, horizon_hours + step_hours, step_hours) centerline, cone_left, cone_right = [], [], [] lat, lon = start_lat, start_lon for hours_elapsed in steps: dist_km = speed_kmh * step_hours lat, lon = destination_point(lat, lon, heading, dist_km) timestamp = start_time + pd.Timedelta(hours=float(hours_elapsed)) centerline.append((timestamp, lat, lon)) # Cone half-angle and radius both grow with sqrt(elapsed time), reflecting # accumulating uncertainty without assuming it's linear or unbounded. half_angle = min(90.0, bearing_std * np.sqrt(hours_elapsed / step_hours)) radius_km = max(speed_std, 0.1) * hours_elapsed total_dist = speed_kmh * hours_elapsed left_lat, left_lon = destination_point(start_lat, start_lon, (heading - half_angle) % 360, total_dist) right_lat, right_lon = destination_point(start_lat, start_lon, (heading + half_angle) % 360, total_dist) cone_left.append((timestamp, left_lat, left_lon)) cone_right.append((timestamp, right_lat, right_lon)) summary = ( f"Moving {_compass_direction(heading)} at ~{speed_kmh:.1f} km/h over the last " f"{len(recent)} fixes; projected range of motion shown for the next {horizon_hours}h. " f"This is not a forecast of a precise path -- the cone reflects this individual's own " f"historical variability (bearing std ~{bearing_std:.0f} deg, speed std ~{speed_std:.1f} km/h)." ) return { "mode": "heading", "centerline": centerline, "cone_left": cone_left, "cone_right": cone_right, "summary": summary, "heading_deg": heading, "speed_kmh": speed_kmh, "bearing_std_deg": bearing_std, "speed_std_kmh": speed_std, } def _bin_bearing(bearing, n_bins): bin_width = 360.0 / n_bins return int(bearing // bin_width) % n_bins def _bin_center(bin_idx, n_bins): bin_width = 360.0 / n_bins return bin_idx * bin_width + bin_width / 2.0 def _build_transition_model(segments, n_bins): """Build a per-bin next-bin transition matrix and per-bin mean speed from one individual's history.""" bins = segments["bearing"].apply(lambda b: _bin_bearing(b, n_bins)).values speeds = segments["speed_kmh"].values transition_counts = np.ones((n_bins, n_bins)) # Laplace smoothing avoids zero-probability dead ends bin_speeds = {i: [] for i in range(n_bins)} for i in range(n_bins): bin_speeds[i] = list(speeds[bins == i]) or [float(np.nanmean(speeds))] for i in range(len(bins) - 1): transition_counts[bins[i], bins[i + 1]] += 1 transition_probs = transition_counts / transition_counts.sum(axis=1, keepdims=True) return transition_probs, bin_speeds, bins[-1] if len(bins) else 0 def predict_markov(individual_df, n_bins=16, horizon_hours=24, step_hours=1, n_runs=50, random_state=None): """Sample an ensemble of forward paths from a bearing-transition model built on this individual's own history. Returns a dict with `paths`: a list of n_runs paths, each a list of (timestamp, lat, lon), plus a `summary`. Communicates uncertainty as a spread of simulated paths rather than a single predicted line. """ rng = np.random.default_rng(random_state) segments = track_segments(individual_df) segments = segments[segments["speed_kmh"].notna()] if len(segments) < 2: raise ValueError("Need at least 2 valid track segments to predict.") transition_probs, bin_speeds, current_bin = _build_transition_model(segments, n_bins) last_fix = individual_df.sort_values("timestamp").iloc[-1] start_lat, start_lon, start_time = last_fix["location_lat"], last_fix["location_long"], last_fix["timestamp"] n_steps = int(horizon_hours / step_hours) paths = [] for _ in range(n_runs): lat, lon = start_lat, start_lon bin_idx = current_bin path = [] for step in range(1, n_steps + 1): bin_idx = rng.choice(n_bins, p=transition_probs[bin_idx]) heading = _bin_center(bin_idx, n_bins) speed = rng.choice(bin_speeds[bin_idx]) lat, lon = destination_point(lat, lon, heading, speed * step_hours) timestamp = start_time + pd.Timedelta(hours=step * step_hours) path.append((timestamp, lat, lon)) paths.append(path) mean_speed = float(segments["speed_kmh"].mean()) dominant_heading = circular_mean_deg(segments["bearing"].values) summary = ( f"Ensemble of {n_runs} simulated paths over the next {horizon_hours}h, sampled from this " f"individual's own historical direction-change patterns (dominant recent heading " f"~{_compass_direction(dominant_heading)}, mean speed ~{mean_speed:.1f} km/h). " f"Shown as a spread, not a single predicted line -- treat as a projected range of motion." ) return {"mode": "markov", "paths": paths, "summary": summary} def predict(individual_df, mode="heading", **kwargs): """Dispatch to predict_heading (default) or predict_markov.""" if mode == "heading": return predict_heading(individual_df, **kwargs) elif mode == "markov": return predict_markov(individual_df, **kwargs) raise ValueError(f"Unknown prediction mode: {mode!r}. Use 'heading' or 'markov'.")