~ruther/ctu-fee-eoa

ref: 8315b8f68fee89eef358a5209cc43b03855e64bd ctu-fee-eoa/codes/eoa_lib/src/initializer/mod.rs -rw-r--r-- 2.3 KiB
8315b8f6 — Rutherther fix(tsp): few more tweaks a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
use nalgebra::{allocator::Allocator, DefaultAllocator, Dim, OVector, Scalar, U1};
use rand::RngCore;

use crate::{binary_string::BinaryString, bounded::{Bounded, BoundedBinaryString}};

pub trait Initializer<D: Dim, T> {
    fn initialize_single(&self, size: D, rng: &mut dyn RngCore) -> T;
    fn initialize(&self, size: D, count: usize, rng: &mut dyn RngCore) -> Vec<T> {
        (0..count).map(|_| self.initialize_single(size, rng)).collect()
    }
}

// Always initializes with zeros
pub struct ZeroInitializer;

impl ZeroInitializer {
    pub fn new() -> Self {
        Self {
        }
    }
}

impl<D> Initializer<D, BinaryString<D>> for ZeroInitializer
where
    D: Dim,
    DefaultAllocator: Allocator<D>
{
    fn initialize_single(&self, size: D, rng: &mut dyn RngCore) -> BinaryString<D> {
        BinaryString::<D>::from_ovector(
            <Self as Initializer<D, OVector<i8, D>>>::initialize_single(self, size, rng)
        )
    }
}

impl<D, T> Initializer<D, OVector<T, D>> for ZeroInitializer
where
    T: Scalar + Default,
    D: Dim,
    DefaultAllocator: Allocator<D>
{
    fn initialize_single(&self, size: D, _rng: &mut dyn RngCore) -> OVector<T, D> {
        OVector::<T, D>::from_element_generic(size, U1, Default::default())
    }
}

pub struct RandomInitializer<D: Dim, T> {
    bounded: Box<dyn Bounded<D, Item = T>>
}

impl<T, D: Dim> RandomInitializer<D, T> {
    pub fn new(bounded: Box<dyn Bounded<D, Item = T>>) -> Self {
        Self {
            bounded
        }
    }
}

impl<D: Dim> RandomInitializer<D, BinaryString<D>>
where
    D: Dim,
    DefaultAllocator: Allocator<D>
{
    pub fn new_binary() -> Self {
        Self {
            bounded: Box::new(BoundedBinaryString::unbounded())
        }
    }
}

impl<D> Initializer<D, BinaryString<D>> for RandomInitializer<D, BinaryString<D>>
where
    D: Dim,
    DefaultAllocator: Allocator<D>
{
    fn initialize_single(&self, size: D, rng: &mut dyn RngCore) -> BinaryString<D> {
        self.bounded.next_random(size, rng)
    }
}

impl<D, T> Initializer<D, OVector<T, D>> for RandomInitializer<D, OVector<T, D>>
where
    T: Scalar + Default,
    D: Dim,
    DefaultAllocator: Allocator<D>
{
    fn initialize_single(&self, size: D, rng: &mut dyn RngCore) -> OVector<T, D> {
        self.bounded.next_random(size, rng)
    }
}