pub struct Matrix<T> {
pub shape: (usize, usize),
pub data: Vec<Vec<T>>,
}
Fields§
§shape: (usize, usize)
§data: Vec<Vec<T>>
Implementations§
Source§impl<T> Matrix<T>
impl<T> Matrix<T>
Sourcepub fn from_vec(data: Vec<Vec<T>>) -> Self
pub fn from_vec(data: Vec<Vec<T>>) -> Self
Examples found in repository?
crates/competitive/src/algorithm/esper.rs (line 76)
69 pub fn solve(self) -> EsperSolver<T, Input, Class, FC, FF> {
70 let data: HashMap<_, _> = self
71 .data
72 .into_iter()
73 .map(|(key, (a, b))| {
74 (
75 key,
76 Matrix::from_vec(a).solve_system_of_linear_equations(&b),
77 )
78 })
79 .collect();
80 EsperSolver {
81 class: self.class,
82 feature: self.feature,
83 data,
84 _marker: PhantomData,
85 }
86 }
87
88 pub fn solve_checked(self) -> EsperSolver<T, Input, Class, FC, FF>
89 where
90 Class: Debug,
91 T: Debug,
92 {
93 let data: HashMap<_, _> = self
94 .data
95 .into_iter()
96 .map(|(key, (a, b))| {
97 let mat = Matrix::from_vec(a);
98 let coeff = mat.solve_system_of_linear_equations(&b);
99 if coeff.is_none() {
100 eprintln!(
101 "failed to solve linear equations: key={:?} A={:?} b={:?}",
102 key, &mat.data, &b
103 );
104 }
105 (key, coeff)
106 })
107 .collect();
108 EsperSolver {
109 class: self.class,
110 feature: self.feature,
111 data,
112 _marker: PhantomData,
113 }
114 }
More examples
crates/competitive/src/math/matrix.rs (lines 227-229)
215 pub fn inverse(&self) -> Option<Matrix<T>> {
216 assert_eq!(self.shape.0, self.shape.1);
217 let n = self.shape.0;
218 let mut c = Matrix::<T>::zeros((n, n * 2));
219 for i in 0..n {
220 c[i][..n].clone_from_slice(&self[i]);
221 c[i][n + i] = T::one();
222 }
223 c.row_reduction(true);
224 if (0..n).any(|i| c[i][i].is_zero()) {
225 None
226 } else {
227 Some(Self::from_vec(
228 c.data.into_iter().map(|r| r[n..].to_vec()).collect(),
229 ))
230 }
231 }
Source§impl<T> Matrix<T>
impl<T> Matrix<T>
Sourcepub fn zeros(shape: (usize, usize)) -> Self
pub fn zeros(shape: (usize, usize)) -> Self
Examples found in repository?
crates/competitive/src/math/matrix.rs (line 78)
76 fn add(self, rhs: Self) -> Self::Output {
77 assert_eq!(self.shape, rhs.shape);
78 let mut res = Matrix::zeros(self.shape);
79 for i in 0..self.shape.0 {
80 for j in 0..self.shape.1 {
81 res[i][j] = self[i][j] + rhs[i][j];
82 }
83 }
84 res
85 }
86}
87impl<T> Sub for &Matrix<T>
88where
89 T: Copy + Zero + Sub<Output = T>,
90{
91 type Output = Matrix<T>;
92 fn sub(self, rhs: Self) -> Self::Output {
93 assert_eq!(self.shape, rhs.shape);
94 let mut res = Matrix::zeros(self.shape);
95 for i in 0..self.shape.0 {
96 for j in 0..self.shape.1 {
97 res[i][j] = self[i][j] - rhs[i][j];
98 }
99 }
100 res
101 }
102}
103impl<T> Mul for &Matrix<T>
104where
105 T: Copy + Zero + Add<Output = T> + Mul<Output = T>,
106{
107 type Output = Matrix<T>;
108 fn mul(self, rhs: Self) -> Self::Output {
109 assert_eq!(self.shape.1, rhs.shape.0);
110 let mut res = Matrix::zeros((self.shape.0, rhs.shape.1));
111 for i in 0..self.shape.0 {
112 for j in 0..rhs.shape.1 {
113 for k in 0..self.shape.1 {
114 res[i][j] = res[i][j] + self[i][k] * rhs[k][j];
115 }
116 }
117 }
118 res
119 }
120}
121impl<T> Matrix<T>
122where
123 T: Copy + Zero + One + Add<Output = T> + Mul<Output = T>,
124{
125 pub fn pow(&self, mut n: usize) -> Self {
126 assert_eq!(self.shape.0, self.shape.1);
127 let mut x = self.clone();
128 let mut res = Matrix::eye(self.shape);
129 while n > 0 {
130 if n & 1 == 1 {
131 res = &res * &x;
132 }
133 x = &x * &x;
134 n >>= 1;
135 }
136 res
137 }
138}
139impl<T> Matrix<T>
140where
141 T: Copy + PartialEq + Zero + One + Sub<Output = T> + Mul<Output = T> + Div<Output = T>,
142{
143 pub fn row_reduction(&mut self, normalize: bool) {
144 let (n, m) = self.shape;
145 let mut c = 0;
146 for r in 0..n {
147 loop {
148 if c >= m {
149 return;
150 }
151 if let Some(pivot) = (r..n).find(|&p| !self[p][c].is_zero()) {
152 self.data.swap(r, pivot);
153 break;
154 };
155 c += 1;
156 }
157 let d = T::one() / self[r][c];
158 if normalize {
159 for j in c..m {
160 self[r][j] = self[r][j] * d;
161 }
162 }
163 for i in (0..n).filter(|&i| i != r) {
164 let mut e = self[i][c];
165 if !normalize {
166 e = e * d;
167 }
168 for j in c..m {
169 self[i][j] = self[i][j] - e * self[r][j];
170 }
171 }
172 c += 1;
173 }
174 }
175 pub fn rank(&mut self) -> usize {
176 let n = self.shape.0;
177 self.row_reduction(false);
178 (0..n)
179 .filter(|&i| !self.data[i].iter().all(|x| x.is_zero()))
180 .count()
181 }
182 pub fn determinant(&mut self) -> T {
183 assert_eq!(self.shape.0, self.shape.1);
184 self.row_reduction(false);
185 let mut d = T::one();
186 for i in 0..self.shape.0 {
187 d = d * self[i][i];
188 }
189 d
190 }
191 pub fn solve_system_of_linear_equations(&self, b: &[T]) -> Option<Vec<T>> {
192 assert_eq!(self.shape.0, b.len());
193 let (n, m) = self.shape;
194 let mut c = Matrix::<T>::zeros((n, m + 1));
195 for i in 0..n {
196 c[i][..m].clone_from_slice(&self[i]);
197 c[i][m] = b[i];
198 }
199 c.row_reduction(true);
200 let mut x = vec![T::zero(); m];
201 for i in 0..n {
202 let mut j = 0usize;
203 while j <= m && c[i][j].is_zero() {
204 j += 1;
205 }
206 if j == m {
207 return None;
208 }
209 if j < m {
210 x[j] = c[i][m];
211 }
212 }
213 Some(x)
214 }
215 pub fn inverse(&self) -> Option<Matrix<T>> {
216 assert_eq!(self.shape.0, self.shape.1);
217 let n = self.shape.0;
218 let mut c = Matrix::<T>::zeros((n, n * 2));
219 for i in 0..n {
220 c[i][..n].clone_from_slice(&self[i]);
221 c[i][n + i] = T::one();
222 }
223 c.row_reduction(true);
224 if (0..n).any(|i| c[i][i].is_zero()) {
225 None
226 } else {
227 Some(Self::from_vec(
228 c.data.into_iter().map(|r| r[n..].to_vec()).collect(),
229 ))
230 }
231 }
Source§impl<T> Matrix<T>
impl<T> Matrix<T>
Sourcepub fn eye(shape: (usize, usize)) -> Self
pub fn eye(shape: (usize, usize)) -> Self
Examples found in repository?
crates/competitive/src/math/matrix.rs (line 128)
125 pub fn pow(&self, mut n: usize) -> Self {
126 assert_eq!(self.shape.0, self.shape.1);
127 let mut x = self.clone();
128 let mut res = Matrix::eye(self.shape);
129 while n > 0 {
130 if n & 1 == 1 {
131 res = &res * &x;
132 }
133 x = &x * &x;
134 n >>= 1;
135 }
136 res
137 }
Source§impl<T> Matrix<T>
impl<T> Matrix<T>
Sourcepub fn row_reduction(&mut self, normalize: bool)
pub fn row_reduction(&mut self, normalize: bool)
Examples found in repository?
crates/competitive/src/math/matrix.rs (line 177)
175 pub fn rank(&mut self) -> usize {
176 let n = self.shape.0;
177 self.row_reduction(false);
178 (0..n)
179 .filter(|&i| !self.data[i].iter().all(|x| x.is_zero()))
180 .count()
181 }
182 pub fn determinant(&mut self) -> T {
183 assert_eq!(self.shape.0, self.shape.1);
184 self.row_reduction(false);
185 let mut d = T::one();
186 for i in 0..self.shape.0 {
187 d = d * self[i][i];
188 }
189 d
190 }
191 pub fn solve_system_of_linear_equations(&self, b: &[T]) -> Option<Vec<T>> {
192 assert_eq!(self.shape.0, b.len());
193 let (n, m) = self.shape;
194 let mut c = Matrix::<T>::zeros((n, m + 1));
195 for i in 0..n {
196 c[i][..m].clone_from_slice(&self[i]);
197 c[i][m] = b[i];
198 }
199 c.row_reduction(true);
200 let mut x = vec![T::zero(); m];
201 for i in 0..n {
202 let mut j = 0usize;
203 while j <= m && c[i][j].is_zero() {
204 j += 1;
205 }
206 if j == m {
207 return None;
208 }
209 if j < m {
210 x[j] = c[i][m];
211 }
212 }
213 Some(x)
214 }
215 pub fn inverse(&self) -> Option<Matrix<T>> {
216 assert_eq!(self.shape.0, self.shape.1);
217 let n = self.shape.0;
218 let mut c = Matrix::<T>::zeros((n, n * 2));
219 for i in 0..n {
220 c[i][..n].clone_from_slice(&self[i]);
221 c[i][n + i] = T::one();
222 }
223 c.row_reduction(true);
224 if (0..n).any(|i| c[i][i].is_zero()) {
225 None
226 } else {
227 Some(Self::from_vec(
228 c.data.into_iter().map(|r| r[n..].to_vec()).collect(),
229 ))
230 }
231 }
pub fn rank(&mut self) -> usize
pub fn determinant(&mut self) -> T
Sourcepub fn solve_system_of_linear_equations(&self, b: &[T]) -> Option<Vec<T>>
pub fn solve_system_of_linear_equations(&self, b: &[T]) -> Option<Vec<T>>
Examples found in repository?
crates/competitive/src/algorithm/esper.rs (line 76)
69 pub fn solve(self) -> EsperSolver<T, Input, Class, FC, FF> {
70 let data: HashMap<_, _> = self
71 .data
72 .into_iter()
73 .map(|(key, (a, b))| {
74 (
75 key,
76 Matrix::from_vec(a).solve_system_of_linear_equations(&b),
77 )
78 })
79 .collect();
80 EsperSolver {
81 class: self.class,
82 feature: self.feature,
83 data,
84 _marker: PhantomData,
85 }
86 }
87
88 pub fn solve_checked(self) -> EsperSolver<T, Input, Class, FC, FF>
89 where
90 Class: Debug,
91 T: Debug,
92 {
93 let data: HashMap<_, _> = self
94 .data
95 .into_iter()
96 .map(|(key, (a, b))| {
97 let mat = Matrix::from_vec(a);
98 let coeff = mat.solve_system_of_linear_equations(&b);
99 if coeff.is_none() {
100 eprintln!(
101 "failed to solve linear equations: key={:?} A={:?} b={:?}",
102 key, &mat.data, &b
103 );
104 }
105 (key, coeff)
106 })
107 .collect();
108 EsperSolver {
109 class: self.class,
110 feature: self.feature,
111 data,
112 _marker: PhantomData,
113 }
114 }
pub fn inverse(&self) -> Option<Matrix<T>>
Trait Implementations§
impl<T: Eq> Eq for Matrix<T>
impl<T> StructuralPartialEq for Matrix<T>
Auto Trait Implementations§
impl<T> Freeze for Matrix<T>
impl<T> RefUnwindSafe for Matrix<T>where
T: RefUnwindSafe,
impl<T> Send for Matrix<T>where
T: Send,
impl<T> Sync for Matrix<T>where
T: Sync,
impl<T> Unpin for Matrix<T>where
T: Unpin,
impl<T> UnwindSafe for Matrix<T>where
T: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more