diff --git a/simulation/ai-polygon/control_qualification.py b/simulation/ai-polygon/control_qualification.py index 4855fb10..3a5e6838 100644 --- a/simulation/ai-polygon/control_qualification.py +++ b/simulation/ai-polygon/control_qualification.py @@ -21,6 +21,17 @@ PHASES = ( ("resume", 3, 1, 0), ("final-hold", 3, 0, 0), ) +# Direct transitions intentionally omit an intervening safety-zero command. +# This isolates recovery from opposed tracks into straight translation. +TRANSITION_PHASES = ( + ("hold", 3, 0, 0), + ("pivot-left", 8, 0, 0.35), + ("exit-left", 6, 1, 0), + ("hold-left", 3, 0, 0), + ("pivot-right", 8, 0, -0.35), + ("exit-right", 6, 1, 0), + ("final-hold", 3, 0, 0), +) CRITERIA = { "translation_fraction_min": 0.5, "turn_fraction_min": 0.45, diff --git a/simulation/ai-polygon/motion_control.py b/simulation/ai-polygon/motion_control.py index ffa56b08..322a2fd0 100644 --- a/simulation/ai-polygon/motion_control.py +++ b/simulation/ai-polygon/motion_control.py @@ -96,23 +96,23 @@ class ChassisSpeedFeedback: # requested yaw differential is retained. Safety zero stays zero. pivot_room = abs(yaw_rate) * self.track_centres / 2 correction = max(-pivot_room, min(pivot_room, correction)) - corrected = velocity + correction - # Feedback may reduce translation to zero, but cannot request an - # unplanned reversal. A pivot retains its opposed side directions. - if velocity * corrected < 0: - corrected = 0.0 nominal = SideSpeeds.from_twist(velocity, yaw_rate, self.track_centres) - proposed = SideSpeeds.from_twist(corrected, yaw_rate, self.track_centres) - # The nominal envelope owns each side's reversal through zero. A - # common correction must also respect a stationary/turning inner belt. - target = SideSpeeds( - *( - value if intent * value > 0 else 0.0 - for intent, value in zip( - vars(nominal).values(), vars(proposed).values(), strict=True - ) - ) - ).bounded(self.max_side) + # Limit the common correction before applying it to either belt. + # Clipping each side independently changes their difference and can + # amplify yaw when one nominal belt is near zero after a pivot. + for intent in vars(nominal).values(): + if intent > 0: + correction = max(correction, -intent) + elif intent < 0: + correction = min(correction, -intent) + else: + correction = 0.0 + corrected = velocity + correction + if velocity * corrected < 0: + corrected, correction = 0.0, -velocity + target = SideSpeeds.from_twist(corrected, yaw_rate, self.track_centres).bounded( + self.max_side + ) applied = target.twist(self.track_centres) self.metrics = dict( nominal_twist=[velocity, yaw_rate], diff --git a/simulation/ai-polygon/navigation/observed_goals.py b/simulation/ai-polygon/navigation/observed_goals.py index 261b77e5..33f60631 100644 --- a/simulation/ai-polygon/navigation/observed_goals.py +++ b/simulation/ai-polygon/navigation/observed_goals.py @@ -258,7 +258,18 @@ class ObservedGoals: and (candidate_mask is None or candidate_mask(before[None])[0]) and supported(before)): return before.tolist() - distance_to_target = np.linalg.norm(candidates[:, :2] - target, axis=1) + # Score the task direction at the existing 3.5 m observation horizon. + # Distance to a remote endpoint mostly rewards longitudinal advance: + # slightly farther side returns can beat a clear straight destination + # and make successive measured goals oscillate across the corridor. + # This reference only ranks actual permitted returns. It is never a + # generated drive goal, a straight-line route or a clearance receipt. + horizon = min(remaining, 3.5) + reference = pose[:2] + forward * horizon + # A smooth local attraction, normalized to metres like boundary_cost. + # Its gradient diminishes near the reference so centimetres of extra + # advance cannot outweigh clearance from an observed corridor edge. + distance_to_target = np.sum((candidates[:, :2] - reference)**2, axis=1) / horizon # The declared task, not the selected lens, owns the preferred direction. x,y,z,w = pose[3:7] heading = math.atan2(2*(w*z+x*y),1-2*(y*y+z*z)) diff --git a/simulation/ai-polygon/qualify_control_matrix.py b/simulation/ai-polygon/qualify_control_matrix.py index a7b7a3b8..ec37c69e 100644 --- a/simulation/ai-polygon/qualify_control_matrix.py +++ b/simulation/ai-polygon/qualify_control_matrix.py @@ -15,7 +15,7 @@ parser = argparse.ArgumentParser() parser.add_argument("--output", type=Path, required=True) parser.add_argument("--reservation", type=Path, required=True) parser.add_argument("--case", action="append", dest="case_ids") -parser.add_argument("--profile", choices=("control", "sweep"), default="control") +parser.add_argument("--profile", choices=("control", "sweep", "transition"), default="control") parser.add_argument("--contact-sample-hz", type=int, default=0, choices=(0, 1, 5, 10, 60)) args = parser.parse_args() receipt = json.loads(args.reservation.read_text(encoding="utf-8-sig")) @@ -40,6 +40,9 @@ from k1link.simulation.ai_polygon.robots import select_robot # noqa: E402 from k1link.simulation.ai_polygon.run_inputs import legacy_run_inputs # noqa: E402 from k1link.simulation.ai_polygon.run_robot import configure_robot # noqa: E402 +if args.profile == "transition": + from control_qualification import TRANSITION_PHASES as PHASES + if args.profile == "sweep": from sweep_qualification import CRITERIA, PHASES, SCHEMA from sweep_qualification import phase_metrics as sweep_metrics diff --git a/src/k1link/fleet/differential_drive.py b/src/k1link/fleet/differential_drive.py index b7a7ed42..1fe9e94b 100644 --- a/src/k1link/fleet/differential_drive.py +++ b/src/k1link/fleet/differential_drive.py @@ -102,13 +102,23 @@ class TwoSideDrive: dt = min(dt, self.limits.max_step_seconds) old = (self.applied.left_mps, self.applied.right_mps) goal = (target.left_mps, target.right_mps) - goal = tuple(0.0 if a * b < 0 else b for a, b in zip(old, goal, strict=True)) fraction = 1.0 for a, b in zip(old, goal, strict=True): + if a * b < 0: + continue rate = ( self.limits.acceleration_mps2 if abs(b) > abs(a) else self.limits.deceleration_mps2 ) if a != b: fraction = min(fraction, rate * dt / abs(b - a)) - self.applied = SideSpeeds(*(a + (b - a) * fraction for a, b in zip(old, goal, strict=True))) + # A reversing side owns its braking phase. Coupling its zero target to + # the other side's acceleration fraction can approach zero forever and + # leave one belt held while the other accelerates into an unwanted arc. + # Reach zero at the declared braking rate; accelerate in the opposite + # direction only on a later tick. Ordinary arcs keep the common fraction. + self.applied = SideSpeeds(*( + math.copysign(max(0.0, abs(a) - self.limits.deceleration_mps2 * dt), a) + if a * b < 0 else a + (b - a) * fraction + for a, b in zip(old, goal, strict=True) + )) return self.applied diff --git a/tests/test_ai_polygon_motion.py b/tests/test_ai_polygon_motion.py index b46a255a..cd5fac13 100644 --- a/tests/test_ai_polygon_motion.py +++ b/tests/test_ai_polygon_motion.py @@ -218,3 +218,49 @@ def test_explicit_control_profile_is_used_by_command_adapter(module): robot["control"]["chassis_speed_feedback"]["enabled"] = False control = module.RoverMotionControl(robot, 0.2) assert control.step(0.2, 0, 1 / 60, 0, 0) == pytest.approx((0.1 / 60, 0)) + + +@pytest.mark.parametrize('side',[0,1]) +def test_small_reversing_side_reaches_zero_while_other_side_accelerates(side): + limits=DriveLimits(.685,1.,.2,.4,.1) + drive=TwoSideDrive(limits) + initial=[-.0025,.193] + if side: + initial.reverse() + drive.applied=SideSpeeds(*initial) + value=drive.step(SideSpeeds(.331,.331),1/60) + actual=list(vars(value).values()) + assert actual[side]==0. + assert actual[1-side]==pytest.approx(.193+.2/60) + next_value=list(vars(drive.step(SideSpeeds(.331,.331),1/60)).values()) + assert 0.=prior[side] + assert max(abs(a-b) for a,b in zip(prior,value,strict=True))<=.4/60+1e-12 + assert value[side]>=0. + + +@pytest.mark.parametrize('yaw',[.2854,-.2854]) +def test_common_speed_feedback_cannot_amplify_yaw_when_a_side_is_near_zero(module,yaw): + feedback=module.ChassisSpeedFeedback( + {'proportional_gain':.75,'max_correction_mps':.15},.37,.685,1.) + v,w=feedback.step(.0952,yaw,.069,-.09) + assert w==pytest.approx(yaw) + before=SideSpeeds.from_twist(.0952,yaw,.685) + after=SideSpeeds.from_twist(v,w,.685) + for a,b in zip(vars(before).values(),vars(after).values(),strict=True): + assert a*b>=-1e-12 diff --git a/tests/test_ai_polygon_observed_goals.py b/tests/test_ai_polygon_observed_goals.py index e05ba0c5..a9f6ec14 100644 --- a/tests/test_ai_polygon_observed_goals.py +++ b/tests/test_ai_polygon_observed_goals.py @@ -246,3 +246,22 @@ def test_native_backup_only_uses_straight_rear_destinations(selector,yaw,shift,s assert selected is not None and selected.get('kind')!='orient' assert selected['reverse'] is reverse assert any(np.array_equal(selected['goal'],p) for p in rear) + + +@pytest.mark.parametrize('yaw,shift',[(0,(0,0)),(73,(42,-17)),(-138,(-250,52))]) +@pytest.mark.parametrize('side',[-1,1]) +def test_uneven_range_horizon_does_not_pull_straight_intent_sideways(selector,yaw,shift,side): + _,pose,_,_,rotation=road(yaw,shift) + # The road is straight and wide. One side merely has farther measured + # returns; maximizing advance toward a far endpoint preferred its edge. + xy=np.array([[x,y] for x in np.arange(.4,3.51,.05) + for y in np.arange(-1.2,1.21,.05) if x<=3.1+.35*side*y]) + points=np.c_[xy@rotation.T+shift,np.zeros(len(xy))] + selector.observe(np.c_[points,np.ones(len(points))],1,pose) + target=np.array(shift)+rotation@[675.,0.] + goal=selector.choose(points,pose,target,None,(),GEOMETRY,1) + local=(np.array(goal[:2])-shift)@rotation + assert local[0]>2.5 and abs(local[1])<.2 + assert np.min(np.linalg.norm(points-goal,axis=1))<1e-9 + # A local reference grants no synthetic ground or permission. + assert selector.choose(np.empty((0,3)),pose,target,goal,(),GEOMETRY,1) is None