2 Module : Gargantext.API.Ngrams.Tools
3 Description : Tools to manage Ngrams Elements (from the API)
4 Copyright : (c) CNRS, 2017-Present
5 License : AGPL + CECILL v3
6 Maintainer : team@gargantext.org
7 Stability : experimental
12 {-# LANGUAGE NoImplicitPrelude #-}
13 {-# LANGUAGE OverloadedStrings #-}
14 {-# LANGUAGE RankNTypes #-}
16 module Gargantext.API.Ngrams.Tools
19 import Control.Concurrent
20 import Control.Lens (_Just, (^.), at, view)
21 import Control.Monad.Reader
22 import Data.Map.Strict (Map)
24 import Data.Text (Text)
26 import Gargantext.API.Ngrams
27 import Gargantext.Core.Types (ListType(..), NodeId, ListId)
28 import Gargantext.Database.Schema.Ngrams (NgramsType)
29 import Gargantext.Prelude
30 import qualified Data.Map.Strict as Map
31 import qualified Data.Set as Set
37 getListNgrams :: RepoCmdM env err m
38 => [ListId] -> NgramsType
39 -> m (Map Text NgramsRepoElement)
40 getListNgrams nodeIds ngramsType = do
42 repo <- liftIO $ readMVar v
45 ngramsMap = repo ^. r_state . at ngramsType . _Just
47 ngrams = Map.unionsWith mergeNgramsElement
48 [ ngramsMap ^. at nodeId . _Just | nodeId <- nodeIds ]
52 mapTermListRoot :: RepoCmdM env err m
53 => [ListId] -> NgramsType
54 -> m (Map Text (ListType, (Maybe Text)))
55 mapTermListRoot nodeIds ngramsType = do
56 ngrams <- getListNgrams nodeIds ngramsType
57 pure $ Map.fromList [(t, (_nre_list nre, _nre_root nre))
58 | (t, nre) <- Map.toList ngrams
62 filterListWithRoot :: ListType -> Map Text (ListType, Maybe Text)
63 -> Map Text (Maybe RootTerm)
64 filterListWithRoot lt m = Map.fromList
65 $ map (\(t,(_,r)) -> (t,r))
66 $ filter isGraphTerm (Map.toList m)
68 isGraphTerm (_t,(l, maybeRoot)) = case maybeRoot of
70 Just r -> case Map.lookup r m of
71 Nothing -> panic $ "Garg.API.Ngrams.Tools: filterWithRoot, unknown key: " <> r
72 Just (l',_) -> l' == lt
75 groupNodesByNgrams :: Map Text (Maybe RootTerm)
76 -> Map Text (Set NodeId)
77 -> Map Text (Set NodeId)
78 groupNodesByNgrams syn occs = Map.fromListWith (<>) occs'
80 occs' = map toSyn (Map.toList occs)
81 toSyn (t,ns) = case Map.lookup t syn of
82 Nothing -> panic $ "[Garg.API.Ngrams.Tools.groupNodesByNgrams] unknown key: " <> t
87 data Diagonal = Diagonal Bool
89 getCoocByNgrams :: Diagonal -> Map Text (Set NodeId) -> Map (Text, Text) Int
90 getCoocByNgrams (Diagonal diag) m =
91 Map.fromList [((t1,t2)
92 ,maybe 0 Set.size $ Set.intersection
95 ) | (t1,t2) <- case diag of
96 True -> [ (x,y) | x <- Map.keys m, y <- Map.keys m, x <= y]
97 False -> listToCombi identity (Map.keys m)