optimization_engine/constraints/
ball2.rs1use super::Constraint;
2
3#[derive(Copy, Clone)]
4pub struct Ball2<'a> {
7 center: Option<&'a [f64]>,
8 radius: f64,
9}
10
11impl<'a> Ball2<'a> {
12 pub fn new(center: Option<&'a [f64]>, radius: f64) -> Self {
15 assert!(radius > 0.0);
16
17 Ball2 { center, radius }
18 }
19}
20
21impl<'a> Constraint for Ball2<'a> {
22 fn project(&self, x: &mut [f64]) {
23 if let Some(center) = &self.center {
24 let mut norm_difference = 0.0;
25 x.iter().zip(center.iter()).for_each(|(a, b)| {
26 let diff_ = *a - *b;
27 norm_difference += diff_ * diff_
28 });
29
30 norm_difference = norm_difference.sqrt();
31
32 if norm_difference > self.radius {
33 x.iter_mut().zip(center.iter()).for_each(|(x, c)| {
34 *x = *c + self.radius * (*x - *c) / norm_difference;
35 });
36 }
37 } else {
38 let norm_x = crate::matrix_operations::norm2(x);
39 if norm_x > self.radius {
40 let norm_over_radius = norm_x / self.radius;
41 x.iter_mut().for_each(|x_| *x_ /= norm_over_radius);
42 }
43 }
44 }
45
46 fn is_convex(&self) -> bool {
47 true
48 }
49}