|
| 1 | +#ifndef STAN_MATH_REV_FUN_NORM1_HPP |
| 2 | +#define STAN_MATH_REV_FUN_NORM1_HPP |
| 3 | + |
| 4 | +#include <stan/math/rev/meta.hpp> |
| 5 | +#include <stan/math/rev/core.hpp> |
| 6 | +#include <stan/math/rev/core/typedefs.hpp> |
| 7 | +#include <stan/math/prim/err.hpp> |
| 8 | +#include <stan/math/prim/fun/Eigen.hpp> |
| 9 | +#include <stan/math/prim/fun/sign.hpp> |
| 10 | + |
| 11 | +namespace stan { |
| 12 | +namespace math { |
| 13 | + |
| 14 | +/** |
| 15 | + * Returns the L1 norm of a vector of var. |
| 16 | + * |
| 17 | + * @tparam T type of the vector (must have one compile-time dimension equal to |
| 18 | + * 1) |
| 19 | + * @param[in] v Vector. |
| 20 | + * @return L1 norm of v. |
| 21 | + */ |
| 22 | +template <typename T, require_eigen_vector_vt<is_var, T>* = nullptr> |
| 23 | +inline var norm1(const T& v) { |
| 24 | + arena_t<T> arena_v = v; |
| 25 | + var res = norm1(arena_v.val()); |
| 26 | + reverse_pass_callback([res, arena_v]() mutable { |
| 27 | + arena_v.adj().array() += res.adj() * sign(arena_v.val().array()); |
| 28 | + }); |
| 29 | + return res; |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * Returns the L1 norm of a `var_value<Vector>`. |
| 34 | + * |
| 35 | + * @tparam A `var_value<>` whose inner type has one compile-time row or column. |
| 36 | + * @param[in] v Vector. |
| 37 | + * @return L1 norm of v. |
| 38 | + */ |
| 39 | +// |
| 40 | +template <typename T, require_var_matrix_t<T>* = nullptr> |
| 41 | +inline var norm1(const T& v) { |
| 42 | + return make_callback_vari(norm1(v.val()), [v](const auto& res) mutable { |
| 43 | + v.adj().array() += res.adj() * sign(v.val().array()); |
| 44 | + }); |
| 45 | +} |
| 46 | + |
| 47 | +} // namespace math |
| 48 | +} // namespace stan |
| 49 | +#endif |
0 commit comments