2 Module : Gargantext.Graph.Distances.Matrix
4 Copyright : (c) CNRS, 2017-Present
5 License : AGPL + CECILL v3
6 Maintainer : team@gargantext.org
7 Stability : experimental
10 Motivation and definition of the @Conditional@ distance.
13 {-# LANGUAGE NoImplicitPrelude #-}
14 {-# LANGUAGE FlexibleContexts #-}
15 {-# LANGUAGE TypeFamilies #-}
17 module Gargantext.Viz.Graph.Distances.Matrice
20 import Data.Array.Accelerate.Data.Bits
21 import Data.Array.Accelerate.Interpreter
23 import Data.Array.Accelerate
24 import Data.Array.Accelerate.Smart
25 import Data.Array.Accelerate.Type
26 import Data.Array.Accelerate.Array.Sugar (fromArr, Array, Z)
28 import Data.Maybe (Maybe(Just))
29 import qualified Gargantext.Prelude as P
30 import qualified Data.Array.Accelerate.Array.Representation as Repr
32 matrix :: Elt c => Int -> [c] -> Matrix c
33 matrix n l = fromList (Z :. n :. n) l
35 myMat :: Int -> Matrix Double
36 myMat n = matrix n [1..]
38 -- | Two ways to get the rank (as documentation)
39 rank :: (Matrix Double) -> Int
40 rank m = arrayRank $ arrayShape m
42 rank' :: (Matrix Double) -> Int
45 Z :. _ :. n = arrayShape m
47 -----------------------------------------------------------------------
48 -- | Conditional Distance
52 proba :: Rank -> Acc (Matrix Double) -> Acc (Matrix Double)
53 proba r mat = zipWith (/) mat (mkSum r mat)
55 mkSum :: Rank -> Acc (Matrix Double) -> Acc (Matrix Double)
56 mkSum r mat = replicate (constant (Z :. (r :: Int) :. All))
60 type Matrix' a = Acc (Matrix a)
62 conditional :: Matrix Double -> (Matrix Double, Matrix Double)
63 conditional m = (run $ ie (use m), run $ sg (use m))
68 xs :: Matrix' Double -> Matrix' Double
69 xs mat = zipWith (-) (proba r mat) (mkSum r $ proba r mat)
70 ys :: Acc (Matrix Double) -> Acc (Matrix Double)
71 ys mat = zipWith (-) (proba r mat) (mkSum r $ transpose $ proba r mat)
73 ie :: Matrix' Double -> Matrix' Double
74 ie mat = map (\x -> x / (2*n-1)) $ zipWith (+) (xs mat) (ys mat)
75 sg :: Acc (Matrix Double) -> Acc (Matrix Double)
76 sg mat = map (\x -> x / (2*n-1)) $ zipWith (-) (xs mat) (ys mat)
81 --miniMax m = fold minimum $ fold maximum m
86 -- filter with threshold
87 -----------------------------------------------------------------------
89 -- | Distributional Distance
91 distributional :: Matrix Double -> Matrix Double
92 distributional m = run $ filter $ ri (use m)
96 filter m = zipWith (\a b -> max a b) m (transpose m)
97 --miniMax m = fold minimum $ fold maximum m
99 ri mat = zipWith (/) mat1 mat2
101 mat1 = mkSum n $ zipWith min (mi mat) (mi $ transpose mat)
104 mi m' = zipWith (\a b -> max (log $ a/b) 0) m'
105 $ zipWith (/) (crossProduct m') (total m')
107 total m'' = replicate (constant (Z :. n :. n)) $ fold (+) 0 $ fold (+) 0 m''
109 crossProduct m = zipWith (*) (cross m ) (cross (transpose m))
110 cross mat = zipWith (-) (mkSum n mat) (mat)