Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support TraceBWConfig #13

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/cargo-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ jobs:
uses: Swatinem/rust-cache@v1
- name: cargo test
run: |
cargo test --no-fail-fast --verbose --features mahimahi --features serde
cargo test --no-fail-fast --verbose --features mahimahi --features serde --features truncated-normal

cargo-test-full:
runs-on: ubuntu-latest
Expand Down
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ serde = { version = "1.0", features = ["derive"], optional = true }
typetag = { version = "0.2.5", optional = true }
humantime-serde = { version = "1.1.1", optional = true }
human-bandwidth = { version = "0.1.1", optional = true }
statrs = { version = "0.17.1", optional = true}


[dev-dependencies]
serde_json = "1.0"
Expand All @@ -39,6 +41,7 @@ serde = ["dep:serde", "dep:typetag", "bandwidth/serde"]
mahimahi = ["dep:itertools"]
human = ["serde", "dep:humantime-serde", "dep:human-bandwidth", "human-bandwidth/serde"]
full = ["model", "mahimahi", "human"]
truncated-normal = ["statrs"]

[package.metadata.docs.rs]
all-features = true
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,9 +144,9 @@ pub type LossPattern = Vec<f64>;
/// The meaning of the duplicate_pattern sequence is:
///
/// - The probability on index 0 describes how likely a packet will be duplicated
/// **if the previous packet was transmitted normally**.
/// **if the previous packet was transmitted normally**.
/// - The probability on index 1 describes how likely a packet will be duplicated
/// **if the previous packet was duplicated**.
/// **if the previous packet was duplicated**.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should also add a unit test for model TraceBw in this file.

/// - ...
///
/// For example, if the duplicate_pattern is [0.8, 0.1], and packet 100 is not duplicated, then the
Expand Down
201 changes: 201 additions & 0 deletions src/model/bw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ dyn_clone::clone_trait_object!(BwTraceConfig);
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

#[cfg(feature = "truncated-normal")]
use super::solve_truncate::solve;

/// The model of a static bandwidth trace.
///
/// ## Examples
Expand Down Expand Up @@ -476,6 +479,129 @@ pub struct RepeatedBwPatternConfig {
pub count: usize,
}

/// This model is used to enable a more compact trace.
///
/// ## Examples
///
/// ```
/// # use netem_trace::model::TraceBwConfig;
/// # use netem_trace::{Bandwidth, Duration, BwTrace};
/// use crate::netem_trace::model::Forever;
/// use netem_trace::model::BwTraceConfig;
///
/// let mut tracebw = TraceBwConfig::new().pattern(
/// vec![
/// (Duration::from_millis(1), vec![Bandwidth::from_mbps(2),Bandwidth::from_mbps(4),]),
/// (Duration::from_millis(2), vec![Bandwidth::from_mbps(1)]),
/// ]
/// ).build();
///
/// assert_eq!(tracebw.next_bw(), Some((Bandwidth::from_mbps(2), Duration::from_millis(1))));
/// assert_eq!(tracebw.next_bw(), Some((Bandwidth::from_mbps(4), Duration::from_millis(1))));
/// assert_eq!(tracebw.next_bw(), Some((Bandwidth::from_mbps(1), Duration::from_millis(2))));
/// assert_eq!(tracebw.next_bw(), None);
/// assert_eq!(tracebw.next_bw(), None);
/// assert_eq!(tracebw.next_bw(), None);
///
/// let repeated_tracebw_config = TraceBwConfig::new().pattern(
/// vec![
/// (Duration::from_millis(1), vec![Bandwidth::from_mbps(2),Bandwidth::from_mbps(4),]),
/// (Duration::from_millis(2), vec![Bandwidth::from_mbps(1)]),
/// ]
/// ).forever();
///
/// let mut repeated_tracebw = repeated_tracebw_config.clone().build();
///
/// assert_eq!(repeated_tracebw.next_bw(), Some((Bandwidth::from_mbps(2), Duration::from_millis(1))));
/// assert_eq!(repeated_tracebw.next_bw(), Some((Bandwidth::from_mbps(4), Duration::from_millis(1))));
/// assert_eq!(repeated_tracebw.next_bw(), Some((Bandwidth::from_mbps(1), Duration::from_millis(2))));
///
/// assert_eq!(repeated_tracebw.next_bw(), Some((Bandwidth::from_mbps(2), Duration::from_millis(1))));
/// assert_eq!(repeated_tracebw.next_bw(), Some((Bandwidth::from_mbps(4), Duration::from_millis(1))));
/// assert_eq!(repeated_tracebw.next_bw(), Some((Bandwidth::from_mbps(1), Duration::from_millis(2))));
///
/// assert_eq!(repeated_tracebw.next_bw(), Some((Bandwidth::from_mbps(2), Duration::from_millis(1))));
/// assert_eq!(repeated_tracebw.next_bw(), Some((Bandwidth::from_mbps(4), Duration::from_millis(1))));
/// assert_eq!(repeated_tracebw.next_bw(), Some((Bandwidth::from_mbps(1), Duration::from_millis(2))));
///
///
/// let boxed_config : Box<dyn BwTraceConfig> = Box::new(repeated_tracebw_config);
/// let json_trace = serde_json::to_string(&boxed_config).unwrap();
///
/// let expected = "{\"RepeatedBwPatternConfig\":{\"pattern\":[{\"TraceBwConfig\":[[1.0,[2.0,4.0]],[2.0,[1.0]]]}],\"count\":0}}";
/// assert_eq!(json_trace , expected);
///
/// let des: Box<dyn BwTraceConfig> = serde_json::from_str(json_trace.as_str()).unwrap();
/// let mut model = des.into_model();
///
/// assert_eq!(model.next_bw(), Some((Bandwidth::from_mbps(2), Duration::from_millis(1))));
/// assert_eq!(model.next_bw(), Some((Bandwidth::from_mbps(4), Duration::from_millis(1))));
/// assert_eq!(model.next_bw(), Some((Bandwidth::from_mbps(1), Duration::from_millis(2))));
///
/// assert_eq!(model.next_bw(), Some((Bandwidth::from_mbps(2), Duration::from_millis(1))));
/// assert_eq!(model.next_bw(), Some((Bandwidth::from_mbps(4), Duration::from_millis(1))));
/// assert_eq!(model.next_bw(), Some((Bandwidth::from_mbps(1), Duration::from_millis(2))));
/// ```

