semantic-kinematics 0.1.0__py3-none-any.whl
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.
- semantic_kinematics/__init__.py +75 -0
- semantic_kinematics/cli.py +206 -0
- semantic_kinematics/config/__init__.py +33 -0
- semantic_kinematics/config/loading.py +92 -0
- semantic_kinematics/config/models.py +222 -0
- semantic_kinematics/core/__init__.py +34 -0
- semantic_kinematics/core/calibration.py +132 -0
- semantic_kinematics/core/detections.py +165 -0
- semantic_kinematics/core/geometry.py +71 -0
- semantic_kinematics/core/tracks.py +120 -0
- semantic_kinematics/core/video.py +117 -0
- semantic_kinematics/detect/__init__.py +25 -0
- semantic_kinematics/detect/base.py +119 -0
- semantic_kinematics/detect/blob.py +101 -0
- semantic_kinematics/detect/maskrcnn.py +144 -0
- semantic_kinematics/detect/tiling.py +165 -0
- semantic_kinematics/kinematics/__init__.py +39 -0
- semantic_kinematics/kinematics/adapter.py +161 -0
- semantic_kinematics/kinematics/engine.py +137 -0
- semantic_kinematics/kinematics/kernels.py +130 -0
- semantic_kinematics/kinematics/metrics.py +327 -0
- semantic_kinematics/models/__init__.py +34 -0
- semantic_kinematics/models/builders.py +105 -0
- semantic_kinematics/models/download.py +211 -0
- semantic_kinematics/models/registry.json +55 -0
- semantic_kinematics/pipeline/__init__.py +16 -0
- semantic_kinematics/pipeline/artifacts.py +85 -0
- semantic_kinematics/pipeline/io.py +278 -0
- semantic_kinematics/pipeline/runner.py +375 -0
- semantic_kinematics/py.typed +0 -0
- semantic_kinematics/runtime.py +60 -0
- semantic_kinematics/track/__init__.py +39 -0
- semantic_kinematics/track/base.py +139 -0
- semantic_kinematics/track/correlation.py +319 -0
- semantic_kinematics/track/merging.py +247 -0
- semantic_kinematics/track/smoothing.py +117 -0
- semantic_kinematics/track/stitching.py +195 -0
- semantic_kinematics/training/__init__.py +10 -0
- semantic_kinematics/training/dataset.py +147 -0
- semantic_kinematics/training/finetune.py +34 -0
- semantic_kinematics/viz/__init__.py +34 -0
- semantic_kinematics/viz/colormaps.py +114 -0
- semantic_kinematics/viz/field_maps.py +277 -0
- semantic_kinematics/viz/fields.py +183 -0
- semantic_kinematics/viz/render.py +311 -0
- semantic_kinematics/viz/sam_overlay.py +120 -0
- semantic_kinematics/viz/trajectories.py +181 -0
- semantic_kinematics-0.1.0.dist-info/METADATA +164 -0
- semantic_kinematics-0.1.0.dist-info/RECORD +52 -0
- semantic_kinematics-0.1.0.dist-info/WHEEL +4 -0
- semantic_kinematics-0.1.0.dist-info/entry_points.txt +2 -0
- semantic_kinematics-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""SemanticKinematics: flow physics from tracked objects in video.
|
|
2
|
+
|
|
3
|
+
Detection (tiled Mask R-CNN), tracking (cross-correlation), camera
|
|
4
|
+
calibration, and Lagrangian gradient regression (via the external ``lgr``
|
|
5
|
+
package), driven by a single validated config file.
|
|
6
|
+
|
|
7
|
+
``PRIMARY_API`` lists the supported entry points; everything else is
|
|
8
|
+
implementation detail and may move between releases.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from semantic_kinematics.config import PipelineConfig, load_config
|
|
14
|
+
from semantic_kinematics.core import (
|
|
15
|
+
CalibrationModel,
|
|
16
|
+
DetectionSet,
|
|
17
|
+
FrameDetections,
|
|
18
|
+
Track,
|
|
19
|
+
TrackSet,
|
|
20
|
+
VideoSource,
|
|
21
|
+
)
|
|
22
|
+
from semantic_kinematics.detect import Detector, register_detector
|
|
23
|
+
from semantic_kinematics.kinematics import (
|
|
24
|
+
KinematicsResult,
|
|
25
|
+
register_window_metric,
|
|
26
|
+
run_kinematics,
|
|
27
|
+
)
|
|
28
|
+
from semantic_kinematics.pipeline import run_pipeline
|
|
29
|
+
from semantic_kinematics.track import (
|
|
30
|
+
Tracker,
|
|
31
|
+
TrackTransform,
|
|
32
|
+
register_tracker,
|
|
33
|
+
register_transform,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
__version__ = "0.1.0"
|
|
37
|
+
|
|
38
|
+
PRIMARY_API: tuple[str, ...] = (
|
|
39
|
+
"load_config",
|
|
40
|
+
"run_pipeline",
|
|
41
|
+
"run_kinematics",
|
|
42
|
+
"Detector",
|
|
43
|
+
"Tracker",
|
|
44
|
+
"TrackTransform",
|
|
45
|
+
"register_detector",
|
|
46
|
+
"register_tracker",
|
|
47
|
+
"register_transform",
|
|
48
|
+
"register_window_metric",
|
|
49
|
+
"CalibrationModel",
|
|
50
|
+
"TrackSet",
|
|
51
|
+
"VideoSource",
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
__all__ = [
|
|
55
|
+
"CalibrationModel",
|
|
56
|
+
"DetectionSet",
|
|
57
|
+
"Detector",
|
|
58
|
+
"FrameDetections",
|
|
59
|
+
"KinematicsResult",
|
|
60
|
+
"PRIMARY_API",
|
|
61
|
+
"PipelineConfig",
|
|
62
|
+
"Track",
|
|
63
|
+
"TrackSet",
|
|
64
|
+
"TrackTransform",
|
|
65
|
+
"Tracker",
|
|
66
|
+
"VideoSource",
|
|
67
|
+
"__version__",
|
|
68
|
+
"load_config",
|
|
69
|
+
"register_detector",
|
|
70
|
+
"register_tracker",
|
|
71
|
+
"register_transform",
|
|
72
|
+
"register_window_metric",
|
|
73
|
+
"run_kinematics",
|
|
74
|
+
"run_pipeline",
|
|
75
|
+
]
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""The ``semkin`` command-line interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import typer
|
|
8
|
+
|
|
9
|
+
app = typer.Typer(
|
|
10
|
+
name="semkin",
|
|
11
|
+
help="Video -> detection -> tracking -> Lagrangian kinematics.",
|
|
12
|
+
no_args_is_help=True,
|
|
13
|
+
pretty_exceptions_show_locals=False,
|
|
14
|
+
)
|
|
15
|
+
models_app = typer.Typer(help="Model weight registry and cache.",
|
|
16
|
+
no_args_is_help=True)
|
|
17
|
+
app.add_typer(models_app, name="models")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _load(config_path: Path):
|
|
21
|
+
from semantic_kinematics.config import load_config
|
|
22
|
+
|
|
23
|
+
return load_config(config_path)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _run(config_path: Path, to: str, force: list[str], force_all: bool,
|
|
27
|
+
verbose: bool) -> None:
|
|
28
|
+
from semantic_kinematics.pipeline import run_pipeline
|
|
29
|
+
|
|
30
|
+
result = run_pipeline(_load(config_path), to=to, force=force,
|
|
31
|
+
force_all=force_all, verbose=verbose)
|
|
32
|
+
for stage, key in result.keys.items():
|
|
33
|
+
if stage in result.dirs:
|
|
34
|
+
hit = " (cache hit)" if stage in result.skipped else ""
|
|
35
|
+
typer.echo(f"{stage:<10} {key}{hit} {result.dirs[stage]}")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@app.command()
|
|
39
|
+
def run(
|
|
40
|
+
config: Path,
|
|
41
|
+
to: str = typer.Option("viz", help="last stage to run"),
|
|
42
|
+
force: list[str] = typer.Option([], "--force", "-f",
|
|
43
|
+
help="recompute this stage and downstream"),
|
|
44
|
+
force_all: bool = typer.Option(False, help="recompute everything"),
|
|
45
|
+
verbose: bool = typer.Option(False, "--verbose", "-v"),
|
|
46
|
+
) -> None:
|
|
47
|
+
"""Run the pipeline end to end (or up to --to)."""
|
|
48
|
+
_run(config, to, force, force_all, verbose)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@app.command()
|
|
52
|
+
def detect(config: Path,
|
|
53
|
+
verbose: bool = typer.Option(False, "--verbose", "-v")) -> None:
|
|
54
|
+
"""Run only the detection stage (plus missing upstreams)."""
|
|
55
|
+
_run(config, "detect", [], False, verbose)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@app.command()
|
|
59
|
+
def track(config: Path,
|
|
60
|
+
verbose: bool = typer.Option(False, "--verbose", "-v")) -> None:
|
|
61
|
+
"""Run through the tracking stage."""
|
|
62
|
+
_run(config, "track", [], False, verbose)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@app.command()
|
|
66
|
+
def kinematics(config: Path,
|
|
67
|
+
verbose: bool = typer.Option(False, "--verbose", "-v")) -> None:
|
|
68
|
+
"""Run through the kinematics stage."""
|
|
69
|
+
_run(config, "kinematics", [], False, verbose)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@app.command()
|
|
73
|
+
def viz(config: Path,
|
|
74
|
+
verbose: bool = typer.Option(False, "--verbose", "-v")) -> None:
|
|
75
|
+
"""Run through the rendering stage."""
|
|
76
|
+
_run(config, "viz", [], False, verbose)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@app.command()
|
|
80
|
+
def validate(config: Path) -> None:
|
|
81
|
+
"""Validate a config (schema, registries, model availability). No compute."""
|
|
82
|
+
import importlib
|
|
83
|
+
|
|
84
|
+
from semantic_kinematics.detect import get_detector
|
|
85
|
+
from semantic_kinematics.kinematics import get_window_metric
|
|
86
|
+
from semantic_kinematics.models import is_cached
|
|
87
|
+
from semantic_kinematics.track import get_tracker, get_transform
|
|
88
|
+
from semantic_kinematics.viz import get_renderer
|
|
89
|
+
|
|
90
|
+
cfg = _load(config)
|
|
91
|
+
# Plugins register their schemes at import time, same as run_pipeline.
|
|
92
|
+
for module in cfg.plugins:
|
|
93
|
+
importlib.import_module(module)
|
|
94
|
+
get_detector(cfg.detection.scheme).config_model.model_validate(
|
|
95
|
+
cfg.detection.params
|
|
96
|
+
)
|
|
97
|
+
get_tracker(cfg.tracking.scheme).config_model.model_validate(
|
|
98
|
+
cfg.tracking.params
|
|
99
|
+
)
|
|
100
|
+
for post in cfg.tracking.postprocess:
|
|
101
|
+
get_transform(post.scheme).config_model.model_validate(post.params)
|
|
102
|
+
for metric in cfg.kinematics.metrics:
|
|
103
|
+
get_window_metric(metric)
|
|
104
|
+
for renderer in cfg.visualization.renderers:
|
|
105
|
+
get_renderer(renderer)
|
|
106
|
+
if not cfg.video.path.is_file():
|
|
107
|
+
raise typer.BadParameter(f"video not found: {cfg.video.path}")
|
|
108
|
+
model = cfg.detection.params.get("model", {})
|
|
109
|
+
if isinstance(model, dict) and model.get("name"):
|
|
110
|
+
cached = is_cached(model["name"])
|
|
111
|
+
typer.echo(f"model {model['name']}: "
|
|
112
|
+
f"{'cached' if cached else 'NOT cached (semkin models fetch)'}")
|
|
113
|
+
typer.echo(f"config OK: {cfg.name}")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@app.command()
|
|
117
|
+
def info(config: Path) -> None:
|
|
118
|
+
"""Print stage keys and cache status without running anything."""
|
|
119
|
+
from semantic_kinematics.core.video import VideoSource
|
|
120
|
+
from semantic_kinematics.pipeline import ArtifactStore
|
|
121
|
+
from semantic_kinematics.pipeline.runner import STAGE_ORDER, _keys
|
|
122
|
+
|
|
123
|
+
cfg = _load(config)
|
|
124
|
+
with VideoSource(cfg.video.path, frame_range=cfg.video.frame_range) as video:
|
|
125
|
+
keys = _keys(cfg, video.fingerprint)
|
|
126
|
+
store = ArtifactStore(cfg.artifacts_dir / cfg.name)
|
|
127
|
+
for stage in STAGE_ORDER:
|
|
128
|
+
status = "complete" if store.is_complete(stage, keys[stage]) else "-"
|
|
129
|
+
typer.echo(f"{stage:<10} {keys[stage]} {status}")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@app.command()
|
|
133
|
+
def registry() -> None:
|
|
134
|
+
"""List registered detectors, trackers, transforms, and window metrics."""
|
|
135
|
+
from semantic_kinematics.detect import registered_detectors
|
|
136
|
+
from semantic_kinematics.kinematics import registered_window_metrics
|
|
137
|
+
from semantic_kinematics.track import (
|
|
138
|
+
registered_trackers,
|
|
139
|
+
registered_transforms,
|
|
140
|
+
)
|
|
141
|
+
from semantic_kinematics.viz import registered_renderers
|
|
142
|
+
|
|
143
|
+
typer.echo(f"detectors: {', '.join(registered_detectors())}")
|
|
144
|
+
typer.echo(f"trackers: {', '.join(registered_trackers())}")
|
|
145
|
+
typer.echo(f"transforms: {', '.join(registered_transforms())}")
|
|
146
|
+
typer.echo(f"metrics: {', '.join(registered_window_metrics())}")
|
|
147
|
+
typer.echo(f"renderers: {', '.join(registered_renderers())}")
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@app.command()
|
|
151
|
+
def train(config: Path) -> None:
|
|
152
|
+
"""Fine-tune a detector (phase 2 — not yet implemented)."""
|
|
153
|
+
from semantic_kinematics.training.finetune import train_maskrcnn
|
|
154
|
+
|
|
155
|
+
train_maskrcnn(Path("."), Path("."))
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@models_app.command("list")
|
|
159
|
+
def models_list() -> None:
|
|
160
|
+
"""Registry entries and their cache status."""
|
|
161
|
+
from semantic_kinematics.models import is_cached, load_registry
|
|
162
|
+
|
|
163
|
+
for name, entry in load_registry().items():
|
|
164
|
+
size_mb = entry["size_bytes"] / 1e6
|
|
165
|
+
status = "cached" if is_cached(name) else "-"
|
|
166
|
+
typer.echo(f"{name:<24} {size_mb:8.1f} MB {status:<7} {entry['domain']}")
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@models_app.command("fetch")
|
|
170
|
+
def models_fetch(name: str, force: bool = typer.Option(False)) -> None:
|
|
171
|
+
"""Download (and verify) a model into the local cache."""
|
|
172
|
+
from semantic_kinematics.models import fetch
|
|
173
|
+
|
|
174
|
+
typer.echo(str(fetch(name, force=force)))
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@models_app.command("verify")
|
|
178
|
+
def models_verify(
|
|
179
|
+
name: str = typer.Argument(None),
|
|
180
|
+
all_models: bool = typer.Option(False, "--all"),
|
|
181
|
+
) -> None:
|
|
182
|
+
"""Re-hash cached models against their registry pins."""
|
|
183
|
+
from semantic_kinematics.models import load_registry, verify
|
|
184
|
+
|
|
185
|
+
names = list(load_registry()) if all_models else [name]
|
|
186
|
+
if names == [None]:
|
|
187
|
+
raise typer.BadParameter("give a model name or --all")
|
|
188
|
+
for n in names:
|
|
189
|
+
ok = verify(n)
|
|
190
|
+
typer.echo(f"{n}: {'verified' if ok else 'not cached'}")
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
@models_app.command("import")
|
|
194
|
+
def models_import(name: str, path: Path) -> None:
|
|
195
|
+
"""Copy locally held weights into the cache slot for a registry name."""
|
|
196
|
+
from semantic_kinematics.models import import_local
|
|
197
|
+
|
|
198
|
+
typer.echo(str(import_local(name, path)))
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def main() -> None:
|
|
202
|
+
app()
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
if __name__ == "__main__":
|
|
206
|
+
main()
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Config system: pydantic-validated pipeline configuration, YAML or JSON.
|
|
2
|
+
|
|
3
|
+
One file drives the whole pipeline. Scheme-bearing sections (detection,
|
|
4
|
+
tracking, post-processing) carry ``{scheme, params}`` where ``params`` is
|
|
5
|
+
validated against the registered scheme's own config model at build time, so
|
|
6
|
+
third-party schemes get exactly the validation built-ins get.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from semantic_kinematics.config.loading import load_config
|
|
10
|
+
from semantic_kinematics.config.models import (
|
|
11
|
+
CalibrationConfig,
|
|
12
|
+
KinematicsConfig,
|
|
13
|
+
ModelSpec,
|
|
14
|
+
PipelineConfig,
|
|
15
|
+
RegressionConfig,
|
|
16
|
+
SchemeConfig,
|
|
17
|
+
TrackingConfig,
|
|
18
|
+
VideoConfig,
|
|
19
|
+
VisualizationConfig,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"CalibrationConfig",
|
|
24
|
+
"KinematicsConfig",
|
|
25
|
+
"ModelSpec",
|
|
26
|
+
"PipelineConfig",
|
|
27
|
+
"RegressionConfig",
|
|
28
|
+
"SchemeConfig",
|
|
29
|
+
"TrackingConfig",
|
|
30
|
+
"VideoConfig",
|
|
31
|
+
"VisualizationConfig",
|
|
32
|
+
"load_config",
|
|
33
|
+
]
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Config loading: YAML/JSON parsing and path resolution.
|
|
2
|
+
|
|
3
|
+
Committed configs contain only relative paths; everything resolves against
|
|
4
|
+
the config file's directory joined with ``base_dir``, so a config travels
|
|
5
|
+
with its data and never encodes a machine.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import logging
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
import yaml
|
|
16
|
+
|
|
17
|
+
from semantic_kinematics.config.models import PipelineConfig
|
|
18
|
+
|
|
19
|
+
__all__ = ["load_config"]
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger("semantic_kinematics.config")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _read(path: Path) -> dict[str, Any]:
|
|
25
|
+
text = path.read_text(encoding="utf-8")
|
|
26
|
+
if path.suffix.lower() in (".yaml", ".yml"):
|
|
27
|
+
data = yaml.safe_load(text)
|
|
28
|
+
elif path.suffix.lower() == ".json":
|
|
29
|
+
data = json.loads(text)
|
|
30
|
+
else:
|
|
31
|
+
raise ValueError(
|
|
32
|
+
f"unsupported config format {path.suffix!r} (use .yaml/.yml/.json)"
|
|
33
|
+
)
|
|
34
|
+
if not isinstance(data, dict):
|
|
35
|
+
raise ValueError(f"config root must be a mapping, got {type(data).__name__}")
|
|
36
|
+
return data
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def load_config(path: Path | str, *, strict_paths: bool = False) -> PipelineConfig:
|
|
40
|
+
"""Load, validate, and path-resolve a pipeline config.
|
|
41
|
+
|
|
42
|
+
With ``strict_paths`` (used on the committed example configs in CI),
|
|
43
|
+
absolute paths anywhere in the file are an error instead of a warning.
|
|
44
|
+
"""
|
|
45
|
+
path = Path(path).resolve()
|
|
46
|
+
config = PipelineConfig.model_validate(_read(path))
|
|
47
|
+
|
|
48
|
+
root = (path.parent / config.base_dir).resolve()
|
|
49
|
+
|
|
50
|
+
def resolve(p: Path | None, label: str) -> Path | None:
|
|
51
|
+
if p is None:
|
|
52
|
+
return None
|
|
53
|
+
if p.is_absolute():
|
|
54
|
+
message = (
|
|
55
|
+
f"{label} is an absolute path ({p}); committed configs "
|
|
56
|
+
f"should use paths relative to the config file"
|
|
57
|
+
)
|
|
58
|
+
if strict_paths:
|
|
59
|
+
raise ValueError(message)
|
|
60
|
+
logger.warning(message)
|
|
61
|
+
return p
|
|
62
|
+
return (root / p).resolve()
|
|
63
|
+
|
|
64
|
+
update: dict[str, Any] = {
|
|
65
|
+
"base_dir": root,
|
|
66
|
+
"artifacts_dir": resolve(config.artifacts_dir, "artifacts_dir"),
|
|
67
|
+
"video": config.video.model_copy(
|
|
68
|
+
update={"path": resolve(config.video.path, "video.path")}
|
|
69
|
+
),
|
|
70
|
+
}
|
|
71
|
+
viz_update: dict[str, Any] = {}
|
|
72
|
+
if config.visualization.flow_mask is not None:
|
|
73
|
+
viz_update["flow_mask"] = resolve(
|
|
74
|
+
config.visualization.flow_mask, "visualization.flow_mask"
|
|
75
|
+
)
|
|
76
|
+
if config.visualization.sam is not None and config.visualization.sam.path is not None:
|
|
77
|
+
viz_update["sam"] = config.visualization.sam.model_copy(
|
|
78
|
+
update={"path": resolve(config.visualization.sam.path,
|
|
79
|
+
"visualization.sam.path")}
|
|
80
|
+
)
|
|
81
|
+
if viz_update:
|
|
82
|
+
update["visualization"] = config.visualization.model_copy(update=viz_update)
|
|
83
|
+
|
|
84
|
+
detection_model = config.detection.params.get("model")
|
|
85
|
+
if isinstance(detection_model, dict) and detection_model.get("path"):
|
|
86
|
+
params = dict(config.detection.params)
|
|
87
|
+
model = dict(detection_model)
|
|
88
|
+
model["path"] = str(resolve(Path(model["path"]), "detection.params.model.path"))
|
|
89
|
+
params["model"] = model
|
|
90
|
+
update["detection"] = config.detection.model_copy(update={"params": params})
|
|
91
|
+
|
|
92
|
+
return config.model_copy(update=update)
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Pydantic v2 models for the pipeline configuration.
|
|
2
|
+
|
|
3
|
+
The tree mirrors a cleaned-up version of the legacy JSON parameter files
|
|
4
|
+
(file_structure / recording / detection / tracking / lgr / output), with the
|
|
5
|
+
machine-specific absolute paths replaced by model-registry names and the
|
|
6
|
+
misleading knobs renamed (``analysis_increment`` was in fact the finite-time
|
|
7
|
+
horizon; it is ``window_time`` here).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any, Literal
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"CalibrationConfig",
|
|
20
|
+
"KinematicsConfig",
|
|
21
|
+
"MetricStyle",
|
|
22
|
+
"ModelSpec",
|
|
23
|
+
"PipelineConfig",
|
|
24
|
+
"RegressionConfig",
|
|
25
|
+
"SchemeConfig",
|
|
26
|
+
"TrackingConfig",
|
|
27
|
+
"VideoConfig",
|
|
28
|
+
"VisualizationConfig",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ModelSpec(BaseModel):
|
|
33
|
+
"""Where a model's weights come from: registry name, local path, or URL.
|
|
34
|
+
|
|
35
|
+
Exactly one of ``name``/``path``/``url`` must be set. ``sha256`` is
|
|
36
|
+
required with ``url`` and optional (extra verification) with ``path``.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
model_config = ConfigDict(extra="forbid")
|
|
40
|
+
|
|
41
|
+
name: str | None = None
|
|
42
|
+
path: Path | None = None
|
|
43
|
+
url: str | None = None
|
|
44
|
+
sha256: str | None = None
|
|
45
|
+
options: dict[str, Any] = Field(default_factory=dict)
|
|
46
|
+
|
|
47
|
+
@model_validator(mode="after")
|
|
48
|
+
def _exactly_one_source(self) -> ModelSpec:
|
|
49
|
+
sources = [s for s in (self.name, self.path, self.url) if s is not None]
|
|
50
|
+
if len(sources) != 1:
|
|
51
|
+
raise ValueError("exactly one of name/path/url must be set")
|
|
52
|
+
if self.url is not None and self.sha256 is None:
|
|
53
|
+
raise ValueError("a url source requires sha256")
|
|
54
|
+
return self
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class SchemeConfig(BaseModel):
|
|
58
|
+
"""A pluggable scheme selection: registry key plus scheme-owned params.
|
|
59
|
+
|
|
60
|
+
``params`` is validated against the scheme's declared config model when
|
|
61
|
+
the scheme is built, not here — that keeps the scheme set open to
|
|
62
|
+
third-party registrations while still rejecting unknown keys.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
model_config = ConfigDict(extra="forbid")
|
|
66
|
+
|
|
67
|
+
scheme: str
|
|
68
|
+
params: dict[str, Any] = Field(default_factory=dict)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class VideoConfig(BaseModel):
|
|
72
|
+
model_config = ConfigDict(extra="forbid")
|
|
73
|
+
|
|
74
|
+
path: Path
|
|
75
|
+
#: Frames per second. None probes the container metadata; set it
|
|
76
|
+
#: explicitly for scientific runs (container fps is often approximate).
|
|
77
|
+
frame_rate: float | None = None
|
|
78
|
+
#: (start, stop), stop exclusive; None = the whole file.
|
|
79
|
+
frame_range: tuple[int, int] | None = None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class CalibrationConfig(BaseModel):
|
|
83
|
+
model_config = ConfigDict(extra="forbid")
|
|
84
|
+
|
|
85
|
+
camera_matrix: list[list[float]] | None = None
|
|
86
|
+
distortion_coefficients: list[float] | None = None
|
|
87
|
+
homography_matrix: list[list[float]] | None = None
|
|
88
|
+
rotation: list[list[float]] | None = None
|
|
89
|
+
center_translation: tuple[float, float] = (0.0, 0.0)
|
|
90
|
+
#: Flip the world y-axis so +y points up and vorticity signs agree with
|
|
91
|
+
#: physical rotation. Set false to reproduce legacy world coordinates.
|
|
92
|
+
world_y_up: bool = True
|
|
93
|
+
|
|
94
|
+
def to_model(self, frame_rate: float):
|
|
95
|
+
"""Build the runtime :class:`~semantic_kinematics.core.CalibrationModel`."""
|
|
96
|
+
from semantic_kinematics.core.calibration import CalibrationModel
|
|
97
|
+
|
|
98
|
+
def arr(value, dtype=np.float64):
|
|
99
|
+
return None if value is None else np.array(value, dtype=dtype)
|
|
100
|
+
|
|
101
|
+
rotation = arr(self.rotation)
|
|
102
|
+
return CalibrationModel(
|
|
103
|
+
camera_matrix=arr(self.camera_matrix),
|
|
104
|
+
distortion=arr(self.distortion_coefficients),
|
|
105
|
+
homography=arr(self.homography_matrix),
|
|
106
|
+
rotation=np.eye(2) if rotation is None else rotation,
|
|
107
|
+
translation=np.array(self.center_translation, dtype=np.float64),
|
|
108
|
+
frame_rate=frame_rate,
|
|
109
|
+
world_y_up=self.world_y_up,
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class TrackingConfig(SchemeConfig):
|
|
114
|
+
model_config = ConfigDict(extra="forbid")
|
|
115
|
+
|
|
116
|
+
#: Tracks shorter than this are culled (unless still active in the
|
|
117
|
+
#: current frame, matching the legacy rule).
|
|
118
|
+
min_track_length: int = 3
|
|
119
|
+
#: Named track transforms applied in order; the runner inserts the
|
|
120
|
+
#: sensor->world calibration between sensor-space and world-space ops.
|
|
121
|
+
postprocess: list[SchemeConfig] = Field(default_factory=list)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class RegressionConfig(BaseModel):
|
|
125
|
+
model_config = ConfigDict(extra="forbid")
|
|
126
|
+
|
|
127
|
+
kind: Literal[
|
|
128
|
+
"pseudoinverse",
|
|
129
|
+
"gaussian",
|
|
130
|
+
"legacy_radial_gaussian",
|
|
131
|
+
"library",
|
|
132
|
+
] = "pseudoinverse"
|
|
133
|
+
regularization: float = 0.0
|
|
134
|
+
#: Kernel bandwidth for the gaussian family; None = estimate from data
|
|
135
|
+
#: (legacy: std of neighbor separation norms).
|
|
136
|
+
sigma: float | None = None
|
|
137
|
+
#: Polynomial order for kind="library" (lgr.fit_library_deformation).
|
|
138
|
+
order: int = 1
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class KinematicsConfig(BaseModel):
|
|
142
|
+
model_config = ConfigDict(extra="forbid")
|
|
143
|
+
|
|
144
|
+
#: World-time interval (seconds) to analyze; None = all observed times.
|
|
145
|
+
flow_time_domain: tuple[float, float] | None = None
|
|
146
|
+
#: Finite-time horizon Tmax per analysis window (the legacy
|
|
147
|
+
#: `analysis_increment`), in seconds.
|
|
148
|
+
window_time: float = 1.0
|
|
149
|
+
k_neighbors: int = 25
|
|
150
|
+
regression: RegressionConfig = Field(default_factory=RegressionConfig)
|
|
151
|
+
metrics: list[str] = Field(
|
|
152
|
+
default_factory=lambda: ["vort", "ftle", "lavd", "dra"]
|
|
153
|
+
)
|
|
154
|
+
#: Reproduce the legacy vorticity sign (a `-1**c` precedence accident
|
|
155
|
+
#: made it the negative of the standard convention).
|
|
156
|
+
legacy_vorticity_sign: bool = False
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class MetricStyle(BaseModel):
|
|
160
|
+
model_config = ConfigDict(extra="forbid")
|
|
161
|
+
|
|
162
|
+
cmap: str = "bwr"
|
|
163
|
+
#: (lo, hi); either side None = auto from data statistics.
|
|
164
|
+
clim: tuple[float | None, float | None] = (None, None)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class VisualizationConfig(BaseModel):
|
|
168
|
+
model_config = ConfigDict(extra="forbid")
|
|
169
|
+
|
|
170
|
+
#: SAM checkpoint for mask overlays; None disables the sam_masks renderer.
|
|
171
|
+
sam: ModelSpec | None = None
|
|
172
|
+
sam_model_type: Literal["vit_h", "vit_l", "vit_b"] = "vit_h"
|
|
173
|
+
#: SAM masks larger than this (pixels) are discarded as background grabs.
|
|
174
|
+
mask_size_threshold: int = 10000
|
|
175
|
+
#: Renderer ops applied in order per frame.
|
|
176
|
+
renderers: list[str] = Field(
|
|
177
|
+
default_factory=lambda: ["darken", "field_overlay", "dots"]
|
|
178
|
+
)
|
|
179
|
+
image_format: Literal["png", "jpeg"] = "png"
|
|
180
|
+
jpeg_quality: int = 90
|
|
181
|
+
metrics: dict[str, MetricStyle] = Field(default_factory=dict)
|
|
182
|
+
#: scipy RBFInterpolator options for the world-space field overlay.
|
|
183
|
+
field_interpolation: dict[str, Any] = Field(
|
|
184
|
+
default_factory=lambda: {"kernel": "linear", "smoothing": 0.02}
|
|
185
|
+
)
|
|
186
|
+
#: Binary image masking the flow region in the frame; None = whole frame.
|
|
187
|
+
flow_mask: Path | None = None
|
|
188
|
+
output_framerate: float | None = None
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class PipelineConfig(BaseModel):
|
|
192
|
+
"""Root configuration: one file drives the full pipeline."""
|
|
193
|
+
|
|
194
|
+
model_config = ConfigDict(extra="forbid")
|
|
195
|
+
|
|
196
|
+
name: str
|
|
197
|
+
#: All relative paths in this config resolve against the config file's
|
|
198
|
+
#: directory joined with base_dir.
|
|
199
|
+
base_dir: Path = Path(".")
|
|
200
|
+
artifacts_dir: Path = Path("artifacts")
|
|
201
|
+
device: str = "auto"
|
|
202
|
+
#: Modules imported before scheme lookup so third-party detectors and
|
|
203
|
+
#: trackers can register themselves.
|
|
204
|
+
plugins: list[str] = Field(default_factory=list)
|
|
205
|
+
|
|
206
|
+
video: VideoConfig
|
|
207
|
+
calibration: CalibrationConfig = Field(default_factory=CalibrationConfig)
|
|
208
|
+
detection: SchemeConfig
|
|
209
|
+
tracking: TrackingConfig
|
|
210
|
+
kinematics: KinematicsConfig = Field(default_factory=KinematicsConfig)
|
|
211
|
+
visualization: VisualizationConfig = Field(default_factory=VisualizationConfig)
|
|
212
|
+
|
|
213
|
+
@model_validator(mode="after")
|
|
214
|
+
def _validate_device(self) -> PipelineConfig:
|
|
215
|
+
d = self.device
|
|
216
|
+
if d not in ("auto", "cpu", "cuda") and not d.startswith("cuda:"):
|
|
217
|
+
hint = (
|
|
218
|
+
" (the legacy value 'gpu' was never valid — use 'cuda' or 'auto')"
|
|
219
|
+
if d == "gpu" else ""
|
|
220
|
+
)
|
|
221
|
+
raise ValueError(f"device must be auto/cpu/cuda[:N], got {d!r}{hint}")
|
|
222
|
+
return self
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Core data model: geometry contract, detections, tracks, calibration, video.
|
|
2
|
+
|
|
3
|
+
Everything downstream (detectors, trackers, kinematics, rendering) speaks the
|
|
4
|
+
types defined here. The coordinate contract lives in :mod:`.geometry` and is
|
|
5
|
+
deliberately the only place where (row, col) and (x, y) meet.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from semantic_kinematics.core.calibration import CalibrationModel
|
|
9
|
+
from semantic_kinematics.core.detections import (
|
|
10
|
+
DetectionSet,
|
|
11
|
+
FrameDetections,
|
|
12
|
+
InstanceMasks,
|
|
13
|
+
)
|
|
14
|
+
from semantic_kinematics.core.geometry import (
|
|
15
|
+
expand_bbox_xyxy,
|
|
16
|
+
rc_to_xy,
|
|
17
|
+
xy_to_rc,
|
|
18
|
+
)
|
|
19
|
+
from semantic_kinematics.core.tracks import Space, Track, TrackSet
|
|
20
|
+
from semantic_kinematics.core.video import VideoSource
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"CalibrationModel",
|
|
24
|
+
"DetectionSet",
|
|
25
|
+
"FrameDetections",
|
|
26
|
+
"InstanceMasks",
|
|
27
|
+
"Space",
|
|
28
|
+
"Track",
|
|
29
|
+
"TrackSet",
|
|
30
|
+
"VideoSource",
|
|
31
|
+
"expand_bbox_xyxy",
|
|
32
|
+
"rc_to_xy",
|
|
33
|
+
"xy_to_rc",
|
|
34
|
+
]
|