1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/*
    Nyx, blazing fast astrodynamics
    Copyright (C) 2018-onwards Christopher Rabotin <christopher.rabotin@gmail.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

use crate::cosmic::Frame;
use crate::errors::TargetingError;
use std::default::Default;
use std::f64::consts::{FRAC_PI_2, FRAC_PI_8, PI};
use std::fmt;

/// Defines the kind of correction to apply in the targeter
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Vary {
    /// Vary position component X
    PositionX,
    /// Vary position component Y
    PositionY,
    /// Vary position component Z
    PositionZ,
    /// Vary velocity component X
    VelocityX,
    /// Vary velocity component Y
    VelocityY,
    /// Vary velocity component Z
    VelocityZ,
    /// Maneuver's in-plane alpha
    MnvrAlpha,
    /// Maneuver's in-plane alpha-dot
    MnvrAlphaDot,
    /// Maneuver's in-plane alpha double-dot
    MnvrAlphaDDot,
    /// Maneuver's out-of-plane beta
    MnvrDelta,
    /// Maneuver's out-of-plane beta dot
    MnvrDeltaDot,
    /// Maneuver's out-of-plane beta double-dot
    MnvrDeltaDDot,
    /// Start epoch difference in seconds
    StartEpoch,
    /// Burn duration difference in seconds
    Duration,
    /// End epoch difference in seconds
    EndEpoch,
    /// Thrust direction in X
    ThrustX,
    /// Thrust direction in Y
    ThrustY,
    /// Thrust direction in Z
    ThrustZ,
    /// Thrust level during the burn.
    ThrustLevel,
    /// Thrust direction rate in X
    ThrustRateX,
    /// Thrust direction rate in Y
    ThrustRateY,
    /// Thrust direction rate in Z
    ThrustRateZ,
    /// Thrust direction acceleration in X
    ThrustAccelX,
    /// Thrust direction acceleration in Y
    ThrustAccelY,
    /// Thrust direction acceleration in Z
    ThrustAccelZ,
}

impl Vary {
    #[allow(clippy::nonminimal_bool)]
    pub fn is_finite_burn(&self) -> bool {
        *self == Self::MnvrAlpha
            || *self == Self::MnvrAlphaDDot
            || *self == Self::MnvrAlphaDDot
            || *self == Self::MnvrDelta
            || *self == Self::MnvrDeltaDDot
            || *self == Self::MnvrDeltaDDot
            || *self == Self::StartEpoch
            || *self == Self::Duration
            || *self == Self::EndEpoch
            || *self == Self::ThrustX
            || *self == Self::ThrustY
            || *self == Self::ThrustZ
            || *self == Self::ThrustLevel
            || *self == Self::ThrustRateX
            || *self == Self::ThrustRateY
            || *self == Self::ThrustRateZ
            || *self == Self::ThrustAccelX
            || *self == Self::ThrustAccelY
            || *self == Self::ThrustAccelZ
    }

    #[allow(clippy::nonminimal_bool)]
    pub fn vec_index(&self) -> usize {
        match self {
            Self::PositionX | Self::ThrustX | Self::MnvrAlphaDDot | Self::MnvrDeltaDDot => 0,
            Self::PositionY | Self::ThrustY | Self::MnvrAlphaDot | Self::MnvrDeltaDot => 1,
            Self::PositionZ | Self::ThrustZ | Self::MnvrAlpha | Self::MnvrDelta => 2,
            Self::VelocityX | Self::ThrustRateX => 3,
            Self::VelocityY | Self::ThrustRateY => 4,
            Self::VelocityZ | Self::ThrustRateZ => 5,
            Self::StartEpoch | Self::ThrustAccelX => 6,
            Self::Duration | Self::EndEpoch | Self::ThrustAccelY => 7,
            Self::ThrustAccelZ => 8,
            _ => unreachable!(),
        }
    }
}

#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Variable {
    /// The component that will be varied in the targeter
    pub component: Vary,
    /// The perturbation for the finite differencing algorithm
    pub perturbation: f64,
    /// The initial guess of this variable
    pub init_guess: f64,
    /// The maximum step this variable may have between each iteration
    pub max_step: f64,
    /// The absolute maximum value this parameter can ever have
    pub max_value: f64,
    /// The absolute minimum value this parameter can ever have
    pub min_value: f64,
    /// The frame in which this variable should be applied, must be either a local frame or inertial
    pub frame: Option<Frame>,
}

impl Variable {
    /// Returns whether the configuration of this variable is valid
    #[allow(clippy::result_large_err)]
    pub fn valid(&self) -> Result<(), TargetingError> {
        if self.max_step < 0.0 {
            let msg = format!(
                "{:?}: max step is negative: {}",
                self.component, self.max_step
            );
            error!("{}", msg);
            return Err(TargetingError::VariableError { msg });
        }
        if self.max_value < 0.0 {
            let msg = format!(
                "{:?}: max value is negative: {}",
                self.component, self.max_value
            );
            error!("{}", msg);
            return Err(TargetingError::VariableError { msg });
        }
        if self.min_value > self.max_value {
            let msg = format!(
                "{:?}: min value is greater than max value: {} > {}",
                self.component, self.min_value, self.max_value
            );
            error!("{}", msg);
            return Err(TargetingError::VariableError { msg });
        }
        Ok(())
    }

    pub fn with_initial_guess(mut self, guess: f64) -> Self {
        self.init_guess = guess;
        self
    }

    pub fn with_pert(mut self, pert: f64) -> Self {
        self.perturbation = pert;
        self
    }

    pub fn with_min(mut self, min_val: f64) -> Self {
        self.min_value = min_val;
        self
    }

    pub fn with_max(mut self, max_val: f64) -> Self {
        self.max_value = max_val;
        self
    }

    /// Ensure that `val` is within the variable bounds
    pub fn apply_bounds(&self, val: f64) -> f64 {
        if val > self.max_value {
            self.max_value
        } else if val < self.min_value {
            self.min_value
        } else {
            val
        }
    }

    /// Ensure that `val` is within the variable bounds
    pub fn ensure_bounds(&self, val: &mut f64) {
        *val = self.check_bounds(*val).0;
    }

    /// Returns the input value unless it is out of bounds, then it returns the bound, and whether the input value was OK
    pub fn check_bounds(&self, val: f64) -> (f64, bool) {
        if val > self.max_value {
            (self.max_value, false)
        } else if val < self.min_value {
            (self.min_value, false)
        } else {
            (val, true)
        }
    }
}

impl Default for Variable {
    fn default() -> Self {
        Self {
            component: Vary::VelocityX,
            perturbation: 0.0001,
            init_guess: 0.0,
            max_step: 0.2,
            max_value: 5.0,
            min_value: -5.0,
            frame: None,
        }
    }
}

impl From<Vary> for Variable {
    fn from(vary: Vary) -> Self {
        match vary {
            Vary::PositionX
            | Vary::PositionY
            | Vary::PositionZ
            | Vary::VelocityX
            | Vary::VelocityY
            | Vary::VelocityZ => Self {
                component: vary,
                ..Default::default()
            },
            Vary::MnvrAlpha | Vary::MnvrAlphaDot | Vary::MnvrAlphaDDot => Self {
                component: vary,
                perturbation: 0.1 * PI,
                max_step: FRAC_PI_8,
                max_value: PI,
                min_value: 0.0,
                ..Default::default()
            },
            Vary::MnvrDelta | Vary::MnvrDeltaDot | Vary::MnvrDeltaDDot => Self {
                component: vary,
                perturbation: 0.1 * PI,
                max_step: FRAC_PI_8,
                max_value: FRAC_PI_2,
                min_value: -FRAC_PI_2,
                ..Default::default()
            },
            Vary::StartEpoch | Vary::EndEpoch => Self {
                component: vary,
                perturbation: 0.5,
                max_step: 60.0,
                max_value: 600.0,
                min_value: -600.0,
                ..Default::default()
            },
            Vary::Duration => Self {
                component: vary,
                perturbation: 1.0,
                max_step: 60.0,
                max_value: 600.0,
                min_value: 0.0,
                ..Default::default()
            },
            Vary::ThrustX | Vary::ThrustY | Vary::ThrustZ => Self {
                component: vary,
                max_value: 1.0,
                min_value: -1.0,
                ..Default::default()
            },
            Vary::ThrustRateX | Vary::ThrustRateY | Vary::ThrustRateZ => Self {
                component: vary,
                perturbation: 1e-10,
                max_value: 1.0,
                min_value: -1.0,
                ..Default::default()
            },
            Vary::ThrustAccelX | Vary::ThrustAccelY | Vary::ThrustAccelZ => Self {
                component: vary,
                perturbation: 1e-15,
                max_value: 1.0,
                min_value: -1.0,
                ..Default::default()
            },
            Vary::ThrustLevel => Self {
                component: vary,
                perturbation: -0.0001, // Perturb the thrust by -1%
                min_value: 0.0001,
                max_value: 1.0,
                init_guess: 1.0,
                ..Default::default()
            },
        }
    }
}

impl fmt::Display for Variable {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}{:?} = {} ± {:} ∈ [{}; {}]",
            match self.frame {
                Some(f) => format!("{f}"),
                None => "".to_string(),
            },
            self.component,
            self.init_guess,
            self.perturbation,
            self.min_value,
            self.max_value
        )
    }
}