pngt 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pngt-0.1.0/.gitignore +44 -0
- pngt-0.1.0/PKG-INFO +58 -0
- pngt-0.1.0/archive.py +236 -0
- pngt-0.1.0/dto.py +291 -0
- pngt-0.1.0/exceptions.py +86 -0
- pngt-0.1.0/package/CHANGELOG.md +18 -0
- pngt-0.1.0/package/LICENSE +21 -0
- pngt-0.1.0/package/README.md +35 -0
- pngt-0.1.0/package/py.typed +0 -0
- pngt-0.1.0/public.py +77 -0
- pngt-0.1.0/pyproject.toml +48 -0
- pngt-0.1.0/reader.py +509 -0
pngt-0.1.0/.gitignore
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
launch.json
|
|
2
|
+
*.pyc
|
|
3
|
+
*.pyc.*
|
|
4
|
+
*.log
|
|
5
|
+
*.log*
|
|
6
|
+
*.bin
|
|
7
|
+
*.csv
|
|
8
|
+
*.tar.xz
|
|
9
|
+
*.tar.gz
|
|
10
|
+
*.json
|
|
11
|
+
*.f1pcap
|
|
12
|
+
*.txt
|
|
13
|
+
*.ini
|
|
14
|
+
*.cpp
|
|
15
|
+
*.exe
|
|
16
|
+
build/*
|
|
17
|
+
dist/*
|
|
18
|
+
smoke-report/
|
|
19
|
+
png-venv/
|
|
20
|
+
.idea/
|
|
21
|
+
.vercel
|
|
22
|
+
*yappi*
|
|
23
|
+
*.part
|
|
24
|
+
.invalid
|
|
25
|
+
*.pem
|
|
26
|
+
.DS_Store
|
|
27
|
+
.coverage
|
|
28
|
+
.coverage_*
|
|
29
|
+
.coverage.*
|
|
30
|
+
htmlcov/
|
|
31
|
+
coverage_reports/
|
|
32
|
+
reports/
|
|
33
|
+
*.diff
|
|
34
|
+
*:Zone.Identifier
|
|
35
|
+
*.db
|
|
36
|
+
.pits_n_giggles.lock
|
|
37
|
+
*.gz
|
|
38
|
+
graphify-out/
|
|
39
|
+
.hypothesis/
|
|
40
|
+
plans/
|
|
41
|
+
*.pngt
|
|
42
|
+
!tests/pngt_sample_data/*.pngt
|
|
43
|
+
!tests/pngt_sample_data/*.json
|
|
44
|
+
data/
|
pngt-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pngt
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Reader for .pngt lap telemetry files recorded by Pits n' Giggles
|
|
5
|
+
Project-URL: Homepage, https://www.pitsngiggles.com
|
|
6
|
+
Project-URL: Source, https://github.com/ashwin-nat/pits-n-giggles
|
|
7
|
+
Project-URL: Issues, https://github.com/ashwin-nat/pits-n-giggles/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/ashwin-nat/pits-n-giggles/blob/pngt-py-v0.1.0/lib/pngt/package/CHANGELOG.md
|
|
9
|
+
Author: Ashwin Natarajan
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: package/LICENSE
|
|
12
|
+
Keywords: f1,pits-n-giggles,pngt,sim-racing,telemetry
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Topic :: Games/Entertainment :: Simulation
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Requires-Dist: numpy>=1.24
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# pngt
|
|
25
|
+
|
|
26
|
+
Reads `.pngt` lap telemetry files recorded by [Pits n' Giggles](https://www.pitsngiggles.com), versions 1
|
|
27
|
+
and 2. A lap comes back as a dict of numpy float32 arrays, one per sensor, keyed by sensor name.
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
pip install pngt
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
import pngt
|
|
35
|
+
|
|
36
|
+
with pngt.open("race.pngt") as f:
|
|
37
|
+
print(f.session.track.name, f.session.session_type)
|
|
38
|
+
print([driver.name for driver in f.drivers]) # f.drivers[5], f.drivers.player
|
|
39
|
+
print({key: sensor.unit for key, sensor in f.sensors.items()})
|
|
40
|
+
|
|
41
|
+
laps = f.laps(5) # driver 5's laps: lap_number, lap_time_ms, valid, ...
|
|
42
|
+
arrays = f.read_lap(5, 12, sensors=["throttle"])
|
|
43
|
+
arrays[pngt.LAP_DISTANCE] # metres, float32
|
|
44
|
+
arrays["throttle"] # in f.sensors["throttle"].unit
|
|
45
|
+
|
|
46
|
+
f.session_data() # the app's own session JSON, as stored
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`f.sensors` lists the sensors a file holds, with label, unit and type. Which ones a file has depends on
|
|
50
|
+
the recording settings. Missing samples are NaN. The library only reads: interpolating, resampling, and
|
|
51
|
+
deciding whether a lap is complete enough are left to you.
|
|
52
|
+
|
|
53
|
+
The [TypeScript reader](https://github.com/ashwin-nat/pits-n-giggles/tree/pngt-py-v0.1.0/lib-ts/pngt) has the same API and passes the same sample files.
|
|
54
|
+
|
|
55
|
+
- Docs: <https://www.pitsngiggles.com/docs/pngt/>
|
|
56
|
+
- Format spec: [SPEC.md](https://github.com/ashwin-nat/pits-n-giggles/blob/pngt-py-v0.1.0/lib/pngt/SPEC.md)
|
|
57
|
+
- Changelog: [CHANGELOG.md](https://github.com/ashwin-nat/pits-n-giggles/blob/pngt-py-v0.1.0/lib/pngt/package/CHANGELOG.md)
|
|
58
|
+
- Issues: <https://github.com/ashwin-nat/pits-n-giggles/issues/new?template=pngt.yml>
|
pngt-0.1.0/archive.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
# MIT License
|
|
2
|
+
#
|
|
3
|
+
# Copyright (c) [2026] [Ashwin Natarajan]
|
|
4
|
+
#
|
|
5
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
# in the Software without restriction, including without limitation the rights
|
|
8
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
# furnished to do so, subject to the following conditions:
|
|
11
|
+
#
|
|
12
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
# copies or substantial portions of the Software.
|
|
14
|
+
#
|
|
15
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
# SOFTWARE.
|
|
22
|
+
|
|
23
|
+
# -------------------------------------- IMPORTS -----------------------------------------------------------------------
|
|
24
|
+
|
|
25
|
+
import dataclasses
|
|
26
|
+
import json
|
|
27
|
+
import zipfile
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
from typing import Iterable, Optional, Union
|
|
30
|
+
|
|
31
|
+
from .dto import (LapTelemetryPaths, PngtContents, SessionBest,
|
|
32
|
+
SessionDataEntry)
|
|
33
|
+
from .exceptions import (EntryTooLargeError, InvalidHeaderError,
|
|
34
|
+
MalformedSessionError, NotAZipFileError,
|
|
35
|
+
SectionNotPresentError, UnsupportedFormatError,
|
|
36
|
+
UnsupportedVersionError)
|
|
37
|
+
|
|
38
|
+
# -------------------------------------- CONSTANTS ----------------------------------------------------------------------
|
|
39
|
+
|
|
40
|
+
HEADER_FORMAT = "pngt"
|
|
41
|
+
READABLE_VERSIONS = (1, 2)
|
|
42
|
+
WRITE_VERSION = 2
|
|
43
|
+
HEADER_ENTRY = "header.json"
|
|
44
|
+
SENSOR_MANIFEST_ENTRY = "manifest.json"
|
|
45
|
+
ZIP_MAGIC = b"PK\x03\x04"
|
|
46
|
+
CONTENT_LAP_TELEMETRY = "lap_telemetry"
|
|
47
|
+
CONTENT_SESSION_DATA = "session_data"
|
|
48
|
+
# v2 manifest.json section holding the mandatory columns' encodings
|
|
49
|
+
MANIFEST_MANDATORY_CHANNELS = "mandatory_channels"
|
|
50
|
+
# Inside a v2 lap .npz, `<key>.nan.npy` holds an array's NaN indices
|
|
51
|
+
NAN_SUFFIX = ".nan"
|
|
52
|
+
# Largest decompressed size an entry may declare. zipfile stops at the declared size, so this bounds a zip bomb
|
|
53
|
+
MAX_ENTRY_BYTES = 256 * 1024 * 1024
|
|
54
|
+
|
|
55
|
+
# -------------------------------------- FUNCTIONS ----------------------------------------------------------------------
|
|
56
|
+
|
|
57
|
+
def build_header(session_data: Optional[SessionDataEntry], has_lap_telemetry: bool,
|
|
58
|
+
version: int = WRITE_VERSION) -> dict:
|
|
59
|
+
"""header.json's content. `contents` names every section and where its entries are, with None for
|
|
60
|
+
one the file does not hold. A file without `contents` is an older lap-telemetry-only one."""
|
|
61
|
+
return {
|
|
62
|
+
"format": HEADER_FORMAT,
|
|
63
|
+
"version": version,
|
|
64
|
+
"contents": {
|
|
65
|
+
CONTENT_LAP_TELEMETRY: dataclasses.asdict(LapTelemetryPaths()) if has_lap_telemetry else None,
|
|
66
|
+
CONTENT_SESSION_DATA: {"path": session_data.entry_name} if session_data else None,
|
|
67
|
+
},
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def validate_pngt_zip(path: Union[Path, str]) -> zipfile.ZipFile:
|
|
72
|
+
"""Sniffs ZIP magic bytes, opens as a ZipFile, reads header.json, checks format
|
|
73
|
+
then version. Returns the open ZipFile; the caller is responsible for closing it.
|
|
74
|
+
|
|
75
|
+
Raises NotAZipFileError / InvalidHeaderError / UnsupportedFormatError /
|
|
76
|
+
UnsupportedVersionError.
|
|
77
|
+
"""
|
|
78
|
+
path = Path(path)
|
|
79
|
+
|
|
80
|
+
with open(path, "rb") as f:
|
|
81
|
+
magic = f.read(4)
|
|
82
|
+
if magic != ZIP_MAGIC:
|
|
83
|
+
raise NotAZipFileError(path)
|
|
84
|
+
|
|
85
|
+
try:
|
|
86
|
+
zf = zipfile.ZipFile(path) # pylint: disable=consider-using-with
|
|
87
|
+
except zipfile.BadZipFile as exc:
|
|
88
|
+
raise NotAZipFileError(path) from exc
|
|
89
|
+
|
|
90
|
+
try:
|
|
91
|
+
raw = read_entry(zf, HEADER_ENTRY, path)
|
|
92
|
+
except KeyError as exc:
|
|
93
|
+
zf.close()
|
|
94
|
+
raise InvalidHeaderError(path, f"{HEADER_ENTRY} is missing") from exc
|
|
95
|
+
except zipfile.BadZipFile as exc:
|
|
96
|
+
zf.close()
|
|
97
|
+
raise NotAZipFileError(path) from exc
|
|
98
|
+
except EntryTooLargeError:
|
|
99
|
+
zf.close()
|
|
100
|
+
raise
|
|
101
|
+
|
|
102
|
+
try:
|
|
103
|
+
header = json.loads(raw)
|
|
104
|
+
except json.JSONDecodeError as exc:
|
|
105
|
+
zf.close()
|
|
106
|
+
raise InvalidHeaderError(path, f"{HEADER_ENTRY} is not valid JSON: {exc}") from exc
|
|
107
|
+
|
|
108
|
+
if not isinstance(header, dict) or "format" not in header or "version" not in header:
|
|
109
|
+
zf.close()
|
|
110
|
+
raise InvalidHeaderError(path, f"{HEADER_ENTRY} is missing required keys 'format'/'version'")
|
|
111
|
+
|
|
112
|
+
actual_format = header["format"]
|
|
113
|
+
if actual_format != HEADER_FORMAT:
|
|
114
|
+
zf.close()
|
|
115
|
+
raise UnsupportedFormatError(path, actual_format)
|
|
116
|
+
|
|
117
|
+
actual_version = header["version"]
|
|
118
|
+
# Reject a JSON true: Python treats it as 1 and would accept it, but the JS reader would not
|
|
119
|
+
if isinstance(actual_version, bool) or actual_version not in READABLE_VERSIONS:
|
|
120
|
+
zf.close()
|
|
121
|
+
raise UnsupportedVersionError(path, actual_version, READABLE_VERSIONS)
|
|
122
|
+
|
|
123
|
+
return zf
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def read_version(zf: zipfile.ZipFile) -> int:
|
|
127
|
+
"""header.json's version, from an archive validate_pngt_zip() has accepted."""
|
|
128
|
+
return json.loads(zf.read(HEADER_ENTRY))["version"]
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def read_contents_from_zip(zf: zipfile.ZipFile, path: Union[Path, str]) -> PngtContents:
|
|
132
|
+
"""Which sections an already-validated archive holds. A header without `contents` is an older
|
|
133
|
+
lap-telemetry-only file."""
|
|
134
|
+
contents = json.loads(zf.read(HEADER_ENTRY)).get("contents")
|
|
135
|
+
if contents is None:
|
|
136
|
+
return PngtContents(has_lap_telemetry=True, session_data_entry=None)
|
|
137
|
+
if not isinstance(contents, dict):
|
|
138
|
+
raise InvalidHeaderError(path, "'contents' is not an object")
|
|
139
|
+
session_data = contents.get(CONTENT_SESSION_DATA)
|
|
140
|
+
if session_data is not None and not (isinstance(session_data, dict) and isinstance(session_data.get("path"), str)):
|
|
141
|
+
raise InvalidHeaderError(path, "'contents.session_data' has no 'path'")
|
|
142
|
+
return PngtContents(
|
|
143
|
+
has_lap_telemetry=contents.get(CONTENT_LAP_TELEMETRY) is not None,
|
|
144
|
+
session_data_entry=None if session_data is None else session_data["path"],
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def open_lap_telemetry_zip(path: Union[Path, str]) -> zipfile.ZipFile:
|
|
149
|
+
"""validate_pngt_zip() for callers that need the lap_telemetry section. Raises
|
|
150
|
+
SectionNotPresentError if the file has none."""
|
|
151
|
+
zf = validate_pngt_zip(path)
|
|
152
|
+
try:
|
|
153
|
+
if not read_contents_from_zip(zf, path).has_lap_telemetry:
|
|
154
|
+
raise SectionNotPresentError(path, CONTENT_LAP_TELEMETRY)
|
|
155
|
+
except Exception:
|
|
156
|
+
zf.close()
|
|
157
|
+
raise
|
|
158
|
+
return zf
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def recompute_totals(driver_laps: Iterable[tuple[int, list[dict]]]) -> tuple[int, Optional[SessionBest]]:
|
|
162
|
+
"""Given each driver's lap dicts (as written to laps.json), returns the total
|
|
163
|
+
lap count across all drivers and the fastest valid+timed lap as SessionBest (or
|
|
164
|
+
None if no lap qualifies). Used by both write_session() and delete_laps(), so
|
|
165
|
+
laps.count always means the same thing regardless of which one last touched
|
|
166
|
+
the file."""
|
|
167
|
+
total = 0
|
|
168
|
+
best_driver = best_lap = best_time = None
|
|
169
|
+
|
|
170
|
+
for driver_index, laps in driver_laps:
|
|
171
|
+
total += len(laps)
|
|
172
|
+
for lap in laps:
|
|
173
|
+
if lap.get("valid") and lap.get("lap_time_ms") is not None:
|
|
174
|
+
if best_time is None or lap["lap_time_ms"] < best_time:
|
|
175
|
+
best_time = lap["lap_time_ms"]
|
|
176
|
+
best_driver = driver_index
|
|
177
|
+
best_lap = lap["lap_number"]
|
|
178
|
+
|
|
179
|
+
session_best = None if best_time is None else SessionBest(
|
|
180
|
+
driver_index=best_driver, lap_number=best_lap, lap_time_ms=best_time
|
|
181
|
+
)
|
|
182
|
+
return total, session_best
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def session_best_to_dict(best: Optional[SessionBest]) -> Optional[dict]:
|
|
186
|
+
"""session.json's laps.session_best shape. Shared by write_session() and
|
|
187
|
+
delete_laps() so the two can't drift into writing different shapes for it."""
|
|
188
|
+
return None if best is None else {
|
|
189
|
+
"driver_index": best.driver_index,
|
|
190
|
+
"lap_number": best.lap_number,
|
|
191
|
+
"lap_time_ms": best.lap_time_ms,
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def read_entry(zf: zipfile.ZipFile, name: str, path) -> bytes:
|
|
196
|
+
"""An entry's bytes. Raises KeyError if the archive lacks it, EntryTooLargeError if it declares more
|
|
197
|
+
than MAX_ENTRY_BYTES."""
|
|
198
|
+
info = zf.getinfo(name)
|
|
199
|
+
if info.file_size > MAX_ENTRY_BYTES:
|
|
200
|
+
raise EntryTooLargeError(path, name, info.file_size, MAX_ENTRY_BYTES)
|
|
201
|
+
return zf.read(info)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def read_json(zf: zipfile.ZipFile, name: str, path) -> dict:
|
|
205
|
+
try:
|
|
206
|
+
raw = read_entry(zf, name, path)
|
|
207
|
+
except KeyError as exc:
|
|
208
|
+
raise MalformedSessionError(path, f"{name} is missing") from exc
|
|
209
|
+
try:
|
|
210
|
+
return json.loads(raw)
|
|
211
|
+
except json.JSONDecodeError as exc:
|
|
212
|
+
raise MalformedSessionError(path, f"{name} is not valid JSON: {exc}") from exc
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def write_json(zf: zipfile.ZipFile, name: str, data: dict) -> None:
|
|
216
|
+
zf.writestr(name, json.dumps(data).encode("utf-8"), compress_type=zipfile.ZIP_DEFLATED)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def rebuild_archive(
|
|
220
|
+
src_path: Path,
|
|
221
|
+
dest_path: Path,
|
|
222
|
+
*,
|
|
223
|
+
skip_names: set,
|
|
224
|
+
overrides: dict,
|
|
225
|
+
) -> None:
|
|
226
|
+
"""Copies every entry from src_path into a new archive at dest_path, skipping
|
|
227
|
+
skip_names and replacing the content of any entry named in overrides with its
|
|
228
|
+
(JSON-serialized) value. Every other entry is copied byte-for-byte, preserving
|
|
229
|
+
its original compression type."""
|
|
230
|
+
with zipfile.ZipFile(src_path) as src_zf, zipfile.ZipFile(dest_path, "w") as dst_zf:
|
|
231
|
+
for name in src_zf.namelist():
|
|
232
|
+
if name in overrides:
|
|
233
|
+
write_json(dst_zf, name, overrides[name])
|
|
234
|
+
elif name not in skip_names:
|
|
235
|
+
info = src_zf.getinfo(name)
|
|
236
|
+
dst_zf.writestr(name, src_zf.read(name), compress_type=info.compress_type)
|
pngt-0.1.0/dto.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
# MIT License
|
|
2
|
+
#
|
|
3
|
+
# Copyright (c) [2026] [Ashwin Natarajan]
|
|
4
|
+
#
|
|
5
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
# in the Software without restriction, including without limitation the rights
|
|
8
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
# furnished to do so, subject to the following conditions:
|
|
11
|
+
#
|
|
12
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
# copies or substantial portions of the Software.
|
|
14
|
+
#
|
|
15
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
# SOFTWARE.
|
|
22
|
+
|
|
23
|
+
# -------------------------------------- IMPORTS -----------------------------------------------------------------------
|
|
24
|
+
|
|
25
|
+
import math
|
|
26
|
+
from dataclasses import dataclass, field
|
|
27
|
+
from enum import Enum
|
|
28
|
+
from typing import Optional, Sequence
|
|
29
|
+
|
|
30
|
+
import numpy as np
|
|
31
|
+
|
|
32
|
+
# -------------------------------------- CONSTANTS ---------------------------------------------------------------------
|
|
33
|
+
|
|
34
|
+
# The two arrays every lap holds, defined by the format; sensor keys are the recording app's
|
|
35
|
+
LAP_DISTANCE = "lap_distance"
|
|
36
|
+
LAP_TIME_MS = "lap_time_ms"
|
|
37
|
+
MANDATORY_TELEMETRY_KEYS = (LAP_DISTANCE, LAP_TIME_MS)
|
|
38
|
+
SESSION_DATA_DIR = "session_data"
|
|
39
|
+
INT32_MAX = 2**31 - 1
|
|
40
|
+
ENCODING_ORDERS = (0, 1, 2)
|
|
41
|
+
|
|
42
|
+
# -------------------------------------- CLASSES -----------------------------------------------------------------------
|
|
43
|
+
|
|
44
|
+
class SensorType(Enum):
|
|
45
|
+
"""How the viewer must interpolate this sensor's values between samples."""
|
|
46
|
+
CONTINUOUS = "continuous"
|
|
47
|
+
DISCRETE = "discrete"
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class SensorEncoding:
|
|
51
|
+
"""How a v2 file stores an array: round(v / scale), differenced `order` times (0, 1 or 2), in the
|
|
52
|
+
narrowest of |i1, <i2, <i4 that holds the lap. Decoded values are within scale / 2 of the original."""
|
|
53
|
+
scale: float
|
|
54
|
+
order: int
|
|
55
|
+
|
|
56
|
+
def __post_init__(self) -> None:
|
|
57
|
+
if self.order not in ENCODING_ORDERS:
|
|
58
|
+
raise ValueError(f"Invalid encoding order {self.order!r}; expected one of {ENCODING_ORDERS}")
|
|
59
|
+
if not (math.isfinite(self.scale) and self.scale > 0):
|
|
60
|
+
raise ValueError(f"Invalid encoding scale {self.scale!r}; expected a finite number above 0")
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def max_steps(self) -> int:
|
|
64
|
+
"""Largest |round(v / scale)| it stores. Any `order` differences of values within it fit int32."""
|
|
65
|
+
return INT32_MAX >> self.order
|
|
66
|
+
|
|
67
|
+
# Read for every array of a v1 file, whose manifest has no encodings: the identity on its stored f32
|
|
68
|
+
DEFAULT_ENCODING = SensorEncoding(scale=1, order=0)
|
|
69
|
+
|
|
70
|
+
# How v2 stores the two mandatory columns, which are not sensors
|
|
71
|
+
MANDATORY_TELEMETRY_ENCODINGS = {
|
|
72
|
+
LAP_DISTANCE: SensorEncoding(scale=0.01, order=2),
|
|
73
|
+
LAP_TIME_MS: SensorEncoding(scale=1, order=1),
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True)
|
|
77
|
+
class SensorConfig:
|
|
78
|
+
"""A sensor registry entry: manifest.json's {key: {label, unit, type, encoding, range?}}. `range`, when
|
|
79
|
+
given, is the sensor's known-fixed (min, max) -- e.g. throttle/brake are 0-100 -- and
|
|
80
|
+
is a hint for viewers (axis scaling); it is not enforced against recorded values.
|
|
81
|
+
|
|
82
|
+
`encoding` is how a v2 file stores the sensor. A v1 file stores every sensor as float32 and reads
|
|
83
|
+
back with DEFAULT_ENCODING."""
|
|
84
|
+
key: str
|
|
85
|
+
label: str
|
|
86
|
+
unit: str
|
|
87
|
+
type: SensorType
|
|
88
|
+
encoding: SensorEncoding
|
|
89
|
+
range: Optional[tuple[float, float]] = None
|
|
90
|
+
should_display: Optional[bool] = True
|
|
91
|
+
|
|
92
|
+
def __post_init__(self) -> None:
|
|
93
|
+
# Code bugs only: the reader and the discovery cache build both from file data before getting here
|
|
94
|
+
assert isinstance(self.type, SensorType), f"{self.key!r}: type {self.type!r} is not a SensorType"
|
|
95
|
+
assert isinstance(self.encoding, SensorEncoding), f"{self.key!r}: encoding {self.encoding!r} is not a SensorEncoding"
|
|
96
|
+
if self.range is not None and self.range[0] >= self.range[1]:
|
|
97
|
+
raise ValueError(f"Invalid range {self.range!r} for sensor {self.key!r}; expected (min, max) with min < max")
|
|
98
|
+
if (self.range is not None and
|
|
99
|
+
max(abs(self.range[0]), abs(self.range[1])) / self.encoding.scale > self.encoding.max_steps):
|
|
100
|
+
raise ValueError(f"Range {self.range!r} of sensor {self.key!r} does not fit in int32 at "
|
|
101
|
+
f"{self.encoding!r}")
|
|
102
|
+
if self.type == SensorType.DISCRETE:
|
|
103
|
+
assert self.encoding.scale == 1 and self.encoding.order == 0 # Must be caught at dev time
|
|
104
|
+
|
|
105
|
+
@dataclass(frozen=True)
|
|
106
|
+
class SessionDataEntry:
|
|
107
|
+
"""An opaque caller-owned blob, stored as `session_data/<file_name>` (the `session_data` section).
|
|
108
|
+
`file_name` is a plain file name like "<stem>.json"; the library never parses `payload`."""
|
|
109
|
+
file_name: str
|
|
110
|
+
payload: bytes
|
|
111
|
+
|
|
112
|
+
def __post_init__(self) -> None:
|
|
113
|
+
if not self.file_name or self.file_name in {".", ".."} or "/" in self.file_name or "\\" in self.file_name:
|
|
114
|
+
raise ValueError(f"Invalid session data file name {self.file_name!r}; expected a plain file name")
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def entry_name(self) -> str:
|
|
118
|
+
"""The entry's path inside the archive."""
|
|
119
|
+
return f"{SESSION_DATA_DIR}/{self.file_name}"
|
|
120
|
+
|
|
121
|
+
@dataclass(frozen=True)
|
|
122
|
+
class LapTelemetryPaths:
|
|
123
|
+
"""Where the lap_telemetry section's entries are in the archive. header.json lists them under
|
|
124
|
+
`contents.lap_telemetry` for completeness; readers use these fixed names, not the header's.
|
|
125
|
+
|
|
126
|
+
Attributes:
|
|
127
|
+
session (str): Session metadata JSON.
|
|
128
|
+
sensor_manifest (str): Sensor registry JSON.
|
|
129
|
+
drivers (str): Driver list JSON.
|
|
130
|
+
drivers_dir (str): Directory of per-driver folders, each holding laps.json and the lap_NNN.npz files.
|
|
131
|
+
"""
|
|
132
|
+
session: str = "session.json"
|
|
133
|
+
sensor_manifest: str = "manifest.json"
|
|
134
|
+
drivers: str = "drivers.json"
|
|
135
|
+
drivers_dir: str = "drivers"
|
|
136
|
+
|
|
137
|
+
def driver_dir(self, driver_index: int) -> str:
|
|
138
|
+
return f"{self.drivers_dir}/{driver_index:02d}"
|
|
139
|
+
|
|
140
|
+
def laps_entry(self, driver_index: int) -> str:
|
|
141
|
+
return f"{self.driver_dir(driver_index)}/laps.json"
|
|
142
|
+
|
|
143
|
+
def lap_entry(self, driver_index: int, lap_number: int) -> str:
|
|
144
|
+
return f"{self.driver_dir(driver_index)}/lap_{lap_number:03d}.npz"
|
|
145
|
+
|
|
146
|
+
@dataclass(frozen=True)
|
|
147
|
+
class PngtContents:
|
|
148
|
+
"""Which sections a .pngt file holds.
|
|
149
|
+
|
|
150
|
+
Attributes:
|
|
151
|
+
has_lap_telemetry (bool): The file holds a lap recording.
|
|
152
|
+
session_data_entry (Optional[str]): Archive entry name of the session JSON, None if the file has none.
|
|
153
|
+
"""
|
|
154
|
+
has_lap_telemetry: bool
|
|
155
|
+
session_data_entry: Optional[str]
|
|
156
|
+
|
|
157
|
+
@dataclass(frozen=True)
|
|
158
|
+
class TrackInfo:
|
|
159
|
+
id: int # the sim's own TrackID enum value, e.g. 10 = Spa
|
|
160
|
+
name: str
|
|
161
|
+
|
|
162
|
+
@dataclass(frozen=True)
|
|
163
|
+
class SessionBest:
|
|
164
|
+
driver_index: int
|
|
165
|
+
lap_number: int
|
|
166
|
+
lap_time_ms: int
|
|
167
|
+
|
|
168
|
+
@dataclass(frozen=True)
|
|
169
|
+
class SessionMetadata:
|
|
170
|
+
"""Caller-filled session identity. laps_count/session_best are write_session()-
|
|
171
|
+
derived, not part of this input type -- see ParsedSessionMetadata."""
|
|
172
|
+
session_uid: int
|
|
173
|
+
session_name: str
|
|
174
|
+
session_type: str
|
|
175
|
+
app_version: str
|
|
176
|
+
game_year: int
|
|
177
|
+
formula: str
|
|
178
|
+
game_version: str
|
|
179
|
+
timestamp: str # ISO-8601, passed through verbatim, never parsed
|
|
180
|
+
track: TrackInfo
|
|
181
|
+
# Lap length in metres. kw_only so ParsedSessionMetadata can keep adding required
|
|
182
|
+
# fields after it; None in files written before this existed, or when unknown.
|
|
183
|
+
track_length_m: Optional[int] = field(default=None, kw_only=True)
|
|
184
|
+
# The recording player's driver index, the lap distances where sectors 2 and 3 start,
|
|
185
|
+
# and the battery size in joules. None when unknown.
|
|
186
|
+
player_index: Optional[int] = field(default=None, kw_only=True)
|
|
187
|
+
sector_starts_m: Optional[tuple[float, float]] = field(default=None, kw_only=True)
|
|
188
|
+
ers_max_capacity_j: Optional[float] = field(default=None, kw_only=True)
|
|
189
|
+
|
|
190
|
+
@dataclass(frozen=True)
|
|
191
|
+
class DriverRecord:
|
|
192
|
+
"""Caller-filled driver identity. is_telemetry_public is write_session()-derived
|
|
193
|
+
from whether driver_index is a key in driver_data -- see ParsedDriver."""
|
|
194
|
+
driver_index: int
|
|
195
|
+
name: str
|
|
196
|
+
team: str
|
|
197
|
+
car_number: int
|
|
198
|
+
nationality: Optional[str]
|
|
199
|
+
platform: Optional[str]
|
|
200
|
+
|
|
201
|
+
@dataclass(frozen=True)
|
|
202
|
+
class LapMetadata:
|
|
203
|
+
"""Caller-filled lap facts. num_points/is_good are write_session()-derived --
|
|
204
|
+
see Lap."""
|
|
205
|
+
lap_number: int
|
|
206
|
+
lap_time_ms: Optional[int]
|
|
207
|
+
valid: bool
|
|
208
|
+
tyre_compound: str
|
|
209
|
+
tyre_laps: int
|
|
210
|
+
pit_in_lap: bool
|
|
211
|
+
pit_out_lap: bool
|
|
212
|
+
ers_harvest_limit_j: Optional[float] # None in recordings made before this field existed
|
|
213
|
+
# Official elapsed time (ms) at the end of sectors 1 and 2; None when the lap has no trustworthy splits.
|
|
214
|
+
sector_ends_ms: Optional[tuple[int, int]] = field(default=None, kw_only=True)
|
|
215
|
+
|
|
216
|
+
@dataclass(frozen=True)
|
|
217
|
+
class CompletedLap:
|
|
218
|
+
metadata: LapMetadata
|
|
219
|
+
# "lap_distance" + "lap_time_ms" + sensor keys, all equal length. The recorder gives float32 arrays
|
|
220
|
+
telemetry: dict[str, Sequence[float]]
|
|
221
|
+
|
|
222
|
+
def __post_init__(self) -> None:
|
|
223
|
+
lengths = {key: len(values) for key, values in self.telemetry.items()}
|
|
224
|
+
if len(set(lengths.values())) > 1:
|
|
225
|
+
raise ValueError(f"Mismatched telemetry array lengths for lap {self.metadata.lap_number}: {lengths}")
|
|
226
|
+
|
|
227
|
+
def __eq__(self, other: object) -> bool:
|
|
228
|
+
"""Same metadata and the same telemetry, value by value. NaN (unavailable) equals NaN."""
|
|
229
|
+
if not isinstance(other, CompletedLap):
|
|
230
|
+
return NotImplemented
|
|
231
|
+
# The generated __eq__ would compare the arrays with ==, which raises for more than one sample
|
|
232
|
+
return (self.metadata == other.metadata
|
|
233
|
+
and self.telemetry.keys() == other.telemetry.keys()
|
|
234
|
+
and all(np.array_equal(np.asarray(values, dtype=np.float64),
|
|
235
|
+
np.asarray(other.telemetry[key], dtype=np.float64), equal_nan=True)
|
|
236
|
+
for key, values in self.telemetry.items()))
|
|
237
|
+
|
|
238
|
+
@dataclass(frozen=True)
|
|
239
|
+
class DriverExportData:
|
|
240
|
+
driver_index: int
|
|
241
|
+
completed_laps: list[CompletedLap]
|
|
242
|
+
in_progress_lap: Optional[CompletedLap] = None
|
|
243
|
+
|
|
244
|
+
def __post_init__(self) -> None:
|
|
245
|
+
if self.in_progress_lap is not None:
|
|
246
|
+
meta = self.in_progress_lap.metadata
|
|
247
|
+
if meta.lap_time_ms is not None or meta.valid:
|
|
248
|
+
raise ValueError(
|
|
249
|
+
f"in_progress_lap {meta.lap_number} must have lap_time_ms=None and valid=False"
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
@dataclass(frozen=True)
|
|
253
|
+
class DeleteLapsResult:
|
|
254
|
+
driver_index: int
|
|
255
|
+
deleted_lap_numbers: list[int]
|
|
256
|
+
driver_folder_removed: bool
|
|
257
|
+
new_laps_count: int
|
|
258
|
+
new_session_best: Optional[SessionBest]
|
|
259
|
+
|
|
260
|
+
@dataclass(frozen=True)
|
|
261
|
+
class MarkLapGoodResult:
|
|
262
|
+
driver_index: int
|
|
263
|
+
lap_number: int
|
|
264
|
+
already_good: bool
|
|
265
|
+
|
|
266
|
+
# -------------------------------------- READ-SIDE TYPES ----------------------------------------------------------------
|
|
267
|
+
|
|
268
|
+
@dataclass(frozen=True)
|
|
269
|
+
class ParsedSessionMetadata(SessionMetadata):
|
|
270
|
+
"""SessionMetadata plus the fields write_session() derives and persists."""
|
|
271
|
+
laps_count: int
|
|
272
|
+
session_best: Optional[SessionBest]
|
|
273
|
+
|
|
274
|
+
@dataclass(frozen=True)
|
|
275
|
+
class ParsedDriver(DriverRecord):
|
|
276
|
+
"""DriverRecord plus the field write_session() derives and persists."""
|
|
277
|
+
is_telemetry_public: bool
|
|
278
|
+
|
|
279
|
+
@dataclass(frozen=True)
|
|
280
|
+
class Lap(LapMetadata):
|
|
281
|
+
"""One laps.json entry as read: LapMetadata plus the fields write_session() derives and persists."""
|
|
282
|
+
# None in v1 files: most v1 writers left both False whatever happened
|
|
283
|
+
pit_in_lap: Optional[bool]
|
|
284
|
+
pit_out_lap: Optional[bool]
|
|
285
|
+
num_points: int
|
|
286
|
+
is_good: bool
|
|
287
|
+
# Distance coverage, persisted at write time. None in files written before these
|
|
288
|
+
# existed; consumers fall back to measuring the lap's own lap_distance array.
|
|
289
|
+
start_distance_m: Optional[float] = None
|
|
290
|
+
end_distance_m: Optional[float] = None
|
|
291
|
+
max_gap_m: Optional[float] = None
|