Class VisionPoseFilter

java.lang.Object
yall.filter.VisionPoseFilter

public class VisionPoseFilter extends Object
Decides which vision pose estimates to trust, and how much.

Each check is set with its withX method. Pass null to turn the check off:

new VisionPoseFilter()
    .withMaxAmbiguity(0.15)       // tighter than the default
    .withMaxTilt(Degrees.of(10))  // on; off by default
    .withMaxYawRate(null);        // off

A new filter starts with these checks:

Checks and their defaults
CheckDefaultRejects an estimate when
Field boundsOn, 0.5 m margin the robot would be off the field
HeightOn, 0.5 m the robot would be floating above or sunk below the floor
TiltOff the robot would be rolled or pitched further than the limit
AmbiguityOn, 0.2 a single-tag estimate is too ambiguous
Tag countOn, 1 tag too few tags were used
Tag distance On, 4 m for one tag, 8 m for severalthe tags are too far away
Yaw rateOn, 720 °/s the robot was spinning too fast, which blurs the image (needs VisionCamera.setRobotOrientation(Rotation3d, AngularVelocity))
AgeOn, 0.5 s the image is too old, or claims to be from the future
Pose jumpOff the estimate is too far from the robot's current pose

Add your own checks with withCustomCheck(String, Predicate). Each has a name, which is the rejection reason and the name its rejections are counted under in PoseFilterStats.

Estimates that used no tags are always rejected by check(VisionPoseEstimate, Field, double, double). Pose sources that don't use tags, such as a QuestNav headset, are checked with checkWithoutTags(VisionPoseEstimate, Field, double) instead, which runs only the checks that don't need tags.

