~ruther/ctu-fee-eoa

ref: e3d7f2139691f8df389f621703c3a7827d765fbf ctu-fee-eoa/codes/eoa_lib/src/terminating/mod.rs -rw-r--r-- 10.6 KiB
e3d7f213 — Rutherther feat(tsp): allow crossing bounds in reverse subsequence perturbation 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
use nalgebra::{allocator::Allocator, DefaultAllocator, Dim, OVector};

use crate::local_search::{LocalSearchCandidate, LocalSearchStats};

pub trait TerminatingCondition<TInput, TResult>
{
    fn should_terminate(
        self: &mut Self,
        candidate: &LocalSearchCandidate<TInput, TResult>,
        stats: &LocalSearchStats<TInput, TResult>,
        cycle: usize
    ) -> bool;
}

// Generic terminating conditions that group multiple conditions
pub struct AndTerminatingConditions<'a, TInput, TResult> {
    terminating_conditions: Vec<&'a mut dyn TerminatingCondition<TInput, TResult>>
}

impl<'a, TInput, TResult> AndTerminatingConditions<'a, TInput, TResult> {
    pub fn new(terminating_conditions: Vec<&'a mut dyn TerminatingCondition<TInput, TResult>>) -> Self {
        Self {
            terminating_conditions
        }
    }

    pub fn conditions(&self) -> &Vec<&'a mut dyn TerminatingCondition<TInput, TResult>> {
        &self.terminating_conditions
    }
}

impl<'a, TInput, TResult> TerminatingCondition<TInput, TResult> for AndTerminatingConditions<'a, TInput, TResult> {
    fn should_terminate(
        self: &mut Self,
        candidate: &LocalSearchCandidate<TInput, TResult>,
        stats: &LocalSearchStats<TInput, TResult>,
        cycle: usize
    ) -> bool {
        return self.terminating_conditions.iter_mut()
            .all(
                |cond| cond.should_terminate(candidate, stats, cycle)
            )
    }
}

pub struct OrTerminatingConditions<'a, TInput, TResult> {
    terminating_conditions: Vec<&'a mut dyn TerminatingCondition<TInput, TResult>>
}

impl<'a, TInput, TResult> OrTerminatingConditions<'a, TInput, TResult> {
    pub fn new(terminating_conditions: Vec<&'a mut dyn TerminatingCondition<TInput, TResult>>) -> Self {
        Self {
            terminating_conditions
        }
    }

    pub fn conditions(&self) -> &Vec<&'a mut dyn TerminatingCondition<TInput, TResult>> {
        &self.terminating_conditions
    }
}

impl<'a, TInput, TResult> TerminatingCondition<TInput, TResult> for OrTerminatingConditions<'a, TInput, TResult> {
    fn should_terminate(
        self: &mut Self,
        candidate: &LocalSearchCandidate<TInput, TResult>,
        stats: &LocalSearchStats<TInput, TResult>,
        cycle: usize
    ) -> bool {
        return self.terminating_conditions.iter_mut()
            .any(
                |cond| cond.should_terminate(candidate, stats, cycle)
            )
    }
}

// Simple terminating conditions based on the number of cycles
pub struct NoBetterForCyclesTerminatingCondition {
    cycles: usize
}

impl NoBetterForCyclesTerminatingCondition {
    pub fn new(cycles: usize) -> Self {
        Self {
            cycles
        }
    }
}

impl<TInput, TResult> TerminatingCondition<TInput, TResult> for NoBetterForCyclesTerminatingCondition {
    fn should_terminate (
        self: &mut Self,
        candidate: &LocalSearchCandidate<TInput, TResult>,
        _: &LocalSearchStats<TInput, TResult>,
        cycle: usize
    ) -> bool {
        (cycle - candidate.cycle) > self.cycles
    }
}

pub struct MaximumCyclesTerminatingCondition {
    cycles: usize
}

impl MaximumCyclesTerminatingCondition {
    pub fn new(cycles: usize) -> Self {
        Self {
            cycles
        }
    }
}

