File size: 11,545 Bytes
4e6a175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Create dataset splits or transfer clip assignments to the pretraining set."""

import argparse
import csv
import random
from collections import Counter, defaultdict
from pathlib import Path


SITES = ("Canopy", "Graminoid")
MIN_VALIDATION_PERCENTAGE = 10
MAX_VALIDATION_PERCENTAGE = 20

# Clips in each tuple must remain in the same split. These are the inseparable
# flights documented in markdown/flights.md; all other clips are singletons.
FLIGHT_GROUPS = {
    "Canopy": (
        ("Canopy-06", "Canopy-07", "Canopy-08", "Canopy-09", "Canopy-10",
         "Canopy-11", "Canopy-17"),
        ("Canopy-12", "Canopy-13", "Canopy-15"),
        ("Canopy-20", "Canopy-21", "Canopy-22"),
    ),
    "Graminoid": (
        ("Graminoid-04", "Graminoid-05"),
        ("Graminoid-09", "Graminoid-10", "Graminoid-11"),
        ("Graminoid-12", "Graminoid-13", "Graminoid-14"),
        ("Graminoid-16", "Graminoid-17", "Graminoid-18"),
    ),
}


def parse_args():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "data_root",
        nargs="?",
        type=Path,
        default=Path("Data"),
        help="dataset root containing samples.csv (default: %(default)s)",
    )
    mode = parser.add_mutually_exclusive_group(required=True)
    mode.add_argument(
        "--test",
        choices=SITES,
        help="burn site assigned entirely to the test split",
    )
    mode.add_argument(
        "--finetune-split",
        type=Path,
        help=(
            "splits.csv whose clip assignments should be transferred to this "
            "more densely sampled dataset"
        ),
    )
    parser.add_argument(
        "--seed",
        type=int,
        default=42,
        help="random seed used for reproducible tie-breaking (default: %(default)s)",
    )
    return parser.parse_args()


def load_samples(manifest):
    clips = {site: set() for site in SITES}
    clip_sites = {}
    frames = []
    seen_frames = set()

    with manifest.open(newline="") as handle:
        reader = csv.DictReader(handle)
        required = {"pair_id", "unit", "rgb_path"}
        if not reader.fieldnames or not required.issubset(reader.fieldnames):
            raise RuntimeError(f"invalid samples.csv header: {manifest}")

        for line_number, row in enumerate(reader, start=2):
            clip = row["pair_id"].strip()
            site = row["unit"].strip()
            rgb_path = row["rgb_path"].strip()
            if not clip:
                raise RuntimeError(f"empty pair_id on samples.csv line {line_number}")
            if not rgb_path:
                raise RuntimeError(f"empty rgb_path on samples.csv line {line_number}")
            path = Path(rgb_path)
            if len(path.parts) < 2 or path.parts[-2] != "rgb":
                raise RuntimeError(
                    f"unexpected rgb_path {rgb_path!r} on samples.csv line "
                    f"{line_number}"
                )
            frame = (Path(*path.parts[:-2]) / path.name).as_posix()
            if site not in clips:
                raise RuntimeError(
                    f"unknown unit {site!r} on samples.csv line {line_number}"
                )
            if frame in seen_frames:
                raise RuntimeError(f"duplicate rgb_path {frame!r} in samples.csv")
            previous_site = clip_sites.setdefault(clip, site)
            if previous_site != site:
                raise RuntimeError(f"clip {clip!r} belongs to multiple units")
            seen_frames.add(frame)
            clips[site].add(clip)
            frames.append((frame, clip, site))

    for site in SITES:
        if not clips[site]:
            raise RuntimeError(f"samples.csv contains no {site} clips")
    return frames, clips


def load_clip_splits(path):
    clip_splits = {}
    unit_splits = defaultdict(set)

    with path.open(newline="") as handle:
        reader = csv.DictReader(handle)
        required = {"frame", "split"}
        if not reader.fieldnames or not required.issubset(reader.fieldnames):
            raise RuntimeError(f"invalid splits.csv header: {path}")

        for line_number, row in enumerate(reader, start=2):
            frame = Path(row["frame"].strip())
            split = row["split"].strip()
            if len(frame.parts) != 3:
                raise RuntimeError(
                    f"unexpected frame path {frame.as_posix()!r} on line "
                    f"{line_number} of {path}"
                )
            if split not in {"train", "val", "test"}:
                raise RuntimeError(
                    f"unknown split {split!r} on line {line_number} of {path}"
                )

            unit, clip = frame.parts[:2]
            if unit not in SITES:
                raise RuntimeError(
                    f"unknown unit {unit!r} on line {line_number} of {path}"
                )
            previous = clip_splits.setdefault(clip, split)
            if previous != split:
                raise RuntimeError(
                    f"clip {clip!r} occurs in both {previous!r} and {split!r}"
                )
            unit_splits[unit].add(split)

    if not clip_splits:
        raise RuntimeError(f"no split assignments found in {path}")

    test_sites = [site for site in SITES if unit_splits[site] == {"test"}]
    if len(test_sites) != 1:
        raise RuntimeError(
            f"expected exactly one entirely held-out unit in {path}, found "
            f"{len(test_sites)}"
        )
    test_site = test_sites[0]
    training_site = next(site for site in SITES if site != test_site)
    if not unit_splits[training_site] or not unit_splits[training_site] <= {
        "train",
        "val",
    }:
        raise RuntimeError(
            f"unexpected assignments for training unit {training_site!r} in "
            f"{path}"
        )
    return clip_splits, test_site


def make_flight_blocks(site, clips):
    blocks = []
    grouped = set()

    for documented_group in FLIGHT_GROUPS[site]:
        present = tuple(clip for clip in documented_group if clip in clips)
        if present:
            blocks.append(present)
            grouped.update(present)

    blocks.extend((clip,) for clip in sorted(clips - grouped))
    return blocks


def choose_validation_blocks(blocks, frame_counts, rng):
    if len(blocks) < 2:
        raise RuntimeError("at least two flight blocks are needed for train/val")

    block_frame_counts = [
        sum(frame_counts[clip] for clip in block) for block in blocks
    ]
    total_frames = sum(block_frame_counts)
    candidates = []

    for mask in range(1, (1 << len(blocks)) - 1):
        val_frames = sum(
            count
            for index, count in enumerate(block_frame_counts)
            if mask & (1 << index)
        )
        if (
            MIN_VALIDATION_PERCENTAGE * total_frames
            <= 100 * val_frames
            <= MAX_VALIDATION_PERCENTAGE * total_frames
        ):
            candidates.append(mask)

    if not candidates:
        raise RuntimeError(
            "no combination of complete flight blocks puts validation between "
            f"{MIN_VALIDATION_PERCENTAGE}% and {MAX_VALIDATION_PERCENTAGE}% "
            "of frames"
        )

    selected_mask = rng.choice(candidates)
    selected = [
        block for index, block in enumerate(blocks) if selected_mask & (1 << index)
    ]
    return selected


def transfer_validation_blocks(blocks, frame_counts, clip_splits, rng):
    fixed_validation = []
    unassigned = []

    for block in blocks:
        assignments = {clip_splits[clip] for clip in block if clip in clip_splits}
        if "test" in assignments:
            raise RuntimeError(
                f"training block {block!r} is assigned to test in finetune splits"
            )
        if len(assignments) > 1:
            raise RuntimeError(
                f"flight block {block!r} crosses train and validation in "
                "finetune splits"
            )
        if assignments == {"val"}:
            fixed_validation.append(block)
        elif not assignments:
            unassigned.append(block)

    total_frames = sum(frame_counts.values())
    fixed_frames = sum(
        frame_counts[clip] for block in fixed_validation for clip in block
    )
    candidates = []

    for mask in range(1 << len(unassigned)):
        val_frames = fixed_frames + sum(
            sum(frame_counts[clip] for clip in block)
            for index, block in enumerate(unassigned)
            if mask & (1 << index)
        )
        if (
            MIN_VALIDATION_PERCENTAGE * total_frames
            <= 100 * val_frames
            <= MAX_VALIDATION_PERCENTAGE * total_frames
        ):
            candidates.append(mask)

    if not candidates:
        raise RuntimeError(
            "no assignment of target-only flight blocks puts validation "
            f"between {MIN_VALIDATION_PERCENTAGE}% and "
            f"{MAX_VALIDATION_PERCENTAGE}% of frames"
        )

    selected_mask = rng.choice(candidates)
    selected = fixed_validation + [
        block
        for index, block in enumerate(unassigned)
        if selected_mask & (1 << index)
    ]
    return selected


def main():
    args = parse_args()
    root = args.data_root.resolve()
    manifest = root / "samples.csv"
    output = root / "splits.csv"
    frames, clips = load_samples(manifest)

    rng = random.Random(args.seed)
    if args.finetune_split:
        clip_splits, test_site = load_clip_splits(args.finetune_split.resolve())
    else:
        clip_splits = None
        test_site = args.test

    training_site = next(site for site in SITES if site != test_site)
    blocks = make_flight_blocks(training_site, clips[training_site])
    frame_counts = Counter(
        clip for _, clip, site in frames if site == training_site
    )
    if clip_splits is None:
        val_blocks = choose_validation_blocks(blocks, frame_counts, rng)
    else:
        val_blocks = transfer_validation_blocks(
            blocks, frame_counts, clip_splits, rng
        )
    val_clips = {clip for block in val_blocks for clip in block}

    target_only = []
    if clip_splits is not None:
        for site in SITES:
            for clip in sorted(clips[site] - clip_splits.keys()):
                if site == test_site:
                    split = "test"
                elif clip in val_clips:
                    split = "val"
                else:
                    split = "train"
                target_only.append(f"{clip}={split}")

    rows = []
    for frame, clip, site in frames:
        if site == test_site:
            split = "test"
        elif clip in val_clips:
            split = "val"
        else:
            split = "train"
        rows.append({"frame": frame, "split": split})

    with output.open("w", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=("frame", "split"))
        writer.writeheader()
        writer.writerows(rows)

    training_frames = sum(frame_counts.values())
    val_frames = sum(frame_counts[clip] for clip in val_clips)
    val_ratio = val_frames / training_frames
    print(f"wrote {output}")
    print(
        f"{training_site}: {training_frames - val_frames} train and "
        f"{val_frames} val frames ({val_ratio:.1%} val)"
    )
    test_frames = sum(1 for _, _, site in frames if site == test_site)
    print(f"{test_site}: {test_frames} test frames")
    if target_only:
        print("target-only clips: " + ", ".join(target_only))


if __name__ == "__main__":
    main()