vLAR commited on
Commit
ae0621a
·
verified ·
1 Parent(s): db5681e

Upload 6 files

Browse files
README.md CHANGED
@@ -135,77 +135,163 @@ Due to the large scale of PhysInOne, the rendered data and annotations are split
135
 
136
  For large-scale downloading and filtering, please refer to the **How to Use** section below.
137
 
138
- # 📥 How to Use(Used only as a temporary placeholder, still in progress.)
139
 
140
- TODO
141
 
142
- ### Filtering and Search
 
143
 
144
- The dataset should support filtering by:
145
 
146
  - **Split**: `train`, `val`, `test`
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
- - **Activity complexity:** `single`, `double`, `triple`
149
 
150
- - **Physical domain:** `mechanics`, `fluid_dynamics`, `optics`, `magnetism`
 
 
151
 
152
- - **Abbreviation:** `MovingHitsFixed`, `FrictionStop`, `LiquidTension`, ... , `GranularFall`
153
 
154
- ### Install Dependencies
 
 
 
 
 
 
155
 
156
  ```bash
157
- pip install datasets huggingface_hub pandas tqdm
158
  ```
159
 
160
- ### Download a Split
 
 
161
 
162
  ```bash
163
- python scripts/download.py \
164
  --split train \
165
- --output_dir ./PhysInOne
166
  ```
167
 
168
- ### Download via Filters
169
 
170
  ```bash
171
- python scripts/download.py \
172
  --split train \
173
  --activity_type double \
174
- --domain mechanics \
175
- --phenomena P01 P03 \
176
- --output_dir ./PhysInOne
177
  ```
178
 
179
- ### Download a certain number of cases (random sampling) via Filters
 
 
180
 
181
  ```bash
182
- python scripts/download.py \
183
  --split train \
184
  --activity_type double \
185
- --domain mechanics \
186
- --phenomena P01 P03 \
187
- --num 3000 \
188
- --output_dir ./PhysInOne
189
  ```
190
 
191
- ### Download by Exported JSON
192
 
193
  ```bash
194
  python scripts/filter_cases.py \
195
  --split train \
196
  --activity_type double \
197
- --domain mechanics \
198
- --phenomena P01 P03 \
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  --num 3000 \
200
- --output_dir selected_cases.json
 
201
  ```
202
 
 
 
 
 
203
  ```bash
204
  python scripts/download.py \
205
- --selection selected_scenes.json \
206
  --output_dir ./PhysInOne
207
  ```
208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
  # 🎬 Visual Overview
210
 
211
  <p align="center">
@@ -234,7 +320,6 @@ This design guarantees that training, validation, and test sets are fully separa
234
 
235
  ### Physical Phenomenon and Abbreviations
236
 
237
-
238
  <details>
239
  <summary>Click to expand full abbreviation table</summary>
240
 
 
135
 
136
  For large-scale downloading and filtering, please refer to the **How to Use** section below.
137
 
138
+ # 📥 How to Use
139
 
140
+ PhysInOne is distributed across multiple Hugging Face dataset repositories because of its large scale. We provide two scripts for selecting and downloading cases:
141
 
142
+ - `filter_cases.py`: parses the case-to-repository assignment file and exports selected cases to JSON.
143
+ - `download.py`: downloads the selected case zip files from the corresponding Hugging Face shard repositories.
144
 
145
+ The scripts support selection by:
146
 
147
  - **Split**: `train`, `val`, `test`
148
+ - **Activity complexity**: `single`, `double`, `triple`
149
+ - **Physical phenomenon abbreviation**: `MovingHitsFixed`, `FrictionStop`, `LiquidTension`, ..., `GranularFall`
150
+ - **Number of cases**: globally sample `N` cases after filtering
151
+
152
+ ## 1. Prepare Metadata Files
153
+
154
+ Place the metadata files as follows:
155
+
156
+ ```text
157
+ metadata/
158
+ repo_assignment.txt
159
+ repo_map.json
160
+ scripts/
161
+ filter_cases.py
162
+ download.py
163
+ ```
164
+
165
+ `repo_assignment.txt` stores the uploaded case-to-part mapping. Each line should follow:
166
+
167
+ ```text
168
+ <Game UE path> <part_id>
169
+ ```
170
 