impl<TInput, TResult> TerminatingCondition<TInput, TResult> for MaximumCyclesTerminatingCondition {
    fn should_terminate (
        self: &mut Self,
        _: &LocalSearchCandidate<TInput, TResult>,
        _: &LocalSearchStats<TInput, TResult>,
        cycle: usize
    ) -> bool {
        cycle > self.cycles
    }
}

// Terminating conditions based on the absolute fitness of the solution
pub struct LowerThanTerminatingCondition<T: PartialOrd> {
    target: T
}

impl<TInput, TResult: PartialOrd> TerminatingCondition<TInput, TResult> for LowerThanTerminatingCondition<TResult> {
    fn should_terminate(
        self: &mut Self,
        candidate: &LocalSearchCandidate<TInput, TResult>,
        _: &LocalSearchStats<TInput, TResult>,
        _: usize
    ) -> bool {
        candidate.fit < self.target
    }
}

// The following conditions are mainly meant for test environment where the optimal result is known
// beforehand.
pub struct EqualTerminatingCondition<T> {
    target: T,
    remember_match: bool,
    matched: bool,
}

impl<T> EqualTerminatingCondition<T> {
    pub fn new(target: T) -> Self {
        Self {
            target,
            remember_match: false,
            matched: false,
        }
    }

    pub fn new_remembered(target: T) -> Self {
        Self {
            target,
            remember_match: true,
            matched: false,
        }
    }

    pub fn reset_match(self: &mut Self) {
        self.matched = false;
    }
}

impl<TInput, TResult> TerminatingCondition<TInput, TResult> for EqualTerminatingCondition<TInput>
where
    TInput: Clone + PartialEq,
    TResult: Clone
{
    fn should_terminate(
        self: &mut Self,
        candidate: &LocalSearchCandidate<TInput, TResult>,
        _: &LocalSearchStats<TInput, TResult>,
        _: usize
    ) -> bool {
        let matched = candidate.pos == self.target;

        if matched && self.remember_match {
            self.matched = true;
        }

        matched || self.matched
    }
}

pub struct CloserThanTerminatingCondition<T> {
    target: T,
    max_distance: f64,
    remember_match: bool,
    matched: bool,
}

impl<T> CloserThanTerminatingCondition<T> {
    pub fn new(target: T, max_distance: f64) -> Self {
        Self {
            target,
            max_distance,
            remember_match: false,
            matched: false,
        }
    }

    pub fn new_remembered(target: T, max_distance: f64) -> Self {
        Self {
            target,
            max_distance,
            remember_match: true,
            matched: false,
        }
    }

    pub fn reset_match(self: &mut Self) {
        self.matched = false;
    }
}

impl<D, TResult> TerminatingCondition<OVector<f64, D>, TResult> for CloserThanTerminatingCondition<OVector<f64, D>>
where
    D: Dim,
    DefaultAllocator: Allocator<D>,
    TResult: Clone,
{
    fn should_terminate(
        self: &mut Self,
        candidate: &LocalSearchCandidate<OVector<f64, D>, TResult>,
        _: &LocalSearchStats<OVector<f64, D>, TResult>,
        _: usize
    ) -> bool {
        let matched = (&candidate.pos - &self.target).magnitude() < self.max_distance;

        if matched && self.remember_match {
            self.matched = true;
        }

        matched || self.matched
    }
}

#[cfg(test)]
pub mod tests {
    use crate::local_search::{LocalSearchCandidate, LocalSearchStats};

    use super::{AndTerminatingConditions, EqualTerminatingCondition, NoBetterForCyclesTerminatingCondition, TerminatingCondition};

