use std::fmt;
use super::critical_power::CriticalPower;
use super::effort::{Effort, Power};
use super::Error;
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Ftp(f64);
impl Ftp {
pub fn new(watts: f64) -> Result<Self, Error> {
if watts.is_finite() && watts > 0.0 {
Ok(Self(watts))
} else {
Err(Error::InvalidPower)
}
}
pub(crate) fn from_raw(watts: f64) -> Self {
Self(watts)
}
pub const fn watts(self) -> f64 {
self.0
}
pub fn power(self) -> Power {
Power::new(self.0).expect("Ftp invariants imply positive finite watts")
}
}
impl fmt::Display for Ftp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:.0} W FTP", self.0)
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for Ftp {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_f64(self.0)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Ftp {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let watts = <f64 as serde::Deserialize>::deserialize(deserializer)?;
Ftp::new(watts).map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum FtpProtocol {
SixtyMin,
TwentyMin,
EightMin,
RampMap,
CriticalPower,
}
pub const TWENTY_MIN_FACTOR: f64 = 0.95;
pub const EIGHT_MIN_FACTOR: f64 = 0.90;
pub const MAP_TO_FTP: f64 = 1.0 / 1.20;
pub const CP_TO_FTP: f64 = 0.96;
fn duration_in_range(seconds: f64, lo: f64, hi: f64) -> Result<(), Error> {
if seconds >= lo && seconds <= hi {
Ok(())
} else {
Err(Error::DurationOutOfModelRange)
}
}
pub fn ftp_from_20min(effort: Effort) -> Result<Ftp, Error> {
ftp_from_protocol(effort, FtpProtocol::TwentyMin)
}
pub fn ftp_from_60min(effort: Effort) -> Result<Ftp, Error> {
ftp_from_protocol(effort, FtpProtocol::SixtyMin)
}
pub fn ftp_from_protocol(effort: Effort, protocol: FtpProtocol) -> Result<Ftp, Error> {
let t = effort.seconds();
let p = effort.power().watts();
let watts = match protocol {
FtpProtocol::SixtyMin => {
duration_in_range(t, 45.0 * 60.0, 75.0 * 60.0)?;
p
}
FtpProtocol::TwentyMin => {
duration_in_range(t, 15.0 * 60.0, 25.0 * 60.0)?;
TWENTY_MIN_FACTOR * p
}
FtpProtocol::EightMin => {
duration_in_range(t, 6.0 * 60.0, 10.0 * 60.0)?;
EIGHT_MIN_FACTOR * p
}
FtpProtocol::RampMap => {
duration_in_range(t, 3.0 * 60.0, 8.0 * 60.0)?;
MAP_TO_FTP * p
}
FtpProtocol::CriticalPower => CP_TO_FTP * p,
};
Ftp::new(watts)
}
pub fn ftp_from_cp(cp: CriticalPower) -> Ftp {
Ftp::from_raw(CP_TO_FTP * cp.cp.watts())
}
pub fn ftp_from_map(map: Power) -> Result<Ftp, Error> {
Ftp::new(MAP_TO_FTP * map.watts())
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::path::PathBuf;
fn fixtures_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/cycling")
}
#[test]
fn fixture_ftp_protocols() {
let text = fs::read_to_string(fixtures_dir().join("ftp.csv")).unwrap();
for (i, line) in text.lines().enumerate() {
if i == 0 || line.trim().is_empty() {
continue;
}
let cols: Vec<_> = line.split(',').collect();
let protocol = match cols[0] {
"twenty" => FtpProtocol::TwentyMin,
"sixty" => FtpProtocol::SixtyMin,
"eight" => FtpProtocol::EightMin,
"ramp" => FtpProtocol::RampMap,
other => panic!("unknown protocol {other}"),
};
let watts: f64 = cols[1].parse().unwrap();
let seconds: f64 = cols[2].parse().unwrap();
let expected: f64 = cols[3].parse().unwrap();
let effort = Effort::from_watts_secs(watts, seconds).unwrap();
let ftp = ftp_from_protocol(effort, protocol).unwrap();
assert!(
(ftp.watts() - expected).abs() < 1e-9,
"row {i}: got {} want {expected}",
ftp.watts()
);
}
}
#[test]
fn duration_guards() {
let short = Effort::from_watts_secs(280.0, 600.0).unwrap();
assert_eq!(ftp_from_20min(short), Err(Error::DurationOutOfModelRange));
let ok = Effort::from_watts_secs(280.0, 1200.0).unwrap();
assert!(ftp_from_20min(ok).is_ok());
}
#[test]
fn map_and_cp_helpers() {
let map = Power::new(300.0).unwrap();
assert!((ftp_from_map(map).unwrap().watts() - 250.0).abs() < 1e-9);
let cp = CriticalPower {
cp: Power::new(250.0).unwrap(),
w_prime: super::super::effort::Work::new(18_000.0).unwrap(),
};
assert!((ftp_from_cp(cp).watts() - 240.0).abs() < 1e-9);
}
#[cfg(feature = "serde")]
#[test]
fn serde_ftp_roundtrip() {
let ftp = Ftp::new(266.0).unwrap();
let back: Ftp = serde_json::from_str(&serde_json::to_string(&ftp).unwrap()).unwrap();
assert_eq!(back, ftp);
}
}