File size: 9,359 Bytes
db604ae
 
 
 
 
ebdfa82
f617916
ccce906
 
 
 
 
 
 
 
 
 
 
 
 
db604ae
 
34e069f
 
 
 
 
 
 
 
2525316
6887c19
2525316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebdfa82
 
 
db604ae
 
 
 
 
 
 
ebdfa82
 
 
 
 
db604ae
 
 
 
f617916
5da54ac
f617916
7daf211
d6dd76f
f617916
d6dd76f
ccce906
6887c19
 
 
 
 
 
5da54ac
6887c19
44d61dd
d6dd76f
44d61dd
d6dd76f
 
 
 
 
 
 
 
f617916
7daf211
 
 
 
 
 
 
 
5da54ac
7daf211
 
 
 
 
 
 
 
 
 
 
 
5da54ac
7daf211
 
5da54ac
d6dd76f
 
f617916
 
 
 
ebdfa82
44d61dd
ebdfa82
db604ae
 
 
be074b5
db604ae
be074b5
db604ae
 
 
 
be074b5
db604ae
ccce906
 
be074b5
 
db604ae
ccce906
f617916
44d61dd
be074b5
 
db604ae
ccce906
be074b5
 
 
 
 
 
 
6887c19
be074b5
db604ae
be074b5
db604ae
be074b5
f617916
db604ae
6ba44c9
5da54ac
6ba44c9
2525316
 
ccce906
be074b5
2525316
6887c19
db604ae
be074b5
5da54ac
ccce906
7daf211
44d61dd
ccce906
44d61dd
 
34e069f
44d61dd
ccce906
44d61dd
ccce906
44d61dd
 
 
7daf211
ccce906
7daf211
44d61dd
 
 
 
 
 
5da54ac
44d61dd
7daf211
44d61dd
5da54ac
44d61dd
 
7daf211
44d61dd
7daf211
6887c19
ccce906
7daf211
6ba44c9
34e069f
5da54ac
34e069f
 
 
7daf211
34e069f
 
 
7daf211
 
34e069f
 
2525316
 
 
34e069f
ccce906
 
 
ebdfa82
d6dd76f
 
f617916
db604ae
 
 
d6dd76f
34e069f
 
 
 
 
 
 
db604ae
 
 
 
f617916
ebdfa82
 
be074b5
44d61dd
 
ccce906
f617916
ebdfa82
 
 
f617916
db604ae
 
34e069f
db604ae
 
ebdfa82
5da54ac
f617916
7daf211
 
f617916
 
7daf211
ebdfa82
 
db604ae
ccce906
f617916
d6dd76f
db604ae
d6dd76f
 
 
 
7daf211
 
d6dd76f
7daf211
 
 
 
d6dd76f
db604ae
 
ebdfa82
 
 
34e069f
db604ae
5da54ac
db604ae
 
f617916
 
db604ae
ebdfa82
db604ae
ccce906
db604ae
d6dd76f
 
ebdfa82
7daf211
 
5da54ac
7daf211
f617916
db604ae
d6dd76f
 
7daf211
d6dd76f
 
f617916
ebdfa82
 
d6dd76f
 
 
 
7daf211
 
d6dd76f
 
 
34e069f
d6dd76f
 
db604ae
 
 
9ed74df
db604ae
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
import gradio as gr
import json
import pandas as pd
import plotly.express as px
import tempfile
import numpy as np
import matplotlib.pyplot as plt


# -----------------------------
# Haversine distance (km)
# -----------------------------
def haversine(lat1, lon1, lat2, lon2):
    R = 6371.0
    phi1, phi2 = np.radians(lat1), np.radians(lat2)
    dphi = np.radians(lat2 - lat1)
    dlambda = np.radians(lon2 - lon1)

    a = np.sin(dphi / 2) ** 2 + np.cos(phi1) * np.cos(phi2) * np.sin(dlambda / 2) ** 2
    return 2 * R * np.arcsin(np.sqrt(a))


# -----------------------------
# Angle difference helper
# -----------------------------
def angle_diff(a, b):
    diff = abs(a - b)
    return min(diff, 360 - diff)