171
+ Example:
172
 
173
+ ```text
174
+ /Game/PhysInOne/Scenes/Train/DoublePhysics/AccelConcaveSpin_AccelSurfaceSpin__bg070__K5ER39.AccelConcaveSpin_AccelSurfaceSpin__bg070__K5ER39 physinone_part1
175
+ ```
176
 
177
+ `repo_map.json` maps each part to its Hugging Face repository ID:
178
 
179
+ ```json
180
+ {
181
+ "physinone_part1": "PhysInOneP01/PhysInOneP01"
182
+ }
183
+ ```
184
+
185
+ ## 2. Install Dependencies
186
 
187
  ```bash
188
+ pip install huggingface_hub tqdm
189
  ```
190
 
191
+ ## 3. Filter Cases
192
+
193
+ ### Filter by split
194
 
195
  ```bash
196
+ python scripts/filter_cases.py \
197
  --split train \
198
+ --output selected_cases.json
199
  ```
200
 
201
+ ### Filter by split and activity complexity
202
 
203
  ```bash
204
+ python scripts/filter_cases.py \
205
  --split train \
206
  --activity_type double \
207
+ --output selected_cases.json
 
 
208
  ```
209
 
210
+ ### Filter by physical phenomenon abbreviation
211
+
212
+ By default, phenomenon matching uses `contains` mode. For example, the following command selects all double-physics cases that contain `FrictionStop`:
213
 
214
  ```bash
215
+ python scripts/filter_cases.py \
216
  --split train \
217
  --activity_type double \
218
+ --phenomena FrictionStop \
219
+ --match_mode contains \
220
+ --output selected_cases.json
 
221
  ```
222
 
223
+ For exact matching, use `--match_mode exact`. Order does not matter. For example, this command selects cases whose phenomenon set is exactly `{AccelConcaveSpin, AccelSurfaceSpin}`:
224
 
225
  ```bash
226
  python scripts/filter_cases.py \
227
  --split train \
228
  --activity_type double \
229
+ --phenomena AccelConcaveSpin AccelSurfaceSpin \
230
+ --match_mode exact \
231
+ --output selected_cases.json
232
+ ```
233
+
234
+ ### Randomly sample a fixed number of cases
235
+
236
+ `--num` is the global number of cases sampled after filtering. The default random seed is `42`.
237
+
238
+ ```bash
239
+ python scripts/filter_cases.py \
240
+ --split train \
241
+ --activity_type double \
242
+ --phenomena FrictionStop \
243
+ --match_mode contains \
244
  --num 3000 \
245
+ --seed 42 \
246
+ --output selected_cases.json
247
  ```
248
 
249
+ ## 4. Download Selected Cases
250
+
251
+ Each selected case is downloaded as a zip file from the corresponding Hugging Face shard repository.
252
+
253
  ```bash
254
  python scripts/download.py \
255
+ --selection selected_cases.json \
256
  --output_dir ./PhysInOne
257
  ```
258
 
259
+ If the dataset repositories are gated or private, pass a Hugging Face token:
260
+
261
+ ```bash
262
+ python scripts/download.py \
263
+ --selection selected_cases.json \
264
+ --output_dir ./PhysInOne \
265
+ --token YOUR_HF_TOKEN
266
+ ```
267
+
268
+ Preview the planned downloads without actually downloading files:
269
+
270
+ ```bash
271
+ python scripts/download.py \
272
+ --selection selected_cases.json \
273
+ --dry_run
274
+ ```
275
+
276
+ By default, downloaded zip files are saved into a flat output folder. To preserve shard/split/activity structure:
277
+
278
+ ```bash
279
+ python scripts/download.py \
280
+ --selection selected_cases.json \
281
+ --output_dir ./PhysInOne \
282
+ --keep_shard_structure
283
+ ```
284
+
285
+ The preserved structure is:
286
+
287
+ ```text
288
+ PhysInOne/
289
+ physinone_part1/
290
+ Train/
291
+ DoublePhysics/
292
+ AccelConcaveSpin_AccelSurfaceSpin__bg070__K5ER39_trajectory.zip
293
+ ```
294
+
295
  # 🎬 Visual Overview
