Skip to content

Commit

Permalink
Refactor marker trait usage
Browse files Browse the repository at this point in the history
  • Loading branch information
reinterpretcat committed Jul 27, 2024
1 parent cec76c3 commit e018625
Show file tree
Hide file tree
Showing 92 changed files with 311 additions and 393 deletions.
9 changes: 2 additions & 7 deletions rosomaxa/src/algorithms/gsom/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ where
min_max_weights: MinMaxWeights,
nodes: NodeHashMap<I, S>,
storage_factory: F,
random: Arc<dyn Random + Send + Sync>,
random: Arc<dyn Random>,
}

/// GSOM network configuration.
Expand All @@ -61,12 +61,7 @@ where
F: StorageFactory<I, S>,
{
/// Creates a new instance of `Network`.
pub fn new(
roots: [I; 4],
config: NetworkConfig,
random: Arc<dyn Random + Send + Sync>,
storage_factory: F,
) -> Self {
pub fn new(roots: [I; 4], config: NetworkConfig, random: Arc<dyn Random>, storage_factory: F) -> Self {
let dimension = roots[0].weights().len();

assert!(roots.iter().all(|r| r.weights().len() == dimension));
Expand Down
25 changes: 12 additions & 13 deletions rosomaxa/src/evolution/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,8 +238,8 @@ where
max_time: Option<usize>,
min_cv: Option<(String, usize, f64, bool, K)>,
target_proximity: Option<(Vec<f64>, f64)>,
) -> Result<Box<dyn Termination<Context = C, Objective = O> + Send + Sync>, GenericError> {
let terminations: Vec<Box<dyn Termination<Context = C, Objective = O> + Send + Sync>> = match (
) -> Result<Box<dyn Termination<Context = C, Objective = O>>, GenericError> {
let terminations: Vec<Box<dyn Termination<Context = C, Objective = O>>> = match (
max_generations,
max_time,
&min_cv,
Expand All @@ -250,7 +250,7 @@ where
vec![Box::new(MaxGeneration::new(3000)), Box::new(MaxTime::new(300.))]
}
_ => {
let mut terminations: Vec<Box<dyn Termination<Context = C, Objective = O> + Send + Sync>> = vec![];
let mut terminations: Vec<Box<dyn Termination<Context = C, Objective = O>>> = vec![];

if let Some(limit) = max_generations {
(logger)(format!("configured to use max-generations: {limit}").as_str());
Expand All @@ -270,16 +270,15 @@ where
.as_str(),
);

let variation: Box<dyn Termination<Context = C, Objective = O> + Send + Sync> =
match interval_type.as_str() {
"sample" => {
Box::new(MinVariation::<C, O, S, K>::new_with_sample(value, threshold, is_global, key))
}
"period" => {
Box::new(MinVariation::<C, O, S, K>::new_with_period(value, threshold, is_global, key))
}
_ => return Err(format!("unknown variation interval type: {interval_type}").into()),
};
let variation: Box<dyn Termination<Context = C, Objective = O>> = match interval_type.as_str() {
"sample" => {
Box::new(MinVariation::<C, O, S, K>::new_with_sample(value, threshold, is_global, key))
}
"period" => {
Box::new(MinVariation::<C, O, S, K>::new_with_period(value, threshold, is_global, key))
}
_ => return Err(format!("unknown variation interval type: {interval_type}").into()),
};

terminations.push(variation)
}
Expand Down
2 changes: 1 addition & 1 deletion rosomaxa/src/example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ impl HeuristicObjective for VectorObjective {
}

impl Shuffled for VectorObjective {
fn get_shuffled(&self, _: &(dyn Random + Send + Sync)) -> Self {
fn get_shuffled(&self, _: &(dyn Random)) -> Self {
self.clone()
}
}
Expand Down
2 changes: 1 addition & 1 deletion rosomaxa/src/hyper/dynamic_selective.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ where
struct SearchAgent<'a, C, O, S> {
slot_machines: HashMap<SearchState, SlotMachines<'a, C, O, S>>,
tracker: HeuristicTracker,
random: Arc<dyn Random + Send + Sync>,
random: Arc<dyn Random>,
}

impl<'a, C, O, S> SearchAgent<'a, C, O, S>
Expand Down
2 changes: 1 addition & 1 deletion rosomaxa/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ pub fn get_default_population<O, S>(
objective: Arc<O>,
environment: Arc<Environment>,
selection_size: usize,
) -> Box<dyn HeuristicPopulation<Objective = O, Individual = S> + Send + Sync>
) -> Box<dyn HeuristicPopulation<Objective = O, Individual = S>>
where
O: HeuristicObjective<Solution = S> + Shuffled + 'static,
S: HeuristicSolution + RosomaxaWeighted + 'static,
Expand Down
13 changes: 4 additions & 9 deletions rosomaxa/src/population/elitism.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ where
S: HeuristicSolution,
{
objective: Arc<O>,
random: Arc<dyn Random + Send + Sync>,
random: Arc<dyn Random>,
selection_size: usize,
max_population_size: usize,
individuals: Vec<S>,
Expand All @@ -39,7 +39,7 @@ where
/// Provides way to get a new objective by shuffling existing one.
pub trait Shuffled {
/// Returns a new objective, potentially shuffled.
fn get_shuffled(&self, random: &(dyn Random + Send + Sync)) -> Self;
fn get_shuffled(&self, random: &(dyn Random)) -> Self;
}

impl<O, S> HeuristicPopulation for Elitism<O, S>
Expand Down Expand Up @@ -113,12 +113,7 @@ where
S: HeuristicSolution,
{
/// Creates a new instance of `Elitism`.
pub fn new(
objective: Arc<O>,
random: Arc<dyn Random + Send + Sync>,
max_population_size: usize,
selection_size: usize,
) -> Self {
pub fn new(objective: Arc<O>, random: Arc<dyn Random>, max_population_size: usize, selection_size: usize) -> Self {
Self::new_with_dedup(
objective,
random,
Expand Down Expand Up @@ -147,7 +142,7 @@ where
/// Creates a new instance of `Elitism` with custom deduplication function.
pub fn new_with_dedup(
objective: Arc<O>,
random: Arc<dyn Random + Send + Sync>,
random: Arc<dyn Random>,
max_population_size: usize,
selection_size: usize,
dedup_fn: DedupFn<O, S>,
Expand Down
8 changes: 2 additions & 6 deletions rosomaxa/src/population/rosomaxa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,11 +338,7 @@ where
network.smooth(1);
}

fn fill_populations(
network: &IndividualNetwork<O, S>,
coordinates: &mut Vec<Coordinate>,
random: &(dyn Random + Send + Sync),
) {
fn fill_populations(network: &IndividualNetwork<O, S>, coordinates: &mut Vec<Coordinate>, random: &(dyn Random)) {
coordinates.clear();
coordinates.extend(network.iter().filter_map(|(coordinate, node)| {
if node.storage.population.size() > 0 {
Expand Down Expand Up @@ -455,7 +451,7 @@ where
S: HeuristicSolution + RosomaxaWeighted,
{
node_size: usize,
random: Arc<dyn Random + Send + Sync>,
random: Arc<dyn Random>,
objective: Arc<O>,
}

Expand Down
2 changes: 1 addition & 1 deletion rosomaxa/src/termination/min_variation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ where
C: HeuristicContext<Objective = O, Solution = S> + Stateful<Key = K>,
O: HeuristicObjective<Solution = S>,
S: HeuristicSolution,
K: Hash + Eq + Clone,
K: Hash + Eq + Clone + Send + Sync,
{
type Context = C;
type Objective = O;
Expand Down
6 changes: 3 additions & 3 deletions rosomaxa/src/termination/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use crate::prelude::*;

/// A trait which specifies criteria when metaheuristic should stop searching for improved solution.
pub trait Termination {
pub trait Termination: Send + Sync {
/// A heuristic objective function type.
type Context: HeuristicContext<Objective = Self::Objective>;

Expand Down Expand Up @@ -37,7 +37,7 @@ where
O: HeuristicObjective<Solution = S>,
S: HeuristicSolution,
{
terminations: Vec<Box<dyn Termination<Context = C, Objective = O> + Send + Sync>>,
terminations: Vec<Box<dyn Termination<Context = C, Objective = O>>>,
}

impl<C, O, S> CompositeTermination<C, O, S>
Expand All @@ -47,7 +47,7 @@ where
S: HeuristicSolution,
{
/// Creates a new instance of `CompositeTermination`.
pub fn new(terminations: Vec<Box<dyn Termination<Context = C, Objective = O> + Send + Sync>>) -> Self {
pub fn new(terminations: Vec<Box<dyn Termination<Context = C, Objective = O>>>) -> Self {
Self { terminations }
}
}
Expand Down
10 changes: 5 additions & 5 deletions rosomaxa/src/utils/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ pub trait Quota: Send + Sync {
#[derive(Clone)]
pub struct Environment {
/// A wrapper on random generator.
pub random: Arc<dyn Random + Send + Sync>,
pub random: Arc<dyn Random>,

/// A global execution quota.
pub quota: Option<Arc<dyn Quota + Send + Sync>>,
pub quota: Option<Arc<dyn Quota>>,

/// Keeps data parallelism settings.
pub parallelism: Parallelism,
Expand All @@ -36,15 +36,15 @@ impl Environment {
/// Creates an instance of `Environment` using optional time quota and defaults.
pub fn new_with_time_quota(max_time: Option<usize>) -> Self {
Self {
quota: max_time.map::<Arc<dyn Quota + Send + Sync>, _>(|time| Arc::new(TimeQuota::new(time as f64))),
quota: max_time.map::<Arc<dyn Quota>, _>(|time| Arc::new(TimeQuota::new(time as f64))),
..Self::default()
}
}

/// Creates an instance of `Environment`.
pub fn new(
random: Arc<dyn Random + Send + Sync>,
quota: Option<Arc<dyn Quota + Send + Sync>>,
random: Arc<dyn Random>,
quota: Option<Arc<dyn Quota>>,
parallelism: Parallelism,
logger: InfoLogger,
is_experimental: bool,
Expand Down
8 changes: 4 additions & 4 deletions rosomaxa/src/utils/iterators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@ pub struct SelectionSamplingIterator<I: Iterator> {
needed: usize,
size: usize,
iterator: I,
random: Arc<dyn Random + Send + Sync>,
random: Arc<dyn Random>,
}

impl<I: Iterator> SelectionSamplingIterator<I> {
/// Creates a new instance of `SelectionSamplingIterator`.
pub fn new(iterator: I, amount: usize, random: Arc<dyn Random + Send + Sync>) -> Self {
pub fn new(iterator: I, amount: usize, random: Arc<dyn Random>) -> Self {
assert!(amount > 0);
Self {
// NOTE relying on lower bound size hint!
Expand Down Expand Up @@ -93,7 +93,7 @@ impl<I: Iterator> Iterator for SelectionSamplingIterator<I> {
pub fn create_range_sampling_iter<I: Iterator>(
iterator: I,
sample_size: usize,
random: &(dyn Random + Send + Sync),
random: &(dyn Random),
) -> impl Iterator<Item = I::Item> {
let iterator_size = iterator.size_hint().0 as f64;
let sample_count = (iterator_size / sample_size as f64).max(1.) - 1.;
Expand Down Expand Up @@ -131,7 +131,7 @@ pub trait SelectionSamplingSearch: Iterator {
fn sample_search<'a, T, R, FM, FI, FC>(
self,
sample_size: usize,
random: Arc<dyn Random + Send + Sync>,
random: Arc<dyn Random>,
mut map_fn: FM,
index_fn: FI,
compare_fn: FC,
Expand Down
8 changes: 4 additions & 4 deletions rosomaxa/src/utils/noise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,19 @@ pub struct Noise {
probability: f64,
range: (f64, f64),
is_addition: bool,
random: Arc<dyn Random + Send + Sync>,
random: Arc<dyn Random>,
}

impl Noise {
/// Creates a new instance of `Noise` which will add some noise in given range
/// to the target value: `value = value + value * sample_from(range)`
pub fn new_with_addition(probability: f64, range: (f64, f64), random: Arc<dyn Random + Send + Sync>) -> Self {
pub fn new_with_addition(probability: f64, range: (f64, f64), random: Arc<dyn Random>) -> Self {
Self { probability, range, is_addition: true, random }
}

/// Creates a new instance of `Noise` which will apply noise by multiplying target value
/// by value from given range: `value = value * sample_from(range)`
pub fn new_with_ratio(probability: f64, range: (f64, f64), random: Arc<dyn Random + Send + Sync>) -> Self {
pub fn new_with_ratio(probability: f64, range: (f64, f64), random: Arc<dyn Random>) -> Self {
Self { probability, range, is_addition: false, random }
}

Expand All @@ -48,7 +48,7 @@ impl Noise {
}

/// Returns random generator.
pub fn random(&self) -> &(dyn Random + Send + Sync) {
pub fn random(&self) -> &(dyn Random) {
self.random.as_ref()
}
}
6 changes: 3 additions & 3 deletions rosomaxa/src/utils/random.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub trait DistributionSampler {
}

/// Provides the way to use randomized values in generic way.
pub trait Random {
pub trait Random: Send + Sync {
/// Produces integral random value, uniformly distributed on the closed interval [min, max]
fn uniform_int(&self, min: i32, max: i32) -> i32;

Expand All @@ -43,11 +43,11 @@ pub trait Random {

/// Provides way to sample from different distributions.
#[derive(Clone)]
pub struct DefaultDistributionSampler(Arc<dyn Random + Send + Sync>);
pub struct DefaultDistributionSampler(Arc<dyn Random>);

impl DefaultDistributionSampler {
/// Creates a new instance of `DefaultDistributionSampler`.
pub fn new(random: Arc<dyn Random + Send + Sync>) -> Self {
pub fn new(random: Arc<dyn Random>) -> Self {
Self(random)
}
}
Expand Down
2 changes: 1 addition & 1 deletion rosomaxa/tests/helpers/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::utils::{DefaultRandom, Random};
use std::sync::Arc;

pub fn create_test_random() -> Arc<dyn Random + Send + Sync> {
pub fn create_test_random() -> Arc<dyn Random> {
Arc::new(DefaultRandom::default())
}
8 changes: 2 additions & 6 deletions rosomaxa/tests/unit/example_test.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
use super::*;

fn just_noise(
probability: f64,
range: (f64, f64),
random: Arc<dyn Random + Send + Sync>,
) -> VectorHeuristicOperatorMode {
fn just_noise(probability: f64, range: (f64, f64), random: Arc<dyn Random>) -> VectorHeuristicOperatorMode {
VectorHeuristicOperatorMode::JustNoise(Noise::new_with_ratio(probability, range, random))
}

fn dimen_noise(
probability: f64,
range: (f64, f64),
dimen: usize,
random: Arc<dyn Random + Send + Sync>,
random: Arc<dyn Random>,
) -> VectorHeuristicOperatorMode {
let dimen = vec![dimen].into_iter().collect();
VectorHeuristicOperatorMode::DimensionNoise(Noise::new_with_ratio(probability, range, random), dimen)
Expand Down
2 changes: 1 addition & 1 deletion rosomaxa/tests/unit/hyper/dynamic_selective_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::time::Duration;
fn can_estimate_median() {
struct DelayableHeuristicOperator {
delay_range: Range<i32>,
random: Arc<dyn Random + Send + Sync>,
random: Arc<dyn Random>,
}
impl HeuristicSearchOperator for DelayableHeuristicOperator {
type Context = VectorContext;
Expand Down
Loading

0 comments on commit e018625

Please sign in to comment.