File size: 5,154 Bytes
b35f113
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Pooling Gain — Automatum Data Highway Area Pools (Multi-Drone)
Compares a pooled (two-drone) recording with its two single-drone recordings:
observed road extent, track length distribution and share of tracks > 1 km.

Usage:
    python 04_pooling_gain.py <path_to_pool_folder> [<single_drone_1_folder> <single_drone_2_folder>] [--plot out.png]

If the single-drone folders are not given, the script looks for them next to the
pool folder (same location name, e.g. Highway-A9-OffenbauRastanlage_01_... and _02_...).
This is the layout after extracting automatum_data_highway_area_pools.zip.
If they are not found (e.g. when only Sample_Data/ was downloaded), only the
pool itself is analysed.

Example:
    python 04_pooling_gain.py ../Sample_Data/Pool-Highway-A9-OffenbauRastanlage_c025-c02598c7-fa60-4302-8cee-12a05f4e0db6
    python 04_pooling_gain.py ../automatum_data_highway_area_pools/Pool-Highway-A9-OffenbauRastanlage_c025-c02598c7-fa60-4302-8cee-12a05f4e0db6 --plot pooling_gain.png

Definitions (same as in the dataset card):
    road extent  = 0.5-99.5 % extent of all vehicle positions along the main road axis
    track length = distance driven per vehicle while it is observed
"""
import sys
import os
import re
import numpy as np
from openautomatumdronedata.dataset import droneDataset


def track_stats(path):
    dataset = droneDataset(path)
    objs = [o for o in dataset.dynWorld.get_list_of_dynamic_objects() if len(o.x_vec) > 1]
    lengths = np.array([np.sum(np.hypot(np.diff(o.x_vec), np.diff(o.y_vec))) for o in objs])
    pts = np.vstack([np.column_stack([o.x_vec, o.y_vec]) for o in objs])
    c = pts.mean(0)
    _, _, vt = np.linalg.svd(pts[::20] - c, full_matrices=False)
    along = (pts - c) @ vt[0]
    lo, hi = np.percentile(along, [0.5, 99.5])
    return {
        "name": os.path.basename(os.path.normpath(path)),
        "n": len(objs),
        "road_extent_m": float(hi - lo),
        "median_len_m": float(np.median(lengths)),
        "p90_len_m": float(np.percentile(lengths, 90)),
        "share_gt_1km": float(np.mean(lengths > 1000.0)),
        "vehicle_km": float(lengths.sum() / 1000.0),
        "lengths": lengths,
    }


def find_singles(pool_path):
    pool_name = os.path.basename(os.path.normpath(pool_path))
    m = re.match(r"Pool-(.+?)_[0-9a-f]{4}-", pool_name)
    if not m:
        return []
    location = m.group(1)
    parent = os.path.dirname(os.path.normpath(pool_path))
    cands = sorted((d for d in os.listdir(parent)
                    if d.startswith(location + "_") and not d.startswith("Pool-")
                    and os.path.isfile(os.path.join(parent, d, "dynamicWorld.json"))),
                   key=lambda d: ("_02_" in d, d))  # drone 1 first, drone 2 ("_02_") second
    return [os.path.join(parent, d) for d in cands]


def main(argv):
    plot_file = None
    if "--plot" in argv:
        i = argv.index("--plot")
        plot_file = argv[i + 1]
        argv = argv[:i] + argv[i + 2:]
    pool = argv[0]
    singles = argv[1:3] if len(argv) >= 3 else find_singles(pool)

    print(f"Loading pool: {pool}")
    rows = [track_stats(pool)]
    if not singles:
        print("Single-drone recordings not found next to the pool folder -> analysing the pool only.\n"
              "Extract automatum_data_highway_area_pools.zip to compare pool vs. single drones.")
    for s in singles:
        print(f"Loading single-drone recording: {s}")
        rows.append(track_stats(s))

    print("\n{:<28} {:>7} {:>11} {:>11} {:>10} {:>9} {:>10}".format(
        "item", "tracks", "extent [m]", "median [m]", "p90 [m]", "> 1 km", "veh-km"))
    for k, r in enumerate(rows):
        label = "pool" if k == 0 else f"single drone {k}"
        print("{:<28} {:>7d} {:>11.0f} {:>11.0f} {:>10.0f} {:>8.1f}% {:>10.0f}".format(
            label, r["n"], r["road_extent_m"], r["median_len_m"], r["p90_len_m"],
            100 * r["share_gt_1km"], r["vehicle_km"]))

    if len(rows) > 1:
        best = max(rows[1:], key=lambda r: r["road_extent_m"])
        print(f"\nPooling gain: road extent x{rows[0]['road_extent_m'] / best['road_extent_m']:.2f} "
              f"vs. best single drone, median track length x{rows[0]['median_len_m'] / best['median_len_m']:.2f}, "
              f"tracks > 1 km: {100 * best['share_gt_1km']:.1f}% -> {100 * rows[0]['share_gt_1km']:.1f}%")

    if plot_file:
        import matplotlib
        matplotlib.use("Agg")
        import matplotlib.pyplot as plt
        bins = np.arange(0, 1500, 50)
        plt.figure(figsize=(8, 4.5))
        for k, r in enumerate(rows):
            label = "pool" if k == 0 else f"single drone {k}"
            plt.hist(r["lengths"], bins=bins, histtype="step", lw=2 if k == 0 else 1.2, label=label)
        plt.axvline(1000, color="k", ls="--", lw=0.8)
        plt.xlabel("observed track length [m]"); plt.ylabel("vehicles"); plt.legend()
        plt.title(rows[0]["name"], fontsize=8)
        plt.tight_layout(); plt.savefig(plot_file, dpi=120)
        print(f"Histogram saved: {os.path.abspath(plot_file)}")


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(__doc__)
    else:
        main(sys.argv[1:])