]> Git — Sourcephile - gargantext.git/blob - src/Gargantext/Viz/Phylo/SynchronicClustering.hs
fix the weightedlogjaccard
[gargantext.git] / src / Gargantext / Viz / Phylo / SynchronicClustering.hs
1 {-|
2 Module : Gargantext.Viz.Phylo.SynchronicClustering
3 Description : Module dedicated to the adaptative synchronic clustering of a Phylo.
4 Copyright : (c) CNRS, 2017-Present
5 License : AGPL + CECILL v3
6 Maintainer : team@gargantext.org
7 Stability : experimental
8 Portability : POSIX
9 -}
10
11 {-# LANGUAGE NoImplicitPrelude #-}
12 {-# LANGUAGE FlexibleContexts #-}
13 {-# LANGUAGE OverloadedStrings #-}
14 {-# LANGUAGE MultiParamTypeClasses #-}
15
16 module Gargantext.Viz.Phylo.SynchronicClustering where
17
18 import Gargantext.Prelude
19 import Gargantext.Viz.AdaptativePhylo
20 import Gargantext.Viz.Phylo.PhyloTools
21 import Gargantext.Viz.Phylo.TemporalMatching (weightedLogJaccard', filterDiago, reduceDiagos)
22 import Gargantext.Viz.Phylo.PhyloExport (processDynamics)
23
24 import Data.List ((++), null, intersect, nub, concat, sort, sortOn, init, all, group, maximum, groupBy)
25 import Data.Map (Map, fromList, fromListWith, foldlWithKey, (!), insert, empty, restrictKeys, elems, mapWithKey, member, singleton)
26
27 import Control.Lens hiding (Level)
28 import Control.Parallel.Strategies (parList, rdeepseq, using)
29 -- import Debug.Trace (trace)
30
31 import qualified Data.Map as Map
32 import qualified Data.Set as Set
33
34
35 -------------------------
36 -- | New Level Maker | --
37 -------------------------
38
39 mergeBranchIds :: [[Int]] -> [Int]
40 mergeBranchIds ids = (head' "mergeBranchIds" . sort . mostFreq) ids
41 where
42 -- | 2) find the most Up Left ids in the hierarchy of similarity
43 -- mostUpLeft :: [[Int]] -> [[Int]]
44 -- mostUpLeft ids' =
45 -- let groupIds = (map (\gIds -> (length $ head' "gIds" gIds, head' "gIds" gIds)) . groupBy (\id id' -> length id == length id') . sortOn length) ids'
46 -- inf = (fst . minimum) groupIds
47 -- in map snd $ filter (\gIds -> fst gIds == inf) groupIds
48 -- | 1) find the most frequent ids
49 mostFreq :: [[Int]] -> [[Int]]
50 mostFreq ids' =
51 let groupIds = (map (\gIds -> (length gIds, head' "gIds" gIds)) . group . sort) ids'
52 sup = (fst . maximum) groupIds
53 in map snd $ filter (\gIds -> fst gIds == sup) groupIds
54
55
56 groupsToBranches' :: Map PhyloGroupId PhyloGroup -> [[PhyloGroup]]
57 groupsToBranches' groups =
58 -- | run the related component algorithm
59 let egos = map (\g -> [getGroupId g]
60 ++ (map fst $ g ^. phylo_groupPeriodParents)
61 ++ (map fst $ g ^. phylo_groupPeriodChilds) ) $ elems groups
62 graph = relatedComponents egos
63 -- | update each group's branch id
64 in map (\ids ->
65 let groups' = elems $ restrictKeys groups (Set.fromList ids)
66 bId = mergeBranchIds $ map (\g -> snd $ g ^. phylo_groupBranchId) groups'
67 in map (\g -> g & phylo_groupBranchId %~ (\(lvl,_) -> (lvl + 1,bId))) groups') graph
68
69 getLastThr :: [PhyloGroup] -> Double
70 getLastThr childs = maximum $ concat $ map (\g -> (g ^. phylo_groupMeta) ! "thr") childs
71
72 mergeGroups :: [Cooc] -> PhyloGroupId -> Map PhyloGroupId PhyloGroupId -> [PhyloGroup] -> PhyloGroup
73 mergeGroups coocs id mapIds childs =
74 let ngrams = (sort . nub . concat) $ map _phylo_groupNgrams childs
75 in PhyloGroup (fst $ fst id) (snd $ fst id) (snd id) ""
76 (sum $ map _phylo_groupSupport childs) ngrams
77 (ngramsToCooc ngrams coocs)
78 ((snd $ fst id),(mergeBranchIds $ map (\g -> snd $ g ^. phylo_groupBranchId) childs))
79 (singleton "thr" [getLastThr childs]) [] (map (\g -> (getGroupId g, 1)) childs)
80 (updatePointers $ concat $ map _phylo_groupPeriodParents childs)
81 (updatePointers $ concat $ map _phylo_groupPeriodChilds childs)
82 where
83 updatePointers :: [Pointer] -> [Pointer]
84 updatePointers pointers = map (\(pId,w) -> (mapIds ! pId,w)) pointers
85
86
87 addPhyloLevel :: Level -> Phylo -> Phylo
88 addPhyloLevel lvl phylo =
89 over ( phylo_periods . traverse )
90 (\phyloPrd -> phyloPrd & phylo_periodLevels
91 %~ (insert (phyloPrd ^. phylo_periodPeriod, lvl) (PhyloLevel (phyloPrd ^. phylo_periodPeriod) lvl empty))) phylo
92
93
94 toNextLevel' :: Phylo -> [PhyloGroup] -> Phylo
95 toNextLevel' phylo groups =
96 let curLvl = getLastLevel phylo
97 oldGroups = fromList $ map (\g -> (getGroupId g, getLevelParentId g)) groups
98 newGroups = concat $ groupsToBranches'
99 $ fromList $ map (\g -> (getGroupId g, g))
100 $ foldlWithKey (\acc id groups' ->
101 -- | 4) create the parent group
102 let parent = mergeGroups (elems $ restrictKeys (phylo ^. phylo_timeCooc) $ periodsToYears [(fst . fst) id]) id oldGroups groups'
103 in acc ++ [parent]) []
104 -- | 3) group the current groups by parentId
105 $ fromListWith (++) $ map (\g -> (getLevelParentId g, [g])) groups
106
107 newPeriods = fromListWith (++) $ map (\g -> (g ^. phylo_groupPeriod, [g])) newGroups
108 in traceSynchronyEnd
109 $ over ( phylo_periods . traverse . phylo_periodLevels . traverse
110 -- | 6) update each period at curLvl + 1
111 . filtered (\phyloLvl -> phyloLvl ^. phylo_levelLevel == (curLvl + 1)))
112 -- | 7) by adding the parents
113 (\phyloLvl ->
114 if member (phyloLvl ^. phylo_levelPeriod) newPeriods
115 then phyloLvl & phylo_levelGroups
116 .~ fromList (map (\g -> (getGroupId g, g)) $ newPeriods ! (phyloLvl ^. phylo_levelPeriod))
117 else phyloLvl)
118 -- | 2) add the curLvl + 1 phyloLevel to the phylo
119 $ addPhyloLevel (curLvl + 1)
120 -- | 1) update the current groups (with level parent pointers) in the phylo
121 $ updatePhyloGroups curLvl (fromList $ map (\g -> (getGroupId g, g)) groups) phylo
122
123 --------------------
124 -- | Clustering | --
125 --------------------
126
127 toPairs :: SynchronyStrategy -> [PhyloGroup] -> [(PhyloGroup,PhyloGroup)]
128 toPairs strategy groups = case strategy of
129 MergeRegularGroups -> pairs
130 $ filter (\g -> all (== 3) $ (g ^. phylo_groupMeta) ! "dynamics") groups
131 MergeAllGroups -> pairs groups
132 where
133 pairs :: [PhyloGroup] -> [(PhyloGroup,PhyloGroup)]
134 pairs gs = filter (\(g,g') -> (not . null) $ intersect (g ^. phylo_groupNgrams) (g' ^. phylo_groupNgrams)) (listToCombi' gs)
135
136
137 toDiamonds :: [PhyloGroup] -> [[PhyloGroup]]
138 toDiamonds groups = foldl' (\acc groups' ->
139 acc ++ ( elems
140 $ Map.filter (\v -> length v > 1)
141 $ fromListWith (++)
142 $ foldl' (\acc' g ->
143 acc' ++ (map (\(id,_) -> (id,[g]) ) $ g ^. phylo_groupPeriodChilds)) [] groups')) []
144 $ elems
145 $ Map.filter (\v -> length v > 1)
146 $ fromListWith (++)
147 $ foldl' (\acc g -> acc ++ (map (\(id,_) -> (id,[g]) ) $ g ^. phylo_groupPeriodParents) ) [] groups
148
149
150 groupsToEdges :: Proximity -> Synchrony -> Double -> Map Int Double -> [PhyloGroup] -> [((PhyloGroup,PhyloGroup),Double)]
151 groupsToEdges prox sync nbDocs diago groups =
152 case sync of
153 ByProximityThreshold thr sens _ strat ->
154 filter (\(_,w) -> w >= thr)
155 $ toEdges sens
156 $ toPairs strat groups
157 ByProximityDistribution sens strat ->
158 let diamonds = sortOn snd
159 $ toEdges sens $ concat
160 $ map (\gs -> toPairs strat gs) $ toDiamonds groups
161 in take (div (length diamonds) 2) diamonds
162 where
163 toEdges :: Double -> [(PhyloGroup,PhyloGroup)] -> [((PhyloGroup,PhyloGroup),Double)]
164 toEdges sens edges =
165 case prox of
166 WeightedLogJaccard _ _ _ -> map (\(g,g') ->
167 ((g,g'), weightedLogJaccard' sens nbDocs diago
168 (g ^. phylo_groupNgrams) (g' ^. phylo_groupNgrams))) edges
169 _ -> undefined
170
171
172
173 toRelatedComponents :: [PhyloGroup] -> [((PhyloGroup,PhyloGroup),Double)] -> [[PhyloGroup]]
174 toRelatedComponents nodes edges =
175 let ref = fromList $ map (\g -> (getGroupId g, g)) nodes
176 clusters = relatedComponents $ ((map (\((g,g'),_) -> [getGroupId g, getGroupId g']) edges) ++ (map (\g -> [getGroupId g]) nodes))
177 in map (\cluster -> map (\gId -> ref ! gId) cluster) clusters
178
179 toParentId :: PhyloGroup -> PhyloGroupId
180 toParentId child = ((child ^. phylo_groupPeriod, child ^. phylo_groupLevel + 1), child ^. phylo_groupIndex)
181
182
183 reduceGroups :: Proximity -> Synchrony -> Map Date Double -> Map Date Cooc -> [PhyloGroup] -> [PhyloGroup]
184 reduceGroups prox sync docs diagos branch =
185 -- | 1) reduce a branch as a set of periods & groups
186 let periods = fromListWith (++)
187 $ map (\g -> (g ^. phylo_groupPeriod,[g])) branch
188 in (concat . concat . elems)
189 $ mapWithKey (\prd groups ->
190 -- | 2) for each period, transform the groups as a proximity graph filtered by a threshold
191 let diago = reduceDiagos $ filterDiago diagos [prd]
192 edges = groupsToEdges prox sync ((sum . elems) $ restrictKeys docs $ periodsToYears [prd]) diago groups
193 in map (\comp ->
194 -- | 4) add to each groups their futur level parent group
195 let parentId = toParentId (head' "parentId" comp)
196 in map (\g -> g & phylo_groupLevelParents %~ (++ [(parentId,1)]) ) comp )
197 -- |3) reduce the graph a a set of related components
198 $ toRelatedComponents groups edges) periods
199
200
201 getGroupRealBId :: Double -> PhyloGroup -> [Int]
202 getGroupRealBId step g =
203 let nb = round(getGroupThr g / step) + 2
204 in take nb (snd $ g ^. phylo_groupBranchId)
205
206
207
208 adjustClustering :: Synchrony -> Double -> [[PhyloGroup]] -> [[PhyloGroup]]
209 adjustClustering sync step branches = case sync of
210 ByProximityThreshold _ _ scope _ ->
211 case scope of
212 SingleBranch -> branches
213 SiblingBranches -> groupBy (\g g' -> (init $ getGroupRealBId step g) == (init $ getGroupRealBId step g'))
214 $ sortOn _phylo_groupBranchId $ concat branches
215 -- SiblingBranches -> elems $ fromListWith (++) $ map (\b -> ((init . snd . _phylo_groupBranchId) $ head' "adjustClustering" b,b)) branches
216 AllBranches -> [concat branches]
217 ByProximityDistribution _ _ -> branches
218
219
220
221 synchronicClustering :: Phylo -> Phylo
222 synchronicClustering phylo =
223 let prox = phyloProximity $ getConfig phylo
224 sync = phyloSynchrony $ getConfig phylo
225 docs = phylo ^. phylo_timeDocs
226 diagos = map coocToDiago $ phylo ^. phylo_timeCooc
227 newBranches = map (\branch -> reduceGroups prox sync docs diagos branch)
228 $ map processDynamics
229 $ adjustClustering sync (getPhyloThresholdStep phylo)
230 $ phyloToLastBranches
231 $ traceSynchronyStart phylo
232 newBranches' = newBranches `using` parList rdeepseq
233 in toNextLevel' phylo $ concat newBranches'
234
235
236 ----------------
237 -- | probes | --
238 ----------------
239
240 -- synchronicDistance :: Phylo -> Level -> String
241 -- synchronicDistance phylo lvl =
242 -- foldl' (\acc branch ->
243 -- acc <> (foldl' (\acc' period ->
244 -- acc' <> let prox = phyloProximity $ getConfig phylo
245 -- sync = phyloSynchrony $ getConfig phylo
246 -- docs = _phylo_timeDocs phylo
247 -- prd = _phylo_groupPeriod $ head' "distance" period
248 -- edges = groupsToEdges prox 0.1 (_bpt_sensibility sync)
249 -- ((sum . elems) $ restrictKeys docs $ periodsToYears [_phylo_groupPeriod $ head' "distance" period]) period
250 -- in foldl' (\mem (_,w) ->
251 -- mem <> show (prd)
252 -- <> "\t"
253 -- <> show (w)
254 -- <> "\n"
255 -- ) "" edges
256 -- ) "" $ elems $ groupByField _phylo_groupPeriod branch)
257 -- ) "period\tdistance\n" $ elems $ groupByField _phylo_groupBranchId $ getGroupsFromLevel lvl phylo