]> gitweb.michael.orlitzky.com - numerical-analysis.git/blob - src/Linear/Matrix.hs
Add reverse2 to Linear.Matrix.
[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 N1,
23 N2,
24 N3,
25 N4,
26 N5,
27 S,
28 Z,
29 generate,
30 mk1,
31 mk2,
32 mk3,
33 mk4,
34 mk5 )
35 import qualified Data.Vector.Fixed as V (
36 and,
37 fromList,
38 head,
39 ifoldl,
40 imap,
41 map,
42 maximum,
43 replicate,
44 reverse,
45 toList,
46 zipWith )
47 import Data.Vector.Fixed.Cont ( Arity, arity )
48 import Linear.Vector ( Vec, delete, element_sum )
49 import Normed ( Normed(..) )
50
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 )
64
65 -- | Our main matrix type.
66 data Mat m n a = (Arity m, Arity n) => Mat (Vec m (Vec n a))
67
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
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 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
84
85 -- | Type synonym for column vectors expressed as n-by-1 matrices.
86 type Col n a = Mat n N1 a
87
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
94
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
98
99
100 instance (Eq a) => Eq (Mat m n a) where
101 -- | Compare a row at a time.
102 --
103 -- Examples:
104 --
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
108 -- >>> m1 == m2
109 -- True
110 -- >>> m1 == m3
111 -- False
112 --
113 (Mat rows1) == (Mat rows2) =
114 V.and $ V.zipWith comp rows1 rows2
115 where
116 -- Compare a row, one column at a time.
117 comp row1 row2 = V.and (V.zipWith (==) row1 row2)
118
119
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
125 -- compile-time).
126 --
127 -- Examples:
128 --
129 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
130 -- >>> show m
131 -- ((1,2),(3,4))
132 --
133 show (Mat rows) =
134 "(" ++ (intercalate "," (V.toList row_strings)) ++ ")"
135 where
136 row_strings = V.map show_vector rows
137 show_vector v1 =
138 "(" ++ (intercalate "," element_strings) ++ ")"
139 where
140 v1l = V.toList v1
141 element_strings = P.map show v1l
142
143
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)
147
148
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)
152
153
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
157
158
159 -- | Safe indexing.
160 --
161 -- Examples:
162 --
163 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
164 -- >>> m !!? (-1,-1)
165 -- Nothing
166 -- >>> m !!? (-1,0)
167 -- Nothing
168 -- >>> m !!? (-1,1)
169 -- Nothing
170 -- >>> m !!? (0,-1)
171 -- Nothing
172 -- >>> m !!? (0,0)
173 -- Just 1
174 -- >>> m !!? (0,1)
175 -- Just 2
176 -- >>> m !!? (1,-1)
177 -- Nothing
178 -- >>> m !!? (1,0)
179 -- Just 3
180 -- >>> m !!? (1,1)
181 -- Just 4
182 -- >>> m !!? (2,-1)
183 -- Nothing
184 -- >>> m !!? (2,0)
185 -- Nothing
186 -- >>> m !!? (2,1)
187 -- Nothing
188 -- >>> m !!? (2,2)
189 -- Nothing
190 --
191 (!!?) :: (Arity m, Arity n) => Mat m n a -> (Int, Int) -> Maybe a
192 (!!?) matrix idx =
193 ifoldl2 f Nothing matrix
194 where
195 f k l found cur = if (k,l) == idx then (Just cur) else found
196
197
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)
201
202
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)
207
208
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
211 row m i =
212 construct lambda
213 where
214 lambda _ j = m !!! (i, j)
215
216
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
219 column m j =
220 construct lambda
221 where
222 lambda i _ = m !!! (i, j)
223
224
225 -- | Transpose @m@; switch it's columns and its rows. This is a dirty
226 -- implementation, but I don't see a better way.
227 --
228 -- TODO: Don't cheat with fromList.
229 --
230 -- Examples:
231 --
232 -- >>> let m = fromList [[1,2], [3,4]] :: Mat2 Int
233 -- >>> transpose m
234 -- ((1,3),(2,4))
235 --
236 transpose :: (Arity m, Arity n) => Mat m n a -> Mat n m a
237 transpose matrix =
238 construct lambda
239 where
240 lambda i j = matrix !!! (j,i)
241
242
243 -- | Is @m@ symmetric?
244 --
245 -- Examples:
246 --
247 -- >>> let m1 = fromList [[1,2], [2,1]] :: Mat2 Int
248 -- >>> symmetric m1
249 -- True
250 --
251 -- >>> let m2 = fromList [[1,2], [3,1]] :: Mat2 Int
252 -- >>> symmetric m2
253 -- False
254 --
255 symmetric :: (Eq a, Arity m) => Mat m m a -> Bool
256 symmetric m =
257 m == (transpose m)
258
259
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.
264 --
265 -- Examples:
266 --
267 -- >>> let lambda i j = i + j
268 -- >>> construct lambda :: Mat3 Int
269 -- ((0,1,2),(1,2,3),(2,3,4))
270 --
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
274 where
275 make_row :: Int -> Vec n a
276 make_row i = generate (lambda i)
277
278
279 -- | Create an identity matrix with the right dimensions.
280 --
281 -- Examples:
282 --
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))
287 --
288 identity_matrix :: (Arity m, Ring.C a) => Mat m m a
289 identity_matrix =
290 construct (\i j -> if i == j then (fromInteger 1) else (fromInteger 0))
291
292
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.
296 --
297 -- Examples:
298 --
299 -- >>> let m1 = fromList [[20,-1], [-1,20]] :: Mat2 Double
300 -- >>> let r = cholesky m1
301 -- >>> frobenius_norm ((transpose r)*r - m1) < 1e-10
302 -- True
303 -- >>> is_upper_triangular r
304 -- True
305 --
306 -- >>> import Naturals ( N7 )
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 -- | Return the (i,j)th minor of m.
470 --
471 -- Examples:
472 --
473 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
474 -- >>> minor m 0 0 :: Mat2 Int
475 -- ((5,6),(8,9))
476 -- >>> minor m 1 1 :: Mat2 Int
477 -- ((1,3),(7,9))
478 --
479 minor :: (m ~ S r,
480 n ~ S t,
481 Arity r,
482 Arity t)
483 => Mat m n a
484 -> Int
485 -> Int
486 -> Mat r t a
487 minor (Mat rows) i j = m
488 where
489 rows' = delete rows i
490 m = Mat $ V.map ((flip delete) j) rows'
491
492
493 class (Eq a, Ring.C a) => Determined p a where
494 determinant :: (p a) -> a
495
496 instance (Eq a, Ring.C a) => Determined (Mat (S Z) (S Z)) a where
497 determinant (Mat rows) = (V.head . V.head) rows
498
499 instance (Ord a,
500 Ring.C a,
501 Absolute.C a,
502 Arity n,
503 Determined (Mat (S n) (S n)) a)
504 => Determined (Mat (S (S n)) (S (S n))) a where
505 -- | The recursive definition with a special-case for triangular matrices.
506 --
507 -- Examples:
508 --
509 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
510 -- >>> determinant m
511 -- -1
512 --
513 determinant m
514 | is_triangular m = product [ m !!! (i,i) | i <- [0..(nrows m)-1] ]
515 | otherwise = determinant_recursive
516 where
517 m' i j = m !!! (i,j)
518
519 det_minor i j = determinant (minor m i j)
520
521 determinant_recursive =
522 sum [ (-1)^(toInteger j) NP.* (m' 0 j) NP.* (det_minor 0 j)
523 | j <- [0..(ncols m)-1] ]
524
525
526
527 -- | Matrix multiplication.
528 --
529 -- Examples:
530 --
531 -- >>> let m1 = fromList [[1,2,3], [4,5,6]] :: Mat N2 N3 Int
532 -- >>> let m2 = fromList [[1,2],[3,4],[5,6]] :: Mat N3 N2 Int
533 -- >>> m1 * m2
534 -- ((22,28),(49,64))
535 --
536 infixl 7 *
537 (*) :: (Ring.C a, Arity m, Arity n, Arity p)
538 => Mat m n a
539 -> Mat n p a
540 -> Mat m p a
541 (*) m1 m2 = construct lambda
542 where
543 lambda i j =
544 sum [(m1 !!! (i,k)) NP.* (m2 !!! (k,j)) | k <- [0..(ncols m1)-1] ]
545
546
547
548 instance (Ring.C a, Arity m, Arity n) => Additive.C (Mat m n a) where
549
550 (Mat rows1) + (Mat rows2) =
551 Mat $ V.zipWith (V.zipWith (+)) rows1 rows2
552
553 (Mat rows1) - (Mat rows2) =
554 Mat $ V.zipWith (V.zipWith (-)) rows1 rows2
555
556 zero = Mat (V.replicate $ V.replicate (fromInteger 0))
557
558
559 instance (Ring.C a, Arity m, Arity n, m ~ n) => Ring.C (Mat m n a) where
560 -- The first * is ring multiplication, the second is matrix
561 -- multiplication.
562 m1 * m2 = m1 * m2
563
564
565 instance (Ring.C a, Arity m, Arity n) => Module.C a (Mat m n a) where
566 -- We can multiply a matrix by a scalar of the same type as its
567 -- elements.
568 x *> (Mat rows) = Mat $ V.map (V.map (NP.* x)) rows
569
570
571 instance (Algebraic.C a,
572 ToRational.C a,
573 Arity m)
574 => Normed (Mat (S m) N1 a) where
575 -- | Generic p-norms for vectors in R^n that are represented as nx1
576 -- matrices.
577 --
578 -- Examples:
579 --
580 -- >>> let v1 = vec2d (3,4)
581 -- >>> norm_p 1 v1
582 -- 7.0
583 -- >>> norm_p 2 v1
584 -- 5.0
585 --
586 norm_p p (Mat rows) =
587 (root p') $ sum [fromRational' (toRational x)^p' | x <- xs]
588 where
589 p' = toInteger p
590 xs = concat $ V.toList $ V.map V.toList rows
591
592 -- | The infinity norm.
593 --
594 -- Examples:
595 --
596 -- >>> let v1 = vec3d (1,5,2)
597 -- >>> norm_infty v1
598 -- 5
599 --
600 norm_infty (Mat rows) =
601 fromRational' $ toRational $ V.maximum $ V.map V.maximum rows
602
603
604 -- | Compute the Frobenius norm of a matrix. This essentially treats
605 -- the matrix as one long vector containing all of its entries (in
606 -- any order, it doesn't matter).
607 --
608 -- Examples:
609 --
610 -- >>> let m = fromList [[1, 2, 3],[4,5,6],[7,8,9]] :: Mat3 Double
611 -- >>> frobenius_norm m == sqrt 285
612 -- True
613 --
614 -- >>> let m = fromList [[1, -1, 1],[-1,1,-1],[1,-1,1]] :: Mat3 Double
615 -- >>> frobenius_norm m == 3
616 -- True
617 --
618 frobenius_norm :: (Algebraic.C a, Ring.C a) => Mat m n a -> a
619 frobenius_norm (Mat rows) =
620 sqrt $ element_sum $ V.map row_sum rows
621 where
622 -- | Square and add up the entries of a row.
623 row_sum = element_sum . V.map (^2)
624
625
626 -- Vector helpers. We want it to be easy to create low-dimension
627 -- column vectors, which are nx1 matrices.
628
629 -- | Convenient constructor for 2D vectors.
630 --
631 -- Examples:
632 --
633 -- >>> import Roots.Simple
634 -- >>> let fst m = m !!! (0,0)
635 -- >>> let snd m = m !!! (1,0)
636 -- >>> let h = 0.5 :: Double
637 -- >>> let g1 m = 1.0 + h NP.* exp(-((fst m)^2))/(1.0 + (snd m)^2)
638 -- >>> let g2 m = 0.5 + h NP.* atan((fst m)^2 + (snd m)^2)
639 -- >>> let g u = vec2d ((g1 u), (g2 u))
640 -- >>> let u0 = vec2d (1.0, 1.0)
641 -- >>> let eps = 1/(10^9)
642 -- >>> fixed_point g eps u0
643 -- ((1.0728549599342185),(1.0820591495686167))
644 --
645 vec1d :: (a) -> Col1 a
646 vec1d (x) = Mat (mk1 (mk1 x))
647
648 vec2d :: (a,a) -> Col2 a
649 vec2d (x,y) = Mat (mk2 (mk1 x) (mk1 y))
650
651 vec3d :: (a,a,a) -> Col3 a
652 vec3d (x,y,z) = Mat (mk3 (mk1 x) (mk1 y) (mk1 z))
653
654 vec4d :: (a,a,a,a) -> Col4 a
655 vec4d (w,x,y,z) = Mat (mk4 (mk1 w) (mk1 x) (mk1 y) (mk1 z))
656
657 vec5d :: (a,a,a,a,a) -> Col5 a
658 vec5d (v,w,x,y,z) = Mat (mk5 (mk1 v) (mk1 w) (mk1 x) (mk1 y) (mk1 z))
659
660 -- Since we commandeered multiplication, we need to create 1x1
661 -- matrices in order to multiply things.
662 scalar :: a -> Mat1 a
663 scalar x = Mat (mk1 (mk1 x))
664
665 dot :: (RealRing.C a, m ~ S t, Arity t)
666 => Col m a
667 -> Col m a
668 -> a
669 v1 `dot` v2 = ((transpose v1) * v2) !!! (0, 0)
670
671
672 -- | The angle between @v1@ and @v2@ in Euclidean space.
673 --
674 -- Examples:
675 --
676 -- >>> let v1 = vec2d (1.0, 0.0)
677 -- >>> let v2 = vec2d (0.0, 1.0)
678 -- >>> angle v1 v2 == pi/2.0
679 -- True
680 --
681 angle :: (Transcendental.C a,
682 RealRing.C a,
683 m ~ S t,
684 Arity t,
685 ToRational.C a)
686 => Col m a
687 -> Col m a
688 -> a
689 angle v1 v2 =
690 acos theta
691 where
692 theta = (recip norms) NP.* (v1 `dot` v2)
693 norms = (norm v1) NP.* (norm v2)
694
695
696 -- | Retrieve the diagonal elements of the given matrix as a \"column
697 -- vector,\" i.e. a m-by-1 matrix. We require the matrix to be
698 -- square to avoid ambiguity in the return type which would ideally
699 -- have dimension min(m,n) supposing an m-by-n matrix.
700 --
701 -- Examples:
702 --
703 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
704 -- >>> diagonal m
705 -- ((1),(5),(9))
706 --
707 diagonal :: (Arity m) => Mat m m a -> Col m a
708 diagonal matrix =
709 construct lambda
710 where
711 lambda i _ = matrix !!! (i,i)
712
713
714 -- | Given a square @matrix@, return a new matrix of the same size
715 -- containing only the on-diagonal entries of @matrix@. The
716 -- off-diagonal entries are set to zero.
717 --
718 -- Examples:
719 --
720 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
721 -- >>> diagonal_part m
722 -- ((1,0,0),(0,5,0),(0,0,9))
723 --
724 diagonal_part :: (Arity m, Ring.C a)
725 => Mat m m a
726 -> Mat m m a
727 diagonal_part matrix =
728 construct lambda
729 where
730 lambda i j = if i == j then matrix !!! (i,j) else 0
731
732
733 -- | Given a square @matrix@, return a new matrix of the same size
734 -- containing only the on-diagonal and below-diagonal entries of
735 -- @matrix@. The above-diagonal entries are set to zero.
736 --
737 -- Examples:
738 --
739 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
740 -- >>> lt_part m
741 -- ((1,0,0),(4,5,0),(7,8,9))
742 --
743 lt_part :: (Arity m, Ring.C a)
744 => Mat m m a
745 -> Mat m m a
746 lt_part matrix =
747 construct lambda
748 where
749 lambda i j = if i >= j then matrix !!! (i,j) else 0
750
751
752 -- | Given a square @matrix@, return a new matrix of the same size
753 -- containing only the below-diagonal entries of @matrix@. The on-
754 -- and above-diagonal entries are set to zero.
755 --
756 -- Examples:
757 --
758 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
759 -- >>> lt_part_strict m
760 -- ((0,0,0),(4,0,0),(7,8,0))
761 --
762 lt_part_strict :: (Arity m, Ring.C a)
763 => Mat m m a
764 -> Mat m m a
765 lt_part_strict matrix =
766 construct lambda
767 where
768 lambda i j = if i > j then matrix !!! (i,j) else 0
769
770
771 -- | Given a square @matrix@, return a new matrix of the same size
772 -- containing only the on-diagonal and above-diagonal entries of
773 -- @matrix@. The below-diagonal entries are set to zero.
774 --
775 -- Examples:
776 --
777 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
778 -- >>> ut_part m
779 -- ((1,2,3),(0,5,6),(0,0,9))
780 --
781 ut_part :: (Arity m, Ring.C a)
782 => Mat m m a
783 -> Mat m m a
784 ut_part = transpose . lt_part . transpose
785
786
787 -- | Given a square @matrix@, return a new matrix of the same size
788 -- containing only the above-diagonal entries of @matrix@. The on-
789 -- and below-diagonal entries are set to zero.
790 --
791 -- Examples:
792 --
793 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
794 -- >>> ut_part_strict m
795 -- ((0,2,3),(0,0,6),(0,0,0))
796 --
797 ut_part_strict :: (Arity m, Ring.C a)
798 => Mat m m a
799 -> Mat m m a
800 ut_part_strict = transpose . lt_part_strict . transpose
801
802
803 -- | Compute the trace of a square matrix, the sum of the elements
804 -- which lie on its diagonal. We require the matrix to be
805 -- square to avoid ambiguity in the return type which would ideally
806 -- have dimension min(m,n) supposing an m-by-n matrix.
807 --
808 -- Examples:
809 --
810 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
811 -- >>> trace m
812 -- 15
813 --
814 trace :: (Arity m, Ring.C a) => Mat m m a -> a
815 trace matrix =
816 let (Mat rows) = diagonal matrix
817 in
818 element_sum $ V.map V.head rows
819
820
821 -- | Zip together two column matrices.
822 --
823 -- Examples:
824 --
825 -- >>> let m1 = fromList [[1],[1],[1]] :: Col3 Int
826 -- >>> let m2 = fromList [[1],[2],[3]] :: Col3 Int
827 -- >>> colzip m1 m2
828 -- (((1,1)),((1,2)),((1,3)))
829 --
830 colzip :: Arity m => Col m a -> Col m a -> Col m (a,a)
831 colzip c1 c2 =
832 construct lambda
833 where
834 lambda i j = (c1 !!! (i,j), c2 !!! (i,j))
835
836
837 -- | Zip together two column matrices using the supplied function.
838 --
839 -- Examples:
840 --
841 -- >>> let c1 = fromList [[1],[2],[3]] :: Col3 Integer
842 -- >>> let c2 = fromList [[4],[5],[6]] :: Col3 Integer
843 -- >>> colzipwith (^) c1 c2
844 -- ((1),(32),(729))
845 --
846 colzipwith :: Arity m
847 => (a -> a -> b)
848 -> Col m a
849 -> Col m a
850 -> Col m b
851 colzipwith f c1 c2 =
852 construct lambda
853 where
854 lambda i j = f (c1 !!! (i,j)) (c2 !!! (i,j))
855
856
857 -- | Map a function over a matrix of any dimensions.
858 --
859 -- Examples:
860 --
861 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
862 -- >>> map2 (^2) m
863 -- ((1,4),(9,16))
864 --
865 map2 :: (a -> b) -> Mat m n a -> Mat m n b
866 map2 f (Mat rows) =
867 Mat $ V.map g rows
868 where
869 g = V.map f
870
871
872 -- | Fold over the entire matrix passing the coordinates @i@ and @j@
873 -- (of the row/column) to the accumulation function.
874 --
875 -- Examples:
876 --
877 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
878 -- >>> ifoldl2 (\i j cur _ -> cur + i + j) 0 m
879 -- 18
880 --
881 ifoldl2 :: forall a b m n.
882 (Int -> Int -> b -> a -> b)
883 -> b
884 -> Mat m n a
885 -> b
886 ifoldl2 f initial (Mat rows) =
887 V.ifoldl row_function initial rows
888 where
889 -- | The order that we need this in (so that @g idx@ makes sense)
890 -- is a little funny. So that we don't need to pass weird
891 -- functions into ifoldl2, we swap the second and third
892 -- arguments of @f@ calling the result @g@.
893 g :: Int -> b -> Int -> a -> b
894 g w x y = f w y x
895
896 row_function :: b -> Int -> Vec n a -> b
897 row_function rowinit idx r = V.ifoldl (g idx) rowinit r
898
899
900 -- | Map a function over a matrix of any dimensions, passing the
901 -- coordinates @i@ and @j@ to the function @f@.
902 --
903 -- Examples:
904 --
905 -- >>> let m = fromList [[1,2],[3,4]] :: Mat2 Int
906 -- >>> imap2 (\i j _ -> i+j) m
907 -- ((0,1),(1,2))
908 --
909 imap2 :: (Int -> Int -> a -> b) -> Mat m n a -> Mat m n b
910 imap2 f (Mat rows) =
911 Mat $ V.imap g rows
912 where
913 g i = V.imap (f i)
914
915
916 -- | Reverse the order of elements in a matrix.
917 --
918 -- Examples:
919 --
920 -- >>> let m1 = fromList [[1,2,3]] :: Row3 Int
921 -- >>> reverse2 m1
922 -- ((3,2,1))
923 --
924 -- >>> let m1 = vec3d (1,2,3 :: Int)
925 -- >>> reverse2 m1
926 -- ((3),(2),(1))
927 --
928 -- >>> let m = fromList [[1,2,3],[4,5,6],[7,8,9]] :: Mat3 Int
929 -- >>> reverse2 m
930 -- ((9,8,7),(6,5,4),(3,2,1))
931 --
932 reverse2 :: (Arity m, Arity n) => Mat m n a -> Mat m n a
933 reverse2 (Mat rows) = Mat $ V.reverse $ V.map V.reverse rows