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 (
35 import qualified Data.Vector.Fixed as V (
48 import Data.Vector.Fixed.Cont ( Arity, arity )
49 import Linear.Vector ( Vec, delete, element_sum )
50 import Normed ( Normed(..) )
52 import NumericPrelude hiding ( (*), abs )
53 import qualified NumericPrelude as NP ( (*) )
54 import qualified Algebra.Absolute as Absolute ( C )
55 import Algebra.Absolute ( abs )
56 import qualified Algebra.Additive as Additive ( C )
57 import qualified Algebra.Algebraic as Algebraic ( C )
58 import Algebra.Algebraic ( root )
59 import qualified Algebra.Field as Field ( C )
60 import qualified Algebra.Ring as Ring ( C )
61 import qualified Algebra.Module as Module ( C )
62 import qualified Algebra.RealRing as RealRing ( C )
63 import qualified Algebra.ToRational as ToRational ( C )
64 import qualified Algebra.Transcendental as Transcendental ( C )
65 import qualified Prelude as P ( map )
67 -- | Our main matrix type.
68 data Mat m n a = (Arity m, Arity n) => Mat (Vec m (Vec n a))
70 -- Type synonyms for n-by-n matrices.
71 type Mat1 a = Mat N1 N1 a
72 type Mat2 a = Mat N2 N2 a
73 type Mat3 a = Mat N3 N3 a
74 type Mat4 a = Mat N4 N4 a
75 type Mat5 a = Mat N5 N5 a
77 -- * Type synonyms for 1-by-n row "vectors".
79 -- | Type synonym for row vectors expressed as 1-by-n matrices.
80 type Row n a = Mat N1 n a
82 type Row1 a = Row N1 a
83 type Row2 a = Row N2 a
84 type Row3 a = Row N3 a
85 type Row4 a = Row N4 a
86 type Row5 a = Row N5 a
88 -- * Type synonyms for n-by-1 column "vectors".
90 -- | Type synonym for column vectors expressed as n-by-1 matrices.
91 type Col n a = Mat n N1 a
93 type Col1 a = Col N1 a
94 type Col2 a = Col N2 a
95 type Col3 a = Col N3 a
96 type Col4 a = Col N4 a
97 type Col5 a = Col N5 a
99 -- We need a big column for Gaussian quadrature.
100 type N10 = S (S (S (S (S N5))))
101 type Col10 a = Col N10 a
104 instance (Eq a) => Eq (Mat m n a) where
105 -- | Compare a row at a time.
109 -- >>> let m1 = fromList [[1,2],[3,4]] :: Mat2 Int
110 -- >>> let m2 = fromList [[1,2],[3,4]] :: Mat2 Int
111 -- >>> let m3 = fromList [[5,6],[7,8]] :: Mat2 Int
117 (Mat rows1) == (Mat rows2) =
118 V.and $ V.zipWith comp rows1 rows2
120 -- Compare a row, one column at a time.
121 comp row1 row2 = V.and (V.zipWith (==) row1 row2)
124 instance (Show a) => Show (Mat m n a) where
125 -- | Display matrices and vectors as ordinary tuples. This is poor
126 -- practice, but these results are primarily displayed
127 -- interactively and convenience trumps correctness (said the guy
128 -- who insists his vector lengths be statically checked at
133 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
138 "(" ++ (intercalate "," (V.toList row_strings)) ++ ")"
140 row_strings = V.map show_vector rows
142 "(" ++ (intercalate "," element_strings) ++ ")"
145 element_strings = P.map show v1l
148 -- | Convert a matrix to a nested list.
149 toList :: Mat m n a -> [[a]]
150 toList (Mat rows) = map V.toList (V.toList rows)
153 -- | Create a matrix from a nested list.
154 fromList :: (Arity m, Arity n) => [[a]] -> Mat m n a
155 fromList vs = Mat (V.fromList $ map V.fromList vs)
158 -- | Unsafe indexing. Much faster than the safe indexing.
159 (!!!) :: (Arity m, Arity n) => Mat m n a -> (Int, Int) -> a
160 (!!!) (Mat rows) (i, j) = (rows ! i) ! j
167 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
195 (!!?) :: (Arity m, Arity n) => Mat m n a -> (Int, Int) -> Maybe a
197 ifoldl2 f Nothing matrix
199 f k l found cur = if (k,l) == idx then (Just cur) else found
202 -- | The number of rows in the matrix.
203 nrows :: forall m n a. (Arity m) => Mat m n a -> Int
204 nrows _ = arity (undefined :: m)
207 -- | The number of columns in the first row of the
208 -- matrix. Implementation stolen from Data.Vector.Fixed.length.
209 ncols :: forall m n a. (Arity n) => Mat m n a -> Int
210 ncols _ = arity (undefined :: n)
213 -- | Return the @i@th row of @m@ as a matrix. Unsafe.
214 row :: (Arity m, Arity n) => Mat m n a -> Int -> Row n a
218 lambda _ j = m !!! (i, j)
221 -- | Return the @j@th column of @m@ as a matrix. Unsafe.
222 column :: (Arity m, Arity n) => Mat m n a -> Int -> Col m a
226 lambda i _ = m !!! (i, j)
229 -- | Transpose @m@; switch it's columns and its rows. This is a dirty
230 -- implementation, but I don't see a better way.
232 -- TODO: Don't cheat with fromList.
236 -- >>> let m = fromList [[1,2], [3,4]] :: Mat2 Int
240 transpose :: (Arity m, Arity n) => Mat m n a -> Mat n m a
244 lambda i j = matrix !!! (j,i)
247 -- | Is @m@ symmetric?
251 -- >>> let m1 = fromList [[1,2], [2,1]] :: Mat2 Int
255 -- >>> let m2 = fromList [[1,2], [3,1]] :: Mat2 Int
259 symmetric :: (Eq a, Arity m) => Mat m m a -> Bool
264 -- | Construct a new matrix from a function @lambda@. The function
265 -- @lambda@ should take two parameters i,j corresponding to the
266 -- entries in the matrix. The i,j entry of the resulting matrix will
267 -- have the value returned by lambda i j.
271 -- >>> let lambda i j = i + j
272 -- >>> construct lambda :: Mat3 Int
273 -- ((0,1,2),(1,2,3),(2,3,4))
275 construct :: forall m n a. (Arity m, Arity n)
276 => (Int -> Int -> a) -> Mat m n a
277 construct lambda = Mat $ generate make_row
279 make_row :: Int -> Vec n a
280 make_row i = generate (lambda i)
283 -- | Create an identity matrix with the right dimensions.
287 -- >>> identity_matrix :: Mat3 Int
288 -- ((1,0,0),(0,1,0),(0,0,1))
289 -- >>> identity_matrix :: Mat3 Double
290 -- ((1.0,0.0,0.0),(0.0,1.0,0.0),(0.0,0.0,1.0))
292 identity_matrix :: (Arity m, Ring.C a) => Mat m m a
294 construct (\i j -> if i == j then (fromInteger 1) else (fromInteger 0))
297 -- | Given a positive-definite matrix @m@, computes the
298 -- upper-triangular matrix @r@ with (transpose r)*r == m and all
299 -- values on the diagonal of @r@ positive.
303 -- >>> let m1 = fromList [[20,-1], [-1,20]] :: Mat2 Double
304 -- >>> let r = cholesky m1
305 -- >>> frobenius_norm ((transpose r)*r - m1) < 1e-10
307 -- >>> is_upper_triangular r
310 -- >>> import Naturals ( N7 )
311 -- >>> let k1 = [6, -3, 0, 0, 0, 0, 0] :: [Double]
312 -- >>> let k2 = [-3, 10.5, -7.5, 0, 0, 0, 0] :: [Double]
313 -- >>> let k3 = [0, -7.5, 12.5, 0, 0, 0, 0] :: [Double]
314 -- >>> let k4 = [0, 0, 0, 6, 0, 0, 0] :: [Double]
315 -- >>> let k5 = [0, 0, 0, 0, 6, 0, 0] :: [Double]
316 -- >>> let k6 = [0, 0, 0, 0, 0, 6, 0] :: [Double]
317 -- >>> let k7 = [0, 0, 0, 0, 0, 0, 15] :: [Double]
318 -- >>> let big_K = fromList [k1,k2,k3,k4,k5,k6,k7] :: Mat N7 N7 Double
320 -- >>> let e1 = [2.449489742783178,0,0,0,0,0,0] :: [Double]
321 -- >>> let e2 = [-1.224744871391589,3,0,0,0,0,0] :: [Double]
322 -- >>> let e3 = [0,-5/2,5/2,0,0,0,0] :: [Double]
323 -- >>> let e4 = [0,0,0,2.449489742783178,0,0,0] :: [Double]
324 -- >>> let e5 = [0,0,0,0,2.449489742783178,0,0] :: [Double]
325 -- >>> let e6 = [0,0,0,0,0,2.449489742783178,0] :: [Double]
326 -- >>> let e7 = [0,0,0,0,0,0,3.872983346207417] :: [Double]
327 -- >>> let expected = fromList [e1,e2,e3,e4,e5,e6,e7] :: Mat N7 N7 Double
329 -- >>> let r = cholesky big_K
330 -- >>> frobenius_norm (r - (transpose expected)) < 1e-12
333 cholesky :: forall m n a. (Algebraic.C a, Arity m, Arity n)
334 => (Mat m n a) -> (Mat m n a)
335 cholesky m = construct r
338 r i j | i == j = sqrt(m !!! (i,j) - sum [(r k i)^2 | k <- [0..i-1]])
340 (((m !!! (i,j)) - sum [(r k i) NP.* (r k j) | k <- [0..i-1]]))/(r i i)
344 -- | Returns True if the given matrix is upper-triangular, and False
345 -- otherwise. The parameter @epsilon@ lets the caller choose a
350 -- >>> let m = fromList [[1,1],[1e-12,1]] :: Mat2 Double
351 -- >>> is_upper_triangular m
353 -- >>> is_upper_triangular' 1e-10 m
356 is_upper_triangular' :: forall m n a.
357 (Ord a, Ring.C a, Absolute.C a, Arity m, Arity n)
358 => a -- ^ The tolerance @epsilon@.
361 is_upper_triangular' epsilon matrix =
362 ifoldl2 f True matrix
364 f :: Int -> Int -> Bool -> a -> Bool
365 f _ _ False _ = False
368 -- use "less than or equal to" so zero is a valid epsilon
369 | otherwise = abs x <= epsilon
372 -- | Returns True if the given matrix is upper-triangular, and False
373 -- otherwise. We don't delegate to the general
374 -- 'is_upper_triangular'' here because it imposes additional
375 -- typeclass constraints throughout the library.
379 -- >>> let m = fromList [[1,0],[1,1]] :: Mat2 Int
380 -- >>> is_upper_triangular m
383 -- >>> let m = fromList [[1,2],[0,3]] :: Mat2 Int
384 -- >>> is_upper_triangular m
387 is_upper_triangular :: forall m n a.
388 (Eq a, Ring.C a, Arity m, Arity n)
390 is_upper_triangular matrix =
391 ifoldl2 f True matrix
393 f :: Int -> Int -> Bool -> a -> Bool
394 f _ _ False _ = False
401 -- | Returns True if the given matrix is lower-triangular, and False
406 -- >>> let m = fromList [[1,0],[1,1]] :: Mat2 Int
407 -- >>> is_lower_triangular m
410 -- >>> let m = fromList [[1,2],[0,3]] :: Mat2 Int
411 -- >>> is_lower_triangular m
414 is_lower_triangular :: (Eq a,
420 is_lower_triangular = is_upper_triangular . transpose
423 -- | Returns True if the given matrix is lower-triangular, and False
424 -- otherwise. The parameter @epsilon@ lets the caller choose a
429 -- >>> let m = fromList [[1,1e-12],[1,1]] :: Mat2 Double
430 -- >>> is_lower_triangular m
432 -- >>> is_lower_triangular' 1e-12 m
435 is_lower_triangular' :: (Ord a,
440 => a -- ^ The tolerance @epsilon@.
443 is_lower_triangular' epsilon = (is_upper_triangular' epsilon) . transpose
446 -- | Returns True if the given matrix is triangular, and False
451 -- >>> let m = fromList [[1,0],[1,1]] :: Mat2 Int
452 -- >>> is_triangular m
455 -- >>> let m = fromList [[1,2],[0,3]] :: Mat2 Int
456 -- >>> is_triangular m
459 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
460 -- >>> is_triangular m
463 is_triangular :: (Ord a,
470 is_triangular m = is_upper_triangular m || is_lower_triangular m
473 -- | Delete the @i@th row and @j@th column from the matrix. The name
474 -- \"preminor\" is made up, but is meant to signify that this is
475 -- usually used in the computationof a minor. A minor is simply the
476 -- determinant of a preminor in that case.
480 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
481 -- >>> preminor m 0 0 :: Mat2 Int
483 -- >>> preminor m 1 1 :: Mat2 Int
486 preminor :: (Arity m, Arity n)
491 preminor (Mat rows) i j = m
493 rows' = delete rows i
494 m = Mat $ V.map ((flip delete) j) rows'
497 -- | Compute the i,jth minor of a @matrix@.
501 -- >>> let m1 = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Double
505 minor :: (Arity m, Determined (Mat m m) a)
510 minor matrix i j = determinant (preminor matrix i j)
512 class (Eq a, Ring.C a) => Determined p a where
513 determinant :: (p a) -> a
515 instance (Eq a, Ring.C a) => Determined (Mat (S Z) (S Z)) a where
516 determinant = unscalar
522 Determined (Mat (S n) (S n)) a)
523 => Determined (Mat (S (S n)) (S (S n))) a where
524 -- | The recursive definition with a special-case for triangular matrices.
528 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
533 | is_triangular m = product [ m !!! (i,i) | i <- [0..(nrows m)-1] ]
534 | otherwise = determinant_recursive
538 determinant_recursive =
539 sum [ (-1)^(toInteger j) NP.* (m' 0 j) NP.* (minor m 0 j)
540 | j <- [0..(ncols m)-1] ]
544 -- | Matrix multiplication.
548 -- >>> let m1 = fromList [[1,2,3], [4,5,6]] :: Mat N2 N3 Int
549 -- >>> let m2 = fromList [[1,2],[3,4],[5,6]] :: Mat N3 N2 Int
554 (*) :: (Ring.C a, Arity m, Arity n, Arity p)
558 (*) m1 m2 = construct lambda
561 sum [(m1 !!! (i,k)) NP.* (m2 !!! (k,j)) | k <- [0..(ncols m1)-1] ]
565 instance (Ring.C a, Arity m, Arity n) => Additive.C (Mat m n a) where
567 (Mat rows1) + (Mat rows2) =
568 Mat $ V.zipWith (V.zipWith (+)) rows1 rows2
570 (Mat rows1) - (Mat rows2) =
571 Mat $ V.zipWith (V.zipWith (-)) rows1 rows2
573 zero = Mat (V.replicate $ V.replicate (fromInteger 0))
576 instance (Ring.C a, Arity m, Arity n, m ~ n) => Ring.C (Mat m n a) where
577 -- The first * is ring multiplication, the second is matrix
582 instance (Ring.C a, Arity m, Arity n) => Module.C a (Mat m n a) where
583 -- We can multiply a matrix by a scalar of the same type as its
585 x *> (Mat rows) = Mat $ V.map (V.map (NP.* x)) rows
588 instance (Algebraic.C a,
591 => Normed (Mat (S m) N1 a) where
592 -- | Generic p-norms for vectors in R^n that are represented as nx1
597 -- >>> let v1 = vec2d (3,4)
603 norm_p p (Mat rows) =
604 (root p') $ sum [fromRational' (toRational x)^p' | x <- xs]
607 xs = concat $ V.toList $ V.map V.toList rows
609 -- | The infinity norm.
613 -- >>> let v1 = vec3d (1,5,2)
617 norm_infty (Mat rows) =
618 fromRational' $ toRational $ V.maximum $ V.map V.maximum rows
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).
627 -- >>> let m = fromList [[1, 2, 3],[4,5,6],[7,8,9]] :: Mat3 Double
628 -- >>> frobenius_norm m == sqrt 285
631 -- >>> let m = fromList [[1, -1, 1],[-1,1,-1],[1,-1,1]] :: Mat3 Double
632 -- >>> frobenius_norm m == 3
635 frobenius_norm :: (Algebraic.C a, Ring.C a) => Mat m n a -> a
636 frobenius_norm (Mat rows) =
637 sqrt $ element_sum $ V.map row_sum rows
639 -- | Square and add up the entries of a row.
640 row_sum = element_sum . V.map (^2)
643 -- Vector helpers. We want it to be easy to create low-dimension
644 -- column vectors, which are nx1 matrices.
646 -- | Convenient constructor for 2D vectors.
650 -- >>> import Roots.Simple
651 -- >>> let fst m = m !!! (0,0)
652 -- >>> let snd m = m !!! (1,0)
653 -- >>> let h = 0.5 :: Double
654 -- >>> let g1 m = 1.0 + h NP.* exp(-((fst m)^2))/(1.0 + (snd m)^2)
655 -- >>> let g2 m = 0.5 + h NP.* atan((fst m)^2 + (snd m)^2)
656 -- >>> let g u = vec2d ((g1 u), (g2 u))
657 -- >>> let u0 = vec2d (1.0, 1.0)
658 -- >>> let eps = 1/(10^9)
659 -- >>> fixed_point g eps u0
660 -- ((1.0728549599342185),(1.0820591495686167))
662 vec1d :: (a) -> Col1 a
663 vec1d (x) = Mat (mk1 (mk1 x))
665 vec2d :: (a,a) -> Col2 a
666 vec2d (x,y) = Mat (mk2 (mk1 x) (mk1 y))
668 vec3d :: (a,a,a) -> Col3 a
669 vec3d (x,y,z) = Mat (mk3 (mk1 x) (mk1 y) (mk1 z))
671 vec4d :: (a,a,a,a) -> Col4 a
672 vec4d (w,x,y,z) = Mat (mk4 (mk1 w) (mk1 x) (mk1 y) (mk1 z))
674 vec5d :: (a,a,a,a,a) -> Col5 a
675 vec5d (v,w,x,y,z) = Mat (mk5 (mk1 v) (mk1 w) (mk1 x) (mk1 y) (mk1 z))
677 -- Since we commandeered multiplication, we need to create 1x1
678 -- matrices in order to multiply things.
679 scalar :: a -> Mat1 a
680 scalar x = Mat (mk1 (mk1 x))
682 -- Get the scalar value out of a 1x1 matrix.
683 unscalar :: Mat1 a -> a
684 unscalar (Mat rows) = V.head $ V.head rows
687 dot :: (Ring.C a, Arity m)
691 v1 `dot` v2 = unscalar $ ((transpose v1) * v2)
694 -- | The angle between @v1@ and @v2@ in Euclidean space.
698 -- >>> let v1 = vec2d (1.0, 0.0)
699 -- >>> let v2 = vec2d (0.0, 1.0)
700 -- >>> angle v1 v2 == pi/2.0
703 angle :: (Transcendental.C a,
714 theta = (recip norms) NP.* (v1 `dot` v2)
715 norms = (norm v1) NP.* (norm v2)
718 -- | Retrieve the diagonal elements of the given matrix as a \"column
719 -- vector,\" i.e. a m-by-1 matrix. We require the matrix to be
720 -- square to avoid ambiguity in the return type which would ideally
721 -- have dimension min(m,n) supposing an m-by-n matrix.
725 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
729 diagonal :: (Arity m) => Mat m m a -> Col m a
733 lambda i _ = matrix !!! (i,i)
736 -- | Given a square @matrix@, return a new matrix of the same size
737 -- containing only the on-diagonal entries of @matrix@. The
738 -- off-diagonal entries are set to zero.
742 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
743 -- >>> diagonal_part m
744 -- ((1,0,0),(0,5,0),(0,0,9))
746 diagonal_part :: (Arity m, Ring.C a)
749 diagonal_part matrix =
752 lambda i j = if i == j then matrix !!! (i,j) else 0
755 -- | Given a square @matrix@, return a new matrix of the same size
756 -- containing only the on-diagonal and below-diagonal entries of
757 -- @matrix@. The above-diagonal entries are set to zero.
761 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
763 -- ((1,0,0),(4,5,0),(7,8,9))
765 lt_part :: (Arity m, Ring.C a)
771 lambda i j = if i >= j then matrix !!! (i,j) else 0
774 -- | Given a square @matrix@, return a new matrix of the same size
775 -- containing only the below-diagonal entries of @matrix@. The on-
776 -- and above-diagonal entries are set to zero.
780 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
781 -- >>> lt_part_strict m
782 -- ((0,0,0),(4,0,0),(7,8,0))
784 lt_part_strict :: (Arity m, Ring.C a)
787 lt_part_strict matrix =
790 lambda i j = if i > j then matrix !!! (i,j) else 0
793 -- | Given a square @matrix@, return a new matrix of the same size
794 -- containing only the on-diagonal and above-diagonal entries of
795 -- @matrix@. The below-diagonal entries are set to zero.
799 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
801 -- ((1,2,3),(0,5,6),(0,0,9))
803 ut_part :: (Arity m, Ring.C a)
806 ut_part = transpose . lt_part . transpose
809 -- | Given a square @matrix@, return a new matrix of the same size
810 -- containing only the above-diagonal entries of @matrix@. The on-
811 -- and below-diagonal entries are set to zero.
815 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
816 -- >>> ut_part_strict m
817 -- ((0,2,3),(0,0,6),(0,0,0))
819 ut_part_strict :: (Arity m, Ring.C a)
822 ut_part_strict = transpose . lt_part_strict . transpose
825 -- | Compute the trace of a square matrix, the sum of the elements
826 -- which lie on its diagonal. We require the matrix to be
827 -- square to avoid ambiguity in the return type which would ideally
828 -- have dimension min(m,n) supposing an m-by-n matrix.
832 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
836 trace :: (Arity m, Ring.C a) => Mat m m a -> a
838 let (Mat rows) = diagonal matrix
840 element_sum $ V.map V.head rows
843 -- | Zip together two matrices.
845 -- TODO: don't cheat with construct (map V.zips instead).
849 -- >>> let m1 = fromList [[1],[1],[1]] :: Col3 Int
850 -- >>> let m2 = fromList [[1],[2],[3]] :: Col3 Int
852 -- (((1,1)),((1,2)),((1,3)))
854 -- >>> let m1 = fromList [[1,2],[3,4]] :: Mat2 Int
855 -- >>> let m2 = fromList [[1,1],[1,1]] :: Mat2 Int
857 -- (((1,1),(2,1)),((3,1),(4,1)))
859 zip2 :: (Arity m, Arity n) => Mat m n a -> Mat m n a -> Mat m n (a,a)
863 lambda i j = (m1 !!! (i,j), m2 !!! (i,j))
866 -- | Zip together three matrices.
868 -- TODO: don't cheat with construct (map V.zips instead).
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)))
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)))
884 zip2three :: (Arity m, Arity n)
892 lambda i j = (m1 !!! (i,j), m2 !!! (i,j), m3 !!! (i,j))
895 -- | Zip together two matrices using the supplied function.
899 -- >>> let c1 = fromList [[1],[2],[3]] :: Col3 Integer
900 -- >>> let c2 = fromList [[4],[5],[6]] :: Col3 Integer
901 -- >>> zipwith2 (^) c1 c2
912 lambda i j = f (c1 !!! (i,j)) (c2 !!! (i,j))
915 -- | Map a function over a matrix of any dimensions.
919 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
923 map2 :: (a -> b) -> Mat m n a -> Mat m n b
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.
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
940 ifoldl2 :: forall a b m n.
941 (Int -> Int -> b -> a -> b)
945 ifoldl2 f initial (Mat rows) =
946 V.ifoldl row_function initial rows
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
955 row_function :: b -> Int -> Vec n a -> b
956 row_function rowinit idx r = V.ifoldl (g idx) rowinit r
959 -- | Fold over the entire matrix passing the coordinates @i@ and @j@
960 -- (of the row/column) to the accumulation function. The fold occurs
961 -- from bottom-right to top-left.
963 -- The order of the arguments in the supplied function are different
964 -- from those in V.ifoldr; we keep them similar to ifoldl2.
968 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
969 -- >>> ifoldr2 (\i j cur _ -> cur + i + j) 0 m
972 ifoldr2 :: forall a b m n.
973 (Int -> Int -> b -> a -> b)
977 ifoldr2 f initial (Mat rows) =
978 V.ifoldr row_function initial rows
980 -- | Swap the order of arguments in @f@ so that it agrees with the
981 -- @f@ passed to ifoldl2.
982 g :: Int -> Int -> a -> b -> b
983 g w x y z = f w x z y
985 row_function :: Int -> Vec n a -> b -> b
986 row_function idx r rowinit = V.ifoldr (g idx) rowinit r
989 -- | Map a function over a matrix of any dimensions, passing the
990 -- coordinates @i@ and @j@ to the function @f@.
994 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
995 -- >>> imap2 (\i j _ -> i+j) m
998 imap2 :: (Int -> Int -> a -> b) -> Mat m n a -> Mat m n b
1005 -- | Reverse the order of elements in a matrix.
1009 -- >>> let m1 = fromList [[1,2,3]] :: Row3 Int
1013 -- >>> let m1 = vec3d (1,2,3 :: Int)
1017 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
1019 -- ((9,8,7),(6,5,4),(3,2,1))
1021 reverse2 :: (Arity m, Arity n) => Mat m n a -> Mat m n a
1022 reverse2 (Mat rows) = Mat $ V.reverse $ V.map V.reverse rows
1025 -- | Unsafely set the (i,j) element of the given matrix.
1029 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
1030 -- >>> set_idx m (1,1) 17
1031 -- ((1,2,3),(4,17,6),(7,8,9))
1033 set_idx :: forall m n a.
1039 set_idx matrix (i,j) newval =
1040 imap2 updater matrix
1042 updater :: Int -> Int -> a -> a
1043 updater k l existing =
1049 -- | Compute the i,jth cofactor of the given @matrix@. This simply
1050 -- premultiplues the i,jth minor by (-1)^(i+j).
1051 cofactor :: (Arity m, Determined (Mat m m) a)
1052 => Mat (S m) (S m) a
1056 cofactor matrix i j =
1057 (-1)^(toInteger i + toInteger j) NP.* (minor matrix i j)
1060 -- | Compute the inverse of a matrix using cofactor expansion
1061 -- (generalized Cramer's rule).
1065 -- >>> let m1 = fromList [[37,22],[17,54]] :: Mat2 Double
1066 -- >>> let e1 = [54/1624, -22/1624] :: [Double]
1067 -- >>> let e2 = [-17/1624, 37/1624] :: [Double]
1068 -- >>> let expected = fromList [e1, e2] :: Mat2 Double
1069 -- >>> let actual = inverse m1
1070 -- >>> frobenius_norm (actual - expected) < 1e-12
1073 inverse :: (Arity m,
1074 Determined (Mat (S m) (S m)) a,
1075 Determined (Mat m m) a,
1077 => Mat (S m) (S m) a
1078 -> Mat (S m) (S m) a
1080 (1 / (determinant matrix)) *> (transpose $ construct lambda)
1082 lambda i j = cofactor matrix i j