    #[test]
    fn test_no_better_for_cycles() {
        let mut no_better_for_cycles = NoBetterForCyclesTerminatingCondition::new(10);

        let stats = LocalSearchStats::new();

        assert!(!no_better_for_cycles.should_terminate(&LocalSearchCandidate::new((), (), 0), &stats, 0));

        assert!(!no_better_for_cycles.should_terminate(&LocalSearchCandidate::new((), (), 0), &stats, 1));
        assert!(!no_better_for_cycles.should_terminate(&LocalSearchCandidate::new((), (), 0), &stats, 2));
        assert!(!no_better_for_cycles.should_terminate(&LocalSearchCandidate::new((), (), 0), &stats, 10));
        assert!(no_better_for_cycles.should_terminate(&LocalSearchCandidate::new((), (), 0), &stats, 11));

        assert!(!no_better_for_cycles.should_terminate(&LocalSearchCandidate::new((), (), 10), &stats, 10));
        assert!(!no_better_for_cycles.should_terminate(&LocalSearchCandidate::new((), (), 10), &stats, 20));
        assert!(no_better_for_cycles.should_terminate(&LocalSearchCandidate::new((), (), 10), &stats, 22));

        assert!(no_better_for_cycles.should_terminate(&LocalSearchCandidate::new((), (), 50), &stats, 126));
    }

    #[test]
    fn test_equal() {
        let mut equal = EqualTerminatingCondition::new(10);
        let stats = LocalSearchStats::new();
        assert!(!equal.should_terminate(&LocalSearchCandidate::new((), 5, 0), &stats, 0));
        assert!(equal.should_terminate(&LocalSearchCandidate::new((), 10, 0), &stats, 0));
        assert!(!equal.should_terminate(&LocalSearchCandidate::new((), 11, 0), &stats, 0));
    }

    #[test]
    fn test_equal_remembering() {
        let mut equal = EqualTerminatingCondition::new_remembered(10);
        let stats = LocalSearchStats::new();
        assert!(!equal.should_terminate(&LocalSearchCandidate::new((), 5, 0), &stats, 0));
        assert!(equal.should_terminate(&LocalSearchCandidate::new((), 10, 0), &stats, 0));
        assert!(equal.should_terminate(&LocalSearchCandidate::new((), 11, 0), &stats, 0));

        equal.reset_match();
        assert!(!equal.should_terminate(&LocalSearchCandidate::new((), 11, 0), &stats, 0));
        assert!(equal.should_terminate(&LocalSearchCandidate::new((), 10, 0), &stats, 0));
    }

    struct DummyTerminatingCondition {
        idx: usize
    }

    impl DummyTerminatingCondition {
        fn new(idx: usize) -> Self {
            Self {
                idx
            }
        }
    }

    impl TerminatingCondition<Vec<bool>, ()> for DummyTerminatingCondition {
        fn should_terminate(
            self: &mut Self,
            candidate: &crate::local_search::LocalSearchCandidate<Vec<bool>, ()>,
            _: &crate::local_search::LocalSearchStats<Vec<bool>, ()>,
            _: usize
        ) -> bool {
            candidate.pos[self.idx]
        }
    }

    #[test]
    fn test_and() {
        let mut first_dummy = DummyTerminatingCondition::new(0);
        let mut second_dummy = DummyTerminatingCondition::new(1);
        let mut and_cond = AndTerminatingConditions::<Vec<bool>, ()>::new(vec![&mut first_dummy, &mut second_dummy]);
        let stats = LocalSearchStats::new();

        let mut terminates = vec![false, false];

        assert_eq!(and_cond.conditions().len(), 2);

        assert!(!and_cond.should_terminate(&LocalSearchCandidate::new((), terminates.clone(), 0), &stats, 0));

        terminates[0] = true;
        terminates[1] = true;

        assert!(and_cond.should_terminate(&LocalSearchCandidate::new((), terminates.clone(), 0), &stats, 0));

        terminates[0] = true;
        terminates[1] = false;

        assert!(!and_cond.should_terminate(&LocalSearchCandidate::new((), terminates.clone(), 0), &stats, 0));

        terminates[0] = false;
        terminates[1] = true;

        assert!(!and_cond.should_terminate(&LocalSearchCandidate::new((), terminates.clone(), 0), &stats, 0));

        terminates[0] = false;
        terminates[1] = false;

        assert!(!and_cond.should_terminate(&LocalSearchCandidate::new((), terminates.clone(), 0), &stats, 0));
    }
}