# -----------------------------
# Robust timestamp parser
# -----------------------------
def parse_timestamp(series):
    ts = pd.to_datetime(series, errors="coerce", utc=True)

    mask = ts.isna()
    if mask.any():
        s = series[mask].dropna()
        numeric = pd.to_numeric(s, errors="coerce")

        if not numeric.empty:
            if numeric.median() > 1e12:
                ts.loc[mask] = pd.to_datetime(numeric, unit="ms", errors="coerce", utc=True)
            else:
                ts.loc[mask] = pd.to_datetime(numeric, unit="s", errors="coerce", utc=True)

    return ts


# -----------------------------
# Load MMSIs
# -----------------------------
def load_geojson(geojson_file):
    if geojson_file is None:
        return gr.update(choices=[])

    with open(geojson_file.name, "r") as f:
        data = json.load(f)

    mmsis = sorted({
        str(f.get("properties", {}).get("mmsi"))
        for f in data.get("features", [])
        if f.get("properties", {}).get("mmsi") is not None
    })

    return gr.update(choices=mmsis)


# -----------------------------
# Anomaly plot
# -----------------------------
def create_anomaly_plot(df):
    df = df.sort_values("last_seen")

    fig, ax = plt.subplots(figsize=(5, 5))

    ax.plot(
        df["longitude"],
        df["latitude"],
        marker='.',
        linestyle='-',
        alpha=0.7,
        color='black'
    )

    anomal = df[df["anomaly"] == True]
    if not anomal.empty:
        ax.scatter(
            anomal["longitude"],
            anomal["latitude"],
            color="blue",
            s=60,
            label="Anomaly"
        )
        ax.legend()

    ax.set_title("Route + Anomalies")
    ax.axis('equal')
    ax.axis('off')

    return fig


# -----------------------------
# Clean route plot (UPDATED)
# -----------------------------
def create_clean_plot(df):
    df = df.sort_values("last_seen")

    fig, ax = plt.subplots(figsize=(5, 5))

    ax.plot(
        df["longitude"],
        df["latitude"],
        marker='.',
        linestyle='-',
        alpha=0.7,
        color='red'   # βœ… updated color
    )

    #ax.set_title("Route")  # βœ… removed any extra wording
    ax.axis('equal')
    ax.axis('off')

    return fig


