Template C++ TrapezoidProfile and ProfiledPIDController on units (#2109)

This commit is contained in:
Oblarg
2019-11-20 23:11:46 -05:00
committed by Peter Johnson
parent f62e23f1af
commit fa85fbfc1c
16 changed files with 320 additions and 448 deletions

View File

@@ -1,133 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "frc/controller/ProfiledPIDController.h"
#include <algorithm>
#include <cmath>
#include "frc/smartdashboard/SendableBuilder.h"
using namespace frc;
ProfiledPIDController::ProfiledPIDController(
double Kp, double Ki, double Kd,
frc::TrapezoidProfile::Constraints constraints, units::second_t period)
: m_controller(Kp, Ki, Kd, period), m_constraints(constraints) {}
void ProfiledPIDController::SetP(double Kp) { m_controller.SetP(Kp); }
void ProfiledPIDController::SetI(double Ki) { m_controller.SetI(Ki); }
void ProfiledPIDController::SetD(double Kd) { m_controller.SetD(Kd); }
double ProfiledPIDController::GetP() const { return m_controller.GetP(); }
double ProfiledPIDController::GetI() const { return m_controller.GetI(); }
double ProfiledPIDController::GetD() const { return m_controller.GetD(); }
units::second_t ProfiledPIDController::GetPeriod() const {
return m_controller.GetPeriod();
}
void ProfiledPIDController::SetGoal(TrapezoidProfile::State goal) {
m_goal = goal;
}
void ProfiledPIDController::SetGoal(units::meter_t goal) {
m_goal = {goal, 0_mps};
}
TrapezoidProfile::State ProfiledPIDController::GetGoal() const {
return m_goal;
}
bool ProfiledPIDController::AtGoal() const {
return AtSetpoint() && m_goal == m_setpoint;
}
void ProfiledPIDController::SetConstraints(
frc::TrapezoidProfile::Constraints constraints) {
m_constraints = constraints;
}
TrapezoidProfile::State ProfiledPIDController::GetSetpoint() const {
return m_setpoint;
}
bool ProfiledPIDController::AtSetpoint() const {
return m_controller.AtSetpoint();
}
void ProfiledPIDController::EnableContinuousInput(double minimumInput,
double maximumInput) {
m_controller.EnableContinuousInput(minimumInput, maximumInput);
}
void ProfiledPIDController::DisableContinuousInput() {
m_controller.DisableContinuousInput();
}
void ProfiledPIDController::SetIntegratorRange(double minimumIntegral,
double maximumIntegral) {
m_controller.SetIntegratorRange(minimumIntegral, maximumIntegral);
}
void ProfiledPIDController::SetTolerance(double positionTolerance,
double velocityTolerance) {
m_controller.SetTolerance(positionTolerance, velocityTolerance);
}
double ProfiledPIDController::GetPositionError() const {
return m_controller.GetPositionError();
}
double ProfiledPIDController::GetVelocityError() const {
return m_controller.GetVelocityError();
}
double ProfiledPIDController::Calculate(units::meter_t measurement) {
frc::TrapezoidProfile profile{m_constraints, m_goal, m_setpoint};
m_setpoint = profile.Calculate(GetPeriod());
return m_controller.Calculate(measurement.to<double>(),
m_setpoint.position.to<double>());
}
double ProfiledPIDController::Calculate(units::meter_t measurement,
TrapezoidProfile::State goal) {
SetGoal(goal);
return Calculate(measurement);
}
double ProfiledPIDController::Calculate(units::meter_t measurement,
units::meter_t goal) {
SetGoal(goal);
return Calculate(measurement);
}
double ProfiledPIDController::Calculate(
units::meter_t measurement, units::meter_t goal,
frc::TrapezoidProfile::Constraints constraints) {
SetConstraints(constraints);
return Calculate(measurement, goal);
}
void ProfiledPIDController::Reset() { m_controller.Reset(); }
void ProfiledPIDController::InitSendable(frc::SendableBuilder& builder) {
builder.SetSmartDashboardType("ProfiledPIDController");
builder.AddDoubleProperty("p", [this] { return GetP(); },
[this](double value) { SetP(value); });
builder.AddDoubleProperty("i", [this] { return GetI(); },
[this](double value) { SetI(value); });
builder.AddDoubleProperty("d", [this] { return GetD(); },
[this](double value) { SetD(value); });
builder.AddDoubleProperty(
"goal", [this] { return GetGoal().position.to<double>(); },
[this](double value) { SetGoal(units::meter_t{value}); });
}

View File

@@ -7,6 +7,8 @@
#pragma once
#include <algorithm>
#include <cmath>
#include <functional>
#include <limits>
@@ -14,6 +16,7 @@
#include "frc/controller/PIDController.h"
#include "frc/smartdashboard/Sendable.h"
#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableHelper.h"
#include "frc/trajectory/TrapezoidProfile.h"
@@ -23,8 +26,20 @@ namespace frc {
* Implements a PID control loop whose setpoint is constrained by a trapezoid
* profile.
*/
class ProfiledPIDController : public Sendable,
public SendableHelper<ProfiledPIDController> {
template <class Distance>
class ProfiledPIDController
: public Sendable,
public SendableHelper<ProfiledPIDController<Distance>> {
using Distance_t = units::unit_t<Distance>;
using Velocity =
units::compound_unit<Distance, units::inverse<units::seconds>>;
using Velocity_t = units::unit_t<Velocity>;
using Acceleration =
units::compound_unit<Velocity, units::inverse<units::seconds>>;
using Acceleration_t = units::unit_t<Acceleration>;
using State = typename TrapezoidProfile<Distance>::State;
using Constraints = typename TrapezoidProfile<Distance>::Constraints;
public:
/**
* Allocates a ProfiledPIDController with the given constants for Kp, Ki, and
@@ -38,8 +53,8 @@ class ProfiledPIDController : public Sendable,
* default is 20 milliseconds.
*/
ProfiledPIDController(double Kp, double Ki, double Kd,
frc::TrapezoidProfile::Constraints constraints,
units::second_t period = 20_ms);
Constraints constraints, units::second_t period = 20_ms)
: m_controller(Kp, Ki, Kd, period), m_constraints(constraints) {}
~ProfiledPIDController() override = default;
@@ -57,96 +72,98 @@ class ProfiledPIDController : public Sendable,
* @param Ki Integral coefficient
* @param Kd Differential coefficient
*/
void SetPID(double Kp, double Ki, double Kd);
void SetPID(double Kp, double Ki, double Kd) {
m_controller.SetPID(Kp, Ki, Kd);
}
/**
* Sets the proportional coefficient of the PID controller gain.
*
* @param Kp proportional coefficient
*/
void SetP(double Kp);
void SetP(double Kp) { m_controller.SetP(Kp); }
/**
* Sets the integral coefficient of the PID controller gain.
*
* @param Ki integral coefficient
*/
void SetI(double Ki);
void SetI(double Ki) { m_controller.SetI(Ki); }
/**
* Sets the differential coefficient of the PID controller gain.
*
* @param Kd differential coefficient
*/
void SetD(double Kd);
void SetD(double Kd) { m_controller.SetD(Kd); }
/**
* Gets the proportional coefficient.
*
* @return proportional coefficient
*/
double GetP() const;
double GetP() const { return m_controller.GetP(); }
/**
* Gets the integral coefficient.
*
* @return integral coefficient
*/
double GetI() const;
double GetI() const { return m_controller.GetI(); }
/**
* Gets the differential coefficient.
*
* @return differential coefficient
*/
double GetD() const;
double GetD() const { return m_controller.GetD(); }
/**
* Gets the period of this controller.
*
* @return The period of the controller.
*/
units::second_t GetPeriod() const;
units::second_t GetPeriod() const { return m_controller.GetPeriod(); }
/**
* Sets the goal for the ProfiledPIDController.
*
* @param goal The desired unprofiled setpoint.
*/
void SetGoal(TrapezoidProfile::State goal);
void SetGoal(State goal) { m_goal = goal; }
/**
* Sets the goal for the ProfiledPIDController.
*
* @param goal The desired unprofiled setpoint.
*/
void SetGoal(units::meter_t goal);
void SetGoal(Distance_t goal) { m_goal = {goal, Velocity_t(0)}; }
/**
* Gets the goal for the ProfiledPIDController.
*/
TrapezoidProfile::State GetGoal() const;
State GetGoal() const { return m_goal; }
/**
* Returns true if the error is within the tolerance of the error.
*
* This will return false until at least one input value has been computed.
*/
bool AtGoal() const;
bool AtGoal() const { return AtSetpoint() && m_goal == m_setpoint; }
/**
* Set velocity and acceleration constraints for goal.
*
* @param constraints Velocity and acceleration constraints for goal.
*/
void SetConstraints(frc::TrapezoidProfile::Constraints constraints);
void SetConstraints(Constraints constraints) { m_constraints = constraints; }
/**
* Returns the current setpoint of the ProfiledPIDController.
*
* @return The current setpoint.
*/
TrapezoidProfile::State GetSetpoint() const;
State GetSetpoint() const { return m_setpoint; }
/**
* Returns true if the error is within the tolerance of the error.
@@ -157,7 +174,7 @@ class ProfiledPIDController : public Sendable,
*
* This will return false until at least one input value has been computed.
*/
bool AtSetpoint() const;
bool AtSetpoint() const { return m_controller.AtSetpoint(); }
/**
* Enables continuous input.
@@ -169,12 +186,15 @@ class ProfiledPIDController : public Sendable,
* @param minimumInput The minimum value expected from the input.
* @param maximumInput The maximum value expected from the input.
*/
void EnableContinuousInput(double minimumInput, double maximumInput);
void EnableContinuousInput(Distance_t minimumInput, Distance_t maximumInput) {
m_controller.EnableContinuousInput(minimumInput.template to<double>(),
maximumInput.template to<double>());
}
/**
* Disables continuous input.
*/
void DisableContinuousInput();
void DisableContinuousInput() { m_controller.DisableContinuousInput(); }
/**
* Sets the minimum and maximum values for the integrator.
@@ -185,7 +205,9 @@ class ProfiledPIDController : public Sendable,
* @param minimumIntegral The minimum value of the integrator.
* @param maximumIntegral The maximum value of the integrator.
*/
void SetIntegratorRange(double minimumIntegral, double maximumIntegral);
void SetIntegratorRange(double minimumIntegral, double maximumIntegral) {
m_controller.SetIntegratorRange(minimumIntegral, maximumIntegral);
}
/**
* Sets the error which is considered tolerable for use with
@@ -196,26 +218,37 @@ class ProfiledPIDController : public Sendable,
*/
void SetTolerance(
double positionTolerance,
double velocityTolerance = std::numeric_limits<double>::infinity());
double velocityTolerance = std::numeric_limits<double>::infinity()) {
m_controller.SetTolerance(positionTolerance, velocityTolerance);
}
/**
* Returns the difference between the setpoint and the measurement.
*
* @return The error.
*/
double GetPositionError() const;
Distance_t GetPositionError() const {
return Distance_t(m_controller.GetPositionError());
}
/**
* Returns the change in error per second.
*/
double GetVelocityError() const;
Velocity_t GetVelocityError() const {
return Velocity_t(m_controller.GetVelocityError());
}
/**
* Returns the next output of the PID controller.
*
* @param measurement The current measurement of the process variable.
*/
double Calculate(units::meter_t measurement);
double Calculate(Distance_t measurement) {
frc::TrapezoidProfile<Distance> profile{m_constraints, m_goal, m_setpoint};
m_setpoint = profile.Calculate(GetPeriod());
return m_controller.Calculate(measurement.template to<double>(),
m_setpoint.position.template to<double>());
}
/**
* Returns the next output of the PID controller.
@@ -223,15 +256,20 @@ class ProfiledPIDController : public Sendable,
* @param measurement The current measurement of the process variable.
* @param goal The new goal of the controller.
*/
double Calculate(units::meter_t measurement, TrapezoidProfile::State goal);
double Calculate(Distance_t measurement, State goal) {
SetGoal(goal);
return Calculate(measurement);
}
/**
* Returns the next output of the PID controller.
*
* @param measurement The current measurement of the process variable.
* @param goal The new goal of the controller.
*/
double Calculate(units::meter_t measurement, units::meter_t goal);
double Calculate(Distance_t measurement, Distance_t goal) {
SetGoal(goal);
return Calculate(measurement);
}
/**
* Returns the next output of the PID controller.
@@ -240,21 +278,36 @@ class ProfiledPIDController : public Sendable,
* @param goal The new goal of the controller.
* @param constraints Velocity and acceleration constraints for goal.
*/
double Calculate(units::meter_t measurement, units::meter_t goal,
frc::TrapezoidProfile::Constraints constraints);
double Calculate(
Distance_t measurement, Distance_t goal,
typename frc::TrapezoidProfile<Distance>::Constraints constraints) {
SetConstraints(constraints);
return Calculate(measurement, goal);
}
/**
* Reset the previous error, the integral term, and disable the controller.
*/
void Reset();
void Reset() { m_controller.Reset(); }
void InitSendable(frc::SendableBuilder& builder) override;
void InitSendable(frc::SendableBuilder& builder) override {
builder.SetSmartDashboardType("ProfiledPIDController");
builder.AddDoubleProperty("p", [this] { return GetP(); },
[this](double value) { SetP(value); });
builder.AddDoubleProperty("i", [this] { return GetI(); },
[this](double value) { SetI(value); });
builder.AddDoubleProperty("d", [this] { return GetD(); },
[this](double value) { SetD(value); });
builder.AddDoubleProperty(
"goal", [this] { return GetGoal().position.template to<double>(); },
[this](double value) { SetGoal(Distance_t{value}); });
}
private:
frc2::PIDController m_controller;
frc::TrapezoidProfile::State m_goal;
frc::TrapezoidProfile::State m_setpoint;
frc::TrapezoidProfile::Constraints m_constraints;
typename frc::TrapezoidProfile<Distance>::State m_goal;
typename frc::TrapezoidProfile<Distance>::State m_setpoint;
typename frc::TrapezoidProfile<Distance>::Constraints m_constraints;
};
} // namespace frc

