File size: 6,382 Bytes
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Independent rigid-bat geometry. Monocular body depth is never an independent grip."""
from pathlib import Path
import numpy as np
from scipy.optimize import least_squares
from .geometry import project, intrinsics, triangulate, barrel_from_independent_knob, to_world
from .storage import StageCache, digest, atomic_json, read_json


def reconstruct_frame(record, mode, calibration, length, max_error_px=3.):
    if not record.get("source") or record.get("independent") is not True:
        raise ValueError("Bat geometry requires documented independent measurements")
    if length <= .1524: raise ValueError("Known bat length must exceed the measurement-point offset")
    if mode == "calibrated_multiview":
        if record.get("world_axes")!="x_pitcher_y_up_z_right_handed":
            raise ValueError("Multiview projections must identify the calibrated world axes")
        if record.get("synchronization_verified") is not True:
            raise ValueError("Multiview endpoints must have verified synchronization")
        cameras = np.asarray(record["projection_matrices"], float)
        endpoints = np.asarray(record["endpoints_pixels"], float)  # views x knob/barrel x xy
        if endpoints.shape != (len(cameras), 2, 2): raise ValueError("Invalid multiview endpoints")
        points = np.array([triangulate(endpoints[:, j], cameras, max_error_px)[0] for j in range(2)])
        if abs(np.linalg.norm(points[1]-points[0])-length) > .03:
            raise ValueError("Triangulated endpoints disagree with measured bat length")
        def residual(flat):
            xyz = flat.reshape(2, 3); errors = []
            for view, camera in enumerate(cameras):
                h = np.c_[xyz, np.ones(2)]@camera.T
                valid = np.isfinite(endpoints[view]).all(axis=1)
                errors.extend((h[valid,:2]/h[valid,2:3]-endpoints[view,valid]).ravel())
            return np.r_[errors, (np.linalg.norm(xyz[1]-xyz[0])-length)/.001]
        points = least_squares(residual, points.ravel(), loss="soft_l1").x.reshape(2,3)
        error = float(np.max(np.abs(residual(points.ravel())[:-1])))
        if error > max_error_px or abs(np.linalg.norm(points[1]-points[0])-length) > .003:
            raise ValueError("Rigid bat fit failed observation/length agreement")
        return points, error, "world_x_pitcher_y_up_z_right_handed"
    if mode != "calibrated_independent_grip": raise ValueError("Unknown bat reconstruction mode")
    k = intrinsics(calibration["intrinsics_oriented_pixels"])
    if not calibration.get("source"): raise ValueError("Documented camera calibration is required")
    pixels = np.asarray(record["endpoints_pixels"], float)
    knob = np.asarray(record["knob_camera_m"], float)
    barrel = barrel_from_independent_knob(knob, pixels[1], k, length, record.get("barrel_anchor_camera_m"))
    points = np.stack([knob, barrel]); error = float(np.linalg.norm(project(points,k)-pixels,axis=1).max())
    if error > max_error_px: raise ValueError("Independent knob measurement fails reprojection")
    return points, error, "camera_x_right_y_down_z_forward_metres"


def run_bat3d(request, capture, config):
    root = Path(request["root"])
    try:
        if config.bat_3d_mode not in {"calibrated_multiview","calibrated_independent_grip"}:
            raise ValueError("independent_geometry_not_qualified")
        geometry = capture["metadata"].get("bat_geometry", {})
        length = capture["metadata"].get("bat_length_m")
        if not length: raise ValueError("Measured bat length unavailable")
        calibration = capture["metadata"].get("calibration", {})
        cache = StageCache(root, "bat3d", digest({"capture": capture["input_sha256"], "geometry": geometry,
                                                "code_hash":request["code_hash"],"environment":request.get("environment"),
                                                "mode": config.bat_3d_mode, "length": length, "calibration": calibration}))
        if cache.valid("trajectory"):
            atomic_json(root/"bat3d_status.json",read_json(cache.root/"status.json")); return
        count = capture["frame_count"]
        points = np.full((count,2,3),np.nan); errors = np.full(count,np.nan); rejected = {}
        space = None
        for key, record in geometry.get("frames", {}).items():
            index = int(key)
            if not 0 <= index < count: raise ValueError("Independent bat frame outside video")
            try:
                value, error, coordinates = reconstruct_frame(record,config.bat_3d_mode,calibration,length)
                if space and coordinates != space: raise ValueError("Mixed bat coordinate systems")
                points[index], errors[index], space = value,error,coordinates
            except (ValueError,KeyError) as error:
                rejected[str(index)] = str(error)
        valid = np.isfinite(points).all(axis=(1,2))
        if not valid.any(): raise ValueError("No independently supported unambiguous bat frames")
        world = np.full_like(points,np.nan)
        if space.startswith("world"): world = points.copy()
        else:
            try: world = to_world(points,calibration)
            except (ValueError,KeyError): pass
        direction = (points[:,1]-points[:,0])/length
        sweet = points[:,1]-.1524*direction
        world_sweet = world[:,1]-.1524*(world[:,1]-world[:,0])/length
        path = cache.root/"trajectory.npz"
        np.savez_compressed(path,endpoints_m=points,endpoints_world_m=world,sweet_spot_m=sweet,
                            sweet_spot_world_m=world_sweet,reprojection_px=errors,accepted_frames=valid)
        result = {"status":"complete" if valid.all() else "partial","cache_key":cache.key,
                  "trajectory_path":str(path.relative_to(root)),"frames_fitted":int(valid.sum()),
                  "coordinate_space":space,"geometry_source":config.bat_3d_mode,"rejected_frames":rejected,
                  "measurement_point":"0.1524m_inward_from_barrel_along_shaft",
                  "validation":"reference-validation-pending","independent_geometry":True}
        atomic_json(cache.root/"status.json",result);cache.commit("trajectory",[path,cache.root/"status.json"])
    except Exception as error:
        result={"status":"unavailable","reason":str(error)[:300],"error_type":type(error).__name__}
    atomic_json(root/"bat3d_status.json",result)