296
 
297
  <p align="center">
 
320
 
321
  ### Physical Phenomenon and Abbreviations
322
 
 
323
  <details>
324
  <summary>Click to expand full abbreviation table</summary>
325
 
assets/metadata/repo_assignment.txt ADDED
The diff for this file is too large to render. See raw diff
 
assets/metadata/repo_map.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "physinone_part1": "PhysInOneP01/PhysInOneP01"
3
+ }
assets/scripts/download.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Download selected PhysInOne case zip files from Hugging Face shard repositories.
4
+
5
+ Input:
6
+ selected_cases.json produced by filter_cases.py
7
+ repo_map.json mapping part IDs to Hugging Face repo IDs
8
+
9
+ Recommended repo_map.json format:
10
+ {
11
+ "physinone_part1": "PhysInOneP01/PhysInOneP01",
12
+ "physinone_part2": "PhysInOneP02/PhysInOneP02"
13
+ }
14
+
15
+ The script downloads each selected case zip using huggingface_hub.hf_hub_download.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import json
22
+ import shutil
23
+ from pathlib import Path
24
+ from urllib.parse import urlparse
25
+
26
+ from huggingface_hub import hf_hub_download
27
+ from tqdm import tqdm
28
+
29
+
30
+ DEFAULT_SELECTION_FILE = Path("selected_cases.json")
31
+ DEFAULT_REPO_MAP_FILE = Path("metadata/repo_map.json")
32
+
33
+
34
+ def normalize_repo_id(value: str) -> str:
35
+ """Accept either a repo id or a Hugging Face URL and return repo id."""
36
+ value = value.strip().rstrip("/")
37
+ if value.startswith("http://") or value.startswith("https://"):
38
+ parsed = urlparse(value)
39
+ # Expected: /datasets/PhysInOneP01/PhysInOneP01[/tree/main]
40
+ parts = [p for p in parsed.path.split("/") if p]
41
+ if len(parts) >= 3 and parts[0] == "datasets":
42
+ return f"{parts[1]}/{parts[2]}"
43
+ raise ValueError(f"Cannot parse Hugging Face dataset repo URL: {value}")
44
+ return value
45
+
46
+
47
+ def load_json(path: Path) -> dict:
48
+ if not path.exists():
49
+ raise FileNotFoundError(f"File not found: {path}")
50
+ return json.loads(path.read_text(encoding="utf-8"))
51
+
52
+
53
+ def load_repo_map(path: Path) -> dict[str, str]:
54
+ data = load_json(path)
55
+ if not isinstance(data, dict):
56
+ raise ValueError("repo_map.json must be a dictionary: part_id -> repo_id")
57
+ return {str(k): normalize_repo_id(str(v)) for k, v in data.items()}
58
+
59
+
60
+ def safe_output_path(output_dir: Path, case: dict, keep_shard_structure: bool) -> Path:
61
+ filename = Path(case["hf_zip_path"]).name
62
+ if keep_shard_structure:
63
+ # Preserve Split/ActivityType layout.
64
+ return output_dir / case["part_id"] / case["split"] / case["activity_type"] / filename
65
+ return output_dir / filename
66
+
67
+
68
+ def main() -> None:
69
+ parser = argparse.ArgumentParser(description="Download PhysInOne selected case zips.")
70
+ parser.add_argument(
71
+ "--selection",
72
+ type=Path,
73
+ default=DEFAULT_SELECTION_FILE,
74
+ help=f"selected_cases.json from filter_cases.py. Default: {DEFAULT_SELECTION_FILE}",
75
+ )
76
+ parser.add_argument(
77
+ "--repo_map",
78
+ type=Path,
79
+ default=DEFAULT_REPO_MAP_FILE,
80
+ help=f"JSON mapping part_id to HF repo id. Default: {DEFAULT_REPO_MAP_FILE}",
81
+ )
82
+ parser.add_argument(
83
+ "--output_dir",
84
+ type=Path,
85
+ default=Path("./PhysInOne"),
86
+ help="Local output directory. Default: ./PhysInOne",
87
+ )
88
+ parser.add_argument(
89
+ "--repo_type",
90
+ type=str,
91
+ default="dataset",
92
+ help="Hugging Face repo type. Default: dataset",
93
+ )
94
+ parser.add_argument(
95
+ "--revision",
96
+ type=str,
97
+ default="main",
98
+ help="Hugging Face revision/branch. Default: main",
99
+ )
100
+ parser.add_argument(
101
+ "--token",
102
+ type=str,
103
+ default=None,
104
+ help="Optional Hugging Face token for gated/private repos.",
105
+ )
106
+ parser.add_argument(
107
+ "--keep_shard_structure",
108
+ action="store_true",
109
+ help="Save as output_dir/part_id/Split/ActivityType/*.zip instead of a flat folder.",
110
+ )
111
+ parser.add_argument(
112
+ "--dry_run",
113
+ action="store_true",
114
+ help="Print planned downloads without downloading.",
115
+ )
116
+ parser.add_argument(
117
+ "--overwrite",
118
+ action="store_true",
119
+ help="Overwrite local files if they already exist.",
120
+ )
121
+
122
+ args = parser.parse_args()
123
+
124
+ selection = load_json(args.selection)
125
+ repo_map = load_repo_map(args.repo_map)
126
+ cases = selection.get("cases", [])
127
+ if not isinstance(cases, list):
128
+ raise ValueError("selection JSON must contain a list field named 'cases'.")
129
+
130
+ args.output_dir.mkdir(parents=True, exist_ok=True)
131
+
132
+ missing_parts = sorted({case["part_id"] for case in cases if case["part_id"] not in repo_map})
133
+ if missing_parts:
134
+ raise KeyError(
135
+ "The following part IDs are missing from repo_map.json: "
136
+ + ", ".join(missing_parts)
137
+ )
138
+
139
+ print(f"Cases to download: {len(cases)}")
140
+ if args.dry_run:
141
+ for case in cases[:20]:
142
+ repo_id = repo_map[case["part_id"]]
143
+ out_path = safe_output_path(args.output_dir, case, args.keep_shard_structure)
144
+ print(f"{repo_id} :: {case['hf_zip_path']} -> {out_path}")
145
+ if len(cases) > 20:
146
+ print(f"... and {len(cases) - 20} more")
147
+ return
148
+
149
+ failures = []
150
+ for case in tqdm(cases, desc="Downloading cases"):
151
+ repo_id = repo_map[case["part_id"]]
152
+ filename = case["hf_zip_path"]
153
+ out_path = safe_output_path(args.output_dir, case, args.keep_shard_structure)
154
+ out_path.parent.mkdir(parents=True, exist_ok=True)
155
+
156
+ if out_path.exists() and not args.overwrite:
157
+ continue
158
+
159
+ try:
160
+ cached_file = hf_hub_download(
161
+ repo_id=repo_id,
162
+ filename=filename,
163
+ repo_type=args.repo_type,
164
+ revision=args.revision,
165
+ token=args.token,
166
+ )
167
+ shutil.copy2(cached_file, out_path)
168
+ except Exception as exc: # Keep going and summarize failures.
169
+ failures.append(
170
+ {
171
+ "case_id": case.get("case_id"),
172
+ "part_id": case.get("part_id"),
173
+ "repo_id": repo_id,
174
+ "hf_zip_path": filename,
175
+ "error": repr(exc),
176
+ }
177
+ )
178
+
179
+ if failures:
180
+ failure_path = args.output_dir / "download_failures.json"
181
+ failure_path.write_text(json.dumps(failures, indent=2, ensure_ascii=False), encoding="utf-8")
182
+ print(f"Finished with {len(failures)} failures. See: {failure_path}")
183
+ else:
184
+ print("All downloads completed successfully.")
185
+
186
+
187
+ if __name__ == "__main__":
188
+ main()
assets/scripts/filter_cases.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Filter PhysInOne cases from repo_assignment.txt.
4
+
5
+ Expected assignment file format:
6
+ /Game/PhysInOne/Scenes/Train/DoublePhysics/CaseName.CaseName physinone_part1
7
+
8
+ The script parses:
9
+ split: Train / Val / Test
10
+ activity_type: SinglePhysics / DoublePhysics / TriplePhysics
11
+ phenomena: abbreviations before "__bg..."
12
+ background: bgXXX
13
+ hash: final six-character code
14
+ part_id: e.g. physinone_part1
15
+ hf_zip_path: expected zip path inside the shard repo, e.g.
16
+ Train/DoublePhysics/AccelConcaveSpin_AccelSurfaceSpin__bg070__K5ER39_trajectory.zip
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import json
23
+ import random
24
+ import re
25
+ from dataclasses import asdict, dataclass
26
+ from pathlib import Path
27
+ from typing import Iterable, Literal
28
+
29
+
30
+ DEFAULT_ASSIGNMENT_FILE = Path("metadata/repo_assignment.txt")
31
+
32
+
33
+ SUPPORTED_PHENOMENA = {
34
+ "MovingHitsFixed",
35
+ "MovingHitsStationary",
36
+ "MovingHitsMoving",
37
+ "WindGravityBalance",
38
+ "WindPushStationary",
39
+ "WindPushSameDir",
40
+ "WindPushOppDir",
41
+ "WindDeflectMotion",
42
+ "ObliqueProjectile",
43
+ "VerticalFall",
44
+ "RollDownSlope",
45
+ "RollUpSlope",
46
+ "MagnetAttract",
47
+ "MagnetRepel",
48
+ "UniformPanelSpin",
49
+ "AccelPanelSpin",
50
+ "UniformConcaveSpin",
51
+ "AccelConcaveSpin",
52
+ "UniformSurfaceSpin",
53
+ "AccelSurfaceSpin",
54
+ "FrictionStop",
55
+ "SpringCompress",
56
+ "SpringStretch",
57
+ "ImpactFracture",
58
+ "MirrorFragmentReflect",
59
+ "ElasticCouple",
60
+ "SpringboardRebound",
61
+ "SeesawCenterPivot",
62
+ "SeesawOffsetPivot",
63
+ "BalloonFloat",
64
+ "BalloonTether",
65
+ "BalloonLift",
66
+ "FixedPlanarRedirect",
67
+ "FixedArrayRedirect",
68
+ "FixedConcaveRedirect",
69
+ "FixedConvexRedirect",
70
+ "DynMirrorRedirect",
71
+ "LaserBlock",
72
+ "MirrorReflect",
73
+ "CartMove",
74
+ "RotTurnableInertia",
75
+ "RotBoardInertia",
76
+ "LinCarryInertia",
77
+ "CatapultLaunch",
78
+ "ChainSuspend",
79
+ "SimplePendulum",
80
+ "DoublePendulum",
81
+ "CrankPush",
82
+ "BlockWallCollapse",
83
+ "StickSupportFail",
84
+ "FloatOnLiquid",
85
+ "DropInLiquid",
86
+ "MovingObjDriveLiquid",
87
+ "LiquidCarryMovingObj",
88
+ "LiquidHitFixedObj",
89
+ "LiquidTransfer",
90
+ "LiquidMultiTransfers",
91
+ "LiquidThroughGrid",
92
+ "LiquidAcrossUneven",
93
+ "LiquidRise",
94
+ "LiquidAlongContours",
95
+ "JetLiquid",
96
+ "LiquidTension",
97
+ "LiquidRefraction",
98
+ "StickyToObjects",
99
+ "StickyFromObjects",
100
+ "ElasticFall",
101
+ "PlasticineFall",
102
+ "NewtonianFluidFall",
103
+ "NonNewtonianFluidFall",
104
+ "GranularFall",
105
+ }
106
+
107
+
108
+ SPLIT_ALIASES = {
109
+ "train": "Train",
110
+ "val": "Val",
111
+ "validation": "Val",
112
+ "test": "Test",
113
+ }
114
+
115
+ ACTIVITY_ALIASES = {
116
+ "single": "SinglePhysics",
117
+ "singlephysics": "SinglePhysics",
118
+ "double": "DoublePhysics",
119
+ "doublephysics": "DoublePhysics",
120
+ "triple": "TriplePhysics",
121
+ "triplephysics": "TriplePhysics",
122
+ }
123
+
124
+
125
+ @dataclass
126
+ class CaseRecord:
127
+ case_id: str
128
+ split: str
129
+ activity_type: str
130
+ phenomena: list[str]
131
+ background: str
132
+ hash: str
133
+ ue_path: str
134
+ part_id: str
135
+ hf_zip_path: str
136
+
137
+
138
+ def normalize_split(value: str | None) -> str | None:
139
+ if value is None:
140
+ return None
141
+ key = value.strip().lower()
142
+ if key not in SPLIT_ALIASES:
143
+ raise ValueError(
144
+ f"Unknown split '{value}'. Expected one of: train, val, test."
145
+ )
146
+ return SPLIT_ALIASES[key]
147
+
148
+
149
+ def normalize_activity(value: str | None) -> str | None:
150
+ if value is None:
151
+ return None
152
+ key = value.strip().lower()
153
+ if key not in ACTIVITY_ALIASES:
154
+ raise ValueError(
155
+ f"Unknown activity_type '{value}'. Expected one of: single, double, triple."
156
+ )
157
+ return ACTIVITY_ALIASES[key]
158
+
159
+
160
+ def validate_phenomena(values: list[str] | None) -> list[str] | None:
161
+ if not values:
162
+ return values
163
+
164
+ invalid = sorted(set(values) - SUPPORTED_PHENOMENA)
165
+ if invalid:
166
+ valid_preview = ", ".join(sorted(SUPPORTED_PHENOMENA))
167
+ raise ValueError(
168
+ "Unsupported phenomenon abbreviation(s): "
169
+ + ", ".join(invalid)
170
+ + "\nExpected one or more of the 71 supported abbreviations:\n"
171
+ + valid_preview
172
+ )
173
+ return values
174
+
175
+
176
+ def parse_case_line(line: str, line_no: int) -> CaseRecord | None:
177
+ line = line.strip()
178
+ if not line or line.startswith("#"):
179
+ return None
180
+
181
+ parts = re.split(r"\s+", line, maxsplit=1)
182
+ if len(parts) != 2:
183
+ raise ValueError(f"Line {line_no}: expected two columns: <ue_path> <part_id>")
184
+
185
+ ue_path, part_id = parts[0], parts[1].strip()
186
+ path_parts = ue_path.split("/")
187
+
188
+ try:
189
+ scenes_idx = path_parts.index("Scenes")
190
+ split = path_parts[scenes_idx + 1]
191
+ activity_type = path_parts[scenes_idx + 2]
192
+ object_ref = path_parts[scenes_idx + 3]
193
+ except (ValueError, IndexError) as exc:
194
+ raise ValueError(f"Line {line_no}: cannot parse UE path: {ue_path}") from exc
195
+
196
+ if split not in {"Train", "Val", "Test"}:
197
+ raise ValueError(
198
+ f"Line {line_no}: unsupported split '{split}' in assignment file. "
199
+ "Expected Train, Val, or Test."
200
+ )
201
+
202
+ if activity_type not in {"SinglePhysics", "DoublePhysics", "TriplePhysics"}:
203
+ raise ValueError(
204
+ f"Line {line_no}: unsupported activity type '{activity_type}' in assignment file. "
205
+ "Expected SinglePhysics, DoublePhysics, or TriplePhysics."
206
+ )
207
+
208
+ case_id = object_ref.split(".")[-1]
209
+
210
+ if "__" not in case_id:
211
+ raise ValueError(f"Line {line_no}: cannot parse case_id: {case_id}")
212
+
213
+ tokens = case_id.split("__")
214
+ phenomenon_token = tokens[0]
215
+ phenomena = phenomenon_token.split("_") if phenomenon_token else []
216
+
217
+ invalid_in_file = sorted(set(phenomena) - SUPPORTED_PHENOMENA)
218
+ if invalid_in_file:
219
+ raise ValueError(
220
+ f"Line {line_no}: assignment file contains unsupported phenomenon "
221
+ f"abbreviation(s): {', '.join(invalid_in_file)} in case_id {case_id}"
222
+ )
223
+
224
+ expected_count = {
225
+ "SinglePhysics": 1,
226
+ "DoublePhysics": 2,
227
+ "TriplePhysics": 3,
228
+ }[activity_type]
229
+ if len(phenomena) != expected_count:
230
+ raise ValueError(
231
+ f"Line {line_no}: activity type {activity_type} expects "
232
+ f"{expected_count} phenomenon abbreviation(s), but got {len(phenomena)} "
233
+ f"in case_id {case_id}"
234
+ )
235
+
236
+ background = ""
237
+ hash_code = ""
238
+ for token in tokens[1:]:
239
+ if re.fullmatch(r"bg\d+", token):
240
+ background = token
241
+ else:
242
+ hash_code = token
243
+
244
+ if not background:
245
+ raise ValueError(f"Line {line_no}: background token not found in case_id: {case_id}")
246
+ if not hash_code:
247
+ raise ValueError(f"Line {line_no}: hash token not found in case_id: {case_id}")
248
+
249
+ hf_zip_path = f"{split}/{activity_type}/{case_id}_trajectory.zip"
250
+
251
+ return CaseRecord(
252
+ case_id=case_id,
253
+ split=split,
254
+ activity_type=activity_type,
255
+ phenomena=phenomena,
256
+ background=background,
257
+ hash=hash_code,
258
+ ue_path=ue_path,
259
+ part_id=part_id,
260
+ hf_zip_path=hf_zip_path,
261
+ )
262
+
263
+
264
+ def load_assignment(path: Path) -> list[CaseRecord]:
265
+ if not path.exists():
266
+ raise FileNotFoundError(
267
+ f"Assignment file not found: {path}\n"
268
+ f"Put repo_assignment.txt at {DEFAULT_ASSIGNMENT_FILE} or pass --assignment_file."
269
+ )
270
+
271
+ records: list[CaseRecord] = []
272
+ with path.open("r", encoding="utf-8") as f:
273
+ for line_no, line in enumerate(f, start=1):
274
+ record = parse_case_line(line, line_no)
275
+ if record is not None:
276
+ records.append(record)
277
+ return records
278
+
279
+
280
+ def record_matches_phenomena(
281
+ record: CaseRecord,
282
+ requested: Iterable[str] | None,
283
+ match_mode: Literal["contains", "exact"],
284
+ ) -> bool:
285
+ requested_list = list(requested or [])
286
+ if not requested_list:
287
+ return True
288
+
289
+ requested_set = set(requested_list)
290
+ record_set = set(record.phenomena)
291
+
292
+ if match_mode == "contains":
293
+ return requested_set.issubset(record_set)
294
+ if match_mode == "exact":
295
+ return requested_set == record_set
296
+
297
+ raise ValueError(f"Unsupported match_mode: {match_mode}")
298
+
299
+
300
+ def filter_records(
301
+ records: list[CaseRecord],
302
+ split: str | None = None,
303
+ activity_type: str | None = None,
304
+ phenomena: list[str] | None = None,
305
+ match_mode: Literal["contains", "exact"] = "contains",
306
+ ) -> list[CaseRecord]:
307
+ split_norm = normalize_split(split)
308
+ activity_norm = normalize_activity(activity_type)
309
+ phenomena = validate_phenomena(phenomena)
310
+
311
+ out = []
312
+ for record in records:
313
+ if split_norm is not None and record.split != split_norm:
314
+ continue
315
+ if activity_norm is not None and record.activity_type != activity_norm:
316
+ continue
317
+ if not record_matches_phenomena(record, phenomena, match_mode):
318
+ continue
319
+ out.append(record)
320
+ return out
321
+
322
+
323
+ def build_stats(records: list[CaseRecord]) -> dict:
324
+ stats: dict = {
325
+ "num_cases": len(records),
326
+ "by_split": {},
327
+ "by_activity_type": {},
328
+ "by_part": {},
329
+ }
330
+ for r in records:
331
+ stats["by_split"][r.split] = stats["by_split"].get(r.split, 0) + 1
332
+ stats["by_activity_type"][r.activity_type] = stats["by_activity_type"].get(r.activity_type, 0) + 1
333
+ stats["by_part"][r.part_id] = stats["by_part"].get(r.part_id, 0) + 1
334
+ return stats
335
+
336
+
337
+ def main() -> None:
338
+ parser = argparse.ArgumentParser(description="Filter PhysInOne cases.")
339
+ parser.add_argument(
340
+ "--assignment_file",
341
+ type=Path,
342
+ default=DEFAULT_ASSIGNMENT_FILE,
343
+ help=f"Path to repo_assignment.txt. Default: {DEFAULT_ASSIGNMENT_FILE}",
344
+ )
345
+ parser.add_argument("--split", type=str, default=None, help="train, val, or test.")
346
+ parser.add_argument(
347
+ "--activity_type",
348
+ type=str,
349
+ default=None,
350
+ help="single, double, or triple.",
351
+ )
352
+ parser.add_argument(
353
+ "--phenomena",
354
+ nargs="*",
355
+ default=None,
356
+ help="One or more phenomenon abbreviations, e.g. AccelConcaveSpin FrictionStop.",
357
+ )
358
+ parser.add_argument(
359
+ "--match_mode",
360
+ choices=["contains", "exact"],
361
+ default="contains",
362
+ help=(
363
+ "contains: selected cases contain all requested phenomena; "
364
+ "exact: selected cases have exactly the requested phenomena. "
365
+ "Order is ignored in both modes."
366
+ ),
367
+ )
368
+ parser.add_argument(
369
+ "--num",
370
+ type=int,
371
+ default=None,
372
+ help="Global number of cases to sample after filtering. Default: keep all matches.",
373
+ )
374
+ parser.add_argument(
375
+ "--seed",
376
+ type=int,
377
+ default=42,
378
+ help="Random seed used when --num is specified. Default: 42.",
379
+ )
380
+ parser.add_argument(
381
+ "--output",
382
+ type=Path,
383
+ default=Path("selected_cases.json"),
384
+ help="Output JSON path. Default: selected_cases.json",
385
+ )
386
+ parser.add_argument(
387
+ "--show_stats",
388
+ action="store_true",
389
+ help="Print dataset/filtering statistics.",
390
+ )
391
+
392
+ args = parser.parse_args()
393
+
394
+ records = load_assignment(args.assignment_file)
395
+ matches = filter_records(
396
+ records,
397
+ split=args.split,
398
+ activity_type=args.activity_type,
399
+ phenomena=args.phenomena,
400
+ match_mode=args.match_mode,
401
+ )
402
+
403
+ if args.num is not None:
404
+ if args.num < 0:
405
+ raise ValueError("--num must be non-negative.")
406
+ rng = random.Random(args.seed)
407
+ if args.num < len(matches):
408
+ matches = rng.sample(matches, args.num)
409
+
410
+ result = {
411
+ "filters": {
412
+ "split": args.split,
413
+ "activity_type": args.activity_type,
414
+ "phenomena": args.phenomena or [],
415
+ "match_mode": args.match_mode,
416
+ "num": args.num,
417
+ "seed": args.seed,
418
+ },
419
+ "stats": build_stats(matches),
420
+ "cases": [asdict(r) for r in matches],
421
+ }
422
+
423
+ args.output.parent.mkdir(parents=True, exist_ok=True)
424
+ args.output.write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
425
+
426
+ print(f"Matched cases: {len(matches)}")
427
+ print(f"Saved selection to: {args.output}")
428
+ if args.show_stats:
429
+ print(json.dumps(result["stats"], indent=2, ensure_ascii=False))
430
+
431
+
432
+ if __name__ == "__main__":
433
+ main()