pub struct TraceBw {
pattern: Vec<(Duration, Vec<Bandwidth>)>, // inner vector is never empty
index1: usize,
index2: usize,
}

/// The configuration struct for [`TraceBw`].
///
/// See [`TraceBwConfig`] for more details.
///
#[derive(Debug, Clone, Default)]
pub struct TraceBwConfig {
pub pattern: Vec<(Duration, Vec<Bandwidth>)>,
}

impl TraceBwConfig {
pub fn new() -> Self {
Self { pattern: vec![] }
}
pub fn pattern(mut self, pattern: Vec<(Duration, Vec<Bandwidth>)>) -> Self {
self.pattern = pattern;
self
}

pub fn build(self) -> TraceBw {
TraceBw {
pattern: self
.pattern
.into_iter()
.filter(|(_, bandwidths)| !bandwidths.is_empty())
.collect(),
index1: 0,
index2: 0,
}
}
}

impl BwTrace for TraceBw {
fn next_bw(&mut self) -> Option<(Bandwidth, Duration)> {
let result = self
.pattern
.get(self.index1)
.and_then(|(duration, bandwidth)| {
bandwidth
.get(self.index2)
.map(|bandwidth| (*bandwidth, *duration))
});
if result.is_some() {
if self.pattern[self.index1].1.len() > self.index2 + 1 {
self.index2 += 1;
} else {
self.index1 += 1;
self.index2 = 0;
}
}
result
}
}

