]> gitweb.michael.orlitzky.com - numerical-analysis.git/blob - src/Linear/Matrix.hs
Add Mat6 and Mat7 synonyms.
[numerical-analysis.git] / src / Linear / Matrix.hs
1 {-# LANGUAGE ExistentialQuantification #-}
2 {-# LANGUAGE FlexibleContexts #-}
3 {-# LANGUAGE FlexibleInstances #-}
4 {-# LANGUAGE MultiParamTypeClasses #-}
5 {-# LANGUAGE NoMonomorphismRestriction #-}
6 {-# LANGUAGE ScopedTypeVariables #-}
7 {-# LANGUAGE TypeFamilies #-}
8 {-# LANGUAGE RebindableSyntax #-}
9
10 -- | Boxed matrices; that is, boxed m-vectors of boxed n-vectors. We
11 -- assume that the underlying representation is
12 -- Data.Vector.Fixed.Boxed.Vec for simplicity. It was tried in
13 -- generality and failed.
14 --
15 module Linear.Matrix
16 where
17
18 import Data.List (intercalate)
19
20 import Data.Vector.Fixed (
21 (!),
22 generate,
23 mk1,
24 mk2,
25 mk3,
26 mk4,
27 mk5 )
28 import qualified Data.Vector.Fixed as V (
29 and,
30 fromList,
31 head,
32 ifoldl,
33 ifoldr,
34 imap,
35 map,
36 maximum,
37 replicate,
38 reverse,
39 toList,
40 zipWith )
41 import Data.Vector.Fixed.Cont ( Arity, arity )
42 import Linear.Vector ( Vec, delete )
43 import Naturals ( N1, N2, N3, N4, N5, N6, N7, N8, N9, N10, S, Z )
44 import Normed ( Normed(..) )
45
46 import NumericPrelude hiding ( (*), abs )
47 import qualified NumericPrelude as NP ( (*) )
48 import qualified Algebra.Absolute as Absolute ( C )
49 import Algebra.Absolute ( abs )
50 import qualified Algebra.Additive as Additive ( C )
51 import qualified Algebra.Algebraic as Algebraic ( C )
52 import Algebra.Algebraic ( root )
53 import qualified Algebra.Field as Field ( C )
54 import qualified Algebra.Ring as Ring ( C )
55 import qualified Algebra.Module as Module ( C )
56 import qualified Algebra.RealRing as RealRing ( C )
57 import qualified Algebra.ToRational as ToRational ( C )
58 import qualified Algebra.Transcendental as Transcendental ( C )
59 import qualified Prelude as P ( map )
60
61 -- | Our main matrix type.
62 data Mat m n a = (Arity m, Arity n) => Mat (Vec m (Vec n a))
63
64 -- Type synonyms for n-by-n matrices.
65 type Mat1 a = Mat N1 N1 a
66 type Mat2 a = Mat N2 N2 a
67 type Mat3 a = Mat N3 N3 a
68 type Mat4 a = Mat N4 N4 a
69 type Mat5 a = Mat N5 N5 a
70 type Mat6 a = Mat N6 N6 a
71 type Mat7 a = Mat N7 N7 a
72
73 -- * Type synonyms for 1-by-n row "vectors".
74
75 -- | Type synonym for row vectors expressed as 1-by-n matrices.
76 type Row n a = Mat N1 n a
77
78 type Row1 a = Row N1 a
79 type Row2 a = Row N2 a
80 type Row3 a = Row N3 a
81 type Row4 a = Row N4 a
82 type Row5 a = Row N5 a
83
84 -- * Type synonyms for n-by-1 column "vectors".
85
86 -- | Type synonym for column vectors expressed as n-by-1 matrices.
87 type Col n a = Mat n N1 a
88
89 type Col1 a = Col N1 a
90 type Col2 a = Col N2 a
91 type Col3 a = Col N3 a
92 type Col4 a = Col N4 a
93 type Col5 a = Col N5 a
94 type Col6 a = Col N6 a
95 type Col7 a = Col N7 a
96 type Col8 a = Col N8 a
97 type Col9 a = Col N9 a
98 type Col10 a = Col N10 a -- We need a big column for Gaussian quadrature.
99
100
101 instance (Eq a) => Eq (Mat m n a) where
102 -- | Compare a row at a time.
103 --
104 -- Examples:
105 --
106 -- >>> let m1 = fromList [[1,2],[3,4]] :: Mat2 Int
107 -- >>> let m2 = fromList [[1,2],[3,4]] :: Mat2 Int
108 -- >>> let m3 = fromList [[5,6],[7,8]] :: Mat2 Int
109 -- >>> m1 == m2
110 -- True
111 -- >>> m1 == m3
112 -- False
113 --
114 (Mat rows_one) == (Mat rows_two) =
115 V.and $ V.zipWith comp rows_one rows_two
116 where
117 -- Compare a row, one column at a time.
118 comp row1 row2 = V.and (V.zipWith (==) row1 row2)
119
120
121 instance (Show a) => Show (Mat m n a) where
122 -- | Display matrices and vectors as ordinary tuples. This is poor
123 -- practice, but these results are primarily displayed
124 -- interactively and convenience trumps correctness (said the guy
125 -- who insists his vector lengths be statically checked at
126 -- compile-time).
127 --
128 -- Examples:
129 --
130 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
131 -- >>> show m
132 -- ((1,2),(3,4))
133 --
134 show (Mat rows) =
135 "(" ++ (intercalate "," (V.toList row_strings)) ++ ")"
136 where
137 row_strings = V.map show_vector rows
138 show_vector v1 =
139 "(" ++ (intercalate "," element_strings) ++ ")"
140 where
141 v1l = V.toList v1
142 element_strings = P.map show v1l
143
144
145 -- | Convert a matrix to a nested list.
146 toList :: Mat m n a -> [[a]]
147 toList (Mat rows) = map V.toList (V.toList rows)
148
149
150 -- | Create a matrix from a nested list.
151 fromList :: (Arity m, Arity n) => [[a]] -> Mat m n a
152 fromList vs = Mat (V.fromList $ map V.fromList vs)
153
154
155 -- | Unsafe indexing. Much faster than the safe indexing.
156 (!!!) :: (Arity m, Arity n) => Mat m n a -> (Int, Int) -> a
157 (!!!) (Mat rows) (i, j) = (rows ! i) ! j
158
159
160 -- | Safe indexing.
161 --
162 -- Examples:
163 --
164 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
165 -- >>> m !!? (-1,-1)
166 -- Nothing
167 -- >>> m !!? (-1,0)
168 -- Nothing
169 -- >>> m !!? (-1,1)
170 -- Nothing
171 -- >>> m !!? (0,-1)
172 -- Nothing
173 -- >>> m !!? (0,0)
174 -- Just 1
175 -- >>> m !!? (0,1)
176 -- Just 2
177 -- >>> m !!? (1,-1)
178 -- Nothing
179 -- >>> m !!? (1,0)
180 -- Just 3
181 -- >>> m !!? (1,1)
182 -- Just 4
183 -- >>> m !!? (2,-1)
184 -- Nothing
185 -- >>> m !!? (2,0)
186 -- Nothing
187 -- >>> m !!? (2,1)
188 -- Nothing
189 -- >>> m !!? (2,2)
190 -- Nothing
191 --
192 (!!?) :: (Arity m, Arity n) => Mat m n a -> (Int, Int) -> Maybe a
193 (!!?) matrix idx =
194 ifoldl2 f Nothing matrix
195 where
196 f k l found cur = if (k,l) == idx then (Just cur) else found
197
198
199 -- | The number of rows in the matrix.
200 nrows :: forall m n a. (Arity m) => Mat m n a -> Int
201 nrows _ = arity (undefined :: m)
202
203
204 -- | The number of columns in the first row of the
205 -- matrix. Implementation stolen from Data.Vector.Fixed.length.
206 ncols :: forall m n a. (Arity n) => Mat m n a -> Int
207 ncols _ = arity (undefined :: n)
208
209
210 -- | Return the @i@th row of @m@ as a matrix. Unsafe.
211 row :: (Arity m, Arity n) => Mat m n a -> Int -> Row n a
212 row m i =
213 construct lambda
214 where
215 lambda _ j = m !!! (i, j)
216
217
218 -- | Return the @j@th column of @m@ as a matrix. Unsafe.
219 column :: (Arity m, Arity n) => Mat m n a -> Int -> Col m a
220 column m j =
221 construct lambda
222 where
223 lambda i _ = m !!! (i, j)
224
225
226 -- | Transpose @m@; switch it's columns and its rows. This is a dirty
227 -- implementation, but I don't see a better way.
228 --
229 -- TODO: Don't cheat with fromList.
230 --
231 -- Examples:
232 --
233 -- >>> let m = fromList [[1,2], [3,4]] :: Mat2 Int
234 -- >>> transpose m
235 -- ((1,3),(2,4))
236 --
237 transpose :: (Arity m, Arity n) => Mat m n a -> Mat n m a
238 transpose matrix =
239 construct lambda
240 where
241 lambda i j = matrix !!! (j,i)
242
243
244 -- | Is @m@ symmetric?
245 --
246 -- Examples:
247 --
248 -- >>> let m1 = fromList [[1,2], [2,1]] :: Mat2 Int
249 -- >>> symmetric m1
250 -- True
251 --
252 -- >>> let m2 = fromList [[1,2], [3,1]] :: Mat2 Int
253 -- >>> symmetric m2
254 -- False
255 --
256 symmetric :: (Eq a, Arity m) => Mat m m a -> Bool
257 symmetric m =
258 m == (transpose m)
259
260
261 -- | Construct a new matrix from a function @lambda@. The function
262 -- @lambda@ should take two parameters i,j corresponding to the
263 -- entries in the matrix. The i,j entry of the resulting matrix will
264 -- have the value returned by lambda i j.
265 --
266 -- Examples:
267 --
268 -- >>> let lambda i j = i + j
269 -- >>> construct lambda :: Mat3 Int
270 -- ((0,1,2),(1,2,3),(2,3,4))
271 --
272 construct :: forall m n a. (Arity m, Arity n)
273 => (Int -> Int -> a) -> Mat m n a
274 construct lambda = Mat $ generate make_row
275 where
276 make_row :: Int -> Vec n a
277 make_row i = generate (lambda i)
278
279
280 -- | Create an identity matrix with the right dimensions.
281 --
282 -- Examples:
283 --
284 -- >>> identity_matrix :: Mat3 Int
285 -- ((1,0,0),(0,1,0),(0,0,1))
286 -- >>> identity_matrix :: Mat3 Double
287 -- ((1.0,0.0,0.0),(0.0,1.0,0.0),(0.0,0.0,1.0))
288 --
289 identity_matrix :: (Arity m, Ring.C a) => Mat m m a
290 identity_matrix =
291 construct (\i j -> if i == j then (fromInteger 1) else (fromInteger 0))
292
293
294 -- | Given a positive-definite matrix @m@, computes the
295 -- upper-triangular matrix @r@ with (transpose r)*r == m and all
296 -- values on the diagonal of @r@ positive.
297 --
298 -- Examples:
299 --
300 -- >>> let m1 = fromList [[20,-1], [-1,20]] :: Mat2 Double
301 -- >>> let r = cholesky m1
302 -- >>> frobenius_norm ((transpose r)*r - m1) < 1e-10
303 -- True
304 -- >>> is_upper_triangular r
305 -- True
306 --
307 -- >>> let k1 = [6, -3, 0, 0, 0, 0, 0] :: [Double]
308 -- >>> let k2 = [-3, 10.5, -7.5, 0, 0, 0, 0] :: [Double]
309 -- >>> let k3 = [0, -7.5, 12.5, 0, 0, 0, 0] :: [Double]
310 -- >>> let k4 = [0, 0, 0, 6, 0, 0, 0] :: [Double]
311 -- >>> let k5 = [0, 0, 0, 0, 6, 0, 0] :: [Double]
312 -- >>> let k6 = [0, 0, 0, 0, 0, 6, 0] :: [Double]
313 -- >>> let k7 = [0, 0, 0, 0, 0, 0, 15] :: [Double]
314 -- >>> let big_K = fromList [k1,k2,k3,k4,k5,k6,k7] :: Mat N7 N7 Double
315 --
316 -- >>> let e1 = [2.449489742783178,0,0,0,0,0,0] :: [Double]
317 -- >>> let e2 = [-1.224744871391589,3,0,0,0,0,0] :: [Double]
318 -- >>> let e3 = [0,-5/2,5/2,0,0,0,0] :: [Double]
319 -- >>> let e4 = [0,0,0,2.449489742783178,0,0,0] :: [Double]
320 -- >>> let e5 = [0,0,0,0,2.449489742783178,0,0] :: [Double]
321 -- >>> let e6 = [0,0,0,0,0,2.449489742783178,0] :: [Double]
322 -- >>> let e7 = [0,0,0,0,0,0,3.872983346207417] :: [Double]
323 -- >>> let expected = fromList [e1,e2,e3,e4,e5,e6,e7] :: Mat N7 N7 Double
324 --
325 -- >>> let r = cholesky big_K
326 -- >>> frobenius_norm (r - (transpose expected)) < 1e-12
327 -- True
328 --
329 cholesky :: forall m n a. (Algebraic.C a, Arity m, Arity n)
330 => (Mat m n a) -> (Mat m n a)
331 cholesky m = construct r
332 where
333 r :: Int -> Int -> a
334 r i j | i == j = sqrt(m !!! (i,j) - sum [(r k i)^2 | k <- [0..i-1]])
335 | i < j =
336 (((m !!! (i,j)) - sum [(r k i) NP.* (r k j) | k <- [0..i-1]]))/(r i i)
337 | otherwise = 0
338
339
340 -- | Returns True if the given matrix is upper-triangular, and False
341 -- otherwise. The parameter @epsilon@ lets the caller choose a
342 -- tolerance.
343 --
344 -- Examples:
345 --
346 -- >>> let m = fromList [[1,1],[1e-12,1]] :: Mat2 Double
347 -- >>> is_upper_triangular m
348 -- False
349 -- >>> is_upper_triangular' 1e-10 m
350 -- True
351 --
352 is_upper_triangular' :: forall m n a.
353 (Ord a, Ring.C a, Absolute.C a, Arity m, Arity n)
354 => a -- ^ The tolerance @epsilon@.
355 -> Mat m n a
356 -> Bool
357 is_upper_triangular' epsilon matrix =
358 ifoldl2 f True matrix
359 where
360 f :: Int -> Int -> Bool -> a -> Bool
361 f _ _ False _ = False
362 f i j True x
363 | i <= j = True
364 -- use "less than or equal to" so zero is a valid epsilon
365 | otherwise = abs x <= epsilon
366
367
368 -- | Returns True if the given matrix is upper-triangular, and False
369 -- otherwise. We don't delegate to the general
370 -- 'is_upper_triangular'' here because it imposes additional
371 -- typeclass constraints throughout the library.
372 --
373 -- Examples:
374 --
375 -- >>> let m = fromList [[1,0],[1,1]] :: Mat2 Int
376 -- >>> is_upper_triangular m
377 -- False
378 --
379 -- >>> let m = fromList [[1,2],[0,3]] :: Mat2 Int
380 -- >>> is_upper_triangular m
381 -- True
382 --
383 is_upper_triangular :: forall m n a.
384 (Eq a, Ring.C a, Arity m, Arity n)
385 => Mat m n a -> Bool
386 is_upper_triangular matrix =
387 ifoldl2 f True matrix
388 where
389 f :: Int -> Int -> Bool -> a -> Bool
390 f _ _ False _ = False
391 f i j True x
392 | i <= j = True
393 | otherwise = x == 0
394
395
396
397 -- | Returns True if the given matrix is lower-triangular, and False
398 -- otherwise.
399 --
400 -- Examples:
401 --
402 -- >>> let m = fromList [[1,0],[1,1]] :: Mat2 Int
403 -- >>> is_lower_triangular m
404 -- True
405 --
406 -- >>> let m = fromList [[1,2],[0,3]] :: Mat2 Int
407 -- >>> is_lower_triangular m
408 -- False
409 --
410 is_lower_triangular :: (Eq a,
411 Ring.C a,
412 Arity m,
413 Arity n)
414 => Mat m n a
415 -> Bool
416 is_lower_triangular = is_upper_triangular . transpose
417
418
419 -- | Returns True if the given matrix is lower-triangular, and False
420 -- otherwise. The parameter @epsilon@ lets the caller choose a
421 -- tolerance.
422 --
423 -- Examples:
424 --
425 -- >>> let m = fromList [[1,1e-12],[1,1]] :: Mat2 Double
426 -- >>> is_lower_triangular m
427 -- False
428 -- >>> is_lower_triangular' 1e-12 m
429 -- True
430 --
431 is_lower_triangular' :: (Ord a,
432 Ring.C a,
433 Absolute.C a,
434 Arity m,
435 Arity n)
436 => a -- ^ The tolerance @epsilon@.
437 -> Mat m n a
438 -> Bool
439 is_lower_triangular' epsilon = (is_upper_triangular' epsilon) . transpose
440
441
442 -- | Returns True if the given matrix is triangular, and False
443 -- otherwise.
444 --
445 -- Examples:
446 --
447 -- >>> let m = fromList [[1,0],[1,1]] :: Mat2 Int
448 -- >>> is_triangular m
449 -- True
450 --
451 -- >>> let m = fromList [[1,2],[0,3]] :: Mat2 Int
452 -- >>> is_triangular m
453 -- True
454 --
455 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
456 -- >>> is_triangular m
457 -- False
458 --
459 is_triangular :: (Ord a,
460 Ring.C a,
461 Absolute.C a,
462 Arity m,
463 Arity n)
464 => Mat m n a
465 -> Bool
466 is_triangular m = is_upper_triangular m || is_lower_triangular m
467
468
469 -- | Delete the @i@th row and @j@th column from the matrix. The name
470 -- \"preminor\" is made up, but is meant to signify that this is
471 -- usually used in the computationof a minor. A minor is simply the
472 -- determinant of a preminor in that case.
473 --
474 -- Examples:
475 --
476 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
477 -- >>> preminor m 0 0 :: Mat2 Int
478 -- ((5,6),(8,9))
479 -- >>> preminor m 1 1 :: Mat2 Int
480 -- ((1,3),(7,9))
481 --
482 preminor :: (Arity m, Arity n)
483 => Mat (S m) (S n) a
484 -> Int
485 -> Int
486 -> Mat m n a
487 preminor (Mat rows) i j = m
488 where
489 rows' = delete rows i
490 m = Mat $ V.map ((flip delete) j) rows'
491
492
493 -- | Compute the i,jth minor of a @matrix@.
494 --
495 -- Examples:
496 --
497 -- >>> let m1 = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Double
498 -- >>> minor m1 1 1
499 -- -12.0
500 --
501 minor :: (Arity m, Determined (Mat m m) a)
502 => Mat (S m) (S m) a
503 -> Int
504 -> Int
505 -> a
506 minor matrix i j = determinant (preminor matrix i j)
507
508 class (Eq a, Ring.C a) => Determined p a where
509 determinant :: (p a) -> a
510
511 instance (Eq a, Ring.C a) => Determined (Mat (S Z) (S Z)) a where
512 determinant = unscalar
513
514 instance (Ord a,
515 Ring.C a,
516 Absolute.C a,
517 Arity n,
518 Determined (Mat (S n) (S n)) a)
519 => Determined (Mat (S (S n)) (S (S n))) a where
520 -- | The recursive definition with a special-case for triangular matrices.
521 --
522 -- Examples:
523 --
524 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
525 -- >>> determinant m
526 -- -1
527 --
528 determinant m
529 | is_triangular m = product [ m !!! (i,i) | i <- [0..(nrows m)-1] ]
530 | otherwise = determinant_recursive
531 where
532 m' i j = m !!! (i,j)
533
534 determinant_recursive =
535 sum [ (-1)^(toInteger j) NP.* (m' 0 j) NP.* (minor m 0 j)
536 | j <- [0..(ncols m)-1] ]
537
538
539
540 -- | Matrix multiplication.
541 --
542 -- Examples:
543 --
544 -- >>> let m1 = fromList [[1,2,3], [4,5,6]] :: Mat N2 N3 Int
545 -- >>> let m2 = fromList [[1,2],[3,4],[5,6]] :: Mat N3 N2 Int
546 -- >>> m1 * m2
547 -- ((22,28),(49,64))
548 --
549 infixl 7 *
550 (*) :: (Ring.C a, Arity m, Arity n, Arity p)
551 => Mat (S m) (S n) a
552 -> Mat (S n) (S p) a
553 -> Mat (S m) (S p) a
554 (*) m1 m2 = construct lambda
555 where
556 lambda i j = (transpose $ row m1 i) `dot` (column m2 j)
557
558
559
560 instance (Ring.C a, Arity m, Arity n) => Additive.C (Mat m n a) where
561
562 (Mat rows_one) + (Mat rows_two) =
563 Mat $ V.zipWith (V.zipWith (+)) rows_one rows_two
564
565 (Mat rows_one) - (Mat rows_two) =
566 Mat $ V.zipWith (V.zipWith (-)) rows_one rows_two
567
568 zero = Mat (V.replicate $ V.replicate (fromInteger 0))
569
570
571 instance (Ring.C a, Arity m, Arity n, m ~ n) => Ring.C (Mat (S m) (S n) a) where
572 -- The first * is ring multiplication, the second is matrix
573 -- multiplication.
574 m1 * m2 = m1 * m2
575
576
577 instance (Ring.C a, Arity m, Arity n) => Module.C a (Mat m n a) where
578 -- We can multiply a matrix by a scalar of the same type as its
579 -- elements.
580 x *> (Mat rows) = Mat $ V.map (V.map (NP.* x)) rows
581
582
583 instance (Absolute.C a,
584 Algebraic.C a,
585 ToRational.C a,
586 Arity m)
587 => Normed (Col (S m) a) where
588 -- | Generic p-norms for vectors in R^n that are represented as n-by-1
589 -- matrices.
590 --
591 -- Examples:
592 --
593 -- >>> let v1 = vec2d (3,4)
594 -- >>> norm_p 1 v1
595 -- 7.0
596 -- >>> norm_p 2 v1
597 -- 5.0
598 --
599 -- >>> let v1 = vec2d (-1,1) :: Col2 Double
600 -- >>> norm_p 1 v1 :: Double
601 -- 2.0
602 --
603 norm_p p (Mat rows) =
604 (root p') $ sum [fromRational' (toRational $ abs x)^p' | x <- xs]
605 where
606 p' = toInteger p
607 xs = concat $ V.toList $ V.map V.toList rows
608
609 -- | The infinity norm.
610 --
611 -- Examples:
612 --
613 -- >>> let v1 = vec3d (1,5,2)
614 -- >>> norm_infty v1
615 -- 5
616 --
617 norm_infty (Mat rows) =
618 fromRational' $ toRational $ V.maximum $ V.map V.maximum rows
619
620
621 -- | Compute the Frobenius norm of a matrix. This essentially treats
622 -- the matrix as one long vector containing all of its entries (in
623 -- any order, it doesn't matter).
624 --
625 -- Examples:
626 --
627 -- >>> let m = fromList [[1, 2, 3],[4,5,6],[7,8,9]] :: Mat3 Double
628 -- >>> frobenius_norm m == sqrt 285
629 -- True
630 --
631 -- >>> let m = fromList [[1, -1, 1],[-1,1,-1],[1,-1,1]] :: Mat3 Double
632 -- >>> frobenius_norm m == 3
633 -- True
634 --
635 frobenius_norm :: (Arity m, Arity n, Algebraic.C a, Ring.C a)
636 => Mat m n a
637 -> a
638 frobenius_norm matrix =
639 sqrt $ element_sum2 $ squares
640 where
641 squares = map2 (^2) matrix
642
643
644 -- Vector helpers. We want it to be easy to create low-dimension
645 -- column vectors, which are nx1 matrices.
646
647 -- | Convenient constructor for 2D vectors.
648 --
649 -- Examples:
650 --
651 -- >>> import Roots.Simple
652 -- >>> let fst m = m !!! (0,0)
653 -- >>> let snd m = m !!! (1,0)
654 -- >>> let h = 0.5 :: Double
655 -- >>> let g1 m = 1.0 + h NP.* exp(-((fst m)^2))/(1.0 + (snd m)^2)
656 -- >>> let g2 m = 0.5 + h NP.* atan((fst m)^2 + (snd m)^2)
657 -- >>> let g u = vec2d ((g1 u), (g2 u))
658 -- >>> let u0 = vec2d (1.0, 1.0)
659 -- >>> let eps = 1/(10^9)
660 -- >>> fixed_point g eps u0
661 -- ((1.0728549599342185),(1.0820591495686167))
662 --
663 vec1d :: (a) -> Col1 a
664 vec1d (x) = Mat (mk1 (mk1 x))
665
666 vec2d :: (a,a) -> Col2 a
667 vec2d (x,y) = Mat (mk2 (mk1 x) (mk1 y))
668
669 vec3d :: (a,a,a) -> Col3 a
670 vec3d (x,y,z) = Mat (mk3 (mk1 x) (mk1 y) (mk1 z))
671
672 vec4d :: (a,a,a,a) -> Col4 a
673 vec4d (w,x,y,z) = Mat (mk4 (mk1 w) (mk1 x) (mk1 y) (mk1 z))
674
675 vec5d :: (a,a,a,a,a) -> Col5 a
676 vec5d (v,w,x,y,z) = Mat (mk5 (mk1 v) (mk1 w) (mk1 x) (mk1 y) (mk1 z))
677
678
679 -- Since we commandeered multiplication, we need to create 1x1
680 -- matrices in order to multiply things.
681 scalar :: a -> Mat1 a
682 scalar x = Mat (mk1 (mk1 x))
683
684 -- Get the scalar value out of a 1x1 matrix.
685 unscalar :: Mat1 a -> a
686 unscalar (Mat rows) = V.head $ V.head rows
687
688
689 dot :: (Ring.C a, Arity m)
690 => Col (S m) a
691 -> Col (S m) a
692 -> a
693 v1 `dot` v2 = element_sum2 $ zipwith2 (NP.*) v1 v2
694
695
696 -- | The angle between @v1@ and @v2@ in Euclidean space.
697 --
698 -- Examples:
699 --
700 -- >>> let v1 = vec2d (1.0, 0.0)
701 -- >>> let v2 = vec2d (0.0, 1.0)
702 -- >>> angle v1 v2 == pi/2.0
703 -- True
704 --
705 angle :: (Transcendental.C a,
706 RealRing.C a,
707 m ~ S t,
708 Arity t,
709 ToRational.C a)
710 => Col m a
711 -> Col m a
712 -> a
713 angle v1 v2 =
714 acos theta
715 where
716 theta = (recip norms) NP.* (v1 `dot` v2)
717 norms = (norm v1) NP.* (norm v2)
718
719
720 -- | Retrieve the diagonal elements of the given matrix as a \"column
721 -- vector,\" i.e. a m-by-1 matrix. We require the matrix to be
722 -- square to avoid ambiguity in the return type which would ideally
723 -- have dimension min(m,n) supposing an m-by-n matrix.
724 --
725 -- Examples:
726 --
727 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
728 -- >>> diagonal m
729 -- ((1),(5),(9))
730 --
731 diagonal :: (Arity m) => Mat m m a -> Col m a
732 diagonal matrix =
733 construct lambda
734 where
735 lambda i _ = matrix !!! (i,i)
736
737
738 -- | Given a square @matrix@, return a new matrix of the same size
739 -- containing only the on-diagonal entries of @matrix@. The
740 -- off-diagonal entries are set to zero.
741 --
742 -- Examples:
743 --
744 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
745 -- >>> diagonal_part m
746 -- ((1,0,0),(0,5,0),(0,0,9))
747 --
748 diagonal_part :: (Arity m, Ring.C a)
749 => Mat m m a
750 -> Mat m m a
751 diagonal_part matrix =
752 construct lambda
753 where
754 lambda i j = if i == j then matrix !!! (i,j) else 0
755
756
757 -- | Given a square @matrix@, return a new matrix of the same size
758 -- containing only the on-diagonal and below-diagonal entries of
759 -- @matrix@. The above-diagonal entries are set to zero.
760 --
761 -- Examples:
762 --
763 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
764 -- >>> lt_part m
765 -- ((1,0,0),(4,5,0),(7,8,9))
766 --
767 lt_part :: (Arity m, Ring.C a)
768 => Mat m m a
769 -> Mat m m a
770 lt_part matrix =
771 construct lambda
772 where
773 lambda i j = if i >= j then matrix !!! (i,j) else 0
774
775
776 -- | Given a square @matrix@, return a new matrix of the same size
777 -- containing only the below-diagonal entries of @matrix@. The on-
778 -- and above-diagonal entries are set to zero.
779 --
780 -- Examples:
781 --
782 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
783 -- >>> lt_part_strict m
784 -- ((0,0,0),(4,0,0),(7,8,0))
785 --
786 lt_part_strict :: (Arity m, Ring.C a)
787 => Mat m m a
788 -> Mat m m a
789 lt_part_strict matrix =
790 construct lambda
791 where
792 lambda i j = if i > j then matrix !!! (i,j) else 0
793
794
795 -- | Given a square @matrix@, return a new matrix of the same size
796 -- containing only the on-diagonal and above-diagonal entries of
797 -- @matrix@. The below-diagonal entries are set to zero.
798 --
799 -- Examples:
800 --
801 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
802 -- >>> ut_part m
803 -- ((1,2,3),(0,5,6),(0,0,9))
804 --
805 ut_part :: (Arity m, Ring.C a)
806 => Mat m m a
807 -> Mat m m a
808 ut_part = transpose . lt_part . transpose
809
810
811 -- | Given a square @matrix@, return a new matrix of the same size
812 -- containing only the above-diagonal entries of @matrix@. The on-
813 -- and below-diagonal entries are set to zero.
814 --
815 -- Examples:
816 --
817 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
818 -- >>> ut_part_strict m
819 -- ((0,2,3),(0,0,6),(0,0,0))
820 --
821 ut_part_strict :: (Arity m, Ring.C a)
822 => Mat m m a
823 -> Mat m m a
824 ut_part_strict = transpose . lt_part_strict . transpose
825
826
827 -- | Compute the trace of a square matrix, the sum of the elements
828 -- which lie on its diagonal. We require the matrix to be
829 -- square to avoid ambiguity in the return type which would ideally
830 -- have dimension min(m,n) supposing an m-by-n matrix.
831 --
832 -- Examples:
833 --
834 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
835 -- >>> trace m
836 -- 15
837 --
838 trace :: (Arity m, Ring.C a) => Mat m m a -> a
839 trace = element_sum2 . diagonal
840
841
842
843 -- | Zip together two matrices.
844 --
845 -- TODO: don't cheat with construct (map V.zips instead).
846 --
847 -- Examples:
848 --
849 -- >>> let m1 = fromList [[1],[1],[1]] :: Col3 Int
850 -- >>> let m2 = fromList [[1],[2],[3]] :: Col3 Int
851 -- >>> zip2 m1 m2
852 -- (((1,1)),((1,2)),((1,3)))
853 --
854 -- >>> let m1 = fromList [[1,2],[3,4]] :: Mat2 Int
855 -- >>> let m2 = fromList [[1,1],[1,1]] :: Mat2 Int
856 -- >>> zip2 m1 m2
857 -- (((1,1),(2,1)),((3,1),(4,1)))
858 --
859 zip2 :: (Arity m, Arity n) => Mat m n a -> Mat m n b -> Mat m n (a,b)
860 zip2 m1 m2 =
861 construct lambda
862 where
863 lambda i j = (m1 !!! (i,j), m2 !!! (i,j))
864
865
866 -- | Zip together three matrices.
867 --
868 -- TODO: don't cheat with construct (map V.zips instead).
869 --
870 -- Examples:
871 --
872 -- >>> let m1 = fromList [[1],[1],[1]] :: Col3 Int
873 -- >>> let m2 = fromList [[1],[2],[3]] :: Col3 Int
874 -- >>> let m3 = fromList [[4],[5],[6]] :: Col3 Int
875 -- >>> zip2three m1 m2 m3
876 -- (((1,1,4)),((1,2,5)),((1,3,6)))
877 --
878 -- >>> let m1 = fromList [[1,2],[3,4]] :: Mat2 Int
879 -- >>> let m2 = fromList [[1,1],[1,1]] :: Mat2 Int
880 -- >>> let m3 = fromList [[8,2],[6,3]] :: Mat2 Int
881 -- >>> zip2three m1 m2 m3
882 -- (((1,1,8),(2,1,2)),((3,1,6),(4,1,3)))
883 --
884 zip2three :: (Arity m, Arity n)
885 => Mat m n a
886 -> Mat m n a
887 -> Mat m n a
888 -> Mat m n (a,a,a)
889 zip2three m1 m2 m3 =
890 construct lambda
891 where
892 lambda i j = (m1 !!! (i,j), m2 !!! (i,j), m3 !!! (i,j))
893
894
895 -- | Zip together two matrices using the supplied function.
896 --
897 -- Examples:
898 --
899 -- >>> let c1 = fromList [[1],[2],[3]] :: Col3 Integer
900 -- >>> let c2 = fromList [[4],[5],[6]] :: Col3 Integer
901 -- >>> zipwith2 (^) c1 c2
902 -- ((1),(32),(729))
903 --
904 zipwith2 :: (Arity m, Arity n)
905 => (a -> b -> c)
906 -> Mat m n a
907 -> Mat m n b
908 -> Mat m n c
909 zipwith2 f c1 c2 =
910 construct lambda
911 where
912 lambda i j = f (c1 !!! (i,j)) (c2 !!! (i,j))
913
914
915 -- | Map a function over a matrix of any dimensions.
916 --
917 -- Examples:
918 --
919 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
920 -- >>> map2 (^2) m
921 -- ((1,4),(9,16))
922 --
923 map2 :: (a -> b) -> Mat m n a -> Mat m n b
924 map2 f (Mat rows) =
925 Mat $ V.map g rows
926 where
927 g = V.map f
928
929
930 -- | Fold over the entire matrix passing the coordinates @i@ and @j@
931 -- (of the row/column) to the accumulation function. The fold occurs
932 -- from top-left to bottom-right.
933 --
934 -- Examples:
935 --
936 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
937 -- >>> ifoldl2 (\i j cur _ -> cur + i + j) 0 m
938 -- 18
939 --
940 ifoldl2 :: forall a b m n.
941 (Int -> Int -> b -> a -> b)
942 -> b
943 -> Mat m n a
944 -> b
945 ifoldl2 f initial (Mat rows) =
946 V.ifoldl row_function initial rows
947 where
948 -- | The order that we need this in (so that @g idx@ makes sense)
949 -- is a little funny. So that we don't need to pass weird
950 -- functions into ifoldl2, we swap the second and third
951 -- arguments of @f@ calling the result @g@.
952 g :: Int -> b -> Int -> a -> b
953 g w x y = f w y x
954
955 row_function :: b -> Int -> Vec n a -> b
956 row_function rowinit idx r = V.ifoldl (g idx) rowinit r
957
958
959 -- | Left fold over the entries of a matrix (top-left to bottom-right).
960 --
961 foldl2 :: forall a b m n.
962 (b -> a -> b)
963 -> b
964 -> Mat m n a
965 -> b
966 foldl2 f initial matrix =
967 -- Use the index fold but ignore the index arguments.
968 let g _ _ = f in ifoldl2 g initial matrix
969
970
971 -- | Fold over the entire matrix passing the coordinates @i@ and @j@
972 -- (of the row/column) to the accumulation function. The fold occurs
973 -- from bottom-right to top-left.
974 --
975 -- The order of the arguments in the supplied function are different
976 -- from those in V.ifoldr; we keep them similar to ifoldl2.
977 --
978 -- Examples:
979 --
980 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
981 -- >>> ifoldr2 (\i j cur _ -> cur + i + j) 0 m
982 -- 18
983 --
984 ifoldr2 :: forall a b m n.
985 (Int -> Int -> b -> a -> b)
986 -> b
987 -> Mat m n a
988 -> b
989 ifoldr2 f initial (Mat rows) =
990 V.ifoldr row_function initial rows
991 where
992 -- | Swap the order of arguments in @f@ so that it agrees with the
993 -- @f@ passed to ifoldl2.
994 g :: Int -> Int -> a -> b -> b
995 g w x y z = f w x z y
996
997 row_function :: Int -> Vec n a -> b -> b
998 row_function idx r rowinit = V.ifoldr (g idx) rowinit r
999
1000
1001 -- | Map a function over a matrix of any dimensions, passing the
1002 -- coordinates @i@ and @j@ to the function @f@.
1003 --
1004 -- Examples:
1005 --
1006 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
1007 -- >>> imap2 (\i j _ -> i+j) m
1008 -- ((0,1),(1,2))
1009 --
1010 imap2 :: (Int -> Int -> a -> b) -> Mat m n a -> Mat m n b
1011 imap2 f (Mat rows) =
1012 Mat $ V.imap g rows
1013 where
1014 g i = V.imap (f i)
1015
1016
1017 -- | Reverse the order of elements in a matrix.
1018 --
1019 -- Examples:
1020 --
1021 -- >>> let m1 = fromList [[1,2,3]] :: Row3 Int
1022 -- >>> reverse2 m1
1023 -- ((3,2,1))
1024 --
1025 -- >>> let m1 = vec3d (1,2,3 :: Int)
1026 -- >>> reverse2 m1
1027 -- ((3),(2),(1))
1028 --
1029 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
1030 -- >>> reverse2 m
1031 -- ((9,8,7),(6,5,4),(3,2,1))
1032 --
1033 reverse2 :: (Arity m, Arity n) => Mat m n a -> Mat m n a
1034 reverse2 (Mat rows) = Mat $ V.reverse $ V.map V.reverse rows
1035
1036
1037 -- | Unsafely set the (i,j) element of the given matrix.
1038 --
1039 -- Examples:
1040 --
1041 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
1042 -- >>> set_idx m (1,1) 17
1043 -- ((1,2,3),(4,17,6),(7,8,9))
1044 --
1045 set_idx :: forall m n a.
1046 (Arity m, Arity n)
1047 => Mat m n a
1048 -> (Int, Int)
1049 -> a
1050 -> Mat m n a
1051 set_idx matrix (i,j) newval =
1052 imap2 updater matrix
1053 where
1054 updater :: Int -> Int -> a -> a
1055 updater k l existing =
1056 if k == i && l == j
1057 then newval
1058 else existing
1059
1060
1061 -- | Compute the i,jth cofactor of the given @matrix@. This simply
1062 -- premultiplues the i,jth minor by (-1)^(i+j).
1063 cofactor :: (Arity m, Determined (Mat m m) a)
1064 => Mat (S m) (S m) a
1065 -> Int
1066 -> Int
1067 -> a
1068 cofactor matrix i j =
1069 (-1)^(toInteger i + toInteger j) NP.* (minor matrix i j)
1070
1071
1072 -- | Compute the inverse of a matrix using cofactor expansion
1073 -- (generalized Cramer's rule).
1074 --
1075 -- Examples:
1076 --
1077 -- >>> let m1 = fromList [[37,22],[17,54]] :: Mat2 Double
1078 -- >>> let e1 = [54/1624, -22/1624] :: [Double]
1079 -- >>> let e2 = [-17/1624, 37/1624] :: [Double]
1080 -- >>> let expected = fromList [e1, e2] :: Mat2 Double
1081 -- >>> let actual = inverse m1
1082 -- >>> frobenius_norm (actual - expected) < 1e-12
1083 -- True
1084 --
1085 inverse :: (Arity m,
1086 Determined (Mat (S m) (S m)) a,
1087 Determined (Mat m m) a,
1088 Field.C a)
1089 => Mat (S m) (S m) a
1090 -> Mat (S m) (S m) a
1091 inverse matrix =
1092 (1 / (determinant matrix)) *> (transpose $ construct lambda)
1093 where
1094 lambda i j = cofactor matrix i j
1095
1096
1097
1098 -- | Retrieve the rows of a matrix as a column matrix. If the given
1099 -- matrix is m-by-n, the result would be an m-by-1 column whose
1100 -- entries are 1-by-n row matrices.
1101 --
1102 -- Examples:
1103 --
1104 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
1105 -- >>> (rows2 m) !!! (0,0)
1106 -- ((1,2))
1107 -- >>> (rows2 m) !!! (1,0)
1108 -- ((3,4))
1109 --
1110 rows2 :: (Arity m, Arity n)
1111 => Mat m n a
1112 -> Col m (Row n a)
1113 rows2 (Mat rows) =
1114 Mat $ V.map (mk1. Mat . mk1) rows
1115
1116
1117
1118 -- | Sum the elements of a matrix.
1119 --
1120 -- Examples:
1121 --
1122 -- >>> let m = fromList [[1,-1],[3,4]] :: Mat2 Int
1123 -- >>> element_sum2 m
1124 -- 7
1125 --
1126 element_sum2 :: (Arity m, Arity n, Additive.C a) => Mat m n a -> a
1127 element_sum2 = foldl2 (+) zero