pub struct Traj<S: Interpolatable>{
pub name: Option<String>,
pub states: Vec<S>,
}
Expand description
Store a trajectory of any State.
Fields§
§name: Option<String>
Optionally name this trajectory
states: Vec<S>
We use a vector because we know that the states are produced in a chronological manner (the direction does not matter).
Implementations§
Source§impl Traj<Spacecraft>
impl Traj<Spacecraft>
Sourcepub fn from_bsp(
target_frame: Frame,
observer_frame: Frame,
almanac: Arc<Almanac>,
sc_template: Spacecraft,
step: Duration,
start_epoch: Option<Epoch>,
end_epoch: Option<Epoch>,
ab_corr: Option<Aberration>,
name: Option<String>,
) -> Result<Self, AlmanacError>
pub fn from_bsp( target_frame: Frame, observer_frame: Frame, almanac: Arc<Almanac>, sc_template: Spacecraft, step: Duration, start_epoch: Option<Epoch>, end_epoch: Option<Epoch>, ab_corr: Option<Aberration>, name: Option<String>, ) -> Result<Self, AlmanacError>
Builds a new trajectory built from the SPICE BSP (SPK) file loaded in the provided Almanac, provided the start and stop epochs.
If the start and stop epochs are not provided, then the full domain of the trajectory will be used.
Examples found in repository?
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
fn main() -> Result<(), Box<dyn Error>> {
pel::init();
// ====================== //
// === ALMANAC SET UP === //
// ====================== //
// Dynamics models require planetary constants and ephemerides to be defined.
// Let's start by grabbing those by using ANISE's MetaAlmanac.
let data_folder: PathBuf = [env!("CARGO_MANIFEST_DIR"), "examples", "04_lro_od"]
.iter()
.collect();
let meta = data_folder.join("lro-dynamics.dhall");
// Load this ephem in the general Almanac we're using for this analysis.
let mut almanac = MetaAlmanac::new(meta.to_string_lossy().to_string())
.map_err(Box::new)?
.process(true)
.map_err(Box::new)?;
let mut moon_pc = almanac.planetary_data.get_by_id(MOON)?;
moon_pc.mu_km3_s2 = 4902.74987;
almanac.planetary_data.set_by_id(MOON, moon_pc)?;
let mut earth_pc = almanac.planetary_data.get_by_id(EARTH)?;
earth_pc.mu_km3_s2 = 398600.436;
almanac.planetary_data.set_by_id(EARTH, earth_pc)?;
// Save this new kernel for reuse.
// In an operational context, this would be part of the "Lock" process, and should not change throughout the mission.
almanac
.planetary_data
.save_as(&data_folder.join("lro-specific.pca"), true)?;
// Lock the almanac (an Arc is a read only structure).
let almanac = Arc::new(almanac);
// Orbit determination requires a Trajectory structure, which can be saved as parquet file.
// In our case, the trajectory comes from the BSP file, so we need to build a Trajectory from the almanac directly.
// To query the Almanac, we need to build the LRO frame in the J2000 orientation in our case.
// Inspecting the LRO BSP in the ANISE GUI shows us that NASA has assigned ID -85 to LRO.
let lro_frame = Frame::from_ephem_j2000(-85);
// To build the trajectory we need to provide a spacecraft template.
let sc_template = Spacecraft::builder()
.dry_mass_kg(1018.0) // Launch masses
.fuel_mass_kg(900.0)
.srp(SrpConfig {
// SRP configuration is arbitrary, but we will be estimating it anyway.
area_m2: 3.9 * 2.7,
cr: 0.96,
})
.orbit(Orbit::zero(MOON_J2000)) // Setting a zero orbit here because it's just a template
.build();
// Now we can build the trajectory from the BSP file.
// We'll arbitrarily set the tracking arc to 48 hours with a one minute time step.
let traj_as_flown = Traj::from_bsp(
lro_frame,
MOON_J2000,
almanac.clone(),
sc_template,
5.seconds(),
Some(Epoch::from_str("2024-01-01 00:00:00 UTC")?),
Some(Epoch::from_str("2024-01-02 00:00:00 UTC")?),
Aberration::LT,
Some("LRO".to_string()),
)?;
println!("{traj_as_flown}");
// ====================== //
// === MODEL MATCHING === //
// ====================== //
// Set up the spacecraft dynamics.
// Specify that the orbital dynamics must account for the graviational pull of the Earth and the Sun.
// The gravity of the Moon will also be accounted for since the spaceraft in a lunar orbit.
let mut orbital_dyn = OrbitalDynamics::point_masses(vec![EARTH, SUN, JUPITER_BARYCENTER]);
// We want to include the spherical harmonics, so let's download the gravitational data from the Nyx Cloud.
// We're using the GRAIL JGGRX model.
let mut jggrx_meta = MetaFile {
uri: "http://public-data.nyxspace.com/nyx/models/Luna_jggrx_1500e_sha.tab.gz".to_string(),
crc32: Some(0x6bcacda8), // Specifying the CRC32 avoids redownloading it if it's cached.
};
// And let's download it if we don't have it yet.
jggrx_meta.process(true)?;
// Build the spherical harmonics.
// The harmonics must be computed in the body fixed frame.
// We're using the long term prediction of the Moon principal axes frame.
let moon_pa_frame = MOON_PA_FRAME.with_orient(31008);
// let moon_pa_frame = IAU_MOON_FRAME;
let sph_harmonics = Harmonics::from_stor(
almanac.frame_from_uid(moon_pa_frame)?,
HarmonicsMem::from_shadr(&jggrx_meta.uri, 80, 80, true)?,
);
// Include the spherical harmonics into the orbital dynamics.
orbital_dyn.accel_models.push(sph_harmonics);
// We define the solar radiation pressure, using the default solar flux and accounting only
// for the eclipsing caused by the Earth and Moon.
// Note that by default, enabling the SolarPressure model will also enable the estimation of the coefficient of reflectivity.
let srp_dyn = SolarPressure::new(vec![EARTH_J2000, MOON_J2000], almanac.clone())?;
// Finalize setting up the dynamics, specifying the force models (orbital_dyn) separately from the
// acceleration models (SRP in this case). Use `from_models` to specify multiple accel models.
let dynamics = SpacecraftDynamics::from_model(orbital_dyn, srp_dyn);
println!("{dynamics}");
// Now we can build the propagator.
let setup = Propagator::default_dp78(dynamics.clone());
// For reference, let's build the trajectory with Nyx's models from that LRO state.
let (sim_final, traj_as_sim) = setup
.with(*traj_as_flown.first(), almanac.clone())
.until_epoch_with_traj(traj_as_flown.last().epoch())?;
println!("SIM INIT: {:x}", traj_as_flown.first());
println!("SIM FINAL: {sim_final:x}");
// Compute RIC difference between SIM and LRO ephem
let sim_lro_delta = sim_final
.orbit
.ric_difference(&traj_as_flown.last().orbit)?;
println!("{traj_as_sim}");
println!(
"SIM v LRO - RIC Position (m): {:.3}",
sim_lro_delta.radius_km * 1e3
);
println!(
"SIM v LRO - RIC Velocity (m/s): {:.3}",
sim_lro_delta.velocity_km_s * 1e3
);
traj_as_sim.ric_diff_to_parquet(
&traj_as_flown,
"./04_lro_sim_truth_error.parquet",
ExportCfg::default(),
)?;
// ==================== //
// === OD SIMULATOR === //
// ==================== //
// After quite some time trying to exactly match the model, we still end up with an oscillatory difference on the order of 150 meters between the propagated state
// and the truth LRO state.
// Therefore, we will actually run an estimation from a dispersed LRO state.
// The sc_seed is the true LRO state from the BSP.
let sc_seed = *traj_as_flown.first();
// Load the Deep Space Network ground stations.
// Nyx allows you to build these at runtime but it's pretty static so we can just load them from YAML.
let ground_station_file: PathBuf = [
env!("CARGO_MANIFEST_DIR"),
"examples",
"04_lro_od",
"dsn-network.yaml",
]
.iter()
.collect();
let devices = GroundStation::load_named(ground_station_file)?;
// Typical OD software requires that you specify your own tracking schedule or you'll have overlapping measurements.
// Nyx can build a tracking schedule for you based on the first station with access.
let trkconfg_yaml: PathBuf = [
env!("CARGO_MANIFEST_DIR"),
"examples",
"04_lro_od",
"tracking-cfg.yaml",
]
.iter()
.collect();
let configs: BTreeMap<String, TrkConfig> = TrkConfig::load_named(trkconfg_yaml)?;
// Build the tracking arc simulation to generate a "standard measurement".
let mut trk = TrackingArcSim::<Spacecraft, GroundStation>::new(
devices.clone(),
traj_as_flown.clone(),
configs,
)?;
trk.build_schedule(almanac.clone())?;
let arc = trk.generate_measurements(almanac.clone())?;
// Save the simulated tracking data
arc.to_parquet_simple("./04_lro_simulated_tracking.parquet")?;
// We'll note that in our case, we have continuous coverage of LRO when the vehicle is not behind the Moon.
println!("{arc}");
// Now that we have simulated measurements, we'll run the orbit determination.
// ===================== //
// === OD ESTIMATION === //
// ===================== //
let sc = SpacecraftUncertainty::builder()
.nominal(sc_seed)
.frame(LocalFrame::RIC)
.x_km(0.5)
.y_km(0.5)
.z_km(0.5)
.vx_km_s(5e-3)
.vy_km_s(5e-3)
.vz_km_s(5e-3)
.build();
// Build the filter initial estimate, which we will reuse in the filter.
let initial_estimate = sc.to_estimate()?;
println!("== FILTER STATE ==\n{sc_seed:x}\n{initial_estimate}");
let kf = KF::new(
// Increase the initial covariance to account for larger deviation.
initial_estimate,
// Until https://github.com/nyx-space/nyx/issues/351, we need to specify the SNC in the acceleration of the Moon J2000 frame.
SNC3::from_diagonal(10 * Unit::Minute, &[1e-11, 1e-11, 1e-11]),
);
// We'll set up the OD process to reject measurements whose residuals are mover than 4 sigmas away from what we expect.
let mut odp = SpacecraftODProcess::ckf(
setup.with(initial_estimate.state().with_stm(), almanac.clone()),
kf,
devices,
Some(ResidRejectCrit::default()),
almanac.clone(),
);
odp.process_arc(&arc)?;
let ric_err = traj_as_flown
.at(odp.estimates.last().unwrap().epoch())?
.orbit
.ric_difference(&odp.estimates.last().unwrap().orbital_state())?;
println!("== RIC at end ==");
println!("RIC Position (m): {}", ric_err.radius_km * 1e3);
println!("RIC Velocity (m/s): {}", ric_err.velocity_km_s * 1e3);
odp.to_parquet(&arc, "./04_lro_od_results.parquet", ExportCfg::default())?;
// In our case, we have the truth trajectory from NASA.
// So we can compute the RIC state difference between the real LRO ephem and what we've just estimated.
// Export the OD trajectory first.
let od_trajectory = odp.to_traj()?;
// Build the RIC difference.
od_trajectory.ric_diff_to_parquet(
&traj_as_flown,
"./04_lro_od_truth_error.parquet",
ExportCfg::default(),
)?;
Ok(())
}
Sourcepub fn to_frame(
&self,
new_frame: Frame,
almanac: Arc<Almanac>,
) -> Result<Self, NyxError>
pub fn to_frame( &self, new_frame: Frame, almanac: Arc<Almanac>, ) -> Result<Self, NyxError>
Allows converting the source trajectory into the (almost) equivalent trajectory in another frame
Sourcepub fn to_parquet_with_step<P: AsRef<Path>>(
&self,
path: P,
step: Duration,
almanac: Arc<Almanac>,
) -> Result<(), Box<dyn Error>>
pub fn to_parquet_with_step<P: AsRef<Path>>( &self, path: P, step: Duration, almanac: Arc<Almanac>, ) -> Result<(), Box<dyn Error>>
A shortcut to to_parquet_with_cfg
Sourcepub fn to_groundtrack_parquet<P: AsRef<Path>>(
&self,
path: P,
body_fixed_frame: Frame,
events: Option<Vec<&dyn EventEvaluator<Spacecraft>>>,
metadata: Option<HashMap<String, String>>,
almanac: Arc<Almanac>,
) -> Result<PathBuf, Box<dyn Error>>
pub fn to_groundtrack_parquet<P: AsRef<Path>>( &self, path: P, body_fixed_frame: Frame, events: Option<Vec<&dyn EventEvaluator<Spacecraft>>>, metadata: Option<HashMap<String, String>>, almanac: Arc<Almanac>, ) -> Result<PathBuf, Box<dyn Error>>
Exports this trajectory to the provided filename in parquet format with only the epoch, the geodetic latitude, longitude, and height at one state per minute. Must provide a body fixed frame to correctly compute the latitude and longitude.
Sourcepub fn from_oem_file<P: AsRef<Path>>(
path: P,
tpl_option: Option<Spacecraft>,
) -> Result<Self, NyxError>
pub fn from_oem_file<P: AsRef<Path>>( path: P, tpl_option: Option<Spacecraft>, ) -> Result<Self, NyxError>
Initialize a new spacecraft trajectory from the path to a CCSDS OEM file.
CCSDS OEM only contains the orbit information but Nyx builds spacecraft trajectories. If not spacecraft template is provided, then a default massless spacecraft will be built.
Sourcepub fn to_oem_file<P: AsRef<Path>>(
&self,
path: P,
cfg: ExportCfg,
) -> Result<PathBuf, NyxError>
pub fn to_oem_file<P: AsRef<Path>>( &self, path: P, cfg: ExportCfg, ) -> Result<PathBuf, NyxError>
Examples found in repository?
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
fn main() -> Result<(), Box<dyn Error>> {
pel::init();
// Dynamics models require planetary constants and ephemerides to be defined.
// Let's start by grabbing those by using ANISE's latest MetaAlmanac.
// This will automatically download the DE440s planetary ephemeris,
// the daily-updated Earth Orientation Parameters, the high fidelity Moon orientation
// parameters (for the Moon Mean Earth and Moon Principal Axes frames), and the PCK11
// planetary constants kernels.
// For details, refer to https://github.com/nyx-space/anise/blob/master/data/latest.dhall.
// Note that we place the Almanac into an Arc so we can clone it cheaply and provide read-only
// references to many functions.
let almanac = Arc::new(MetaAlmanac::latest().map_err(Box::new)?);
// Define the orbit epoch
let epoch = Epoch::from_gregorian_utc_hms(2024, 2, 29, 12, 13, 14);
// Define the orbit.
// First we need to fetch the Earth J2000 from information from the Almanac.
// This allows the frame to include the gravitational parameters and the shape of the Earth,
// defined as a tri-axial ellipoid. Note that this shape can be changed manually or in the Almanac
// by loading a different set of planetary constants.
let earth_j2000 = almanac.frame_from_uid(EARTH_J2000)?;
let orbit =
Orbit::try_keplerian_altitude(300.0, 0.015, 68.5, 65.2, 75.0, 0.0, epoch, earth_j2000)?;
// Print in in Keplerian form.
println!("{orbit:x}");
// There are two ways to propagate an orbit. We can make a quick approximation assuming only two-body
// motion. This is a useful first order approximation but it isn't used in real-world applications.
// This approach is a feature of ANISE.
let future_orbit_tb = orbit.at_epoch(epoch + Unit::Day * 3)?;
println!("{future_orbit_tb:x}");
// Two body propagation relies solely on Kepler's laws, so only the true anomaly will change.
println!(
"SMA changed by {:.3e} km",
orbit.sma_km()? - future_orbit_tb.sma_km()?
);
println!(
"ECC changed by {:.3e}",
orbit.ecc()? - future_orbit_tb.ecc()?
);
println!(
"INC changed by {:.3e} deg",
orbit.inc_deg()? - future_orbit_tb.inc_deg()?
);
println!(
"RAAN changed by {:.3e} deg",
orbit.raan_deg()? - future_orbit_tb.raan_deg()?
);
println!(
"AOP changed by {:.3e} deg",
orbit.aop_deg()? - future_orbit_tb.aop_deg()?
);
println!(
"TA changed by {:.3} deg",
orbit.ta_deg()? - future_orbit_tb.ta_deg()?
);
// Nyx is used for high fidelity propagation, not Keplerian propagation as above.
// Nyx only propagates Spacecraft at the moment, which allows it to account for acceleration
// models such as solar radiation pressure.
// Let's build a cubesat sized spacecraft, with an SRP area of 10 cm^2 and a mass of 9.6 kg.
let sc = Spacecraft::builder()
.orbit(orbit)
.dry_mass_kg(9.60)
.srp(SrpConfig {
area_m2: 10e-4,
cr: 1.1,
})
.build();
println!("{sc:x}");
// Set up the spacecraft dynamics.
// Specify that the orbital dynamics must account for the graviational pull of the Moon and the Sun.
// The gravity of the Earth will also be accounted for since the spaceraft in an Earth orbit.
let mut orbital_dyn = OrbitalDynamics::point_masses(vec![MOON, SUN]);
// We want to include the spherical harmonics, so let's download the gravitational data from the Nyx Cloud.
// We're using the JGM3 model here, which is the default in GMAT.
let mut jgm3_meta = MetaFile {
uri: "http://public-data.nyxspace.com/nyx/models/JGM3.cof.gz".to_string(),
crc32: Some(0xF446F027), // Specifying the CRC32 avoids redownloading it if it's cached.
};
// And let's download it if we don't have it yet.
jgm3_meta.process(true)?;
// Build the spherical harmonics.
// The harmonics must be computed in the body fixed frame.
// We're using the long term prediction of the Earth centered Earth fixed frame, IAU Earth.
let harmonics_21x21 = Harmonics::from_stor(
almanac.frame_from_uid(IAU_EARTH_FRAME)?,
HarmonicsMem::from_cof(&jgm3_meta.uri, 21, 21, true).unwrap(),
);
// Include the spherical harmonics into the orbital dynamics.
orbital_dyn.accel_models.push(harmonics_21x21);
// We define the solar radiation pressure, using the default solar flux and accounting only
// for the eclipsing caused by the Earth.
let srp_dyn = SolarPressure::default(EARTH_J2000, almanac.clone())?;
// Finalize setting up the dynamics, specifying the force models (orbital_dyn) separately from the
// acceleration models (SRP in this case). Use `from_models` to specify multiple accel models.
let dynamics = SpacecraftDynamics::from_model(orbital_dyn, srp_dyn);
println!("{dynamics}");
// Finally, let's propagate this orbit to the same epoch as above.
// The first returned value is the spacecraft state at the final epoch.
// The second value is the full trajectory where the step size is variable step used by the propagator.
let (future_sc, trajectory) = Propagator::default(dynamics)
.with(sc, almanac.clone())
.until_epoch_with_traj(future_orbit_tb.epoch)?;
println!("=== High fidelity propagation ===");
println!(
"SMA changed by {:.3} km",
orbit.sma_km()? - future_sc.orbit.sma_km()?
);
println!(
"ECC changed by {:.6}",
orbit.ecc()? - future_sc.orbit.ecc()?
);
println!(
"INC changed by {:.3e} deg",
orbit.inc_deg()? - future_sc.orbit.inc_deg()?
);
println!(
"RAAN changed by {:.3} deg",
orbit.raan_deg()? - future_sc.orbit.raan_deg()?
);
println!(
"AOP changed by {:.3} deg",
orbit.aop_deg()? - future_sc.orbit.aop_deg()?
);
println!(
"TA changed by {:.3} deg",
orbit.ta_deg()? - future_sc.orbit.ta_deg()?
);
// We also have access to the full trajectory throughout the propagation.
println!("{trajectory}");
// With the trajectory, let's build a few data products.
// 1. Export the trajectory as a CCSDS OEM version 2.0 file and as a parquet file, which includes the Keplerian orbital elements.
trajectory.to_oem_file(
"./01_cubesat_hf_prop.oem",
ExportCfg::builder().step(Unit::Minute * 2).build(),
)?;
trajectory.to_parquet_with_cfg(
"./01_cubesat_hf_prop.parquet",
ExportCfg::builder().step(Unit::Minute * 2).build(),
almanac.clone(),
)?;
// 2. Compare the difference in the radial-intrack-crosstrack frame between the high fidelity
// and Keplerian propagation. The RIC frame is commonly used to compute the difference in position
// and velocity of different spacecraft.
// 3. Compute the azimuth, elevation, range, and range-rate data of that spacecraft as seen from Boulder, CO, USA.
let boulder_station = GroundStation::from_point(
"Boulder, CO, USA".to_string(),
40.014984, // latitude in degrees
-105.270546, // longitude in degrees
1.6550, // altitude in kilometers
almanac.frame_from_uid(IAU_EARTH_FRAME)?,
);
// We iterate over the trajectory, grabbing a state every two minutes.
let mut offset_s = vec![];
let mut epoch_str = vec![];
let mut ric_x_km = vec![];
let mut ric_y_km = vec![];
let mut ric_z_km = vec![];
let mut ric_vx_km_s = vec![];
let mut ric_vy_km_s = vec![];
let mut ric_vz_km_s = vec![];
let mut azimuth_deg = vec![];
let mut elevation_deg = vec![];
let mut range_km = vec![];
let mut range_rate_km_s = vec![];
for state in trajectory.every(Unit::Minute * 2) {
// Try to compute the Keplerian/two body state just in time.
// This method occasionally fails to converge on an appropriate true anomaly
// from the mean anomaly. If that happens, we just skip this state.
// The high fidelity and Keplerian states diverge continuously, and we're curious
// about the divergence in this quick analysis.
let this_epoch = state.epoch();
match orbit.at_epoch(this_epoch) {
Ok(tb_then) => {
offset_s.push((this_epoch - orbit.epoch).to_seconds());
epoch_str.push(format!("{this_epoch}"));
// Compute the two body state just in time.
let ric = state.orbit.ric_difference(&tb_then)?;
ric_x_km.push(ric.radius_km.x);
ric_y_km.push(ric.radius_km.y);
ric_z_km.push(ric.radius_km.z);
ric_vx_km_s.push(ric.velocity_km_s.x);
ric_vy_km_s.push(ric.velocity_km_s.y);
ric_vz_km_s.push(ric.velocity_km_s.z);
// Compute the AER data for each state.
let aer = almanac.azimuth_elevation_range_sez(
state.orbit,
boulder_station.to_orbit(this_epoch, &almanac)?,
None,
None,
)?;
azimuth_deg.push(aer.azimuth_deg);
elevation_deg.push(aer.elevation_deg);
range_km.push(aer.range_km);
range_rate_km_s.push(aer.range_rate_km_s);
}
Err(e) => warn!("{} {e}", state.epoch()),
};
}
// Build the data frames.
let ric_df = df!(
"Offset (s)" => offset_s.clone(),
"Epoch" => epoch_str.clone(),
"RIC X (km)" => ric_x_km,
"RIC Y (km)" => ric_y_km,
"RIC Z (km)" => ric_z_km,
"RIC VX (km/s)" => ric_vx_km_s,
"RIC VY (km/s)" => ric_vy_km_s,
"RIC VZ (km/s)" => ric_vz_km_s,
)?;
println!("RIC difference at start\n{}", ric_df.head(Some(10)));
println!("RIC difference at end\n{}", ric_df.tail(Some(10)));
let aer_df = df!(
"Offset (s)" => offset_s.clone(),
"Epoch" => epoch_str.clone(),
"azimuth (deg)" => azimuth_deg,
"elevation (deg)" => elevation_deg,
"range (km)" => range_km,
"range rate (km/s)" => range_rate_km_s,
)?;
// Finally, let's see when the spacecraft is visible, assuming 15 degrees minimum elevation.
let mask = aer_df.column("elevation (deg)")?.gt(15.0)?;
let cubesat_visible = aer_df.filter(&mask)?;
println!("{cubesat_visible}");
Ok(())
}
Source§impl<S: Interpolatable> Traj<S>
impl<S: Interpolatable> Traj<S>
pub fn new() -> Self
Sourcepub fn at(&self, epoch: Epoch) -> Result<S, TrajError>
pub fn at(&self, epoch: Epoch) -> Result<S, TrajError>
Evaluate the trajectory at this specific epoch.
Examples found in repository?
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
fn main() -> Result<(), Box<dyn Error>> {
pel::init();
// ====================== //
// === ALMANAC SET UP === //
// ====================== //
// Dynamics models require planetary constants and ephemerides to be defined.
// Let's start by grabbing those by using ANISE's MetaAlmanac.
let data_folder: PathBuf = [env!("CARGO_MANIFEST_DIR"), "examples", "04_lro_od"]
.iter()
.collect();
let meta = data_folder.join("lro-dynamics.dhall");
// Load this ephem in the general Almanac we're using for this analysis.
let mut almanac = MetaAlmanac::new(meta.to_string_lossy().to_string())
.map_err(Box::new)?
.process(true)
.map_err(Box::new)?;
let mut moon_pc = almanac.planetary_data.get_by_id(MOON)?;
moon_pc.mu_km3_s2 = 4902.74987;
almanac.planetary_data.set_by_id(MOON, moon_pc)?;
let mut earth_pc = almanac.planetary_data.get_by_id(EARTH)?;
earth_pc.mu_km3_s2 = 398600.436;
almanac.planetary_data.set_by_id(EARTH, earth_pc)?;
// Save this new kernel for reuse.
// In an operational context, this would be part of the "Lock" process, and should not change throughout the mission.
almanac
.planetary_data
.save_as(&data_folder.join("lro-specific.pca"), true)?;
// Lock the almanac (an Arc is a read only structure).
let almanac = Arc::new(almanac);
// Orbit determination requires a Trajectory structure, which can be saved as parquet file.
// In our case, the trajectory comes from the BSP file, so we need to build a Trajectory from the almanac directly.
// To query the Almanac, we need to build the LRO frame in the J2000 orientation in our case.
// Inspecting the LRO BSP in the ANISE GUI shows us that NASA has assigned ID -85 to LRO.
let lro_frame = Frame::from_ephem_j2000(-85);
// To build the trajectory we need to provide a spacecraft template.
let sc_template = Spacecraft::builder()
.dry_mass_kg(1018.0) // Launch masses
.fuel_mass_kg(900.0)
.srp(SrpConfig {
// SRP configuration is arbitrary, but we will be estimating it anyway.
area_m2: 3.9 * 2.7,
cr: 0.96,
})
.orbit(Orbit::zero(MOON_J2000)) // Setting a zero orbit here because it's just a template
.build();
// Now we can build the trajectory from the BSP file.
// We'll arbitrarily set the tracking arc to 48 hours with a one minute time step.
let traj_as_flown = Traj::from_bsp(
lro_frame,
MOON_J2000,
almanac.clone(),
sc_template,
5.seconds(),
Some(Epoch::from_str("2024-01-01 00:00:00 UTC")?),
Some(Epoch::from_str("2024-01-02 00:00:00 UTC")?),
Aberration::LT,
Some("LRO".to_string()),
)?;
println!("{traj_as_flown}");
// ====================== //
// === MODEL MATCHING === //
// ====================== //
// Set up the spacecraft dynamics.
// Specify that the orbital dynamics must account for the graviational pull of the Earth and the Sun.
// The gravity of the Moon will also be accounted for since the spaceraft in a lunar orbit.
let mut orbital_dyn = OrbitalDynamics::point_masses(vec![EARTH, SUN, JUPITER_BARYCENTER]);
// We want to include the spherical harmonics, so let's download the gravitational data from the Nyx Cloud.
// We're using the GRAIL JGGRX model.
let mut jggrx_meta = MetaFile {
uri: "http://public-data.nyxspace.com/nyx/models/Luna_jggrx_1500e_sha.tab.gz".to_string(),
crc32: Some(0x6bcacda8), // Specifying the CRC32 avoids redownloading it if it's cached.
};
// And let's download it if we don't have it yet.
jggrx_meta.process(true)?;
// Build the spherical harmonics.
// The harmonics must be computed in the body fixed frame.
// We're using the long term prediction of the Moon principal axes frame.
let moon_pa_frame = MOON_PA_FRAME.with_orient(31008);
// let moon_pa_frame = IAU_MOON_FRAME;
let sph_harmonics = Harmonics::from_stor(
almanac.frame_from_uid(moon_pa_frame)?,
HarmonicsMem::from_shadr(&jggrx_meta.uri, 80, 80, true)?,
);
// Include the spherical harmonics into the orbital dynamics.
orbital_dyn.accel_models.push(sph_harmonics);
// We define the solar radiation pressure, using the default solar flux and accounting only
// for the eclipsing caused by the Earth and Moon.
// Note that by default, enabling the SolarPressure model will also enable the estimation of the coefficient of reflectivity.
let srp_dyn = SolarPressure::new(vec![EARTH_J2000, MOON_J2000], almanac.clone())?;
// Finalize setting up the dynamics, specifying the force models (orbital_dyn) separately from the
// acceleration models (SRP in this case). Use `from_models` to specify multiple accel models.
let dynamics = SpacecraftDynamics::from_model(orbital_dyn, srp_dyn);
println!("{dynamics}");
// Now we can build the propagator.
let setup = Propagator::default_dp78(dynamics.clone());
// For reference, let's build the trajectory with Nyx's models from that LRO state.
let (sim_final, traj_as_sim) = setup
.with(*traj_as_flown.first(), almanac.clone())
.until_epoch_with_traj(traj_as_flown.last().epoch())?;
println!("SIM INIT: {:x}", traj_as_flown.first());
println!("SIM FINAL: {sim_final:x}");
// Compute RIC difference between SIM and LRO ephem
let sim_lro_delta = sim_final
.orbit
.ric_difference(&traj_as_flown.last().orbit)?;
println!("{traj_as_sim}");
println!(
"SIM v LRO - RIC Position (m): {:.3}",
sim_lro_delta.radius_km * 1e3
);
println!(
"SIM v LRO - RIC Velocity (m/s): {:.3}",
sim_lro_delta.velocity_km_s * 1e3
);
traj_as_sim.ric_diff_to_parquet(
&traj_as_flown,
"./04_lro_sim_truth_error.parquet",
ExportCfg::default(),
)?;
// ==================== //
// === OD SIMULATOR === //
// ==================== //
// After quite some time trying to exactly match the model, we still end up with an oscillatory difference on the order of 150 meters between the propagated state
// and the truth LRO state.
// Therefore, we will actually run an estimation from a dispersed LRO state.
// The sc_seed is the true LRO state from the BSP.
let sc_seed = *traj_as_flown.first();
// Load the Deep Space Network ground stations.
// Nyx allows you to build these at runtime but it's pretty static so we can just load them from YAML.
let ground_station_file: PathBuf = [
env!("CARGO_MANIFEST_DIR"),
"examples",
"04_lro_od",
"dsn-network.yaml",
]
.iter()
.collect();
let devices = GroundStation::load_named(ground_station_file)?;
// Typical OD software requires that you specify your own tracking schedule or you'll have overlapping measurements.
// Nyx can build a tracking schedule for you based on the first station with access.
let trkconfg_yaml: PathBuf = [
env!("CARGO_MANIFEST_DIR"),
"examples",
"04_lro_od",
"tracking-cfg.yaml",
]
.iter()
.collect();
let configs: BTreeMap<String, TrkConfig> = TrkConfig::load_named(trkconfg_yaml)?;
// Build the tracking arc simulation to generate a "standard measurement".
let mut trk = TrackingArcSim::<Spacecraft, GroundStation>::new(
devices.clone(),
traj_as_flown.clone(),
configs,
)?;
trk.build_schedule(almanac.clone())?;
let arc = trk.generate_measurements(almanac.clone())?;
// Save the simulated tracking data
arc.to_parquet_simple("./04_lro_simulated_tracking.parquet")?;
// We'll note that in our case, we have continuous coverage of LRO when the vehicle is not behind the Moon.
println!("{arc}");
// Now that we have simulated measurements, we'll run the orbit determination.
// ===================== //
// === OD ESTIMATION === //
// ===================== //
let sc = SpacecraftUncertainty::builder()
.nominal(sc_seed)
.frame(LocalFrame::RIC)
.x_km(0.5)
.y_km(0.5)
.z_km(0.5)
.vx_km_s(5e-3)
.vy_km_s(5e-3)
.vz_km_s(5e-3)
.build();
// Build the filter initial estimate, which we will reuse in the filter.
let initial_estimate = sc.to_estimate()?;
println!("== FILTER STATE ==\n{sc_seed:x}\n{initial_estimate}");
let kf = KF::new(
// Increase the initial covariance to account for larger deviation.
initial_estimate,
// Until https://github.com/nyx-space/nyx/issues/351, we need to specify the SNC in the acceleration of the Moon J2000 frame.
SNC3::from_diagonal(10 * Unit::Minute, &[1e-11, 1e-11, 1e-11]),
);
// We'll set up the OD process to reject measurements whose residuals are mover than 4 sigmas away from what we expect.
let mut odp = SpacecraftODProcess::ckf(
setup.with(initial_estimate.state().with_stm(), almanac.clone()),
kf,
devices,
Some(ResidRejectCrit::default()),
almanac.clone(),
);
odp.process_arc(&arc)?;
let ric_err = traj_as_flown
.at(odp.estimates.last().unwrap().epoch())?
.orbit
.ric_difference(&odp.estimates.last().unwrap().orbital_state())?;
println!("== RIC at end ==");
println!("RIC Position (m): {}", ric_err.radius_km * 1e3);
println!("RIC Velocity (m/s): {}", ric_err.velocity_km_s * 1e3);
odp.to_parquet(&arc, "./04_lro_od_results.parquet", ExportCfg::default())?;
// In our case, we have the truth trajectory from NASA.
// So we can compute the RIC state difference between the real LRO ephem and what we've just estimated.
// Export the OD trajectory first.
let od_trajectory = odp.to_traj()?;
// Build the RIC difference.
od_trajectory.ric_diff_to_parquet(
&traj_as_flown,
"./04_lro_od_truth_error.parquet",
ExportCfg::default(),
)?;
Ok(())
}
Sourcepub fn first(&self) -> &S
pub fn first(&self) -> &S
Returns the first state in this ephemeris
Examples found in repository?
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
fn main() -> Result<(), Box<dyn Error>> {
pel::init();
// ====================== //
// === ALMANAC SET UP === //
// ====================== //
// Dynamics models require planetary constants and ephemerides to be defined.
// Let's start by grabbing those by using ANISE's MetaAlmanac.
let data_folder: PathBuf = [env!("CARGO_MANIFEST_DIR"), "examples", "04_lro_od"]
.iter()
.collect();
let meta = data_folder.join("lro-dynamics.dhall");
// Load this ephem in the general Almanac we're using for this analysis.
let mut almanac = MetaAlmanac::new(meta.to_string_lossy().to_string())
.map_err(Box::new)?
.process(true)
.map_err(Box::new)?;
let mut moon_pc = almanac.planetary_data.get_by_id(MOON)?;
moon_pc.mu_km3_s2 = 4902.74987;
almanac.planetary_data.set_by_id(MOON, moon_pc)?;
let mut earth_pc = almanac.planetary_data.get_by_id(EARTH)?;
earth_pc.mu_km3_s2 = 398600.436;
almanac.planetary_data.set_by_id(EARTH, earth_pc)?;
// Save this new kernel for reuse.
// In an operational context, this would be part of the "Lock" process, and should not change throughout the mission.
almanac
.planetary_data
.save_as(&data_folder.join("lro-specific.pca"), true)?;
// Lock the almanac (an Arc is a read only structure).
let almanac = Arc::new(almanac);
// Orbit determination requires a Trajectory structure, which can be saved as parquet file.
// In our case, the trajectory comes from the BSP file, so we need to build a Trajectory from the almanac directly.
// To query the Almanac, we need to build the LRO frame in the J2000 orientation in our case.
// Inspecting the LRO BSP in the ANISE GUI shows us that NASA has assigned ID -85 to LRO.
let lro_frame = Frame::from_ephem_j2000(-85);
// To build the trajectory we need to provide a spacecraft template.
let sc_template = Spacecraft::builder()
.dry_mass_kg(1018.0) // Launch masses
.fuel_mass_kg(900.0)
.srp(SrpConfig {
// SRP configuration is arbitrary, but we will be estimating it anyway.
area_m2: 3.9 * 2.7,
cr: 0.96,
})
.orbit(Orbit::zero(MOON_J2000)) // Setting a zero orbit here because it's just a template
.build();
// Now we can build the trajectory from the BSP file.
// We'll arbitrarily set the tracking arc to 48 hours with a one minute time step.
let traj_as_flown = Traj::from_bsp(
lro_frame,
MOON_J2000,
almanac.clone(),
sc_template,
5.seconds(),
Some(Epoch::from_str("2024-01-01 00:00:00 UTC")?),
Some(Epoch::from_str("2024-01-02 00:00:00 UTC")?),
Aberration::LT,
Some("LRO".to_string()),
)?;
println!("{traj_as_flown}");
// ====================== //
// === MODEL MATCHING === //
// ====================== //
// Set up the spacecraft dynamics.
// Specify that the orbital dynamics must account for the graviational pull of the Earth and the Sun.
// The gravity of the Moon will also be accounted for since the spaceraft in a lunar orbit.
let mut orbital_dyn = OrbitalDynamics::point_masses(vec![EARTH, SUN, JUPITER_BARYCENTER]);
// We want to include the spherical harmonics, so let's download the gravitational data from the Nyx Cloud.
// We're using the GRAIL JGGRX model.
let mut jggrx_meta = MetaFile {
uri: "http://public-data.nyxspace.com/nyx/models/Luna_jggrx_1500e_sha.tab.gz".to_string(),
crc32: Some(0x6bcacda8), // Specifying the CRC32 avoids redownloading it if it's cached.
};
// And let's download it if we don't have it yet.
jggrx_meta.process(true)?;
// Build the spherical harmonics.
// The harmonics must be computed in the body fixed frame.
// We're using the long term prediction of the Moon principal axes frame.
let moon_pa_frame = MOON_PA_FRAME.with_orient(31008);
// let moon_pa_frame = IAU_MOON_FRAME;
let sph_harmonics = Harmonics::from_stor(
almanac.frame_from_uid(moon_pa_frame)?,
HarmonicsMem::from_shadr(&jggrx_meta.uri, 80, 80, true)?,
);
// Include the spherical harmonics into the orbital dynamics.
orbital_dyn.accel_models.push(sph_harmonics);
// We define the solar radiation pressure, using the default solar flux and accounting only
// for the eclipsing caused by the Earth and Moon.
// Note that by default, enabling the SolarPressure model will also enable the estimation of the coefficient of reflectivity.
let srp_dyn = SolarPressure::new(vec![EARTH_J2000, MOON_J2000], almanac.clone())?;
// Finalize setting up the dynamics, specifying the force models (orbital_dyn) separately from the
// acceleration models (SRP in this case). Use `from_models` to specify multiple accel models.
let dynamics = SpacecraftDynamics::from_model(orbital_dyn, srp_dyn);
println!("{dynamics}");
// Now we can build the propagator.
let setup = Propagator::default_dp78(dynamics.clone());
// For reference, let's build the trajectory with Nyx's models from that LRO state.
let (sim_final, traj_as_sim) = setup
.with(*traj_as_flown.first(), almanac.clone())
.until_epoch_with_traj(traj_as_flown.last().epoch())?;
println!("SIM INIT: {:x}", traj_as_flown.first());
println!("SIM FINAL: {sim_final:x}");
// Compute RIC difference between SIM and LRO ephem
let sim_lro_delta = sim_final
.orbit
.ric_difference(&traj_as_flown.last().orbit)?;
println!("{traj_as_sim}");
println!(
"SIM v LRO - RIC Position (m): {:.3}",
sim_lro_delta.radius_km * 1e3
);
println!(
"SIM v LRO - RIC Velocity (m/s): {:.3}",
sim_lro_delta.velocity_km_s * 1e3
);
traj_as_sim.ric_diff_to_parquet(
&traj_as_flown,
"./04_lro_sim_truth_error.parquet",
ExportCfg::default(),
)?;
// ==================== //
// === OD SIMULATOR === //
// ==================== //
// After quite some time trying to exactly match the model, we still end up with an oscillatory difference on the order of 150 meters between the propagated state
// and the truth LRO state.
// Therefore, we will actually run an estimation from a dispersed LRO state.
// The sc_seed is the true LRO state from the BSP.
let sc_seed = *traj_as_flown.first();
// Load the Deep Space Network ground stations.
// Nyx allows you to build these at runtime but it's pretty static so we can just load them from YAML.
let ground_station_file: PathBuf = [
env!("CARGO_MANIFEST_DIR"),
"examples",
"04_lro_od",
"dsn-network.yaml",
]
.iter()
.collect();
let devices = GroundStation::load_named(ground_station_file)?;
// Typical OD software requires that you specify your own tracking schedule or you'll have overlapping measurements.
// Nyx can build a tracking schedule for you based on the first station with access.
let trkconfg_yaml: PathBuf = [
env!("CARGO_MANIFEST_DIR"),
"examples",
"04_lro_od",
"tracking-cfg.yaml",
]
.iter()
.collect();
let configs: BTreeMap<String, TrkConfig> = TrkConfig::load_named(trkconfg_yaml)?;
// Build the tracking arc simulation to generate a "standard measurement".
let mut trk = TrackingArcSim::<Spacecraft, GroundStation>::new(
devices.clone(),
traj_as_flown.clone(),
configs,
)?;
trk.build_schedule(almanac.clone())?;
let arc = trk.generate_measurements(almanac.clone())?;
// Save the simulated tracking data
arc.to_parquet_simple("./04_lro_simulated_tracking.parquet")?;
// We'll note that in our case, we have continuous coverage of LRO when the vehicle is not behind the Moon.
println!("{arc}");
// Now that we have simulated measurements, we'll run the orbit determination.
// ===================== //
// === OD ESTIMATION === //
// ===================== //
let sc = SpacecraftUncertainty::builder()
.nominal(sc_seed)
.frame(LocalFrame::RIC)
.x_km(0.5)
.y_km(0.5)
.z_km(0.5)
.vx_km_s(5e-3)
.vy_km_s(5e-3)
.vz_km_s(5e-3)
.build();
// Build the filter initial estimate, which we will reuse in the filter.
let initial_estimate = sc.to_estimate()?;
println!("== FILTER STATE ==\n{sc_seed:x}\n{initial_estimate}");
let kf = KF::new(
// Increase the initial covariance to account for larger deviation.
initial_estimate,
// Until https://github.com/nyx-space/nyx/issues/351, we need to specify the SNC in the acceleration of the Moon J2000 frame.
SNC3::from_diagonal(10 * Unit::Minute, &[1e-11, 1e-11, 1e-11]),
);
// We'll set up the OD process to reject measurements whose residuals are mover than 4 sigmas away from what we expect.
let mut odp = SpacecraftODProcess::ckf(
setup.with(initial_estimate.state().with_stm(), almanac.clone()),
kf,
devices,
Some(ResidRejectCrit::default()),
almanac.clone(),
);
odp.process_arc(&arc)?;
let ric_err = traj_as_flown
.at(odp.estimates.last().unwrap().epoch())?
.orbit
.ric_difference(&odp.estimates.last().unwrap().orbital_state())?;
println!("== RIC at end ==");
println!("RIC Position (m): {}", ric_err.radius_km * 1e3);
println!("RIC Velocity (m/s): {}", ric_err.velocity_km_s * 1e3);
odp.to_parquet(&arc, "./04_lro_od_results.parquet", ExportCfg::default())?;
// In our case, we have the truth trajectory from NASA.
// So we can compute the RIC state difference between the real LRO ephem and what we've just estimated.
// Export the OD trajectory first.
let od_trajectory = odp.to_traj()?;
// Build the RIC difference.
od_trajectory.ric_diff_to_parquet(
&traj_as_flown,
"./04_lro_od_truth_error.parquet",
ExportCfg::default(),
)?;
Ok(())
}
Sourcepub fn last(&self) -> &S
pub fn last(&self) -> &S
Returns the last state in this ephemeris
Examples found in repository?
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
fn main() -> Result<(), Box<dyn Error>> {
pel::init();
// ====================== //
// === ALMANAC SET UP === //
// ====================== //
// Dynamics models require planetary constants and ephemerides to be defined.
// Let's start by grabbing those by using ANISE's MetaAlmanac.
let data_folder: PathBuf = [env!("CARGO_MANIFEST_DIR"), "examples", "04_lro_od"]
.iter()
.collect();
let meta = data_folder.join("lro-dynamics.dhall");
// Load this ephem in the general Almanac we're using for this analysis.
let mut almanac = MetaAlmanac::new(meta.to_string_lossy().to_string())
.map_err(Box::new)?
.process(true)
.map_err(Box::new)?;
let mut moon_pc = almanac.planetary_data.get_by_id(MOON)?;
moon_pc.mu_km3_s2 = 4902.74987;
almanac.planetary_data.set_by_id(MOON, moon_pc)?;
let mut earth_pc = almanac.planetary_data.get_by_id(EARTH)?;
earth_pc.mu_km3_s2 = 398600.436;
almanac.planetary_data.set_by_id(EARTH, earth_pc)?;
// Save this new kernel for reuse.
// In an operational context, this would be part of the "Lock" process, and should not change throughout the mission.
almanac
.planetary_data
.save_as(&data_folder.join("lro-specific.pca"), true)?;
// Lock the almanac (an Arc is a read only structure).
let almanac = Arc::new(almanac);
// Orbit determination requires a Trajectory structure, which can be saved as parquet file.
// In our case, the trajectory comes from the BSP file, so we need to build a Trajectory from the almanac directly.
// To query the Almanac, we need to build the LRO frame in the J2000 orientation in our case.
// Inspecting the LRO BSP in the ANISE GUI shows us that NASA has assigned ID -85 to LRO.
let lro_frame = Frame::from_ephem_j2000(-85);
// To build the trajectory we need to provide a spacecraft template.
let sc_template = Spacecraft::builder()
.dry_mass_kg(1018.0) // Launch masses
.fuel_mass_kg(900.0)
.srp(SrpConfig {
// SRP configuration is arbitrary, but we will be estimating it anyway.
area_m2: 3.9 * 2.7,
cr: 0.96,
})
.orbit(Orbit::zero(MOON_J2000)) // Setting a zero orbit here because it's just a template
.build();
// Now we can build the trajectory from the BSP file.
// We'll arbitrarily set the tracking arc to 48 hours with a one minute time step.
let traj_as_flown = Traj::from_bsp(
lro_frame,
MOON_J2000,
almanac.clone(),
sc_template,
5.seconds(),
Some(Epoch::from_str("2024-01-01 00:00:00 UTC")?),
Some(Epoch::from_str("2024-01-02 00:00:00 UTC")?),
Aberration::LT,
Some("LRO".to_string()),
)?;
println!("{traj_as_flown}");
// ====================== //
// === MODEL MATCHING === //
// ====================== //
// Set up the spacecraft dynamics.
// Specify that the orbital dynamics must account for the graviational pull of the Earth and the Sun.
// The gravity of the Moon will also be accounted for since the spaceraft in a lunar orbit.
let mut orbital_dyn = OrbitalDynamics::point_masses(vec![EARTH, SUN, JUPITER_BARYCENTER]);
// We want to include the spherical harmonics, so let's download the gravitational data from the Nyx Cloud.
// We're using the GRAIL JGGRX model.
let mut jggrx_meta = MetaFile {
uri: "http://public-data.nyxspace.com/nyx/models/Luna_jggrx_1500e_sha.tab.gz".to_string(),
crc32: Some(0x6bcacda8), // Specifying the CRC32 avoids redownloading it if it's cached.
};
// And let's download it if we don't have it yet.
jggrx_meta.process(true)?;
// Build the spherical harmonics.
// The harmonics must be computed in the body fixed frame.
// We're using the long term prediction of the Moon principal axes frame.
let moon_pa_frame = MOON_PA_FRAME.with_orient(31008);
// let moon_pa_frame = IAU_MOON_FRAME;
let sph_harmonics = Harmonics::from_stor(
almanac.frame_from_uid(moon_pa_frame)?,
HarmonicsMem::from_shadr(&jggrx_meta.uri, 80, 80, true)?,
);
// Include the spherical harmonics into the orbital dynamics.
orbital_dyn.accel_models.push(sph_harmonics);
// We define the solar radiation pressure, using the default solar flux and accounting only
// for the eclipsing caused by the Earth and Moon.
// Note that by default, enabling the SolarPressure model will also enable the estimation of the coefficient of reflectivity.
let srp_dyn = SolarPressure::new(vec![EARTH_J2000, MOON_J2000], almanac.clone())?;
// Finalize setting up the dynamics, specifying the force models (orbital_dyn) separately from the
// acceleration models (SRP in this case). Use `from_models` to specify multiple accel models.
let dynamics = SpacecraftDynamics::from_model(orbital_dyn, srp_dyn);
println!("{dynamics}");
// Now we can build the propagator.
let setup = Propagator::default_dp78(dynamics.clone());
// For reference, let's build the trajectory with Nyx's models from that LRO state.
let (sim_final, traj_as_sim) = setup
.with(*traj_as_flown.first(), almanac.clone())
.until_epoch_with_traj(traj_as_flown.last().epoch())?;
println!("SIM INIT: {:x}", traj_as_flown.first());
println!("SIM FINAL: {sim_final:x}");
// Compute RIC difference between SIM and LRO ephem
let sim_lro_delta = sim_final
.orbit
.ric_difference(&traj_as_flown.last().orbit)?;
println!("{traj_as_sim}");
println!(
"SIM v LRO - RIC Position (m): {:.3}",
sim_lro_delta.radius_km * 1e3
);
println!(
"SIM v LRO - RIC Velocity (m/s): {:.3}",
sim_lro_delta.velocity_km_s * 1e3
);
traj_as_sim.ric_diff_to_parquet(
&traj_as_flown,
"./04_lro_sim_truth_error.parquet",
ExportCfg::default(),
)?;
// ==================== //
// === OD SIMULATOR === //
// ==================== //
// After quite some time trying to exactly match the model, we still end up with an oscillatory difference on the order of 150 meters between the propagated state
// and the truth LRO state.
// Therefore, we will actually run an estimation from a dispersed LRO state.
// The sc_seed is the true LRO state from the BSP.
let sc_seed = *traj_as_flown.first();
// Load the Deep Space Network ground stations.
// Nyx allows you to build these at runtime but it's pretty static so we can just load them from YAML.
let ground_station_file: PathBuf = [
env!("CARGO_MANIFEST_DIR"),
"examples",
"04_lro_od",
"dsn-network.yaml",
]
.iter()
.collect();
let devices = GroundStation::load_named(ground_station_file)?;
// Typical OD software requires that you specify your own tracking schedule or you'll have overlapping measurements.
// Nyx can build a tracking schedule for you based on the first station with access.
let trkconfg_yaml: PathBuf = [
env!("CARGO_MANIFEST_DIR"),
"examples",
"04_lro_od",
"tracking-cfg.yaml",
]
.iter()
.collect();
let configs: BTreeMap<String, TrkConfig> = TrkConfig::load_named(trkconfg_yaml)?;
// Build the tracking arc simulation to generate a "standard measurement".
let mut trk = TrackingArcSim::<Spacecraft, GroundStation>::new(
devices.clone(),
traj_as_flown.clone(),
configs,
)?;
trk.build_schedule(almanac.clone())?;
let arc = trk.generate_measurements(almanac.clone())?;
// Save the simulated tracking data
arc.to_parquet_simple("./04_lro_simulated_tracking.parquet")?;
// We'll note that in our case, we have continuous coverage of LRO when the vehicle is not behind the Moon.
println!("{arc}");
// Now that we have simulated measurements, we'll run the orbit determination.
// ===================== //
// === OD ESTIMATION === //
// ===================== //
let sc = SpacecraftUncertainty::builder()
.nominal(sc_seed)
.frame(LocalFrame::RIC)
.x_km(0.5)
.y_km(0.5)
.z_km(0.5)
.vx_km_s(5e-3)
.vy_km_s(5e-3)
.vz_km_s(5e-3)
.build();
// Build the filter initial estimate, which we will reuse in the filter.
let initial_estimate = sc.to_estimate()?;
println!("== FILTER STATE ==\n{sc_seed:x}\n{initial_estimate}");
let kf = KF::new(
// Increase the initial covariance to account for larger deviation.
initial_estimate,
// Until https://github.com/nyx-space/nyx/issues/351, we need to specify the SNC in the acceleration of the Moon J2000 frame.
SNC3::from_diagonal(10 * Unit::Minute, &[1e-11, 1e-11, 1e-11]),
);
// We'll set up the OD process to reject measurements whose residuals are mover than 4 sigmas away from what we expect.
let mut odp = SpacecraftODProcess::ckf(
setup.with(initial_estimate.state().with_stm(), almanac.clone()),
kf,
devices,
Some(ResidRejectCrit::default()),
almanac.clone(),
);
odp.process_arc(&arc)?;
let ric_err = traj_as_flown
.at(odp.estimates.last().unwrap().epoch())?
.orbit
.ric_difference(&odp.estimates.last().unwrap().orbital_state())?;
println!("== RIC at end ==");
println!("RIC Position (m): {}", ric_err.radius_km * 1e3);
println!("RIC Velocity (m/s): {}", ric_err.velocity_km_s * 1e3);
odp.to_parquet(&arc, "./04_lro_od_results.parquet", ExportCfg::default())?;
// In our case, we have the truth trajectory from NASA.
// So we can compute the RIC state difference between the real LRO ephem and what we've just estimated.
// Export the OD trajectory first.
let od_trajectory = odp.to_traj()?;
// Build the RIC difference.
od_trajectory.ric_diff_to_parquet(
&traj_as_flown,
"./04_lro_od_truth_error.parquet",
ExportCfg::default(),
)?;
Ok(())
}
Sourcepub fn every(&self, step: Duration) -> TrajIterator<'_, S>
pub fn every(&self, step: Duration) -> TrajIterator<'_, S>
Creates an iterator through the trajectory by the provided step size
Examples found in repository?
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
fn main() -> Result<(), Box<dyn Error>> {
pel::init();
// Dynamics models require planetary constants and ephemerides to be defined.
// Let's start by grabbing those by using ANISE's latest MetaAlmanac.
// This will automatically download the DE440s planetary ephemeris,
// the daily-updated Earth Orientation Parameters, the high fidelity Moon orientation
// parameters (for the Moon Mean Earth and Moon Principal Axes frames), and the PCK11
// planetary constants kernels.
// For details, refer to https://github.com/nyx-space/anise/blob/master/data/latest.dhall.
// Note that we place the Almanac into an Arc so we can clone it cheaply and provide read-only
// references to many functions.
let almanac = Arc::new(MetaAlmanac::latest().map_err(Box::new)?);
// Define the orbit epoch
let epoch = Epoch::from_gregorian_utc_hms(2024, 2, 29, 12, 13, 14);
// Define the orbit.
// First we need to fetch the Earth J2000 from information from the Almanac.
// This allows the frame to include the gravitational parameters and the shape of the Earth,
// defined as a tri-axial ellipoid. Note that this shape can be changed manually or in the Almanac
// by loading a different set of planetary constants.
let earth_j2000 = almanac.frame_from_uid(EARTH_J2000)?;
// Placing this GEO bird just above Colorado.
// In theory, the eccentricity is zero, but in practice, it's about 1e-5 to 1e-6 at best.
let orbit = Orbit::try_keplerian(42164.0, 1e-5, 0., 163.0, 75.0, 0.0, epoch, earth_j2000)?;
// Print in in Keplerian form.
println!("{orbit:x}");
let state_bf = almanac.transform_to(orbit, IAU_EARTH_FRAME, None)?;
let (orig_lat_deg, orig_long_deg, orig_alt_km) = state_bf.latlongalt()?;
// Nyx is used for high fidelity propagation, not Keplerian propagation as above.
// Nyx only propagates Spacecraft at the moment, which allows it to account for acceleration
// models such as solar radiation pressure.
// Let's build a cubesat sized spacecraft, with an SRP area of 10 cm^2 and a mass of 9.6 kg.
let sc = Spacecraft::builder()
.orbit(orbit)
.dry_mass_kg(9.60)
.srp(SrpConfig {
area_m2: 10e-4,
cr: 1.1,
})
.build();
println!("{sc:x}");
// Set up the spacecraft dynamics.
// Specify that the orbital dynamics must account for the graviational pull of the Moon and the Sun.
// The gravity of the Earth will also be accounted for since the spaceraft in an Earth orbit.
let mut orbital_dyn = OrbitalDynamics::point_masses(vec![MOON, SUN]);
// We want to include the spherical harmonics, so let's download the gravitational data from the Nyx Cloud.
// We're using the JGM3 model here, which is the default in GMAT.
let mut jgm3_meta = MetaFile {
uri: "http://public-data.nyxspace.com/nyx/models/JGM3.cof.gz".to_string(),
crc32: Some(0xF446F027), // Specifying the CRC32 avoids redownloading it if it's cached.
};
// And let's download it if we don't have it yet.
jgm3_meta.process(true)?;
// Build the spherical harmonics.
// The harmonics must be computed in the body fixed frame.
// We're using the long term prediction of the Earth centered Earth fixed frame, IAU Earth.
let harmonics_21x21 = Harmonics::from_stor(
almanac.frame_from_uid(IAU_EARTH_FRAME)?,
HarmonicsMem::from_cof(&jgm3_meta.uri, 21, 21, true).unwrap(),
);
// Include the spherical harmonics into the orbital dynamics.
orbital_dyn.accel_models.push(harmonics_21x21);
// We define the solar radiation pressure, using the default solar flux and accounting only
// for the eclipsing caused by the Earth and Moon.
let srp_dyn = SolarPressure::new(vec![EARTH_J2000, MOON_J2000], almanac.clone())?;
// Finalize setting up the dynamics, specifying the force models (orbital_dyn) separately from the
// acceleration models (SRP in this case). Use `from_models` to specify multiple accel models.
let dynamics = SpacecraftDynamics::from_model(orbital_dyn, srp_dyn);
println!("{dynamics}");
// Finally, let's propagate this orbit to the same epoch as above.
// The first returned value is the spacecraft state at the final epoch.
// The second value is the full trajectory where the step size is variable step used by the propagator.
let (future_sc, trajectory) = Propagator::default(dynamics)
.with(sc, almanac.clone())
.until_epoch_with_traj(epoch + Unit::Century * 0.03)?;
println!("=== High fidelity propagation ===");
println!(
"SMA changed by {:.3} km",
orbit.sma_km()? - future_sc.orbit.sma_km()?
);
println!(
"ECC changed by {:.6}",
orbit.ecc()? - future_sc.orbit.ecc()?
);
println!(
"INC changed by {:.3e} deg",
orbit.inc_deg()? - future_sc.orbit.inc_deg()?
);
println!(
"RAAN changed by {:.3} deg",
orbit.raan_deg()? - future_sc.orbit.raan_deg()?
);
println!(
"AOP changed by {:.3} deg",
orbit.aop_deg()? - future_sc.orbit.aop_deg()?
);
println!(
"TA changed by {:.3} deg",
orbit.ta_deg()? - future_sc.orbit.ta_deg()?
);
// We also have access to the full trajectory throughout the propagation.
println!("{trajectory}");
println!("Spacecraft params after 3 years without active control:\n{future_sc:x}");
// With the trajectory, let's build a few data products.
// 1. Export the trajectory as a parquet file, which includes the Keplerian orbital elements.
let analysis_step = Unit::Minute * 5;
trajectory.to_parquet(
"./03_geo_hf_prop.parquet",
Some(vec![
&EclipseLocator::cislunar(almanac.clone()).to_penumbra_event()
]),
ExportCfg::builder().step(analysis_step).build(),
almanac.clone(),
)?;
// 2. Compute the latitude, longitude, and altitude throughout the trajectory by rotating the spacecraft position into the Earth body fixed frame.
// We iterate over the trajectory, grabbing a state every two minutes.
let mut offset_s = vec![];
let mut epoch_str = vec![];
let mut longitude_deg = vec![];
let mut latitude_deg = vec![];
let mut altitude_km = vec![];
for state in trajectory.every(analysis_step) {
// Convert the GEO bird state into the body fixed frame, and keep track of its latitude, longitude, and altitude.
// These define the GEO stationkeeping box.
let this_epoch = state.epoch();
offset_s.push((this_epoch - orbit.epoch).to_seconds());
epoch_str.push(this_epoch.to_isoformat());
let state_bf = almanac.transform_to(state.orbit, IAU_EARTH_FRAME, None)?;
let (lat_deg, long_deg, alt_km) = state_bf.latlongalt()?;
longitude_deg.push(long_deg);
latitude_deg.push(lat_deg);
altitude_km.push(alt_km);
}
println!(
"Longitude changed by {:.3} deg -- Box is 0.1 deg E-W",
orig_long_deg - longitude_deg.last().unwrap()
);
println!(
"Latitude changed by {:.3} deg -- Box is 0.05 deg N-S",
orig_lat_deg - latitude_deg.last().unwrap()
);
println!(
"Altitude changed by {:.3} km -- Box is 30 km",
orig_alt_km - altitude_km.last().unwrap()
);
// Build the station keeping data frame.
let mut sk_df = df!(
"Offset (s)" => offset_s.clone(),
"Epoch (UTC)" => epoch_str.clone(),
"Longitude E-W (deg)" => longitude_deg,
"Latitude N-S (deg)" => latitude_deg,
"Altitude (km)" => altitude_km,
)?;
// Create a file to write the Parquet to
let file = File::create("./03_geo_lla.parquet").expect("Could not create file");
// Create a ParquetWriter and write the DataFrame to the file
ParquetWriter::new(file).finish(&mut sk_df)?;
Ok(())
}
More examples
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
fn main() -> Result<(), Box<dyn Error>> {
pel::init();
// Dynamics models require planetary constants and ephemerides to be defined.
// Let's start by grabbing those by using ANISE's latest MetaAlmanac.
// This will automatically download the DE440s planetary ephemeris,
// the daily-updated Earth Orientation Parameters, the high fidelity Moon orientation
// parameters (for the Moon Mean Earth and Moon Principal Axes frames), and the PCK11
// planetary constants kernels.
// For details, refer to https://github.com/nyx-space/anise/blob/master/data/latest.dhall.
// Note that we place the Almanac into an Arc so we can clone it cheaply and provide read-only
// references to many functions.
let almanac = Arc::new(MetaAlmanac::latest().map_err(Box::new)?);
// Define the orbit epoch
let epoch = Epoch::from_gregorian_utc_hms(2024, 2, 29, 12, 13, 14);
// Define the orbit.
// First we need to fetch the Earth J2000 from information from the Almanac.
// This allows the frame to include the gravitational parameters and the shape of the Earth,
// defined as a tri-axial ellipoid. Note that this shape can be changed manually or in the Almanac
// by loading a different set of planetary constants.
let earth_j2000 = almanac.frame_from_uid(EARTH_J2000)?;
let orbit =
Orbit::try_keplerian_altitude(300.0, 0.015, 68.5, 65.2, 75.0, 0.0, epoch, earth_j2000)?;
// Print in in Keplerian form.
println!("{orbit:x}");
// There are two ways to propagate an orbit. We can make a quick approximation assuming only two-body
// motion. This is a useful first order approximation but it isn't used in real-world applications.
// This approach is a feature of ANISE.
let future_orbit_tb = orbit.at_epoch(epoch + Unit::Day * 3)?;
println!("{future_orbit_tb:x}");
// Two body propagation relies solely on Kepler's laws, so only the true anomaly will change.
println!(
"SMA changed by {:.3e} km",
orbit.sma_km()? - future_orbit_tb.sma_km()?
);
println!(
"ECC changed by {:.3e}",
orbit.ecc()? - future_orbit_tb.ecc()?
);
println!(
"INC changed by {:.3e} deg",
orbit.inc_deg()? - future_orbit_tb.inc_deg()?
);
println!(
"RAAN changed by {:.3e} deg",
orbit.raan_deg()? - future_orbit_tb.raan_deg()?
);
println!(
"AOP changed by {:.3e} deg",
orbit.aop_deg()? - future_orbit_tb.aop_deg()?
);
println!(
"TA changed by {:.3} deg",
orbit.ta_deg()? - future_orbit_tb.ta_deg()?
);
// Nyx is used for high fidelity propagation, not Keplerian propagation as above.
// Nyx only propagates Spacecraft at the moment, which allows it to account for acceleration
// models such as solar radiation pressure.
// Let's build a cubesat sized spacecraft, with an SRP area of 10 cm^2 and a mass of 9.6 kg.
let sc = Spacecraft::builder()
.orbit(orbit)
.dry_mass_kg(9.60)
.srp(SrpConfig {
area_m2: 10e-4,
cr: 1.1,
})
.build();
println!("{sc:x}");
// Set up the spacecraft dynamics.
// Specify that the orbital dynamics must account for the graviational pull of the Moon and the Sun.
// The gravity of the Earth will also be accounted for since the spaceraft in an Earth orbit.
let mut orbital_dyn = OrbitalDynamics::point_masses(vec![MOON, SUN]);
// We want to include the spherical harmonics, so let's download the gravitational data from the Nyx Cloud.
// We're using the JGM3 model here, which is the default in GMAT.
let mut jgm3_meta = MetaFile {
uri: "http://public-data.nyxspace.com/nyx/models/JGM3.cof.gz".to_string(),
crc32: Some(0xF446F027), // Specifying the CRC32 avoids redownloading it if it's cached.
};
// And let's download it if we don't have it yet.
jgm3_meta.process(true)?;
// Build the spherical harmonics.
// The harmonics must be computed in the body fixed frame.
// We're using the long term prediction of the Earth centered Earth fixed frame, IAU Earth.
let harmonics_21x21 = Harmonics::from_stor(
almanac.frame_from_uid(IAU_EARTH_FRAME)?,
HarmonicsMem::from_cof(&jgm3_meta.uri, 21, 21, true).unwrap(),
);
// Include the spherical harmonics into the orbital dynamics.
orbital_dyn.accel_models.push(harmonics_21x21);
// We define the solar radiation pressure, using the default solar flux and accounting only
// for the eclipsing caused by the Earth.
let srp_dyn = SolarPressure::default(EARTH_J2000, almanac.clone())?;
// Finalize setting up the dynamics, specifying the force models (orbital_dyn) separately from the
// acceleration models (SRP in this case). Use `from_models` to specify multiple accel models.
let dynamics = SpacecraftDynamics::from_model(orbital_dyn, srp_dyn);
println!("{dynamics}");
// Finally, let's propagate this orbit to the same epoch as above.
// The first returned value is the spacecraft state at the final epoch.
// The second value is the full trajectory where the step size is variable step used by the propagator.
let (future_sc, trajectory) = Propagator::default(dynamics)
.with(sc, almanac.clone())
.until_epoch_with_traj(future_orbit_tb.epoch)?;
println!("=== High fidelity propagation ===");
println!(
"SMA changed by {:.3} km",
orbit.sma_km()? - future_sc.orbit.sma_km()?
);
println!(
"ECC changed by {:.6}",
orbit.ecc()? - future_sc.orbit.ecc()?
);
println!(
"INC changed by {:.3e} deg",
orbit.inc_deg()? - future_sc.orbit.inc_deg()?
);
println!(
"RAAN changed by {:.3} deg",
orbit.raan_deg()? - future_sc.orbit.raan_deg()?
);
println!(
"AOP changed by {:.3} deg",
orbit.aop_deg()? - future_sc.orbit.aop_deg()?
);
println!(
"TA changed by {:.3} deg",
orbit.ta_deg()? - future_sc.orbit.ta_deg()?
);
// We also have access to the full trajectory throughout the propagation.
println!("{trajectory}");
// With the trajectory, let's build a few data products.
// 1. Export the trajectory as a CCSDS OEM version 2.0 file and as a parquet file, which includes the Keplerian orbital elements.
trajectory.to_oem_file(
"./01_cubesat_hf_prop.oem",
ExportCfg::builder().step(Unit::Minute * 2).build(),
)?;
trajectory.to_parquet_with_cfg(
"./01_cubesat_hf_prop.parquet",
ExportCfg::builder().step(Unit::Minute * 2).build(),
almanac.clone(),
)?;
// 2. Compare the difference in the radial-intrack-crosstrack frame between the high fidelity
// and Keplerian propagation. The RIC frame is commonly used to compute the difference in position
// and velocity of different spacecraft.
// 3. Compute the azimuth, elevation, range, and range-rate data of that spacecraft as seen from Boulder, CO, USA.
let boulder_station = GroundStation::from_point(
"Boulder, CO, USA".to_string(),
40.014984, // latitude in degrees
-105.270546, // longitude in degrees
1.6550, // altitude in kilometers
almanac.frame_from_uid(IAU_EARTH_FRAME)?,
);
// We iterate over the trajectory, grabbing a state every two minutes.
let mut offset_s = vec![];
let mut epoch_str = vec![];
let mut ric_x_km = vec![];
let mut ric_y_km = vec![];
let mut ric_z_km = vec![];
let mut ric_vx_km_s = vec![];
let mut ric_vy_km_s = vec![];
let mut ric_vz_km_s = vec![];
let mut azimuth_deg = vec![];
let mut elevation_deg = vec![];
let mut range_km = vec![];
let mut range_rate_km_s = vec![];
for state in trajectory.every(Unit::Minute * 2) {
// Try to compute the Keplerian/two body state just in time.
// This method occasionally fails to converge on an appropriate true anomaly
// from the mean anomaly. If that happens, we just skip this state.
// The high fidelity and Keplerian states diverge continuously, and we're curious
// about the divergence in this quick analysis.
let this_epoch = state.epoch();
match orbit.at_epoch(this_epoch) {
Ok(tb_then) => {
offset_s.push((this_epoch - orbit.epoch).to_seconds());
epoch_str.push(format!("{this_epoch}"));
// Compute the two body state just in time.
let ric = state.orbit.ric_difference(&tb_then)?;
ric_x_km.push(ric.radius_km.x);
ric_y_km.push(ric.radius_km.y);
ric_z_km.push(ric.radius_km.z);
ric_vx_km_s.push(ric.velocity_km_s.x);
ric_vy_km_s.push(ric.velocity_km_s.y);
ric_vz_km_s.push(ric.velocity_km_s.z);
// Compute the AER data for each state.
let aer = almanac.azimuth_elevation_range_sez(
state.orbit,
boulder_station.to_orbit(this_epoch, &almanac)?,
None,
None,
)?;
azimuth_deg.push(aer.azimuth_deg);
elevation_deg.push(aer.elevation_deg);
range_km.push(aer.range_km);
range_rate_km_s.push(aer.range_rate_km_s);
}
Err(e) => warn!("{} {e}", state.epoch()),
};
}
// Build the data frames.
let ric_df = df!(
"Offset (s)" => offset_s.clone(),
"Epoch" => epoch_str.clone(),
"RIC X (km)" => ric_x_km,
"RIC Y (km)" => ric_y_km,
"RIC Z (km)" => ric_z_km,
"RIC VX (km/s)" => ric_vx_km_s,
"RIC VY (km/s)" => ric_vy_km_s,
"RIC VZ (km/s)" => ric_vz_km_s,
)?;
println!("RIC difference at start\n{}", ric_df.head(Some(10)));
println!("RIC difference at end\n{}", ric_df.tail(Some(10)));
let aer_df = df!(
"Offset (s)" => offset_s.clone(),
"Epoch" => epoch_str.clone(),
"azimuth (deg)" => azimuth_deg,
"elevation (deg)" => elevation_deg,
"range (km)" => range_km,
"range rate (km/s)" => range_rate_km_s,
)?;
// Finally, let's see when the spacecraft is visible, assuming 15 degrees minimum elevation.
let mask = aer_df.column("elevation (deg)")?.gt(15.0)?;
let cubesat_visible = aer_df.filter(&mask)?;
println!("{cubesat_visible}");
Ok(())
}
Sourcepub fn every_between(
&self,
step: Duration,
start: Epoch,
end: Epoch,
) -> TrajIterator<'_, S>
pub fn every_between( &self, step: Duration, start: Epoch, end: Epoch, ) -> TrajIterator<'_, S>
Creates an iterator through the trajectory by the provided step size between the provided bounds
Sourcepub fn to_parquet_simple<P: AsRef<Path>>(
&self,
path: P,
almanac: Arc<Almanac>,
) -> Result<PathBuf, Box<dyn Error>>
pub fn to_parquet_simple<P: AsRef<Path>>( &self, path: P, almanac: Arc<Almanac>, ) -> Result<PathBuf, Box<dyn Error>>
Store this trajectory arc to a parquet file with the default configuration (depends on the state type, search for export_params
in the documentation for details).
Sourcepub fn to_parquet_with_cfg<P: AsRef<Path>>(
&self,
path: P,
cfg: ExportCfg,
almanac: Arc<Almanac>,
) -> Result<PathBuf, Box<dyn Error>>
pub fn to_parquet_with_cfg<P: AsRef<Path>>( &self, path: P, cfg: ExportCfg, almanac: Arc<Almanac>, ) -> Result<PathBuf, Box<dyn Error>>
Store this trajectory arc to a parquet file with the provided configuration
Examples found in repository?
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
fn main() -> Result<(), Box<dyn Error>> {
pel::init();
// Dynamics models require planetary constants and ephemerides to be defined.
// Let's start by grabbing those by using ANISE's latest MetaAlmanac.
// This will automatically download the DE440s planetary ephemeris,
// the daily-updated Earth Orientation Parameters, the high fidelity Moon orientation
// parameters (for the Moon Mean Earth and Moon Principal Axes frames), and the PCK11
// planetary constants kernels.
// For details, refer to https://github.com/nyx-space/anise/blob/master/data/latest.dhall.
// Note that we place the Almanac into an Arc so we can clone it cheaply and provide read-only
// references to many functions.
let almanac = Arc::new(MetaAlmanac::latest().map_err(Box::new)?);
// Define the orbit epoch
let epoch = Epoch::from_gregorian_utc_hms(2024, 2, 29, 12, 13, 14);
// Define the orbit.
// First we need to fetch the Earth J2000 from information from the Almanac.
// This allows the frame to include the gravitational parameters and the shape of the Earth,
// defined as a tri-axial ellipoid. Note that this shape can be changed manually or in the Almanac
// by loading a different set of planetary constants.
let earth_j2000 = almanac.frame_from_uid(EARTH_J2000)?;
let orbit =
Orbit::try_keplerian_altitude(300.0, 0.015, 68.5, 65.2, 75.0, 0.0, epoch, earth_j2000)?;
// Print in in Keplerian form.
println!("{orbit:x}");
// There are two ways to propagate an orbit. We can make a quick approximation assuming only two-body
// motion. This is a useful first order approximation but it isn't used in real-world applications.
// This approach is a feature of ANISE.
let future_orbit_tb = orbit.at_epoch(epoch + Unit::Day * 3)?;
println!("{future_orbit_tb:x}");
// Two body propagation relies solely on Kepler's laws, so only the true anomaly will change.
println!(
"SMA changed by {:.3e} km",
orbit.sma_km()? - future_orbit_tb.sma_km()?
);
println!(
"ECC changed by {:.3e}",
orbit.ecc()? - future_orbit_tb.ecc()?
);
println!(
"INC changed by {:.3e} deg",
orbit.inc_deg()? - future_orbit_tb.inc_deg()?
);
println!(
"RAAN changed by {:.3e} deg",
orbit.raan_deg()? - future_orbit_tb.raan_deg()?
);
println!(
"AOP changed by {:.3e} deg",
orbit.aop_deg()? - future_orbit_tb.aop_deg()?
);
println!(
"TA changed by {:.3} deg",
orbit.ta_deg()? - future_orbit_tb.ta_deg()?
);
// Nyx is used for high fidelity propagation, not Keplerian propagation as above.
// Nyx only propagates Spacecraft at the moment, which allows it to account for acceleration
// models such as solar radiation pressure.
// Let's build a cubesat sized spacecraft, with an SRP area of 10 cm^2 and a mass of 9.6 kg.
let sc = Spacecraft::builder()
.orbit(orbit)
.dry_mass_kg(9.60)
.srp(SrpConfig {
area_m2: 10e-4,
cr: 1.1,
})
.build();
println!("{sc:x}");
// Set up the spacecraft dynamics.
// Specify that the orbital dynamics must account for the graviational pull of the Moon and the Sun.
// The gravity of the Earth will also be accounted for since the spaceraft in an Earth orbit.
let mut orbital_dyn = OrbitalDynamics::point_masses(vec![MOON, SUN]);
// We want to include the spherical harmonics, so let's download the gravitational data from the Nyx Cloud.
// We're using the JGM3 model here, which is the default in GMAT.
let mut jgm3_meta = MetaFile {
uri: "http://public-data.nyxspace.com/nyx/models/JGM3.cof.gz".to_string(),
crc32: Some(0xF446F027), // Specifying the CRC32 avoids redownloading it if it's cached.
};
// And let's download it if we don't have it yet.
jgm3_meta.process(true)?;
// Build the spherical harmonics.
// The harmonics must be computed in the body fixed frame.
// We're using the long term prediction of the Earth centered Earth fixed frame, IAU Earth.
let harmonics_21x21 = Harmonics::from_stor(
almanac.frame_from_uid(IAU_EARTH_FRAME)?,
HarmonicsMem::from_cof(&jgm3_meta.uri, 21, 21, true).unwrap(),
);
// Include the spherical harmonics into the orbital dynamics.
orbital_dyn.accel_models.push(harmonics_21x21);
// We define the solar radiation pressure, using the default solar flux and accounting only
// for the eclipsing caused by the Earth.
let srp_dyn = SolarPressure::default(EARTH_J2000, almanac.clone())?;
// Finalize setting up the dynamics, specifying the force models (orbital_dyn) separately from the
// acceleration models (SRP in this case). Use `from_models` to specify multiple accel models.
let dynamics = SpacecraftDynamics::from_model(orbital_dyn, srp_dyn);
println!("{dynamics}");
// Finally, let's propagate this orbit to the same epoch as above.
// The first returned value is the spacecraft state at the final epoch.
// The second value is the full trajectory where the step size is variable step used by the propagator.
let (future_sc, trajectory) = Propagator::default(dynamics)
.with(sc, almanac.clone())
.until_epoch_with_traj(future_orbit_tb.epoch)?;
println!("=== High fidelity propagation ===");
println!(
"SMA changed by {:.3} km",
orbit.sma_km()? - future_sc.orbit.sma_km()?
);
println!(
"ECC changed by {:.6}",
orbit.ecc()? - future_sc.orbit.ecc()?
);
println!(
"INC changed by {:.3e} deg",
orbit.inc_deg()? - future_sc.orbit.inc_deg()?
);
println!(
"RAAN changed by {:.3} deg",
orbit.raan_deg()? - future_sc.orbit.raan_deg()?
);
println!(
"AOP changed by {:.3} deg",
orbit.aop_deg()? - future_sc.orbit.aop_deg()?
);
println!(
"TA changed by {:.3} deg",
orbit.ta_deg()? - future_sc.orbit.ta_deg()?
);
// We also have access to the full trajectory throughout the propagation.
println!("{trajectory}");
// With the trajectory, let's build a few data products.
// 1. Export the trajectory as a CCSDS OEM version 2.0 file and as a parquet file, which includes the Keplerian orbital elements.
trajectory.to_oem_file(
"./01_cubesat_hf_prop.oem",
ExportCfg::builder().step(Unit::Minute * 2).build(),
)?;
trajectory.to_parquet_with_cfg(
"./01_cubesat_hf_prop.parquet",
ExportCfg::builder().step(Unit::Minute * 2).build(),
almanac.clone(),
)?;
// 2. Compare the difference in the radial-intrack-crosstrack frame between the high fidelity
// and Keplerian propagation. The RIC frame is commonly used to compute the difference in position
// and velocity of different spacecraft.
// 3. Compute the azimuth, elevation, range, and range-rate data of that spacecraft as seen from Boulder, CO, USA.
let boulder_station = GroundStation::from_point(
"Boulder, CO, USA".to_string(),
40.014984, // latitude in degrees
-105.270546, // longitude in degrees
1.6550, // altitude in kilometers
almanac.frame_from_uid(IAU_EARTH_FRAME)?,
);
// We iterate over the trajectory, grabbing a state every two minutes.
let mut offset_s = vec![];
let mut epoch_str = vec![];
let mut ric_x_km = vec![];
let mut ric_y_km = vec![];
let mut ric_z_km = vec![];
let mut ric_vx_km_s = vec![];
let mut ric_vy_km_s = vec![];
let mut ric_vz_km_s = vec![];
let mut azimuth_deg = vec![];
let mut elevation_deg = vec![];
let mut range_km = vec![];
let mut range_rate_km_s = vec![];
for state in trajectory.every(Unit::Minute * 2) {
// Try to compute the Keplerian/two body state just in time.
// This method occasionally fails to converge on an appropriate true anomaly
// from the mean anomaly. If that happens, we just skip this state.
// The high fidelity and Keplerian states diverge continuously, and we're curious
// about the divergence in this quick analysis.
let this_epoch = state.epoch();
match orbit.at_epoch(this_epoch) {
Ok(tb_then) => {
offset_s.push((this_epoch - orbit.epoch).to_seconds());
epoch_str.push(format!("{this_epoch}"));
// Compute the two body state just in time.
let ric = state.orbit.ric_difference(&tb_then)?;
ric_x_km.push(ric.radius_km.x);
ric_y_km.push(ric.radius_km.y);
ric_z_km.push(ric.radius_km.z);
ric_vx_km_s.push(ric.velocity_km_s.x);
ric_vy_km_s.push(ric.velocity_km_s.y);
ric_vz_km_s.push(ric.velocity_km_s.z);
// Compute the AER data for each state.
let aer = almanac.azimuth_elevation_range_sez(
state.orbit,
boulder_station.to_orbit(this_epoch, &almanac)?,
None,
None,
)?;
azimuth_deg.push(aer.azimuth_deg);
elevation_deg.push(aer.elevation_deg);
range_km.push(aer.range_km);
range_rate_km_s.push(aer.range_rate_km_s);
}
Err(e) => warn!("{} {e}", state.epoch()),
};
}
// Build the data frames.
let ric_df = df!(
"Offset (s)" => offset_s.clone(),
"Epoch" => epoch_str.clone(),
"RIC X (km)" => ric_x_km,
"RIC Y (km)" => ric_y_km,
"RIC Z (km)" => ric_z_km,
"RIC VX (km/s)" => ric_vx_km_s,
"RIC VY (km/s)" => ric_vy_km_s,
"RIC VZ (km/s)" => ric_vz_km_s,
)?;
println!("RIC difference at start\n{}", ric_df.head(Some(10)));
println!("RIC difference at end\n{}", ric_df.tail(Some(10)));
let aer_df = df!(
"Offset (s)" => offset_s.clone(),
"Epoch" => epoch_str.clone(),
"azimuth (deg)" => azimuth_deg,
"elevation (deg)" => elevation_deg,
"range (km)" => range_km,
"range rate (km/s)" => range_rate_km_s,
)?;
// Finally, let's see when the spacecraft is visible, assuming 15 degrees minimum elevation.
let mask = aer_df.column("elevation (deg)")?.gt(15.0)?;
let cubesat_visible = aer_df.filter(&mask)?;
println!("{cubesat_visible}");
Ok(())
}
Sourcepub fn to_parquet<P: AsRef<Path>>(
&self,
path: P,
events: Option<Vec<&dyn EventEvaluator<S>>>,
cfg: ExportCfg,
almanac: Arc<Almanac>,
) -> Result<PathBuf, Box<dyn Error>>
pub fn to_parquet<P: AsRef<Path>>( &self, path: P, events: Option<Vec<&dyn EventEvaluator<S>>>, cfg: ExportCfg, almanac: Arc<Almanac>, ) -> Result<PathBuf, Box<dyn Error>>
Store this trajectory arc to a parquet file with the provided configuration and event evaluators
Examples found in repository?
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
fn main() -> Result<(), Box<dyn Error>> {
pel::init();
// Dynamics models require planetary constants and ephemerides to be defined.
// Let's start by grabbing those by using ANISE's latest MetaAlmanac.
// This will automatically download the DE440s planetary ephemeris,
// the daily-updated Earth Orientation Parameters, the high fidelity Moon orientation
// parameters (for the Moon Mean Earth and Moon Principal Axes frames), and the PCK11
// planetary constants kernels.
// For details, refer to https://github.com/nyx-space/anise/blob/master/data/latest.dhall.
// Note that we place the Almanac into an Arc so we can clone it cheaply and provide read-only
// references to many functions.
let almanac = Arc::new(MetaAlmanac::latest().map_err(Box::new)?);
// Fetch the EME2000 frame from the Almabac
let eme2k = almanac.frame_from_uid(EARTH_J2000).unwrap();
// Define the orbit epoch
let epoch = Epoch::from_gregorian_utc_hms(2024, 2, 29, 12, 13, 14);
// Build the spacecraft itself.
// Using slide 6 of https://aerospace.org/sites/default/files/2018-11/Davis-Mayberry_HPSEP_11212018.pdf
// for the "next gen" SEP characteristics.
// GTO start
let orbit = Orbit::keplerian(24505.9, 0.725, 7.05, 0.0, 0.0, 0.0, epoch, eme2k);
let sc = Spacecraft::builder()
.orbit(orbit)
.dry_mass_kg(1000.0) // 1000 kg of dry mass
.fuel_mass_kg(1000.0) // 1000 kg of fuel, totalling 2.0 tons
.srp(SrpConfig::from_area(3.0 * 6.0)) // Assuming 1 kW/m^2 or 18 kW, giving a margin of 4.35 kW for on-propulsion consumption
.thruster(Thruster {
// "NEXT-STEP" row in Table 2
isp_s: 4435.0,
thrust_N: 0.472,
})
.mode(GuidanceMode::Thrust) // Start thrusting immediately.
.build();
let prop_time = 180.0 * Unit::Day;
// Define the guidance law -- we're just using a Ruggiero controller as demonstrated in AAS-2004-5089.
let objectives = &[
Objective::within_tolerance(StateParameter::SMA, 42_165.0, 20.0),
Objective::within_tolerance(StateParameter::Eccentricity, 0.001, 5e-5),
Objective::within_tolerance(StateParameter::Inclination, 0.05, 1e-2),
];
// Ensure that we only thrust if we have more than 20% illumination.
let ruggiero_ctrl = Ruggiero::from_max_eclipse(objectives, sc, 0.2).unwrap();
println!("{ruggiero_ctrl}");
// Define the high fidelity dynamics
// Set up the spacecraft dynamics.
// Specify that the orbital dynamics must account for the graviational pull of the Moon and the Sun.
// The gravity of the Earth will also be accounted for since the spaceraft in an Earth orbit.
let mut orbital_dyn = OrbitalDynamics::point_masses(vec![MOON, SUN]);
// We want to include the spherical harmonics, so let's download the gravitational data from the Nyx Cloud.
// We're using the JGM3 model here, which is the default in GMAT.
let mut jgm3_meta = MetaFile {
uri: "http://public-data.nyxspace.com/nyx/models/JGM3.cof.gz".to_string(),
crc32: Some(0xF446F027), // Specifying the CRC32 avoids redownloading it if it's cached.
};
// And let's download it if we don't have it yet.
jgm3_meta.process(true)?;
// Build the spherical harmonics.
// The harmonics must be computed in the body fixed frame.
// We're using the long term prediction of the Earth centered Earth fixed frame, IAU Earth.
let harmonics = Harmonics::from_stor(
almanac.frame_from_uid(IAU_EARTH_FRAME)?,
HarmonicsMem::from_cof(&jgm3_meta.uri, 8, 8, true).unwrap(),
);
// Include the spherical harmonics into the orbital dynamics.
orbital_dyn.accel_models.push(harmonics);
// We define the solar radiation pressure, using the default solar flux and accounting only
// for the eclipsing caused by the Earth.
let srp_dyn = SolarPressure::default(EARTH_J2000, almanac.clone())?;
// Finalize setting up the dynamics, specifying the force models (orbital_dyn) separately from the
// acceleration models (SRP in this case). Use `from_models` to specify multiple accel models.
let sc_dynamics = SpacecraftDynamics::from_model(orbital_dyn, srp_dyn)
.with_guidance_law(ruggiero_ctrl.clone());
println!("{:x}", orbit);
// We specify a minimum step in the propagator because the Ruggiero control would otherwise drive this step very low.
let (final_state, traj) = Propagator::rk89(
sc_dynamics.clone(),
IntegratorOptions::builder()
.min_step(10.0_f64.seconds())
.error_ctrl(ErrorControl::RSSCartesianStep)
.build(),
)
.with(sc, almanac.clone())
.for_duration_with_traj(prop_time)?;
let fuel_usage = sc.fuel_mass_kg - final_state.fuel_mass_kg;
println!("{:x}", final_state.orbit);
println!("fuel usage: {:.3} kg", fuel_usage);
// Finally, export the results for analysis, including the penumbra percentage throughout the orbit raise.
traj.to_parquet(
"./03_geo_raise.parquet",
Some(vec![
&EclipseLocator::cislunar(almanac.clone()).to_penumbra_event()
]),
ExportCfg::default(),
almanac,
)?;
for status_line in ruggiero_ctrl.status(&final_state) {
println!("{status_line}");
}
ruggiero_ctrl
.achieved(&final_state)
.expect("objective not achieved");
Ok(())
}
More examples
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
fn main() -> Result<(), Box<dyn Error>> {
pel::init();
// Dynamics models require planetary constants and ephemerides to be defined.
// Let's start by grabbing those by using ANISE's latest MetaAlmanac.
// This will automatically download the DE440s planetary ephemeris,
// the daily-updated Earth Orientation Parameters, the high fidelity Moon orientation
// parameters (for the Moon Mean Earth and Moon Principal Axes frames), and the PCK11
// planetary constants kernels.
// For details, refer to https://github.com/nyx-space/anise/blob/master/data/latest.dhall.
// Note that we place the Almanac into an Arc so we can clone it cheaply and provide read-only
// references to many functions.
let almanac = Arc::new(MetaAlmanac::latest().map_err(Box::new)?);
// Define the orbit epoch
let epoch = Epoch::from_gregorian_utc_hms(2024, 2, 29, 12, 13, 14);
// Define the orbit.
// First we need to fetch the Earth J2000 from information from the Almanac.
// This allows the frame to include the gravitational parameters and the shape of the Earth,
// defined as a tri-axial ellipoid. Note that this shape can be changed manually or in the Almanac
// by loading a different set of planetary constants.
let earth_j2000 = almanac.frame_from_uid(EARTH_J2000)?;
// Placing this GEO bird just above Colorado.
// In theory, the eccentricity is zero, but in practice, it's about 1e-5 to 1e-6 at best.
let orbit = Orbit::try_keplerian(42164.0, 1e-5, 0., 163.0, 75.0, 0.0, epoch, earth_j2000)?;
// Print in in Keplerian form.
println!("{orbit:x}");
let state_bf = almanac.transform_to(orbit, IAU_EARTH_FRAME, None)?;
let (orig_lat_deg, orig_long_deg, orig_alt_km) = state_bf.latlongalt()?;
// Nyx is used for high fidelity propagation, not Keplerian propagation as above.
// Nyx only propagates Spacecraft at the moment, which allows it to account for acceleration
// models such as solar radiation pressure.
// Let's build a cubesat sized spacecraft, with an SRP area of 10 cm^2 and a mass of 9.6 kg.
let sc = Spacecraft::builder()
.orbit(orbit)
.dry_mass_kg(9.60)
.srp(SrpConfig {
area_m2: 10e-4,
cr: 1.1,
})
.build();
println!("{sc:x}");
// Set up the spacecraft dynamics.
// Specify that the orbital dynamics must account for the graviational pull of the Moon and the Sun.
// The gravity of the Earth will also be accounted for since the spaceraft in an Earth orbit.
let mut orbital_dyn = OrbitalDynamics::point_masses(vec![MOON, SUN]);
// We want to include the spherical harmonics, so let's download the gravitational data from the Nyx Cloud.
// We're using the JGM3 model here, which is the default in GMAT.
let mut jgm3_meta = MetaFile {
uri: "http://public-data.nyxspace.com/nyx/models/JGM3.cof.gz".to_string(),
crc32: Some(0xF446F027), // Specifying the CRC32 avoids redownloading it if it's cached.
};
// And let's download it if we don't have it yet.
jgm3_meta.process(true)?;
// Build the spherical harmonics.
// The harmonics must be computed in the body fixed frame.
// We're using the long term prediction of the Earth centered Earth fixed frame, IAU Earth.
let harmonics_21x21 = Harmonics::from_stor(
almanac.frame_from_uid(IAU_EARTH_FRAME)?,
HarmonicsMem::from_cof(&jgm3_meta.uri, 21, 21, true).unwrap(),
);
// Include the spherical harmonics into the orbital dynamics.
orbital_dyn.accel_models.push(harmonics_21x21);
// We define the solar radiation pressure, using the default solar flux and accounting only
// for the eclipsing caused by the Earth and Moon.
let srp_dyn = SolarPressure::new(vec![EARTH_J2000, MOON_J2000], almanac.clone())?;
// Finalize setting up the dynamics, specifying the force models (orbital_dyn) separately from the
// acceleration models (SRP in this case). Use `from_models` to specify multiple accel models.
let dynamics = SpacecraftDynamics::from_model(orbital_dyn, srp_dyn);
println!("{dynamics}");
// Finally, let's propagate this orbit to the same epoch as above.
// The first returned value is the spacecraft state at the final epoch.
// The second value is the full trajectory where the step size is variable step used by the propagator.
let (future_sc, trajectory) = Propagator::default(dynamics)
.with(sc, almanac.clone())
.until_epoch_with_traj(epoch + Unit::Century * 0.03)?;
println!("=== High fidelity propagation ===");
println!(
"SMA changed by {:.3} km",
orbit.sma_km()? - future_sc.orbit.sma_km()?
);
println!(
"ECC changed by {:.6}",
orbit.ecc()? - future_sc.orbit.ecc()?
);
println!(
"INC changed by {:.3e} deg",
orbit.inc_deg()? - future_sc.orbit.inc_deg()?
);
println!(
"RAAN changed by {:.3} deg",
orbit.raan_deg()? - future_sc.orbit.raan_deg()?
);
println!(
"AOP changed by {:.3} deg",
orbit.aop_deg()? - future_sc.orbit.aop_deg()?
);
println!(
"TA changed by {:.3} deg",
orbit.ta_deg()? - future_sc.orbit.ta_deg()?
);
// We also have access to the full trajectory throughout the propagation.
println!("{trajectory}");
println!("Spacecraft params after 3 years without active control:\n{future_sc:x}");
// With the trajectory, let's build a few data products.
// 1. Export the trajectory as a parquet file, which includes the Keplerian orbital elements.
let analysis_step = Unit::Minute * 5;
trajectory.to_parquet(
"./03_geo_hf_prop.parquet",
Some(vec![
&EclipseLocator::cislunar(almanac.clone()).to_penumbra_event()
]),
ExportCfg::builder().step(analysis_step).build(),
almanac.clone(),
)?;
// 2. Compute the latitude, longitude, and altitude throughout the trajectory by rotating the spacecraft position into the Earth body fixed frame.
// We iterate over the trajectory, grabbing a state every two minutes.
let mut offset_s = vec![];
let mut epoch_str = vec![];
let mut longitude_deg = vec![];
let mut latitude_deg = vec![];
let mut altitude_km = vec![];
for state in trajectory.every(analysis_step) {
// Convert the GEO bird state into the body fixed frame, and keep track of its latitude, longitude, and altitude.
// These define the GEO stationkeeping box.
let this_epoch = state.epoch();
offset_s.push((this_epoch - orbit.epoch).to_seconds());
epoch_str.push(this_epoch.to_isoformat());
let state_bf = almanac.transform_to(state.orbit, IAU_EARTH_FRAME, None)?;
let (lat_deg, long_deg, alt_km) = state_bf.latlongalt()?;
longitude_deg.push(long_deg);
latitude_deg.push(lat_deg);
altitude_km.push(alt_km);
}
println!(
"Longitude changed by {:.3} deg -- Box is 0.1 deg E-W",
orig_long_deg - longitude_deg.last().unwrap()
);
println!(
"Latitude changed by {:.3} deg -- Box is 0.05 deg N-S",
orig_lat_deg - latitude_deg.last().unwrap()
);
println!(
"Altitude changed by {:.3} km -- Box is 30 km",
orig_alt_km - altitude_km.last().unwrap()
);
// Build the station keeping data frame.
let mut sk_df = df!(
"Offset (s)" => offset_s.clone(),
"Epoch (UTC)" => epoch_str.clone(),
"Longitude E-W (deg)" => longitude_deg,
"Latitude N-S (deg)" => latitude_deg,
"Altitude (km)" => altitude_km,
)?;
// Create a file to write the Parquet to
let file = File::create("./03_geo_lla.parquet").expect("Could not create file");
// Create a ParquetWriter and write the DataFrame to the file
ParquetWriter::new(file).finish(&mut sk_df)?;
Ok(())
}
Sourcepub fn resample(&self, step: Duration) -> Result<Self, NyxError>
pub fn resample(&self, step: Duration) -> Result<Self, NyxError>
Allows resampling this trajectory at a fixed interval instead of using the propagator step size. This may lead to aliasing due to the Nyquist–Shannon sampling theorem.
Sourcepub fn rebuild(&self, epochs: &[Epoch]) -> Result<Self, NyxError>
pub fn rebuild(&self, epochs: &[Epoch]) -> Result<Self, NyxError>
Rebuilds this trajectory with the provided epochs. This may lead to aliasing due to the Nyquist–Shannon sampling theorem.
Sourcepub fn ric_diff_to_parquet<P: AsRef<Path>>(
&self,
other: &Self,
path: P,
cfg: ExportCfg,
) -> Result<PathBuf, Box<dyn Error>>
pub fn ric_diff_to_parquet<P: AsRef<Path>>( &self, other: &Self, path: P, cfg: ExportCfg, ) -> Result<PathBuf, Box<dyn Error>>
Export the difference in RIC from of this trajectory compare to the “other” trajectory in parquet format.
§Notes
- The RIC frame accounts for the transport theorem by performing a finite differencing of the RIC frame.
Examples found in repository?
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
fn main() -> Result<(), Box<dyn Error>> {
pel::init();
// ====================== //
// === ALMANAC SET UP === //
// ====================== //
// Dynamics models require planetary constants and ephemerides to be defined.
// Let's start by grabbing those by using ANISE's MetaAlmanac.
let data_folder: PathBuf = [env!("CARGO_MANIFEST_DIR"), "examples", "04_lro_od"]
.iter()
.collect();
let meta = data_folder.join("lro-dynamics.dhall");
// Load this ephem in the general Almanac we're using for this analysis.
let mut almanac = MetaAlmanac::new(meta.to_string_lossy().to_string())
.map_err(Box::new)?
.process(true)
.map_err(Box::new)?;
let mut moon_pc = almanac.planetary_data.get_by_id(MOON)?;
moon_pc.mu_km3_s2 = 4902.74987;
almanac.planetary_data.set_by_id(MOON, moon_pc)?;
let mut earth_pc = almanac.planetary_data.get_by_id(EARTH)?;
earth_pc.mu_km3_s2 = 398600.436;
almanac.planetary_data.set_by_id(EARTH, earth_pc)?;
// Save this new kernel for reuse.
// In an operational context, this would be part of the "Lock" process, and should not change throughout the mission.
almanac
.planetary_data
.save_as(&data_folder.join("lro-specific.pca"), true)?;
// Lock the almanac (an Arc is a read only structure).
let almanac = Arc::new(almanac);
// Orbit determination requires a Trajectory structure, which can be saved as parquet file.
// In our case, the trajectory comes from the BSP file, so we need to build a Trajectory from the almanac directly.
// To query the Almanac, we need to build the LRO frame in the J2000 orientation in our case.
// Inspecting the LRO BSP in the ANISE GUI shows us that NASA has assigned ID -85 to LRO.
let lro_frame = Frame::from_ephem_j2000(-85);
// To build the trajectory we need to provide a spacecraft template.
let sc_template = Spacecraft::builder()
.dry_mass_kg(1018.0) // Launch masses
.fuel_mass_kg(900.0)
.srp(SrpConfig {
// SRP configuration is arbitrary, but we will be estimating it anyway.
area_m2: 3.9 * 2.7,
cr: 0.96,
})
.orbit(Orbit::zero(MOON_J2000)) // Setting a zero orbit here because it's just a template
.build();
// Now we can build the trajectory from the BSP file.
// We'll arbitrarily set the tracking arc to 48 hours with a one minute time step.
let traj_as_flown = Traj::from_bsp(
lro_frame,
MOON_J2000,
almanac.clone(),
sc_template,
5.seconds(),
Some(Epoch::from_str("2024-01-01 00:00:00 UTC")?),
Some(Epoch::from_str("2024-01-02 00:00:00 UTC")?),
Aberration::LT,
Some("LRO".to_string()),
)?;
println!("{traj_as_flown}");
// ====================== //
// === MODEL MATCHING === //
// ====================== //
// Set up the spacecraft dynamics.
// Specify that the orbital dynamics must account for the graviational pull of the Earth and the Sun.
// The gravity of the Moon will also be accounted for since the spaceraft in a lunar orbit.
let mut orbital_dyn = OrbitalDynamics::point_masses(vec![EARTH, SUN, JUPITER_BARYCENTER]);
// We want to include the spherical harmonics, so let's download the gravitational data from the Nyx Cloud.
// We're using the GRAIL JGGRX model.
let mut jggrx_meta = MetaFile {
uri: "http://public-data.nyxspace.com/nyx/models/Luna_jggrx_1500e_sha.tab.gz".to_string(),
crc32: Some(0x6bcacda8), // Specifying the CRC32 avoids redownloading it if it's cached.
};
// And let's download it if we don't have it yet.
jggrx_meta.process(true)?;
// Build the spherical harmonics.
// The harmonics must be computed in the body fixed frame.
// We're using the long term prediction of the Moon principal axes frame.
let moon_pa_frame = MOON_PA_FRAME.with_orient(31008);
// let moon_pa_frame = IAU_MOON_FRAME;
let sph_harmonics = Harmonics::from_stor(
almanac.frame_from_uid(moon_pa_frame)?,
HarmonicsMem::from_shadr(&jggrx_meta.uri, 80, 80, true)?,
);
// Include the spherical harmonics into the orbital dynamics.
orbital_dyn.accel_models.push(sph_harmonics);
// We define the solar radiation pressure, using the default solar flux and accounting only
// for the eclipsing caused by the Earth and Moon.
// Note that by default, enabling the SolarPressure model will also enable the estimation of the coefficient of reflectivity.
let srp_dyn = SolarPressure::new(vec![EARTH_J2000, MOON_J2000], almanac.clone())?;
// Finalize setting up the dynamics, specifying the force models (orbital_dyn) separately from the
// acceleration models (SRP in this case). Use `from_models` to specify multiple accel models.
let dynamics = SpacecraftDynamics::from_model(orbital_dyn, srp_dyn);
println!("{dynamics}");
// Now we can build the propagator.
let setup = Propagator::default_dp78(dynamics.clone());
// For reference, let's build the trajectory with Nyx's models from that LRO state.
let (sim_final, traj_as_sim) = setup
.with(*traj_as_flown.first(), almanac.clone())
.until_epoch_with_traj(traj_as_flown.last().epoch())?;
println!("SIM INIT: {:x}", traj_as_flown.first());
println!("SIM FINAL: {sim_final:x}");
// Compute RIC difference between SIM and LRO ephem
let sim_lro_delta = sim_final
.orbit
.ric_difference(&traj_as_flown.last().orbit)?;
println!("{traj_as_sim}");
println!(
"SIM v LRO - RIC Position (m): {:.3}",
sim_lro_delta.radius_km * 1e3
);
println!(
"SIM v LRO - RIC Velocity (m/s): {:.3}",
sim_lro_delta.velocity_km_s * 1e3
);
traj_as_sim.ric_diff_to_parquet(
&traj_as_flown,
"./04_lro_sim_truth_error.parquet",
ExportCfg::default(),
)?;
// ==================== //
// === OD SIMULATOR === //
// ==================== //
// After quite some time trying to exactly match the model, we still end up with an oscillatory difference on the order of 150 meters between the propagated state
// and the truth LRO state.
// Therefore, we will actually run an estimation from a dispersed LRO state.
// The sc_seed is the true LRO state from the BSP.
let sc_seed = *traj_as_flown.first();
// Load the Deep Space Network ground stations.
// Nyx allows you to build these at runtime but it's pretty static so we can just load them from YAML.
let ground_station_file: PathBuf = [
env!("CARGO_MANIFEST_DIR"),
"examples",
"04_lro_od",
"dsn-network.yaml",
]
.iter()
.collect();
let devices = GroundStation::load_named(ground_station_file)?;
// Typical OD software requires that you specify your own tracking schedule or you'll have overlapping measurements.
// Nyx can build a tracking schedule for you based on the first station with access.
let trkconfg_yaml: PathBuf = [
env!("CARGO_MANIFEST_DIR"),
"examples",
"04_lro_od",
"tracking-cfg.yaml",
]
.iter()
.collect();
let configs: BTreeMap<String, TrkConfig> = TrkConfig::load_named(trkconfg_yaml)?;
// Build the tracking arc simulation to generate a "standard measurement".
let mut trk = TrackingArcSim::<Spacecraft, GroundStation>::new(
devices.clone(),
traj_as_flown.clone(),
configs,
)?;
trk.build_schedule(almanac.clone())?;
let arc = trk.generate_measurements(almanac.clone())?;
// Save the simulated tracking data
arc.to_parquet_simple("./04_lro_simulated_tracking.parquet")?;
// We'll note that in our case, we have continuous coverage of LRO when the vehicle is not behind the Moon.
println!("{arc}");
// Now that we have simulated measurements, we'll run the orbit determination.
// ===================== //
// === OD ESTIMATION === //
// ===================== //
let sc = SpacecraftUncertainty::builder()
.nominal(sc_seed)
.frame(LocalFrame::RIC)
.x_km(0.5)
.y_km(0.5)
.z_km(0.5)
.vx_km_s(5e-3)
.vy_km_s(5e-3)
.vz_km_s(5e-3)
.build();
// Build the filter initial estimate, which we will reuse in the filter.
let initial_estimate = sc.to_estimate()?;
println!("== FILTER STATE ==\n{sc_seed:x}\n{initial_estimate}");
let kf = KF::new(
// Increase the initial covariance to account for larger deviation.
initial_estimate,
// Until https://github.com/nyx-space/nyx/issues/351, we need to specify the SNC in the acceleration of the Moon J2000 frame.
SNC3::from_diagonal(10 * Unit::Minute, &[1e-11, 1e-11, 1e-11]),
);
// We'll set up the OD process to reject measurements whose residuals are mover than 4 sigmas away from what we expect.
let mut odp = SpacecraftODProcess::ckf(
setup.with(initial_estimate.state().with_stm(), almanac.clone()),
kf,
devices,
Some(ResidRejectCrit::default()),
almanac.clone(),
);
odp.process_arc(&arc)?;
let ric_err = traj_as_flown
.at(odp.estimates.last().unwrap().epoch())?
.orbit
.ric_difference(&odp.estimates.last().unwrap().orbital_state())?;
println!("== RIC at end ==");
println!("RIC Position (m): {}", ric_err.radius_km * 1e3);
println!("RIC Velocity (m/s): {}", ric_err.velocity_km_s * 1e3);
odp.to_parquet(&arc, "./04_lro_od_results.parquet", ExportCfg::default())?;
// In our case, we have the truth trajectory from NASA.
// So we can compute the RIC state difference between the real LRO ephem and what we've just estimated.
// Export the OD trajectory first.
let od_trajectory = odp.to_traj()?;
// Build the RIC difference.
od_trajectory.ric_diff_to_parquet(
&traj_as_flown,
"./04_lro_od_truth_error.parquet",
ExportCfg::default(),
)?;
Ok(())
}
Source§impl<S: Interpolatable> Traj<S>
impl<S: Interpolatable> Traj<S>
Sourcepub fn find_bracketed<E>(
&self,
start: Epoch,
end: Epoch,
event: &E,
almanac: Arc<Almanac>,
) -> Result<EventDetails<S>, EventError>where
E: EventEvaluator<S>,
pub fn find_bracketed<E>(
&self,
start: Epoch,
end: Epoch,
event: &E,
almanac: Arc<Almanac>,
) -> Result<EventDetails<S>, EventError>where
E: EventEvaluator<S>,
Find the exact state where the request event happens. The event function is expected to be monotone in the provided interval because we find the event using a Brent solver.
Sourcepub fn find<E>(
&self,
event: &E,
almanac: Arc<Almanac>,
) -> Result<Vec<EventDetails<S>>, EventError>where
E: EventEvaluator<S>,
pub fn find<E>(
&self,
event: &E,
almanac: Arc<Almanac>,
) -> Result<Vec<EventDetails<S>>, EventError>where
E: EventEvaluator<S>,
Find all of the states where the event happens
§Limitations
This method uses a Brent solver. If the function that defines the event is not unimodal, the event finder may not converge correctly.
§Heuristic detail
The initial search step is 1% of the duration of the trajectory duration. For example, if the trajectory is 100 days long, then we split the trajectory into 100 chunks of 1 day and see whether the event is in there. If the event happens twice or more times within 1% of the trajectory duration, only the one of such events will be found.
If this heuristic fails to find any such events, then find_minmax
is called on the event with a time precision of Unit::Second
.
Then we search only within the min and max bounds of the provided event.
Sourcepub fn find_minmax<E>(
&self,
event: &E,
precision: Unit,
almanac: Arc<Almanac>,
) -> Result<(S, S), EventError>where
E: EventEvaluator<S>,
pub fn find_minmax<E>(
&self,
event: &E,
precision: Unit,
almanac: Arc<Almanac>,
) -> Result<(S, S), EventError>where
E: EventEvaluator<S>,
Find the minimum and maximum of the provided event through the trajectory
Sourcepub fn find_arcs<E>(
&self,
event: &E,
almanac: Arc<Almanac>,
) -> Result<Vec<EventArc<S>>, EventError>where
E: EventEvaluator<S>,
pub fn find_arcs<E>(
&self,
event: &E,
almanac: Arc<Almanac>,
) -> Result<Vec<EventArc<S>>, EventError>where
E: EventEvaluator<S>,
Identifies and pairs rising and falling edge events in a trajectory.
This function processes a sequence of events in a trajectory and pairs each rising edge event with its subsequent falling edge event to form arcs. Each arc represents a complete cycle of an event rising above and then falling below a specified threshold. Use this to analyze a trajectory’s behavior when understanding the complete cycle of an event (from rising to falling) is essential, e.g. ground station passes.
§Arguments
event
: A reference to an object implementing theEventEvaluator<S>
trait, which is used to evaluate and classify events in the trajectory.
§Returns
Result<Vec<EventArc>, NyxError>
: On success, returns a vector of EventArc, where each struct contains a pair ofEventDetails
(one for the rising edge and one for the falling edge). Returns an error if any issues occur during the event evaluation process.
§Logic
- Sorts the events by their epoch to ensure chronological processing.
- Iterates through the sorted events, identifying transitions from falling to rising edges and vice versa.
- Pairs a rising edge with the subsequent falling edge to form an arc.
- Handles edge cases where the trajectory starts or ends with a rising or falling edge.
- Prints debug information for each event and arc.
§Note
If no zero crossing happens in the trajectory, i.e. the there is “event is true” and “event is false”, then this function checks whether the event is true at the start and end of the trajectory. If so, it means that there is a single arc that spans the whole trajectory.
Trait Implementations§
Source§impl<S: Interpolatable> Add for Traj<S>
impl<S: Interpolatable> Add for Traj<S>
Source§impl<S: Interpolatable> AddAssign<&Traj<S>> for Traj<S>
impl<S: Interpolatable> AddAssign<&Traj<S>> for Traj<S>
Source§fn add_assign(&mut self, rhs: &Self)
fn add_assign(&mut self, rhs: &Self)
Attempt to add two trajectories together and assign it to self
§Warnings
- This will panic if the frames mismatch!
- This is inefficient because both
self
andrhs
are cloned.
Source§impl<S: Interpolatable> Debug for Traj<S>
impl<S: Interpolatable> Debug for Traj<S>
Source§impl<S: Interpolatable> Default for Traj<S>
impl<S: Interpolatable> Default for Traj<S>
Source§impl<S: Interpolatable> Display for Traj<S>
impl<S: Interpolatable> Display for Traj<S>
impl<S: Interpolatable> StructuralPartialEq for Traj<S>
Auto Trait Implementations§
impl<S> Freeze for Traj<S>where
DefaultAllocator: Sized,
impl<S> RefUnwindSafe for Traj<S>
impl<S> Send for Traj<S>where
DefaultAllocator: Sized,
impl<S> Sync for Traj<S>where
DefaultAllocator: Sized,
impl<S> Unpin for Traj<S>
impl<S> UnwindSafe for Traj<S>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read more§impl<T> Pointable for T
impl<T> Pointable for T
§impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
§fn to_subset(&self) -> Option<SS>
fn to_subset(&self) -> Option<SS>
self
from the equivalent element of its
superset. Read more§fn is_in_subset(&self) -> bool
fn is_in_subset(&self) -> bool
self
is actually part of its subset T
(and can be converted to it).§fn to_subset_unchecked(&self) -> SS
fn to_subset_unchecked(&self) -> SS
self.to_subset
but without any property checks. Always succeeds.§fn from_subset(element: &SS) -> SP
fn from_subset(element: &SS) -> SP
self
to the equivalent element of its superset.