View File

@@ -40,18 +40,27 @@ namespace frc {
* `Calculate()` and to determine when the profile has completed via
* `IsFinished()`.
*/
template <class Distance>
class TrapezoidProfile {
using Distance_t = units::unit_t<Distance>;
using Velocity =
units::compound_unit<Distance, units::inverse<units::seconds>>;
using Velocity_t = units::unit_t<Velocity>;
using Acceleration =
units::compound_unit<Velocity, units::inverse<units::seconds>>;
using Acceleration_t = units::unit_t<Acceleration>;
public:
class Constraints {
public:
units::meters_per_second_t maxVelocity = 0_mps;
units::meters_per_second_squared_t maxAcceleration = 0_mps_sq;
Velocity_t maxVelocity{0};
Acceleration_t maxAcceleration{0};
};
class State {
public:
units::meter_t position = 0_m;
units::meters_per_second_t velocity = 0_mps;
Distance_t position{0};
Velocity_t velocity{0};
bool operator==(const State& rhs) const {
return position == rhs.position && velocity == rhs.velocity;
}
@@ -66,7 +75,7 @@ class TrapezoidProfile {
* @param initial The initial state (usually the current state).
*/
TrapezoidProfile(Constraints constraints, State goal,
State initial = State{0_m, 0_mps});
State initial = State{Distance_t(0), Velocity_t(0)});
TrapezoidProfile(const TrapezoidProfile&) = default;
TrapezoidProfile& operator=(const TrapezoidProfile&) = default;
@@ -86,7 +95,7 @@ class TrapezoidProfile {
*
* @param target The target distance.
*/
units::second_t TimeLeftUntil(units::meter_t target) const;
units::second_t TimeLeftUntil(Distance_t target) const;
/**
* Returns the total time the profile takes to reach the goal.
@@ -135,5 +144,6 @@ class TrapezoidProfile {
units::second_t m_endFullSpeed;
units::second_t m_endDeccel;
};
} // namespace frc
#include "TrapezoidProfile.inc"

View File

@@ -5,12 +5,14 @@
/* the project. */
/*----------------------------------------------------------------------------*/
#include "frc/trajectory/TrapezoidProfile.h"
#pragma once
using namespace frc;
#include <algorithm>
TrapezoidProfile::TrapezoidProfile(Constraints constraints, State goal,
State initial)
namespace frc {
template <class Distance>
TrapezoidProfile<Distance>::TrapezoidProfile(Constraints constraints,
State goal, State initial)
: m_direction{ShouldFlipAcceleration(initial, goal) ? -1 : 1},
m_constraints(constraints),
m_initial(Direct(initial)),
@@ -24,30 +26,30 @@ TrapezoidProfile::TrapezoidProfile(Constraints constraints, State goal,
// ended at zero velocity
units::second_t cutoffBegin =
m_initial.velocity / m_constraints.maxAcceleration;
units::meter_t cutoffDistBegin =
Distance_t cutoffDistBegin =
cutoffBegin * cutoffBegin * m_constraints.maxAcceleration / 2.0;
units::second_t cutoffEnd = m_goal.velocity / m_constraints.maxAcceleration;
units::meter_t cutoffDistEnd =
Distance_t cutoffDistEnd =
cutoffEnd * cutoffEnd * m_constraints.maxAcceleration / 2.0;
// Now we can calculate the parameters as if it was a full trapezoid instead
// of a truncated one
units::meter_t fullTrapezoidDist =
Distance_t fullTrapezoidDist =
cutoffDistBegin + (m_goal.position - m_initial.position) + cutoffDistEnd;
units::second_t accelerationTime =
m_constraints.maxVelocity / m_constraints.maxAcceleration;
units::meter_t fullSpeedDist =
Distance_t fullSpeedDist =
fullTrapezoidDist -
accelerationTime * accelerationTime * m_constraints.maxAcceleration;
// Handle the case where the profile never reaches full speed
if (fullSpeedDist < 0_m) {
if (fullSpeedDist < Distance_t(0)) {
accelerationTime =
units::math::sqrt(fullTrapezoidDist / m_constraints.maxAcceleration);
fullSpeedDist = 0_m;
fullSpeedDist = Distance_t(0);
}
m_endAccel = accelerationTime - cutoffBegin;
@@ -55,7 +57,9 @@ TrapezoidProfile::TrapezoidProfile(Constraints constraints, State goal,
m_endDeccel = m_endFullSpeed + accelerationTime - cutoffEnd;
}
TrapezoidProfile::State TrapezoidProfile::Calculate(units::second_t t) const {
template <class Distance>
typename TrapezoidProfile<Distance>::State
TrapezoidProfile<Distance>::Calculate(units::second_t t) const {
State result = m_initial;
if (t < m_endAccel) {
@@ -83,9 +87,11 @@ TrapezoidProfile::State TrapezoidProfile::Calculate(units::second_t t) const {
return Direct(result);
}
units::second_t TrapezoidProfile::TimeLeftUntil(units::meter_t target) const {
units::meter_t position = m_initial.position * m_direction;
units::meters_per_second_t velocity = m_initial.velocity * m_direction;
template <class Distance>
units::second_t TrapezoidProfile<Distance>::TimeLeftUntil(
Distance_t target) const {
Distance_t position = m_initial.position * m_direction;
Velocity_t velocity = m_initial.velocity * m_direction;
units::second_t endAccel = m_endAccel * m_direction;
units::second_t endFullSpeed = m_endFullSpeed * m_direction - endAccel;
@@ -101,21 +107,19 @@ units::second_t TrapezoidProfile::TimeLeftUntil(units::meter_t target) const {
units::second_t endDeccel = m_endDeccel - endAccel - endFullSpeed;
endDeccel = units::math::max(endDeccel, 0_s);
const units::meters_per_second_squared_t acceleration =
m_constraints.maxAcceleration;
const units::meters_per_second_squared_t decceleration =
-m_constraints.maxAcceleration;
const Acceleration_t acceleration = m_constraints.maxAcceleration;
const Acceleration_t decceleration = -m_constraints.maxAcceleration;
units::meter_t distToTarget = units::math::abs(target - position);
Distance_t distToTarget = units::math::abs(target - position);
if (distToTarget < 1e-6_m) {
if (distToTarget < Distance_t(1e-6)) {
return 0_s;
}
units::meter_t accelDist =
Distance_t accelDist =
velocity * endAccel + 0.5 * acceleration * endAccel * endAccel;
units::meters_per_second_t deccelVelocity;
Velocity_t deccelVelocity;
if (endAccel > 0_s) {
deccelVelocity = units::math::sqrt(
units::math::abs(velocity * velocity + 2 * acceleration * accelDist));
@@ -123,20 +127,20 @@ units::second_t TrapezoidProfile::TimeLeftUntil(units::meter_t target) const {
deccelVelocity = velocity;
}
units::meter_t deccelDist =
Distance_t deccelDist =
deccelVelocity * endDeccel + 0.5 * decceleration * endDeccel * endDeccel;
deccelDist = units::math::max(deccelDist, 0_m);
deccelDist = units::math::max(deccelDist, Distance_t(0));
units::meter_t fullSpeedDist = m_constraints.maxVelocity * endFullSpeed;
Distance_t fullSpeedDist = m_constraints.maxVelocity * endFullSpeed;
if (accelDist > distToTarget) {
accelDist = distToTarget;
fullSpeedDist = 0_m;
deccelDist = 0_m;
fullSpeedDist = Distance_t(0);
deccelDist = Distance_t(0);
} else if (accelDist + fullSpeedDist > distToTarget) {
fullSpeedDist = distToTarget - accelDist;
deccelDist = 0_m;
deccelDist = Distance_t(0);
} else {
deccelDist = distToTarget - fullSpeedDist - accelDist;
}
@@ -156,3 +160,4 @@ units::second_t TrapezoidProfile::TimeLeftUntil(units::meter_t target) const {
return accelTime + fullSpeedTime + deccelTime;
}
} // namespace frc