# -----------------------------
# Main processing
# -----------------------------
def filter_vessel(geojson_file, mmsi):

    if geojson_file is None:
        raise gr.Error("Upload GeoJSON first")
    if not mmsi:
        raise gr.Error("Select MMSI")

    with open(geojson_file.name, "r") as f:
        data = json.load(f)

    rows = []

    for ftr in data.get("features", []):
        props = ftr.get("properties", {})
        if str(props.get("mmsi")) != str(mmsi):
            continue

        geom = ftr.get("geometry", {})
        coords = geom.get("coordinates")

        if not coords:
            continue

        lon, lat = coords if geom.get("type") == "Point" else (coords[0], coords[1])

        rows.append({
            "mmsi": props.get("mmsi"),
            "latitude": lat,
            "longitude": lon,
            "speed_knots": props.get("speed_knots"),
            "course_deg": props.get("course_deg"),
            "last_seen": props.get("timestamp") or props.get("last_seen"),
        })

    df = pd.DataFrame(rows)

    if df.empty:
        raise gr.Error("No data for selected MMSI")

    # -----------------------------
    # timestamp fix
    # -----------------------------
    df["last_seen"] = df["last_seen"].astype(str).str.strip()
    df["last_seen"] = parse_timestamp(df["last_seen"])
    df = df.dropna(subset=["last_seen"]).sort_values("last_seen").reset_index(drop=True)

    if df.empty:
        raise gr.Error("No valid timestamps after parsing")

    # -----------------------------
    # features
    # -----------------------------
    df["speed_knots"] = df["speed_knots"].fillna(0)
    df["speed_kmh_reported"] = df["speed_knots"] * 1.852

    df["speed_anomaly"] = False
    df["teleportation_anomaly"] = False
    df["turn_anomaly"] = False
    df["anomaly"] = False

    if len(df) > 1:

        df["prev_lat"] = df["latitude"].shift(1)
        df["prev_lon"] = df["longitude"].shift(1)
        df["prev_time"] = df["last_seen"].shift(1)
        df["prev_course"] = df["course_deg"].shift(1)

        # distance
        df["distance_km"] = df.apply(
            lambda r: haversine(r["prev_lat"], r["prev_lon"], r["latitude"], r["longitude"])
            if pd.notnull(r["prev_lat"]) else 0,
            axis=1,
        )

        # time fix
        df["time_hours"] = (df["last_seen"] - df["prev_time"]).dt.total_seconds() / 3600
        df.loc[df["time_hours"] < 0.001, "time_hours"] = np.nan

        # computed speed
        df["computed_speed_kmh"] = df["distance_km"] / df["time_hours"]
        df["computed_speed_kmh"] = df["computed_speed_kmh"].replace([np.inf, -np.inf], np.nan)
        df.loc[df["computed_speed_kmh"] > 1000, "computed_speed_kmh"] = np.nan

        # SPEED anomaly
        df["speed_anomaly"] = df["speed_kmh_reported"] > 70

        # TELEPORT anomaly
        df["teleportation_anomaly"] = df["computed_speed_kmh"] > 120

        # TURN anomaly
        df["turn_angle"] = df.apply(
            lambda r: angle_diff(r["course_deg"], r["prev_course"])
            if pd.notnull(r["prev_course"]) and pd.notnull(r["course_deg"])
            else np.nan,
            axis=1
        )

        moving = df["speed_kmh_reported"] > 5
        df["turn_anomaly"] = (df["turn_angle"] > 90) & moving

        df["anomaly"] = (
            df["speed_anomaly"] |
            df["teleportation_anomaly"] |
            df["turn_anomaly"]
        )

    # -----------------------------
    # Plotly map
    # -----------------------------
    df["label"] = df["anomaly"].map({True: "Anomaly", False: "Normal"})

    fig_map = px.scatter_mapbox(
        df,
        lat="latitude",
        lon="longitude",
        color="label",
        hover_data=[
            "speed_knots",
            "speed_kmh_reported",
            "computed_speed_kmh",
            "turn_angle",
            "last_seen"
        ],
        zoom=5,
        height=700,
    )

    fig_map.add_trace(
        dict(
            type="scattermapbox",
            mode="lines+markers",
            lat=df["latitude"],
            lon=df["longitude"],
            line=dict(width=2, color="black"),
            name="Route",
        )
    )

    fig_map.update_layout(
        mapbox_style="open-street-map",
        margin=dict(l=0, r=0, t=30, b=0),
        title=f"MMSI {mmsi} - AIS Anomaly Detection",
    )

    # -----------------------------
    # matplotlib plots
    # -----------------------------
    fig_anomaly = create_anomaly_plot(df)
    fig_clean = create_clean_plot(df)

    # -----------------------------
    # export
    # -----------------------------
    json_output = df.to_json(orient="records", indent=2, date_format="iso")

    tmp_file = tempfile.NamedTemporaryFile(suffix=".geojson", delete=False)
    with open(tmp_file.name, "w") as f:
        json.dump(data, f, indent=2)

    return (
        fig_map,
        df,
        json_output,
        fig_anomaly,
        fig_clean,
        tmp_file.name,
        "OK",
        "OK",
        "OK",
        f"Total points: {len(df)}"
    )


# -----------------------------
# UI
# -----------------------------
with gr.Blocks(title="AIS Anomaly Detection") as demo:

    gr.Markdown("# 🚒 AIS Vessel Route + Clean Plot Separation")

    with gr.Row():
        geojson_file = gr.File(label="Upload GeoJSON")
        mmsi_dropdown = gr.Dropdown(label="Select MMSI", choices=[], interactive=True)

    geojson_file.change(load_geojson, geojson_file, mmsi_dropdown)

    run_btn = gr.Button("Analyze Vessel", variant="primary")

    map_out = gr.Plot()
    table_out = gr.Dataframe()
    json_out = gr.Code(language="json")

    mpl_anomaly_out = gr.Plot(label="Route + Anomalies")
    mpl_clean_out = gr.Plot(label="Route")

    download_out = gr.File()

    speed_out = gr.Textbox(label="⚑ Speed Anomaly")
    teleport_out = gr.Textbox(label="🧭 Teleportation Anomaly")
    turn_out = gr.Textbox(label="πŸ”„ Turn Anomaly")
    summary_out = gr.Textbox(label="πŸ“Š Summary")

    run_btn.click(
        filter_vessel,
        [geojson_file, mmsi_dropdown],
        [
            map_out,
            table_out,
            json_out,
            mpl_anomaly_out,
            mpl_clean_out,
            download_out,
            speed_out,
            teleport_out,
            turn_out,
            summary_out
        ],
    )

if __name__ == "__main__":
    ## LAunch
    demo.launch()