impl BwTrace for StaticBw {
fn next_bw(&mut self) -> Option<(Bandwidth, Duration)> {
if let Some(duration) = self.duration.take() {
Expand Down Expand Up @@ -685,6 +811,79 @@ impl NormalizedBwConfig {
}
}

#[cfg(feature = "truncated-normal")]
impl NormalizedBwConfig {
/// This is another implementation for converting NormalizedBwConfig into NormalizedBw, where the impact
/// of truncation (`lower_bound` and `upper_bound` field) on the mathematical expectation of the distribution
/// is taking account by modifing the center of the distribution.
///
/// ## Examples
///
/// ```
///
/// # use netem_trace::model::NormalizedBwConfig;
/// # use netem_trace::{Bandwidth, Duration, BwTrace};
/// # use crate::netem_trace::model::Forever;
/// let normal_bw = NormalizedBwConfig::new()
/// .mean(Bandwidth::from_mbps(12))
/// .std_dev(Bandwidth::from_mbps(12))
/// .duration(Duration::from_secs(100))
/// .step(Duration::from_millis(1))
/// .seed(42);
///
/// let mut default_build = normal_bw.clone().build();
/// let mut truncate_build = normal_bw.clone().build_truncated();
///
/// fn avg_mbps(mut model: impl BwTrace) -> f64{
/// let mut count = 0;
/// std::iter::from_fn( move ||{
/// model.next_bw().map(|b| b.0.as_gbps_f64() * 1000.0)
/// }).inspect(|_| count += 1).sum::<f64>() / count as f64
/// }
///
/// assert_eq!(avg_mbps(default_build), 12.974758080079994); // significantly higher than the expected mean
/// assert_eq!(avg_mbps(truncate_build), 11.97642456625989);
///
/// let normal_bw = NormalizedBwConfig::new()
/// .mean(Bandwidth::from_mbps(12))
/// .std_dev(Bandwidth::from_mbps(12))
/// .duration(Duration::from_secs(100))
/// .lower_bound(Bandwidth::from_mbps(8))
/// .upper_bound(Bandwidth::from_mbps(20))
/// .step(Duration::from_millis(1))
/// .seed(42);
///
/// let mut default_build = normal_bw.clone().build();
/// let mut truncate_build = normal_bw.clone().build_truncated();
///
/// assert_eq!(avg_mbps(default_build), 13.221356471729928); // significantly higher than the expected mean
/// assert_eq!(avg_mbps(truncate_build), 11.978819427569897);
///
/// ```
///

pub fn build_truncated(mut self) -> NormalizedBw {
let mean = self
.mean
.unwrap_or_else(|| Bandwidth::from_mbps(12))
.as_gbps_f64();
let sigma = self
.std_dev
.unwrap_or_else(|| Bandwidth::from_mbps(0))
.as_gbps_f64()
/ mean;
let lower = self
.lower_bound
.unwrap_or_else(|| Bandwidth::from_mbps(0))
.as_gbps_f64()
/ mean;
let upper = self.upper_bound.map(|upper| upper.as_gbps_f64() / mean);
let new_mean = mean * solve(1f64, sigma, Some(lower), upper).unwrap_or(1f64);
self.mean = Some(Bandwidth::from_gbps_f64(new_mean));
self.build()
}
}

impl SawtoothBwConfig {
pub fn new() -> Self {
Self {
Expand Down Expand Up @@ -831,6 +1030,7 @@ impl_bw_trace_config!(StaticBwConfig);
impl_bw_trace_config!(NormalizedBwConfig);
impl_bw_trace_config!(SawtoothBwConfig);
impl_bw_trace_config!(RepeatedBwPatternConfig);
impl_bw_trace_config!(TraceBwConfig);

/// Turn a [`BwTraceConfig`] into a forever repeated [`RepeatedBwPatternConfig`].
pub trait Forever: BwTraceConfig {
Expand All @@ -854,6 +1054,7 @@ macro_rules! impl_forever {
impl_forever!(StaticBwConfig);
impl_forever!(NormalizedBwConfig);
impl_forever!(SawtoothBwConfig);
impl_forever!(TraceBwConfig);

impl Forever for RepeatedBwPatternConfig {
fn forever(self) -> RepeatedBwPatternConfig {
Expand Down
10 changes: 8 additions & 2 deletions src/model/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ pub mod bw;
#[cfg(feature = "bw-model")]
pub use bw::{
BwTraceConfig, Forever, NormalizedBwConfig, RepeatedBwPatternConfig, SawtoothBwConfig,
StaticBwConfig,
StaticBwConfig, TraceBwConfig,
};
#[cfg(feature = "bw-model")]
pub use bw::{NormalizedBw, RepeatedBwPattern, SawtoothBw, StaticBw};
pub use bw::{NormalizedBw, RepeatedBwPattern, SawtoothBw, StaticBw, TraceBw};

#[cfg(feature = "delay-model")]
pub mod delay;
Expand All @@ -45,3 +45,9 @@ pub mod duplicate;
pub use duplicate::{DuplicateTraceConfig, RepeatedDuplicatePatternConfig, StaticDuplicateConfig};
#[cfg(feature = "duplicate-model")]
pub use duplicate::{RepeatedDuplicatePattern, StaticDuplicate};

#[cfg(feature = "truncated-normal")]
pub mod solve_truncate;

#[cfg(feature = "serde")]
pub mod trace_serde;
Comment on lines +52 to +53
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you please confirm that this mod is valid if only feature serde is enabled? Can the library still be correctly compiled if you don't enable feature bw-model but enable serde, since you have used some structs valid with only bw-model enabled?

I do think you can just merge this module into the bw module, as you only impl se/des for TraceBwConfig.

Loading
Loading