alpaqa 0.0.1
Nonconvex constrained optimization
box.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "vec.hpp"
4
5namespace alpaqa {
6
7struct Box {
10};
11
12/// Project a vector onto a box.
13/// @f[ \Pi_C(v) @f]
14template <class Vec>
15inline auto project(const Vec &v, ///< [in] The vector to project
16 const Box &box ///< [in] The box to project onto
17) {
18 using binary_real_f = real_t (*)(real_t, real_t);
19 return v.binaryExpr(box.lowerbound, binary_real_f(std::fmax))
20 .binaryExpr(box.upperbound, binary_real_f(std::fmin));
21}
22
23/// Get the difference between the given vector and its projection.
24/// @f[ v - \Pi_C(v) @f]
25/// @warning Beware catastrophic cancellation!
26template <class Vec>
27inline auto
28projecting_difference(const Vec &v, ///< [in] The vector to project
29 const Box &box ///< [in] The box to project onto
30) {
31 return v - project(v, box);
32}
33
34/// Get the distance squared between the given vector and its projection.
35/// @f[ \left\| v - \Pi_C(v) \right\|_2^2 @f]
36/// @warning Beware catastrophic cancellation!
37inline real_t dist_squared(crvec v, ///< [in] The vector to project
38 const Box &box ///< [in] The box to project onto
39) {
40 return projecting_difference(v, box).squaredNorm();
41}
42
43/// Get the distance squared between the given vector and its projection in the
44/// Σ norm.
45/// @f[ \left\| v - \Pi_C(v) \right\|_\Sigma^2
46/// = \left(v - \Pi_C(v)\right)^\top \Sigma \left(v - \Pi_C(v)\right) @f]
47/// @warning Beware catastrophic cancellation!
48inline real_t dist_squared(crvec v, ///< [in] The vector to project
49 const Box &box, ///< [in] The box to project onto
50 crvec Σ ///< [in] Diagonal matrix defining norm
51) {
52 // TODO: Does this allocate?
53 // Does it have dangling references to temporaries?
54 auto d = v - project(v, box);
55 return d.dot(Σ.asDiagonal() * d);
56}
57
58} // namespace alpaqa
int Σ
Definition: test.py:72
auto project(const Vec &v, const Box &box)
Project a vector onto a box.
Definition: box.hpp:15
Eigen::Ref< const vec > crvec
Default type for immutable references to vectors.
Definition: vec.hpp:18
vec upperbound
Definition: box.hpp:8
realvec vec
Default type for vectors.
Definition: vec.hpp:14
vec lowerbound
Definition: box.hpp:9
double real_t
Default floating point type.
Definition: vec.hpp:8
real_t dist_squared(crvec v, const Box &box)
Get the distance squared between the given vector and its projection.
Definition: box.hpp:37
auto projecting_difference(const Vec &v, const Box &box)
Get the difference between the given vector and its projection.
Definition: box.hpp:28