1 {-# LANGUAGE ExistentialQuantification #-}
2 {-# LANGUAGE FlexibleContexts #-}
3 {-# LANGUAGE FlexibleInstances #-}
4 {-# LANGUAGE MultiParamTypeClasses #-}
5 {-# LANGUAGE NoMonomorphismRestriction #-}
6 {-# LANGUAGE ScopedTypeVariables #-}
7 {-# LANGUAGE TypeFamilies #-}
8 {-# LANGUAGE RebindableSyntax #-}
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.
18 import Data.List (intercalate)
20 import Data.Vector.Fixed (
36 import qualified Data.Vector.Fixed as V (
47 import Data.Vector.Fixed.Cont ( Arity, arity )
48 import Linear.Vector ( Vec, delete, element_sum )
49 import Normed ( Normed(..) )
51 import NumericPrelude hiding ( (*), abs )
52 import qualified NumericPrelude as NP ( (*) )
53 import qualified Algebra.Absolute as Absolute ( C )
54 import Algebra.Absolute ( abs )
55 import qualified Algebra.Additive as Additive ( C )
56 import qualified Algebra.Algebraic as Algebraic ( C )
57 import Algebra.Algebraic ( root )
58 import qualified Algebra.Ring as Ring ( C )
59 import qualified Algebra.Module as Module ( C )
60 import qualified Algebra.RealRing as RealRing ( C )
61 import qualified Algebra.ToRational as ToRational ( C )
62 import qualified Algebra.Transcendental as Transcendental ( C )
63 import qualified Prelude as P ( map )
65 -- | Our main matrix type.
66 data Mat m n a = (Arity m, Arity n) => Mat (Vec m (Vec n a))
68 -- Type synonyms for n-by-n matrices.
69 type Mat1 a = Mat N1 N1 a
70 type Mat2 a = Mat N2 N2 a
71 type Mat3 a = Mat N3 N3 a
72 type Mat4 a = Mat N4 N4 a
73 type Mat5 a = Mat N5 N5 a
75 -- | Type synonym for row vectors expressed as 1-by-n matrices.
76 type Row n a = Mat N1 n a
78 -- Type synonyms for 1-by-n row "vectors".
79 type Row1 a = Row N1 a
80 type Row2 a = Row N2 a
81 type Row3 a = Row N3 a
82 type Row4 a = Row N4 a
83 type Row5 a = Row N5 a
85 -- | Type synonym for column vectors expressed as n-by-1 matrices.
86 type Col n a = Mat n N1 a
88 -- Type synonyms for n-by-1 column "vectors".
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
95 -- We need a big column for Gaussian quadrature.
96 type N10 = S (S (S (S (S N5))))
97 type Col10 a = Col N10 a
100 instance (Eq a) => Eq (Mat m n a) where
101 -- | Compare a row at a time.
105 -- >>> let m1 = fromList [[1,2],[3,4]] :: Mat2 Int
106 -- >>> let m2 = fromList [[1,2],[3,4]] :: Mat2 Int
107 -- >>> let m3 = fromList [[5,6],[7,8]] :: Mat2 Int
113 (Mat rows1) == (Mat rows2) =
114 V.and $ V.zipWith comp rows1 rows2
116 -- Compare a row, one column at a time.
117 comp row1 row2 = V.and (V.zipWith (==) row1 row2)
120 instance (Show a) => Show (Mat m n a) where
121 -- | Display matrices and vectors as ordinary tuples. This is poor
122 -- practice, but these results are primarily displayed
123 -- interactively and convenience trumps correctness (said the guy
124 -- who insists his vector lengths be statically checked at
129 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
134 "(" ++ (intercalate "," (V.toList row_strings)) ++ ")"
136 row_strings = V.map show_vector rows
138 "(" ++ (intercalate "," element_strings) ++ ")"
141 element_strings = P.map show v1l
144 -- | Convert a matrix to a nested list.
145 toList :: Mat m n a -> [[a]]
146 toList (Mat rows) = map V.toList (V.toList rows)
149 -- | Create a matrix from a nested list.
150 fromList :: (Arity m, Arity n) => [[a]] -> Mat m n a
151 fromList vs = Mat (V.fromList $ map V.fromList vs)
154 -- | Unsafe indexing. Much faster than the safe indexing.
155 (!!!) :: (Arity m, Arity n) => Mat m n a -> (Int, Int) -> a
156 (!!!) (Mat rows) (i, j) = (rows ! i) ! j
163 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
191 (!!?) :: (Arity m, Arity n) => Mat m n a -> (Int, Int) -> Maybe a
193 ifoldl2 f Nothing matrix
195 f k l found cur = if (k,l) == idx then (Just cur) else found
198 -- | The number of rows in the matrix.
199 nrows :: forall m n a. (Arity m) => Mat m n a -> Int
200 nrows _ = arity (undefined :: m)
203 -- | The number of columns in the first row of the
204 -- matrix. Implementation stolen from Data.Vector.Fixed.length.
205 ncols :: forall m n a. (Arity n) => Mat m n a -> Int
206 ncols _ = arity (undefined :: n)
209 -- | Return the @i@th row of @m@ as a matrix. Unsafe.
210 row :: (Arity m, Arity n) => Mat m n a -> Int -> Row n a
214 lambda _ j = m !!! (i, j)
217 -- | Return the @j@th column of @m@ as a matrix. Unsafe.
218 column :: (Arity m, Arity n) => Mat m n a -> Int -> Col m a
222 lambda i _ = m !!! (i, j)
225 -- | Transpose @m@; switch it's columns and its rows. This is a dirty
226 -- implementation, but I don't see a better way.
228 -- TODO: Don't cheat with fromList.
232 -- >>> let m = fromList [[1,2], [3,4]] :: Mat2 Int
236 transpose :: (Arity m, Arity n) => Mat m n a -> Mat n m a
240 lambda i j = matrix !!! (j,i)
243 -- | Is @m@ symmetric?
247 -- >>> let m1 = fromList [[1,2], [2,1]] :: Mat2 Int
251 -- >>> let m2 = fromList [[1,2], [3,1]] :: Mat2 Int
255 symmetric :: (Eq a, Arity m) => Mat m m a -> Bool
260 -- | Construct a new matrix from a function @lambda@. The function
261 -- @lambda@ should take two parameters i,j corresponding to the
262 -- entries in the matrix. The i,j entry of the resulting matrix will
263 -- have the value returned by lambda i j.
267 -- >>> let lambda i j = i + j
268 -- >>> construct lambda :: Mat3 Int
269 -- ((0,1,2),(1,2,3),(2,3,4))
271 construct :: forall m n a. (Arity m, Arity n)
272 => (Int -> Int -> a) -> Mat m n a
273 construct lambda = Mat $ generate make_row
275 make_row :: Int -> Vec n a
276 make_row i = generate (lambda i)
279 -- | Create an identity matrix with the right dimensions.
283 -- >>> identity_matrix :: Mat3 Int
284 -- ((1,0,0),(0,1,0),(0,0,1))
285 -- >>> identity_matrix :: Mat3 Double
286 -- ((1.0,0.0,0.0),(0.0,1.0,0.0),(0.0,0.0,1.0))
288 identity_matrix :: (Arity m, Ring.C a) => Mat m m a
290 construct (\i j -> if i == j then (fromInteger 1) else (fromInteger 0))
293 -- | Given a positive-definite matrix @m@, computes the
294 -- upper-triangular matrix @r@ with (transpose r)*r == m and all
295 -- values on the diagonal of @r@ positive.
299 -- >>> let m1 = fromList [[20,-1], [-1,20]] :: Mat2 Double
301 -- ((4.47213595499958,-0.22360679774997896),(0.0,4.466542286825459))
302 -- >>> (transpose (cholesky m1)) * (cholesky m1)
303 -- ((20.000000000000004,-1.0),(-1.0,20.0))
305 cholesky :: forall m n a. (Algebraic.C a, Arity m, Arity n)
306 => (Mat m n a) -> (Mat m n a)
307 cholesky m = construct r
310 r i j | i == j = sqrt(m !!! (i,j) - sum [(r k i)^2 | k <- [0..i-1]])
312 (((m !!! (i,j)) - sum [(r k i) NP.* (r k j) | k <- [0..i-1]]))/(r i i)
316 -- | Returns True if the given matrix is upper-triangular, and False
317 -- otherwise. The parameter @epsilon@ lets the caller choose a
322 -- >>> let m = fromList [[1,1],[1e-12,1]] :: Mat2 Double
323 -- >>> is_upper_triangular m
325 -- >>> is_upper_triangular' 1e-10 m
330 -- 1. Don't cheat with lists.
332 is_upper_triangular' :: (Ord a, Ring.C a, Absolute.C a, Arity m, Arity n)
333 => a -- ^ The tolerance @epsilon@.
336 is_upper_triangular' epsilon m =
339 results = [[ test i j | i <- [0..(nrows m)-1]] | j <- [0..(ncols m)-1] ]
341 test :: Int -> Int -> Bool
344 -- use "less than or equal to" so zero is a valid epsilon
345 | otherwise = abs (m !!! (i,j)) <= epsilon
348 -- | Returns True if the given matrix is upper-triangular, and False
349 -- otherwise. A specialized version of 'is_upper_triangular\'' with
354 -- >>> let m = fromList [[1,0],[1,1]] :: Mat2 Int
355 -- >>> is_upper_triangular m
358 -- >>> let m = fromList [[1,2],[0,3]] :: Mat2 Int
359 -- >>> is_upper_triangular m
364 -- 1. The Ord constraint is too strong here, Eq would suffice.
366 is_upper_triangular :: (Ord a, Ring.C a, Absolute.C a, Arity m, Arity n)
368 is_upper_triangular = is_upper_triangular' 0
371 -- | Returns True if the given matrix is lower-triangular, and False
372 -- otherwise. This is a specialized version of 'is_lower_triangular\''
373 -- with @epsilon = 0@.
377 -- >>> let m = fromList [[1,0],[1,1]] :: Mat2 Int
378 -- >>> is_lower_triangular m
381 -- >>> let m = fromList [[1,2],[0,3]] :: Mat2 Int
382 -- >>> is_lower_triangular m
385 is_lower_triangular :: (Ord a,
392 is_lower_triangular = is_upper_triangular . transpose
395 -- | Returns True if the given matrix is lower-triangular, and False
396 -- otherwise. The parameter @epsilon@ lets the caller choose a
401 -- >>> let m = fromList [[1,1e-12],[1,1]] :: Mat2 Double
402 -- >>> is_lower_triangular m
404 -- >>> is_lower_triangular' 1e-12 m
407 is_lower_triangular' :: (Ord a,
412 => a -- ^ The tolerance @epsilon@.
415 is_lower_triangular' epsilon = (is_upper_triangular' epsilon) . transpose
418 -- | Returns True if the given matrix is triangular, and False
423 -- >>> let m = fromList [[1,0],[1,1]] :: Mat2 Int
424 -- >>> is_triangular m
427 -- >>> let m = fromList [[1,2],[0,3]] :: Mat2 Int
428 -- >>> is_triangular m
431 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
432 -- >>> is_triangular m
435 is_triangular :: (Ord a,
442 is_triangular m = is_upper_triangular m || is_lower_triangular m
445 -- | Return the (i,j)th minor of m.
449 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
450 -- >>> minor m 0 0 :: Mat2 Int
452 -- >>> minor m 1 1 :: Mat2 Int
463 minor (Mat rows) i j = m
465 rows' = delete rows i
466 m = Mat $ V.map ((flip delete) j) rows'
469 class (Eq a, Ring.C a) => Determined p a where
470 determinant :: (p a) -> a
472 instance (Eq a, Ring.C a) => Determined (Mat (S Z) (S Z)) a where
473 determinant (Mat rows) = (V.head . V.head) rows
479 Determined (Mat (S n) (S n)) a)
480 => Determined (Mat (S (S n)) (S (S n))) a where
481 -- | The recursive definition with a special-case for triangular matrices.
485 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
490 | is_triangular m = product [ m !!! (i,i) | i <- [0..(nrows m)-1] ]
491 | otherwise = determinant_recursive
495 det_minor i j = determinant (minor m i j)
497 determinant_recursive =
498 sum [ (-1)^(toInteger j) NP.* (m' 0 j) NP.* (det_minor 0 j)
499 | j <- [0..(ncols m)-1] ]
503 -- | Matrix multiplication.
507 -- >>> let m1 = fromList [[1,2,3], [4,5,6]] :: Mat N2 N3 Int
508 -- >>> let m2 = fromList [[1,2],[3,4],[5,6]] :: Mat N3 N2 Int
513 (*) :: (Ring.C a, Arity m, Arity n, Arity p)
517 (*) m1 m2 = construct lambda
520 sum [(m1 !!! (i,k)) NP.* (m2 !!! (k,j)) | k <- [0..(ncols m1)-1] ]
524 instance (Ring.C a, Arity m, Arity n) => Additive.C (Mat m n a) where
526 (Mat rows1) + (Mat rows2) =
527 Mat $ V.zipWith (V.zipWith (+)) rows1 rows2
529 (Mat rows1) - (Mat rows2) =
530 Mat $ V.zipWith (V.zipWith (-)) rows1 rows2
532 zero = Mat (V.replicate $ V.replicate (fromInteger 0))
535 instance (Ring.C a, Arity m, Arity n, m ~ n) => Ring.C (Mat m n a) where
536 -- The first * is ring multiplication, the second is matrix
541 instance (Ring.C a, Arity m, Arity n) => Module.C a (Mat m n a) where
542 -- We can multiply a matrix by a scalar of the same type as its
544 x *> (Mat rows) = Mat $ V.map (V.map (NP.* x)) rows
547 instance (Algebraic.C a,
550 => Normed (Mat (S m) N1 a) where
551 -- | Generic p-norms for vectors in R^n that are represented as nx1
556 -- >>> let v1 = vec2d (3,4)
562 norm_p p (Mat rows) =
563 (root p') $ sum [fromRational' (toRational x)^p' | x <- xs]
566 xs = concat $ V.toList $ V.map V.toList rows
568 -- | The infinity norm.
572 -- >>> let v1 = vec3d (1,5,2)
576 norm_infty (Mat rows) =
577 fromRational' $ toRational $ V.maximum $ V.map V.maximum rows
580 -- | Compute the Frobenius norm of a matrix. This essentially treats
581 -- the matrix as one long vector containing all of its entries (in
582 -- any order, it doesn't matter).
586 -- >>> let m = fromList [[1, 2, 3],[4,5,6],[7,8,9]] :: Mat3 Double
587 -- >>> frobenius_norm m == sqrt 285
590 -- >>> let m = fromList [[1, -1, 1],[-1,1,-1],[1,-1,1]] :: Mat3 Double
591 -- >>> frobenius_norm m == 3
594 frobenius_norm :: (Algebraic.C a, Ring.C a) => Mat m n a -> a
595 frobenius_norm (Mat rows) =
596 sqrt $ element_sum $ V.map row_sum rows
598 -- | Square and add up the entries of a row.
599 row_sum = element_sum . V.map (^2)
602 -- Vector helpers. We want it to be easy to create low-dimension
603 -- column vectors, which are nx1 matrices.
605 -- | Convenient constructor for 2D vectors.
609 -- >>> import Roots.Simple
610 -- >>> let fst m = m !!! (0,0)
611 -- >>> let snd m = m !!! (1,0)
612 -- >>> let h = 0.5 :: Double
613 -- >>> let g1 m = 1.0 + h NP.* exp(-((fst m)^2))/(1.0 + (snd m)^2)
614 -- >>> let g2 m = 0.5 + h NP.* atan((fst m)^2 + (snd m)^2)
615 -- >>> let g u = vec2d ((g1 u), (g2 u))
616 -- >>> let u0 = vec2d (1.0, 1.0)
617 -- >>> let eps = 1/(10^9)
618 -- >>> fixed_point g eps u0
619 -- ((1.0728549599342185),(1.0820591495686167))
621 vec1d :: (a) -> Col1 a
622 vec1d (x) = Mat (mk1 (mk1 x))
624 vec2d :: (a,a) -> Col2 a
625 vec2d (x,y) = Mat (mk2 (mk1 x) (mk1 y))
627 vec3d :: (a,a,a) -> Col3 a
628 vec3d (x,y,z) = Mat (mk3 (mk1 x) (mk1 y) (mk1 z))
630 vec4d :: (a,a,a,a) -> Col4 a
631 vec4d (w,x,y,z) = Mat (mk4 (mk1 w) (mk1 x) (mk1 y) (mk1 z))
633 vec5d :: (a,a,a,a,a) -> Col5 a
634 vec5d (v,w,x,y,z) = Mat (mk5 (mk1 v) (mk1 w) (mk1 x) (mk1 y) (mk1 z))
636 -- Since we commandeered multiplication, we need to create 1x1
637 -- matrices in order to multiply things.
638 scalar :: a -> Mat1 a
639 scalar x = Mat (mk1 (mk1 x))
641 dot :: (RealRing.C a, n ~ N1, m ~ S t, Arity t)
645 v1 `dot` v2 = ((transpose v1) * v2) !!! (0, 0)
648 -- | The angle between @v1@ and @v2@ in Euclidean space.
652 -- >>> let v1 = vec2d (1.0, 0.0)
653 -- >>> let v2 = vec2d (0.0, 1.0)
654 -- >>> angle v1 v2 == pi/2.0
657 angle :: (Transcendental.C a,
669 theta = (recip norms) NP.* (v1 `dot` v2)
670 norms = (norm v1) NP.* (norm v2)
673 -- | Retrieve the diagonal elements of the given matrix as a \"column
674 -- vector,\" i.e. a m-by-1 matrix. We require the matrix to be
675 -- square to avoid ambiguity in the return type which would ideally
676 -- have dimension min(m,n) supposing an m-by-n matrix.
680 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
684 diagonal :: (Arity m) => Mat m m a -> Col m a
688 lambda i _ = matrix !!! (i,i)
691 -- | Given a square @matrix@, return a new matrix of the same size
692 -- containing only the on-diagonal entries of @matrix@. The
693 -- off-diagonal entries are set to zero.
697 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
698 -- >>> diagonal_part m
699 -- ((1,0,0),(0,5,0),(0,0,9))
701 diagonal_part :: (Arity m, Ring.C a)
704 diagonal_part matrix =
707 lambda i j = if i == j then matrix !!! (i,j) else 0
710 -- | Given a square @matrix@, return a new matrix of the same size
711 -- containing only the on-diagonal and below-diagonal entries of
712 -- @matrix@. The above-diagonal entries are set to zero.
716 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
718 -- ((1,0,0),(4,5,0),(7,8,9))
720 lt_part :: (Arity m, Ring.C a)
726 lambda i j = if i >= j then matrix !!! (i,j) else 0
729 -- | Given a square @matrix@, return a new matrix of the same size
730 -- containing only the below-diagonal entries of @matrix@. The on-
731 -- and above-diagonal entries are set to zero.
735 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
736 -- >>> lt_part_strict m
737 -- ((0,0,0),(4,0,0),(7,8,0))
739 lt_part_strict :: (Arity m, Ring.C a)
742 lt_part_strict matrix =
745 lambda i j = if i > j then matrix !!! (i,j) else 0
748 -- | Given a square @matrix@, return a new matrix of the same size
749 -- containing only the on-diagonal and above-diagonal entries of
750 -- @matrix@. The below-diagonal entries are set to zero.
754 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
756 -- ((1,2,3),(0,5,6),(0,0,9))
758 ut_part :: (Arity m, Ring.C a)
761 ut_part = transpose . lt_part . transpose
764 -- | Given a square @matrix@, return a new matrix of the same size
765 -- containing only the above-diagonal entries of @matrix@. The on-
766 -- and below-diagonal entries are set to zero.
770 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
771 -- >>> ut_part_strict m
772 -- ((0,2,3),(0,0,6),(0,0,0))
774 ut_part_strict :: (Arity m, Ring.C a)
777 ut_part_strict = transpose . lt_part_strict . transpose
780 -- | Compute the trace of a square matrix, the sum of the elements
781 -- which lie on its diagonal. We require the matrix to be
782 -- square to avoid ambiguity in the return type which would ideally
783 -- have dimension min(m,n) supposing an m-by-n matrix.
787 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
791 trace :: (Arity m, Ring.C a) => Mat m m a -> a
793 let (Mat rows) = diagonal matrix
795 element_sum $ V.map V.head rows
798 -- | Zip together two column matrices.
802 -- >>> let m1 = fromList [[1],[1],[1]] :: Col3 Int
803 -- >>> let m2 = fromList [[1],[2],[3]] :: Col3 Int
805 -- (((1,1)),((1,2)),((1,3)))
807 colzip :: Arity m => Col m a -> Col m a -> Col m (a,a)
811 lambda i j = (c1 !!! (i,j), c2 !!! (i,j))
814 -- | Zip together two column matrices using the supplied function.
818 -- >>> let c1 = fromList [[1],[2],[3]] :: Col3 Integer
819 -- >>> let c2 = fromList [[4],[5],[6]] :: Col3 Integer
820 -- >>> colzipwith (^) c1 c2
823 colzipwith :: Arity m
831 lambda i j = f (c1 !!! (i,j)) (c2 !!! (i,j))
834 -- | Map a function over a matrix of any dimensions.
838 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
842 map2 :: (a -> b) -> Mat m n a -> Mat m n b
849 -- | Fold over the entire matrix passing the coordinates @i@ and @j@
850 -- (of the row/column) to the accumulation function.
854 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
855 -- >>> ifoldl2 (\i j cur _ -> cur + i + j) 0 m
858 ifoldl2 :: forall a b m n.
859 (Int -> Int -> b -> a -> b)
863 ifoldl2 f initial (Mat rows) =
864 V.ifoldl row_function initial rows
866 -- | The order that we need this in (so that @g idx@ makes sense)
867 -- is a little funny. So that we don't need to pass weird
868 -- functions into ifoldl2, we swap the second and third
869 -- arguments of @f@ calling the result @g@.
870 g :: Int -> b -> Int -> a -> b
873 row_function :: b -> Int -> Vec n a -> b
874 row_function rowinit idx r = V.ifoldl (g idx) rowinit r
877 -- | Map a function over a matrix of any dimensions, passing the
878 -- coordinates @i@ and @j@ to the function @f@.
882 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
883 -- >>> imap2 (\i j _ -> i+j) m
886 imap2 :: (Int -> Int -> a -> b) -> Mat m n a -> Mat m n b