Skip to content

Commit

Permalink
Merge pull request #205 from TilBlechschmidt/issue-204
Browse files Browse the repository at this point in the history
Limit usage of std::Instant to non-wasm targets
  • Loading branch information
ChristopherRabotin authored Jul 27, 2023
2 parents eec86a3 + 5e2d283 commit 80bbdce
Show file tree
Hide file tree
Showing 8 changed files with 81 additions and 20 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@ dist/
*.parquet
*.profraw
lcov.txt

.DS_Store
3 changes: 3 additions & 0 deletions src/cosmic/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ use hifitime::SECONDS_PER_DAY;
use std::fmt;
use std::fs::File;
use std::io::Read;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;

/// A trait allowing for something to have an epoch
Expand Down Expand Up @@ -180,10 +181,12 @@ impl Xb {
return Err(NyxError::LoadingError("XB buffer is empty".to_string()));
}

#[cfg(not(target_arch = "wasm32"))]
let decode_start = Instant::now();

match Self::decode(input_xb_buf) {
Ok(xb) => {
#[cfg(not(target_arch = "wasm32"))]
debug!("Loaded XB in {} ms.", decode_start.elapsed().as_millis());
Ok(xb)
}
Expand Down
37 changes: 24 additions & 13 deletions src/mc/montecarlo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ use crate::mc::DispersedState;
use crate::md::trajectory::Interpolatable;
use crate::md::EventEvaluator;
use crate::propagators::{ErrorCtrl, Propagator};
use crate::time::{Duration, Epoch, Unit};
#[cfg(not(target_arch = "wasm32"))]
use crate::time::Unit;
use crate::time::{Duration, Epoch};
use crate::State;
use indicatif::{ParallelProgressIterator, ProgressBar, ProgressStyle};
use rand_distr::Distribution;
Expand All @@ -34,6 +36,7 @@ use rayon::prelude::*;
use std::f64;
use std::fmt;
use std::sync::mpsc::channel;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant as StdInstant;

/// A Monte Carlo framework, automatically running on all threads via a thread pool. This framework is targeted toward analysis of time-continuous variables.
Expand Down Expand Up @@ -126,6 +129,7 @@ where
let (tx, rx) = channel();

// Generate all states (must be done separately because the rng is not thread safe)
#[cfg(not(target_arch = "wasm32"))]
let start = StdInstant::now();
init_states.par_iter().progress_with(pb).for_each_with(
(prop, tx),
Expand All @@ -147,12 +151,15 @@ where
},
);

let clock_time = StdInstant::now() - start;
println!(
"Propagated {} states in {}",
num_runs,
clock_time.as_secs_f64() * Unit::Second
);
#[cfg(not(target_arch = "wasm32"))]
{
let clock_time = StdInstant::now() - start;
println!(
"Propagated {} states in {}",
num_runs,
clock_time.as_secs_f64() * Unit::Second
);
}

// Collect all of the results and sort them by run index
let mut runs = rx
Expand Down Expand Up @@ -214,6 +221,7 @@ where
let (tx, rx) = channel();

// And propagate on the thread pool
#[cfg(not(target_arch = "wasm32"))]
let start = StdInstant::now();
init_states.par_iter().progress_with(pb).for_each_with(
(prop, tx),
Expand All @@ -236,12 +244,15 @@ where
},
);

let clock_time = StdInstant::now() - start;
println!(
"Propagated {} states in {}",
num_runs,
clock_time.as_secs_f64() * Unit::Second
);
#[cfg(not(target_arch = "wasm32"))]
{
let clock_time = StdInstant::now() - start;
println!(
"Propagated {} states in {}",
num_runs,
clock_time.as_secs_f64() * Unit::Second
);
}

// Collect all of the results and sort them by run index
let mut runs = rx.iter().collect::<Vec<Run<S, PropResult<S>>>>();
Expand Down
5 changes: 5 additions & 0 deletions src/md/opti/raphson_finite_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use crate::propagators::error_ctrl::ErrorCtrl;
use crate::pseudo_inverse;
use hifitime::TimeUnits;
use rayon::prelude::*;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;

