[wpimath] Add nearest to Pose2d and Translation2d (#4882)

Co-authored-by: David Vo <auscompgeek@users.noreply.github.com>
This commit is contained in:
Ryan Blue
2023-02-03 18:27:16 -05:00
committed by GitHub
parent 08a536291b
commit 7b828ce84f
10 changed files with 279 additions and 0 deletions

View File

@@ -9,6 +9,9 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import edu.wpi.first.math.interpolation.Interpolatable;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
/** Represents a 2D pose containing translational and rotational elements. */
@@ -238,6 +241,23 @@ public class Pose2d implements Interpolatable<Pose2d> {
return new Twist2d(translationPart.getX(), translationPart.getY(), dtheta);
}
/**
* Returns the nearest Pose2d from a list of poses. If two or more poses in the list have the same
* distance from this pose, return the one with the closest rotation component.
*
* @param poses The list of poses to find the nearest.
* @return The nearest Pose2d from the list.
*/
public Pose2d nearest(List<Pose2d> poses) {
return Collections.min(
poses,
Comparator.comparing(
(Pose2d other) -> this.getTranslation().getDistance(other.getTranslation()))
.thenComparing(
(Pose2d other) ->
Math.abs(this.getRotation().minus(other.getRotation()).getRadians())));
}
@Override
public String toString() {
return String.format("Pose2d(%s, %s)", m_translation, m_rotation);

View File

@@ -10,6 +10,9 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import edu.wpi.first.math.MathUtil;
import edu.wpi.first.math.interpolation.Interpolatable;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
/**
@@ -185,6 +188,16 @@ public class Translation2d implements Interpolatable<Translation2d> {
return new Translation2d(m_x / scalar, m_y / scalar);
}
/**
* Returns the nearest Translation2d from a list of translations.
*
* @param translations The list of translations.
* @return The nearest Translation2d from the list.
*/
public Translation2d nearest(List<Translation2d> translations) {
return Collections.min(translations, Comparator.comparing(this::getDistance));
}
@Override
public String toString() {
return String.format("Translation2d(X: %.2f, Y: %.2f)", m_x, m_y);