File size: 3,651 Bytes
27b6a20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Per-individual and per-study movement analysis.

Distance/speed/activity-pattern metrics work for any study in the common
event schema (see ingest.py). Dive metrics only apply to studies whose raw
data includes a depth/pressure sensor column -- none of this project's three
default studies are depth-instrumented (they're Argos/GPS location-only), so
dive_metrics() detects that and returns None rather than fabricating numbers.
"""

import numpy as np
import pandas as pd

from clean import haversine_km
from predict import track_segments

DEPTH_COLUMN_CANDIDATES = ["depth", "pressure", "argos:depth", "eobs:pressure"]


def individual_summary(individual_df):
    """Total distance (km), average speed (km/h), and track span for one individual's fixes."""
    df = individual_df.sort_values("timestamp")
    segments = track_segments(df)
    total_distance_km = float(
        haversine_km(
            df["location_lat"].values[:-1], df["location_long"].values[:-1],
            df["location_lat"].values[1:], df["location_long"].values[1:],
        ).sum()
    ) if len(df) > 1 else 0.0

    valid_speeds = segments["speed_kmh"].replace([np.inf, -np.inf], np.nan).dropna()
    avg_speed_kmh = float(valid_speeds.mean()) if len(valid_speeds) else 0.0

    return {
        "individual_local_identifier": df["individual_local_identifier"].iloc[0],
        "n_fixes": len(df),
        "start_time": df["timestamp"].min(),
        "end_time": df["timestamp"].max(),
        "total_distance_km": round(total_distance_km, 1),
        "average_speed_kmh": round(avg_speed_kmh, 2),
    }


def study_summary(study_df):
    """Per-individual summary table for every individual in a study's DataFrame."""
    rows = [individual_summary(g) for _, g in study_df.groupby("individual_local_identifier", sort=False)]
    return pd.DataFrame(rows).sort_values("total_distance_km", ascending=False).reset_index(drop=True)


def activity_pattern(individual_df):
    """Fix count by hour-of-day (0-23, UTC as provided by Movebank), a simple activity proxy.

    Not a true diel activity/dive-behavior classification -- just how the
    fixes are distributed across the day, which can hint at surfacing
    patterns if the tag only reports while at the surface.
    """
    df = individual_df.copy()
    df["hour"] = pd.to_datetime(df["timestamp"]).dt.hour
    return df.groupby("hour").size().reindex(range(24), fill_value=0)


def dive_metrics(individual_df):
    """Dive/surface summary if the raw data includes a depth or pressure column, else None."""
    depth_col = next((c for c in DEPTH_COLUMN_CANDIDATES if c in individual_df.columns), None)
    if depth_col is None:
        return None

    depths = individual_df[depth_col].dropna()
    if depths.empty:
        return None

    return {
        "depth_column_used": depth_col,
        "max_depth": float(depths.max()),
        "mean_depth": float(depths.mean()),
        "n_dive_records": int(len(depths)),
    }


def movement_corridor_bins(study_df, grid_size_deg=0.5):
    """Aggregate all individuals' fixes into a lat/lon grid for a movement-corridor density overlay.

    Returns a DataFrame of (lat_bin, lon_bin, count), suitable for a heatmap
    showing which areas the study's tracked individuals used most, as a
    reasonable "movement corridor" proxy without fitting a formal utilization
    distribution model.
    """
    df = study_df.copy()
    df["lat_bin"] = (df["location_lat"] / grid_size_deg).round() * grid_size_deg
    df["lon_bin"] = (df["location_long"] / grid_size_deg).round() * grid_size_deg
    return df.groupby(["lat_bin", "lon_bin"]).size().reset_index(name="count")