Skip to content

Commit

Permalink
remove multiparallel
Browse files Browse the repository at this point in the history
  • Loading branch information
0xJepsen committed Nov 5, 2023
1 parent d0fe416 commit 46d3cb9
Show file tree
Hide file tree
Showing 6 changed files with 36 additions and 92 deletions.
3 changes: 1 addition & 2 deletions src/agents/block_admin.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use crate::settings::{SimulationConfig, parameters::Fixed};

use super::*;

Expand Down Expand Up @@ -29,7 +28,7 @@ impl BlockAdmin {
///
/// # Returns
/// * [`Result<Self>`] - A result containing the new BlockAdmin or an error.
pub async fn new(environment: &Environment, config: &SimulationConfig<Fixed>) -> Result<Self> {
pub async fn new(environment: &Environment, config: &SimulationConfig) -> Result<Self> {
let client = RevmMiddleware::new(environment, "block_admin".into())?;
let timestep_size = config.block.timestep_size;
let block_number = client.get_block_number().await?.as_u64();
Expand Down
4 changes: 3 additions & 1 deletion src/config/dispute_game.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
simulation = "dispute_game"
simulation = "DisputeGame"
output_directory = "analysis/dispute_game"

[block]
timestep_size = 15
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ struct Args {
enum Commands {
/// Represents the `Bind` subcommand.
Simulate {
#[clap(index = 1, default_value = "src/config/gbm.toml")]
#[clap(index = 1, default_value = "src/config/dispute_game.toml")]
config_path: String,
},
}
Expand Down
54 changes: 2 additions & 52 deletions src/settings/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use serde::{Deserialize, Serialize};
/// This struct holds all the necessary parameters and configurations needed to run a simulation.
/// It encompasses several sub-configurations such as `TrajectoryParameters` and `GBMParameters`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SimulationConfig<P: Parameterized<f64>> {
pub struct SimulationConfig {
/// The type of simulation to run, defined by an enum `SimulationType`.
pub simulation: SimulationType,

Expand All @@ -24,17 +24,11 @@ pub struct SimulationConfig<P: Parameterized<f64>> {
/// Name of the file where the simulation results will be written.
pub output_file_name: Option<String>,

/// Parameters specific to the trajectory of the simulation.
pub trajectory: TrajectoryParameters<P>,

/// Parameters specific to the Geometric Brownian Motion (GBM) if applicable.
pub gbm: Option<GBMParameters<P>>,

/// Parameters related to block configurations.
pub block: BlockParameters,
}

impl SimulationConfig<Meta> {
impl SimulationConfig {
/// Creates a new `SimulationConfig` instance from a configuration file.
///
/// Reads the specified configuration file and deserializes it into a `SimulationConfig` object.
Expand All @@ -45,48 +39,4 @@ impl SimulationConfig<Meta> {
.build()?;
s.try_deserialize()
}
}

impl Parameterized<SimulationConfig<Fixed>> for SimulationConfig<Meta> {
/// Generates a list of `SimulationConfig` instances with fixed parameters.
///
/// This method is responsible for taking the meta parameters defined in the configuration,
/// generating the actual fixed parameters, and creating a list of complete `SimulationConfig` instances.
fn generate(&self) -> Vec<SimulationConfig<Fixed>> {
let mut result = vec![];
let trajectories = self.trajectory.generate();

let gbms = self
.gbm
.as_ref()
.map(|gbm| gbm.generate())
.unwrap_or_default();

if gbms.is_empty() {
panic!("You must supply either a gbm configuration.");
}

for trajectory in &trajectories {
for gbm in &gbms {
let output_directory = self.output_directory.clone()
+ "/gbm_drift="
+ &gbm.drift.0.to_string()
+ "_vol="
+ &gbm.volatility.0.to_string();
let output_file_name =
format!("trajectory={}", trajectory.output_tag.clone().unwrap());
result.push(SimulationConfig {
simulation: self.simulation,
max_parallel: None,
output_directory,
output_file_name: Some(output_file_name),
trajectory: trajectory.clone(),
gbm: Some(*gbm),
block: self.block,
});
}
}

result
}
}
10 changes: 7 additions & 3 deletions src/simulations/dispute_game.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::*;
use alloy_primitives::Bytes;
use anyhow::Ok;
use arbiter_core::environment::{builder::EnvironmentBuilder, cheatcodes::Cheatcodes, Environment};
use ethers::types::U256 as eU256;

Expand Down Expand Up @@ -27,10 +27,14 @@ pub struct SimulationContracts {
pub factory: DisputeGameFactory<RevmMiddleware>,
}

pub async fn setup(config: SimulationConfig<Fixed>) -> Result<Simulation> {
pub async fn setup(config: SimulationConfig) -> Result<Simulation> {

let (environment, admin, alice, bob, multisig) = set_up_agents().await?;
todo!()

let contracts = deploy_contracts(admin.clone()).await?;

todo!("setup the agents and return them")

}
pub async fn set_up_agents() -> Result<(
Environment,
Expand Down
55 changes: 22 additions & 33 deletions src/simulations/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ impl SimulationType {
///
/// This function matches on the `SimulationType` to determine which simulation setup to use,
/// then executes the chosen simulation.
async fn run(config: SimulationConfig<Fixed>) -> Result<()> {
async fn run(config: SimulationConfig) -> Result<()> {
let simulation = match config.simulation {
SimulationType::DisputeGame => {
dispute_game::setup(config.clone()).await?
Expand All @@ -69,8 +69,6 @@ pub fn batch(config_path: &str) -> Result<()> {
//
let config = SimulationConfig::new(config_path)?;

let direct_configs: Vec<SimulationConfig<Fixed>> = config.generate();

// Create a multi-threaded runtime
let rt = Builder::new_multi_thread().build()?;

Expand All @@ -80,39 +78,30 @@ pub fn batch(config_path: &str) -> Result<()> {
.map(|max_parallel| Arc::new(Semaphore::new(max_parallel)));

rt.block_on(async {
let mut handles = vec![];
let errors = Arc::new(tokio::sync::Mutex::new(vec![]));
let errors_clone = errors.clone();
let semaphore_clone = semaphore.clone();
// Acquire a permit inside the spawned task
let permit = if let Some(ref semaphore_clone) = semaphore_clone {
// Acquire a permit outside the spawned task
let permit = semaphore_clone.acquire().await.unwrap();
Some(permit)
} else {
None
};

for config in direct_configs {
let errors_clone = errors.clone();
let semaphore_clone = semaphore.clone();
handles.push(tokio::spawn(async move {
// Acquire a permit inside the spawned task
let permit = if let Some(ref semaphore_clone) = semaphore_clone {
// Acquire a permit outside the spawned task
let permit = semaphore_clone.acquire().await.unwrap();
Some(permit)
} else {
None
};

let result = SimulationType::run(config).await;
match result {
Err(e) => {
let mut errors_clone_lock = errors_clone.lock().await;
errors_clone_lock.push(e);
// Drop the permit when the simulation is done.
drop(permit);
}
Result::Ok(_) => {
drop(permit);
}
}
}));
}
let result = SimulationType::run(config).await;
match result {
Err(e) => {
let mut errors_clone_lock = errors_clone.lock().await;
errors_clone_lock.push(e);
// Drop the permit when the simulation is done.
drop(permit);
}
Result::Ok(_) => {
drop(permit);
}

for handle in handles {
handle.await?;
}

Ok(())
Expand Down

0 comments on commit 46d3cb9

Please sign in to comment.