ctb_formats_math/
center_of_gravity.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Center of gravity (CG) and moment calculations for aircraft weight and
21//! balance determination.
22//!
23//! Provides functions and data structures to compute moments, resolve pilot
24//! station arms (directly or relative to a reference datum), and calculate the
25//! loaded center of gravity across empty weight, occupants, and ballast.
26
27#[allow(
28    unused_imports,
29    clippy::wildcard_imports,
30    reason = "Standard workspace module prelude"
31)]
32use crate::utilities::*;
33
34/// Inputs for aircraft center of gravity and moment calculations.
35#[derive(Debug, Clone, PartialEq, Default)]
36pub struct CenterOfGravityInput {
37    /// Empty weight of the aircraft.
38    pub empty_weight: f64,
39    /// Empty center of gravity / arm of the aircraft.
40    pub empty_cg: f64,
41    /// Reference datum position, if calculating pilot arms relative to datum.
42    pub datum: Option<f64>,
43    /// Weight of the front pilot / occupant.
44    pub front_pilot_weight: f64,
45    /// Explicit arm for the front pilot (used when datum is not provided).
46    pub front_pilot_arm: Option<f64>,
47    /// Distance of front pilot in front of datum (used when datum is provided).
48    pub front_pilot_distance_in_front_of_datum: Option<f64>,
49    /// Weight of the rear pilot / occupant.
50    pub rear_pilot_weight: f64,
51    /// Explicit arm for the rear pilot (used when datum is not provided).
52    pub rear_pilot_arm: Option<f64>,
53    /// Distance of rear pilot behind datum (used when datum is provided).
54    pub rear_pilot_distance_behind_datum: Option<f64>,
55    /// Ballast weight.
56    pub ballast_weight: f64,
57    /// Ballast arm.
58    pub ballast_arm: f64,
59}
60
61/// Results of the center of gravity and moment evaluation.
62#[derive(Debug, Clone, PartialEq)]
63pub struct CenterOfGravityResult {
64    /// Empty moment (empty weight $\times$ empty CG).
65    pub empty_moment: f64,
66    /// Front pilot station arm.
67    pub front_pilot_arm: f64,
68    /// Front pilot moment (front pilot weight $\times$ front pilot arm).
69    pub front_pilot_moment: f64,
70    /// Rear pilot station arm.
71    pub rear_pilot_arm: f64,
72    /// Rear pilot moment (rear pilot weight $\times$ rear pilot arm).
73    pub rear_pilot_moment: f64,
74    /// Ballast moment (ballast weight $\times$ ballast arm).
75    pub ballast_moment: f64,
76    /// Total combined moment of all stations.
77    pub total_moment: f64,
78    /// Total combined weight of all stations.
79    pub total_weight: f64,
80    /// Loaded center of gravity position (total moment $/$ total weight).
81    pub loaded_cg: f64,
82}
83
84/// Calculates the moment of a station given its weight and arm ($weight \times arm$).
85pub fn calculate_moment(weight: f64, arm: f64) -> f64 {
86    weight * arm
87}
88
89/// Calculates front pilot arm given datum and distance in front of datum
90/// ($datum - distance$).
91pub fn front_pilot_arm_from_datum(datum: f64, distance_in_front: f64) -> f64 {
92    datum - distance_in_front
93}
94
95/// Calculates rear pilot arm given datum and distance behind datum
96/// ($datum + distance$).
97pub fn rear_pilot_arm_from_datum(datum: f64, distance_behind: f64) -> f64 {
98    datum + distance_behind
99}
100
101/// Calculates the loaded center of gravity from total moment and total weight.
102/// Returns an error if total weight is zero or non-finite.
103pub fn calculate_loaded_cg(
104    total_moment: f64,
105    total_weight: f64,
106) -> Result<f64> {
107    if total_weight == 0.0 {
108        bail!("Total weight cannot be zero");
109    }
110    let cg = total_moment / total_weight;
111    if !cg.is_finite() {
112        bail!("Calculated center of gravity is not finite: {cg}");
113    }
114    Ok(cg)
115}
116
117/// Evaluates aircraft weight, moments, and loaded center of gravity from inputs.
118pub fn calculate_center_of_gravity(
119    input: &CenterOfGravityInput,
120) -> Result<CenterOfGravityResult> {
121    let (front_pilot_arm, rear_pilot_arm) = if let Some(datum) = input.datum {
122        let (Some(front_dist), Some(rear_dist)) = (
123            input.front_pilot_distance_in_front_of_datum,
124            input.rear_pilot_distance_behind_datum,
125        ) else {
126            bail!(
127                "If providing Datum, must provide Pilot Distances Relative to Datum"
128            );
129        };
130        (
131            front_pilot_arm_from_datum(datum, front_dist),
132            rear_pilot_arm_from_datum(datum, rear_dist),
133        )
134    } else {
135        let (Some(front_arm), Some(rear_arm)) =
136            (input.front_pilot_arm, input.rear_pilot_arm)
137        else {
138            bail!("If not providing Pilot Arms, must provide Datum");
139        };
140        (front_arm, rear_arm)
141    };
142
143    let empty_moment = calculate_moment(input.empty_weight, input.empty_cg);
144    let front_pilot_moment =
145        calculate_moment(input.front_pilot_weight, front_pilot_arm);
146    let rear_pilot_moment =
147        calculate_moment(input.rear_pilot_weight, rear_pilot_arm);
148    let ballast_moment =
149        calculate_moment(input.ballast_weight, input.ballast_arm);
150
151    let total_moment =
152        empty_moment + front_pilot_moment + rear_pilot_moment + ballast_moment;
153    let total_weight = input.empty_weight
154        + input.front_pilot_weight
155        + input.rear_pilot_weight
156        + input.ballast_weight;
157
158    let loaded_cg = calculate_loaded_cg(total_moment, total_weight)?;
159
160    Ok(CenterOfGravityResult {
161        empty_moment,
162        front_pilot_arm,
163        front_pilot_moment,
164        rear_pilot_arm,
165        rear_pilot_moment,
166        ballast_moment,
167        total_moment,
168        total_weight,
169        loaded_cg,
170    })
171}
172
173#[cfg(test)]
174#[allow(
175    clippy::panic,
176    clippy::expect_used,
177    clippy::unwrap_used,
178    clippy::unwrap_in_result,
179    clippy::panic_in_result_fn,
180    clippy::indexing_slicing,
181    clippy::arithmetic_side_effects,
182    reason = "Standard repository test boilerplate"
183)]
184mod tests {
185    use super::*;
186
187    #[crate::ctb_test]
188    fn test_calculate_moment() {
189        assert_eq!(calculate_moment(100.0, 50.0), 5000.0);
190        assert_eq!(calculate_moment(0.0, 50.0), 0.0);
191    }
192
193    #[crate::ctb_test]
194    fn test_arms_from_datum() {
195        assert_eq!(front_pilot_arm_from_datum(100.0, 20.0), 80.0);
196        assert_eq!(rear_pilot_arm_from_datum(100.0, 30.0), 130.0);
197    }
198
199    #[crate::ctb_test]
200    fn test_calculate_loaded_cg() {
201        assert_eq!(calculate_loaded_cg(10000.0, 100.0).unwrap(), 100.0);
202        calculate_loaded_cg(10000.0, 0.0).unwrap_err();
203    }
204
205    #[crate::ctb_test]
206    fn test_cg_with_explicit_arms() {
207        let input = CenterOfGravityInput {
208            empty_weight: 1000.0,
209            empty_cg: 80.0,
210            datum: None,
211            front_pilot_weight: 180.0,
212            front_pilot_arm: Some(70.0),
213            front_pilot_distance_in_front_of_datum: None,
214            rear_pilot_weight: 170.0,
215            rear_pilot_arm: Some(110.0),
216            rear_pilot_distance_behind_datum: None,
217            ballast_weight: 50.0,
218            ballast_arm: 40.0,
219        };
220
221        let result = calculate_center_of_gravity(&input).unwrap();
222        assert_eq!(result.empty_moment, 80000.0);
223        assert_eq!(result.front_pilot_arm, 70.0);
224        assert_eq!(result.front_pilot_moment, 12600.0);
225        assert_eq!(result.rear_pilot_arm, 110.0);
226        assert_eq!(result.rear_pilot_moment, 18700.0);
227        assert_eq!(result.ballast_moment, 2000.0);
228        assert_eq!(result.total_moment, 113300.0);
229        assert_eq!(result.total_weight, 1400.0);
230        let expected_cg = 113300.0 / 1400.0;
231        assert!((result.loaded_cg - expected_cg).abs() < 1e-9);
232    }
233
234    #[crate::ctb_test]
235    fn test_cg_with_datum() {
236        let input = CenterOfGravityInput {
237            empty_weight: 1000.0,
238            empty_cg: 80.0,
239            datum: Some(90.0),
240            front_pilot_weight: 180.0,
241            front_pilot_arm: None,
242            front_pilot_distance_in_front_of_datum: Some(20.0),
243            rear_pilot_weight: 170.0,
244            rear_pilot_arm: None,
245            rear_pilot_distance_behind_datum: Some(20.0),
246            ballast_weight: 50.0,
247            ballast_arm: 40.0,
248        };
249
250        let result = calculate_center_of_gravity(&input).unwrap();
251        assert_eq!(result.front_pilot_arm, 70.0);
252        assert_eq!(result.rear_pilot_arm, 110.0);
253        assert_eq!(result.total_moment, 113300.0);
254        assert_eq!(result.total_weight, 1400.0);
255    }
256
257    #[crate::ctb_test]
258    fn test_cg_validation_errors() {
259        // Missing datum when arms not provided
260        let input_no_arms = CenterOfGravityInput {
261            empty_weight: 1000.0,
262            empty_cg: 80.0,
263            datum: None,
264            front_pilot_weight: 180.0,
265            front_pilot_arm: None,
266            front_pilot_distance_in_front_of_datum: None,
267            rear_pilot_weight: 170.0,
268            rear_pilot_arm: None,
269            rear_pilot_distance_behind_datum: None,
270            ballast_weight: 50.0,
271            ballast_arm: 40.0,
272        };
273        calculate_center_of_gravity(&input_no_arms).unwrap_err();
274
275        // Datum provided but missing relative distances
276        let input_missing_rel = CenterOfGravityInput {
277            empty_weight: 1000.0,
278            empty_cg: 80.0,
279            datum: Some(100.0),
280            front_pilot_weight: 180.0,
281            front_pilot_arm: None,
282            front_pilot_distance_in_front_of_datum: Some(10.0),
283            rear_pilot_weight: 170.0,
284            rear_pilot_arm: None,
285            rear_pilot_distance_behind_datum: None,
286            ballast_weight: 50.0,
287            ballast_arm: 40.0,
288        };
289        calculate_center_of_gravity(&input_missing_rel).unwrap_err();
290
291        // Zero total weight
292        let input_zero_weight = CenterOfGravityInput {
293            empty_weight: 0.0,
294            empty_cg: 0.0,
295            datum: None,
296            front_pilot_weight: 0.0,
297            front_pilot_arm: Some(10.0),
298            front_pilot_distance_in_front_of_datum: None,
299            rear_pilot_weight: 0.0,
300            rear_pilot_arm: Some(20.0),
301            rear_pilot_distance_behind_datum: None,
302            ballast_weight: 0.0,
303            ballast_arm: 0.0,
304        };
305        calculate_center_of_gravity(&input_zero_weight).unwrap_err();
306    }
307}