Accepted estimates get standard deviations that grow with the square of the tag distance: base * (1 + distance² / distanceDivisor), with a smaller base for multi-tag estimates. See withStdDevs(Matrix, Matrix, double).

  • Constructor Details

    • VisionPoseFilter

      public VisionPoseFilter()
      Creates a filter with the default checks described in the class documentation.
  • Method Details

    • acceptAll

      public static VisionPoseFilter acceptAll()
      Creates a filter that accepts every estimate that used a tag. Turn checks on with the withX methods.
      Returns:
      A filter with every check off.
    • withFieldBounds

      public VisionPoseFilter withFieldBounds(Distance margin)
      Rejects estimates that put the robot off the field.
      Parameters:
      margin - How far past the field edge to still accept, for measurement error. null turns the check off.
      Returns:
      This filter, for chaining.
    • withMaxHeightError

      public VisionPoseFilter withMaxHeightError(Distance maxHeightError)
      Rejects estimates that put the robot above or below the floor.
      Parameters:
      maxHeightError - Largest accepted distance between the estimated robot origin and the floor. null turns the check off.
      Returns:
      This filter, for chaining.
    • withMaxTilt

      public VisionPoseFilter withMaxTilt(Angle maxTilt)
      Rejects estimates that roll or pitch the robot further than the limit. Leave this off if the robot drives over ramps or bumps.
      Parameters:
      maxTilt - Largest accepted roll or pitch. null turns the check off.
      Returns:
      This filter, for chaining.
    • withMaxAmbiguity

      public VisionPoseFilter withMaxAmbiguity(Double ambiguity)
      Rejects single-tag estimates whose pose ambiguity is above the limit. Multi-tag estimates and cameras that don't report ambiguity aren't checked.
      Parameters:
      ambiguity - Largest accepted ambiguity, 0 to 1. null turns the check off.
      Returns:
      This filter, for chaining.
    • withMinTagCount

      public VisionPoseFilter withMinTagCount(Integer tagCount)
      Rejects estimates that used fewer tags than the limit. Estimates that used no tags are always rejected.
      Parameters:
      tagCount - Fewest tags accepted. null turns the check off.
      Returns:
      This filter, for chaining.
    • withMaxTagDistance

      public VisionPoseFilter withMaxTagDistance(Distance maxSingleTagDistance, Distance maxMultiTagDistance)
      Rejects estimates whose tags are, on average, further away than the limit.
      Parameters:
      maxSingleTagDistance - Limit for estimates from one tag. null turns this limit off.
      maxMultiTagDistance - Limit for estimates from several tags. null turns this limit off.
      Returns:
      This filter, for chaining.
    • withMaxYawRate

      public VisionPoseFilter withMaxYawRate(AngularVelocity maxYawRate)
      Rejects estimates taken while the robot spun faster than the limit. Needs the yaw rate from VisionCamera.setRobotOrientation(Rotation3d, AngularVelocity); without it, estimates aren't checked.
      Parameters:
      maxYawRate - Fastest accepted spin. null turns the check off.
      Returns:
      This filter, for chaining.
    • withMaxAge

      public VisionPoseFilter withMaxAge(Time maxAge)
      Rejects estimates from images older than the limit, and from images timestamped in the future.
      Parameters:
      maxAge - Oldest accepted image. null turns the check off.
      Returns:
      This filter, for chaining.
    • withMaxDistanceFromPose

      public VisionPoseFilter withMaxDistanceFromPose(Supplier<Pose2d> currentPose, Distance maxDistance)
      Rejects estimates further than the limit from the robot's current pose. Turn this on only once the robot knows where it is, or vision can never correct a bad starting pose.
      Parameters:
      currentPose - Supplies the robot's current pose, usually from the drivetrain's pose estimator. null turns the check off.
      maxDistance - Largest accepted distance from the current pose. null turns the check off.
      Returns:
      This filter, for chaining.
    • withCustomCheck

      public VisionPoseFilter withCustomCheck(String name, Predicate<VisionPoseEstimate> accepts)
      Adds a check of your own, run after the built-in ones. Its name is the rejection reason, and PoseFilterStats counts its rejections under that name.
      filter.withCustomCheck("not in our half", e -> e.pose().getX() < 8.27);
      
      Parameters:
      name - Name of the check, shown as the rejection reason. Must not be empty. A check with the same name is replaced.
      accepts - Returns true to accept an estimate. null removes the check.
      Returns:
      This filter, for chaining.
      Throws:
      IllegalArgumentException - if the name is null or blank.
    • getCustomChecks

      public Map<String, Predicate<VisionPoseEstimate>> getCustomChecks()
      The custom checks, by name.
      Returns:
      The checks, in the order they were added.
    • getDistanceDivisor

      public double getDistanceDivisor()
      The divisor for the squared tag distance in the standard deviation formula.
      Returns:
      The divisor.
    • withStdDevs

      public VisionPoseFilter withStdDevs(Matrix<N3,N1> singleTagBase, Matrix<N3,N1> multiTagBase, double distanceDivisor)
      Sets how standard deviations are computed for accepted estimates: base * (1 + d² / distanceDivisor), where d is the average tag distance in meters. A smaller divisor makes distant tags count for less.
      Parameters:
      singleTagBase - Base standard deviations of x (m), y (m) and heading (rad) for one tag.
      multiTagBase - Base standard deviations for several tags.
      distanceDivisor - Divisor for the squared tag distance.
      Returns:
      This filter, for chaining.
    • withHeadingAssistedThetaStdDev

      public VisionPoseFilter withHeadingAssistedThetaStdDev(Angle thetaStdDev)
      Sets the heading standard deviation for heading-assisted estimates (Limelight MegaTag2, PhotonVision's trig solve). Their heading is the one given to setRobotOrientation, so it should carry almost no weight.
      Parameters:
      thetaStdDev - Heading standard deviation.
      Returns:
      This filter, for chaining.
    • getFieldBoundsMargin

      public Optional<Distance> getFieldBoundsMargin()
      The field bounds margin.
      Returns:
      The margin, or empty if the check is off.
    • getMaxHeightError

      public Optional<Distance> getMaxHeightError()
      The largest accepted height error.
      Returns:
      The limit, or empty if the check is off.
    • getMaxTilt

      public Optional<Angle> getMaxTilt()
      The largest accepted roll or pitch.
      Returns:
      The limit, or empty if the check is off.
    • getMaxAmbiguity

      public Optional<Double> getMaxAmbiguity()
      The largest accepted single-tag ambiguity.
      Returns:
      The limit, or empty if the check is off.
    • getMinTagCount

      public Optional<Integer> getMinTagCount()
      The fewest tags accepted.
      Returns:
      The limit, or empty if the check is off.
    • getMaxSingleTagDistance

      public Optional<Distance> getMaxSingleTagDistance()
      The largest accepted average tag distance for a single-tag estimate.
      Returns:
      The limit, or empty if it is off.
    • getMaxMultiTagDistance

      public Optional<Distance> getMaxMultiTagDistance()
      The largest accepted average tag distance for a multi-tag estimate.
      Returns:
      The limit, or empty if it is off.
    • getMaxYawRate

      public Optional<AngularVelocity> getMaxYawRate()
      The fastest accepted spin.
      Returns:
      The limit, or empty if the check is off.
    • getMaxAge

      public Optional<Time> getMaxAge()
      The oldest accepted image.
      Returns:
      The limit, or empty if the check is off.
    • getMaxDistanceFromPose

      public Optional<Distance> getMaxDistanceFromPose()
      The largest accepted distance from the current pose.
      Returns:
      The limit, or empty if the check is off.
    • withMinSingleTagArea

      public VisionPoseFilter withMinSingleTagArea(Double minAreaPercent)
      Rejects single-tag estimates whose tag covers less than the given percentage of the image. Multi-tag estimates and cameras that don't report target area aren't checked.
      Parameters:
      minAreaPercent - Smallest accepted image area percentage (0 to 100). null turns the check off.
      Returns:
      This filter, for chaining.
    • withYawRateWindow

      public VisionPoseFilter withYawRateWindow(Time halfWindow)
      Checks the peak yaw rate over a symmetric window (timestamp +/- halfWindow) rather than only the instantaneous yaw rate when the frame arrived.
      Parameters:
      halfWindow - Half-width of the yaw-rate window around each image timestamp. null turns windowed checking off.
      Returns:
      This filter, for chaining.
    • recordYawRate

      public void recordYawRate(double timestampSeconds, double yawRateDegreesPerSecond)
      Records a timestamped robot yaw-rate sample for withYawRateWindow(Time). Called automatically by VisionCamera.setRobotOrientation(Rotation3d, AngularVelocity).
      Parameters:
      timestampSeconds - Monotonic timestamp in seconds.
      yawRateDegreesPerSecond - Robot yaw rate in degrees per second.
    • withStdDevScale

      public VisionPoseFilter withStdDevScale(double xyScale)
      Applies a constant multiplier to accepted X/Y standard deviations (for example, tightening trust during alignment or right after traversing a bump).
      Parameters:
      xyScale - Positive multiplier applied to X and Y standard deviations.
      Returns:
      This filter, for chaining.
    • withStdDevScale

      public VisionPoseFilter withStdDevScale(DoubleSupplier xyScaleSupplier)
      Applies a dynamic multiplier to accepted X/Y standard deviations (for example, switching between normal driving, close-in alignment, and post-bump relocalization snap modes).
      Parameters:
      xyScaleSupplier - Supplies a positive multiplier each time standard deviations are computed. null resets the scale to 1.0.
      Returns:
      This filter, for chaining.
    • withStdDevCalculator

      public VisionPoseFilter withStdDevCalculator(Function<VisionPoseEstimate, Matrix<N3,N1>> calculator)
      Supplies a custom standard-deviation calculator that replaces the built-in base * (1 + d² / distanceDivisor) model for accepted estimates (for example, d^1.5 / tagCount or ambiguity-weighted covariance). If the calculator returns null or any non-finite / non-positive entry, the filter safely falls back to its built-in formula.
      Parameters:
      calculator - Function computing [x, y, theta] standard deviations for an accepted estimate, or null to restore the built-in model.
      Returns:
      This filter, for chaining.
    • applySuggestedBaseStdDevs

      public boolean applySuggestedBaseStdDevs(PoseFilterStats stats, long minSamples, Matrix<N3,N1> minBase, Matrix<N3,N1> maxBase)
      Applies PoseFilterStats.getSuggestedBaseStdDevs(double) as the multi-tag base standard deviations once at least minSamples accepted poses have been collected, clamping each axis into [minBase, maxBase] so noisy calibration runs cannot produce extreme weights.
      Parameters:
      stats - Collected pose-filter statistics from a stationary calibration run.
      minSamples - Minimum accepted sample count required before applying (must be >= 2).
      minBase - Per-axis lower clamp [x, y, theta] (all finite and positive).
      maxBase - Per-axis upper clamp [x, y, theta] (all finite and >= minBase).
      Returns:
      true if the base standard deviations were updated, false if not enough valid samples were available.
    • withHighTagCountBoost

      public VisionPoseFilter withHighTagCountBoost(Integer minTags, Double xyScale)
      Applies an extra X/Y standard deviation multiplier when an estimate sees at least minTags AprilTags (for example, trusting a 3+ tag shooter-camera solve more tightly).
      Parameters:
      minTags - Fewest tags required for the boost (must be >= 2). null turns the boost off.
      xyScale - Positive multiplier applied to X and Y standard deviations (e.g. 0.35). null turns the boost off.
      Returns:
      This filter, for chaining.
    • withPreEnableAlignment

      public VisionPoseFilter withPreEnableAlignment(BooleanSupplier isEnabled, Integer minPreEnableTags, Angle preEnableThetaStdDev)
      Enables pre-enable (disabled) field alignment: while isEnabled returns false, the pose-jump gate is bypassed so vision can snap to the field from an unknown starting pose, at least minPreEnableTags tags are required, and heading uses preEnableThetaStdDev so multi-tag solves can align the gyro before the match starts.
      Parameters:
      isEnabled - Supplies whether the robot is currently enabled (e.g. DriverStation::isEnabled). null turns pre-enable alignment off.
      minPreEnableTags - Fewest tags required while disabled (must be >= 1). null defaults to 2.
      preEnableThetaStdDev - Heading standard deviation while disabled. null defaults to 2 deg.
      Returns:
      This filter, for chaining.
    • getMinSingleTagArea

      public Optional<Double> getMinSingleTagArea()
      The smallest accepted single-tag image area percentage.
      Returns:
      The limit, or empty if the check is off.
    • getYawRateWindow

      public Optional<Time> getYawRateWindow()
      The yaw-rate window half-width.
      Returns:
      The window half-width, or empty if windowed checking is off.
    • getHighTagCountBoostMinTags

      public Optional<Integer> getHighTagCountBoostMinTags()
      The minimum tag count required to trigger the high-tag-count trust boost.
      Returns:
      The minimum tag count, or empty if the boost is off.
    • isPreEnableAlignmentActive

      public boolean isPreEnableAlignmentActive()
      Whether pre-enable alignment mode is currently active (configured and robot disabled).
      Returns:
      true if pre-enable alignment is active right now.
    • check

      public Optional<String> check(VisionPoseEstimate estimate, Field field, double nowSeconds, double yawRateDegreesPerSecond)
      Checks an estimate.
      Parameters:
      estimate - Estimate to check.
      field - Field the robot is on, for the bounds check. null skips that check.
      nowSeconds - Current Timer.getMonotonicTimestamp().
      yawRateDegreesPerSecond - Robot yaw rate when the image was taken, or Double.NaN if unknown.
      Returns:
      Why the estimate was rejected, or empty if it passes every enabled check.
    • check

      public Optional<String> check(VisionPoseEstimate estimate, Field field, double nowSeconds, double yawRateDegreesPerSecond, double averageTagAreaPercent)
      Checks an estimate with optional average AprilTag image area.
      Parameters:
      estimate - Estimate to check.
      field - Field the robot is on, for the bounds check. null skips that check.
      nowSeconds - Current Timer.getMonotonicTimestamp().
      yawRateDegreesPerSecond - Robot yaw rate when the image was taken, or Double.NaN if unknown.
      averageTagAreaPercent - Average image area percentage of the AprilTags in the frame, or Double.NaN if unknown.
      Returns:
      Why the estimate was rejected, or empty if it passes every enabled check.
    • checkWithoutTags

      public Optional<String> checkWithoutTags(VisionPoseEstimate estimate, Field field, double nowSeconds)
      Checks an estimate that doesn't come from AprilTags, such as a QuestNav headset's tracked pose. Only the checks that don't need tags run: non-finite pose, age, field bounds, height, tilt, pose jump and the custom checks. The tag count, ambiguity, tag area, tag distance and yaw rate checks are skipped, and an estimate with no tags isn't rejected for it.
      Parameters:
      estimate - Estimate to check.
      field - Field the robot is on, for the bounds check. null skips that check.
      nowSeconds - Current Timer.getMonotonicTimestamp().
      Returns:
      Why the estimate was rejected, or empty if it passes every enabled check.
    • applyStdDevs

      public VisionPoseEstimate applyStdDevs(VisionPoseEstimate estimate)
      Computes the standard deviations for an estimate.
      Parameters:
      estimate - Estimate to weigh.
      Returns:
      The estimate with VisionPoseEstimate.stdDevs() filled in.