1use crate::{LinearOp, Matrix, MatrixSparsityRef, NonLinearOp, NonLinearOpJacobian, Op};
2use num_traits::Zero;
3
4pub struct MatrixOp<M: Matrix> {
5 m: M,
6}
7
8impl<M: Matrix> MatrixOp<M> {
9 pub fn new(m: M) -> Self {
10 Self { m }
11 }
12 pub fn m_mut(&mut self) -> &mut M {
13 &mut self.m
14 }
15 pub fn m(&self) -> &M {
16 &self.m
17 }
18}
19
20impl<M: Matrix> Op for MatrixOp<M> {
21 type V = M::V;
22 type T = M::T;
23 type M = M;
24 type C = M::C;
25 fn nstates(&self) -> usize {
26 self.m.nrows()
27 }
28 fn nout(&self) -> usize {
29 self.m.ncols()
30 }
31 fn nparams(&self) -> usize {
32 0
33 }
34 fn context(&self) -> &Self::C {
35 self.m.context()
36 }
37}
38
39impl<M: Matrix> LinearOp for MatrixOp<M> {
40 fn gemv_inplace(&self, x: &Self::V, t: Self::T, beta: Self::T, y: &mut Self::V) {
41 self.m.gemv(t, x, beta, y);
42 }
43 fn sparsity(&self) -> Option<<Self::M as Matrix>::Sparsity> {
44 self.m.sparsity().map(|s| s.to_owned())
45 }
46}
47
48impl<M: Matrix> NonLinearOp for MatrixOp<M> {
49 fn call_inplace(&self, x: &Self::V, t: Self::T, y: &mut Self::V) {
50 self.m.gemv(t, x, Self::T::zero(), y);
51 }
52}
53
54impl<M: Matrix> NonLinearOpJacobian for MatrixOp<M> {
55 fn jac_mul_inplace(&self, _x: &Self::V, t: Self::T, v: &Self::V, y: &mut Self::V) {
56 self.m.gemv(t, v, Self::T::zero(), y);
57 }
58
59 fn jacobian(&self, _x: &Self::V, _t: Self::T) -> Self::M {
60 self.m.clone()
61 }
62
63 fn jacobian_inplace(&self, _x: &Self::V, _t: Self::T, y: &mut Self::M) {
64 y.copy_from(&self.m);
65 }
66
67 fn jacobian_sparsity(&self) -> Option<<Self::M as Matrix>::Sparsity> {
68 self.m.sparsity().map(|s| s.to_owned())
69 }
70}