-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathball2.rs
More file actions
54 lines (47 loc) · 1.71 KB
/
ball2.rs
File metadata and controls
54 lines (47 loc) · 1.71 KB
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
use super::Constraint;
#[derive(Copy, Clone)]
/// A Euclidean ball, that is, a set given by $B_2^r = \\{x \in \mathbb{R}^n {}:{} \Vert{}x{}\Vert \leq r\\}$
/// or a Euclidean ball centered at a point $x_c$, that is, $B_2^{x_c, r} = \\{x \in \mathbb{R}^n {}:{} \Vert{}x-x_c{}\Vert \leq r\\}$
pub struct Ball2<'a> {
center: Option<&'a [f64]>,
radius: f64,
}
impl<'a> Ball2<'a> {
/// Construct a new Euclidean ball with given center and radius
/// If no `center` is given, then it is assumed to be in the origin
pub fn new(center: Option<&'a [f64]>, radius: f64) -> Self {
assert!(radius > 0.0);
Ball2 { center, radius }
}
}
impl<'a> Constraint for Ball2<'a> {
fn project(&self, x: &mut [f64]) {
if let Some(center) = &self.center {
assert_eq!(
x.len(),
center.len(),
"x and xc have incompatible dimensions"
);
let mut norm_difference = 0.0;
x.iter().zip(center.iter()).for_each(|(a, b)| {
let diff_ = *a - *b;
norm_difference += diff_ * diff_
});
norm_difference = norm_difference.sqrt();
if norm_difference > self.radius {
x.iter_mut().zip(center.iter()).for_each(|(x, c)| {
*x = *c + self.radius * (*x - *c) / norm_difference;
});
}
} else {
let norm_x = crate::matrix_operations::norm2(x);
if norm_x > self.radius {
let norm_over_radius = norm_x / self.radius;
x.iter_mut().for_each(|x_| *x_ /= norm_over_radius);
}
}
}
fn is_convex(&self) -> bool {
true
}
}