impl<'a, E: ErrorCtrl, const V: usize, const O: usize> Optimizer<'a, E, V, O> {
Expand Down Expand Up @@ -195,6 +196,7 @@ impl<'a, E: ErrorCtrl, const V: usize, const O: usize> Optimizer<'a, E, V, O> {

let width = f64::from(max_obj_val).log10() as usize + 2 + max_obj_tol;

#[cfg(not(target_arch = "wasm32"))]
let start_instant = Instant::now();

for it in 0..=self.iterations {
Expand Down Expand Up @@ -457,7 +459,10 @@ impl<'a, E: ErrorCtrl, const V: usize, const O: usize> Optimizer<'a, E, V, O> {
}

if converged {
#[cfg(not(target_arch = "wasm32"))]
let conv_dur = Instant::now() - start_instant;
#[cfg(target_arch = "wasm32")]
let conv_dur = Duration::ZERO.into();
let mut corrected_state = xi_start;

let mut state_correction = Vector6::<f64>::zeros();
Expand Down
5 changes: 5 additions & 0 deletions src/md/opti/raphson_hyperdual.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pub use crate::md::{Variable, Vary};
use crate::propagators::error_ctrl::ErrorCtrl;
use crate::pseudo_inverse;
use crate::utils::are_eigenvalues_stable;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;

impl<'a, E: ErrorCtrl, const V: usize, const O: usize> Optimizer<'a, E, V, O> {
Expand Down Expand Up @@ -118,6 +119,7 @@ impl<'a, E: ErrorCtrl, const V: usize, const O: usize> Optimizer<'a, E, V, O> {

let width = f64::from(max_obj_val).log10() as usize + 2 + max_obj_tol;

#[cfg(not(target_arch = "wasm32"))]
let start_instant = Instant::now();

for it in 0..=self.iterations {
Expand Down Expand Up @@ -216,7 +218,10 @@ impl<'a, E: ErrorCtrl, const V: usize, const O: usize> Optimizer<'a, E, V, O> {
}

if converged {
#[cfg(not(target_arch = "wasm32"))]
let conv_dur = Instant::now() - start_instant;
#[cfg(target_arch = "wasm32")]
let conv_dur = Duration::ZERO.into();
let mut state = xi_start;
// Convert the total correction from VNC back to integration frame in case that's needed.
for (i, var) in self.variables.iter().enumerate() {
Expand Down
12 changes: 12 additions & 0 deletions src/md/trajectory/orbit_traj.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ use std::io::{BufRead, BufReader, BufWriter, Write};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Arc;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;

impl Traj<Orbit> {
Expand All @@ -44,19 +45,30 @@ impl Traj<Orbit> {
"No trajectory to convert".to_string(),
)));
}

#[cfg(not(target_arch = "wasm32"))]
let start_instant = Instant::now();
let mut traj = Self::new();
for state in &self.states {
traj.states.push(cosm.frame_chg(state, new_frame));
}
traj.finalize();

#[cfg(not(target_arch = "wasm32"))]
info!(
"Converted trajectory from {} to {} in {} ms: {traj}",
self.first().frame,
new_frame,
(Instant::now() - start_instant).as_millis()
);

#[cfg(target_arch = "wasm32")]
info!(
"Converted trajectory from {} to {}: {traj}",
self.first().frame,
new_frame,
);

Ok(traj)
}

Expand Down
12 changes: 12 additions & 0 deletions src/md/trajectory/sc_traj.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ use std::collections::HashMap;
use std::error::Error;
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;

impl Traj<Spacecraft> {
Expand All @@ -38,6 +39,8 @@ impl Traj<Spacecraft> {
"No trajectory to convert".to_string(),
)));
}

#[cfg(not(target_arch = "wasm32"))]
let start_instant = Instant::now();
let mut traj = Self::new();
for state in &self.states {
Expand All @@ -46,12 +49,21 @@ impl Traj<Spacecraft> {
}
traj.finalize();

#[cfg(not(target_arch = "wasm32"))]
info!(
"Converted trajectory from {} to {} in {} ms: {traj}",
self.first().orbit.frame,
new_frame,
(Instant::now() - start_instant).as_millis()
);

#[cfg(target_arch = "wasm32")]
info!(
"Converted trajectory from {} to {}: {traj}",
self.first().orbit.frame,
new_frame,
);

Ok(traj)
}

Expand Down
25 changes: 19 additions & 6 deletions src/propagators/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ use rayon::iter::ParallelBridge;
use rayon::prelude::ParallelIterator;
use std::f64;
use std::sync::mpsc::{channel, Sender};
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;

/// A Propagator allows propagating a set of dynamics forward or backward in time.
Expand Down Expand Up @@ -78,8 +79,11 @@ where
return Ok(self.state);
}
let stop_time = self.state.epoch() + duration;

#[cfg(not(target_arch = "wasm32"))]
let tick = Instant::now();
let log_progress = duration.abs() >= 2 * Unit::Minute;

if log_progress {
// Prevent the print spam for orbit determination cases
info!("Propagating for {} until {}", duration, stop_time);
Expand All @@ -98,9 +102,12 @@ where
{
if stop_time == epoch {
// No propagation necessary
if log_progress {
let tock: Duration = tick.elapsed().into();
info!("Done in {}", tock);
#[cfg(not(target_arch = "wasm32"))]
{
if log_progress {
let tock: Duration = tick.elapsed().into();
info!("Done in {}", tock);
}
}
return Ok(self.state);
}
Expand All @@ -120,13 +127,19 @@ where

// Restore the step size for subsequent calls
self.set_step(prev_step_size, prev_step_kind);

if backprop {
self.step_size = -self.step_size; // Restore to a positive step size
}
if log_progress {
let tock: Duration = tick.elapsed().into();
info!("Done in {}", tock);

#[cfg(not(target_arch = "wasm32"))]
{
if log_progress {
let tock: Duration = tick.elapsed().into();
info!("Done in {}", tock);
}
}

return Ok(self.state);
} else {
self.single_step()?;
Expand Down

0 comments on commit 80bbdce

Please sign in to comment.