2 Module : Gargantext.API.Ngrams.NTree
3 Description : Tree of Ngrams
4 Copyright : (c) CNRS, 2017-Present
5 License : AGPL + CECILL v3
6 Maintainer : team@gargantext.org
7 Stability : experimental
12 {-# LANGUAGE TemplateHaskell #-}
14 module Gargantext.API.Ngrams.NTree
17 import Data.Aeson.TH (deriveJSON)
18 import Data.Text (Text)
20 import Data.Maybe (catMaybes)
24 import qualified Data.Set as Set
25 import qualified Data.Map as Map
26 import qualified Data.List as List
27 import GHC.Generics (Generic)
28 import Test.QuickCheck
30 import Gargantext.Prelude
32 import Gargantext.API.Ngrams.Types
33 import Gargantext.Core.Types (ListType(..), NodeId)
34 import Gargantext.Core.Utils.Prefix (unPrefix, unPrefixSwagger)
39 data MyTree = MyTree { mt_label :: Text
41 , mt_children :: [MyTree]
42 } deriving (Generic, Show)
44 toMyTree :: Tree (Text,Double) -> MyTree
45 toMyTree (Node (l,v) xs) = MyTree l v (map toMyTree xs)
47 deriveJSON (unPrefix "mt_") ''MyTree
49 instance ToSchema MyTree where
50 declareNamedSchema = genericDeclareNamedSchema (unPrefixSwagger "mt_")
51 instance Arbitrary MyTree
53 arbitrary = MyTree <$> arbitrary <*> arbitrary <*> arbitrary
55 toTree :: ListType -> Map Text (Set NodeId) -> Map Text NgramsRepoElement -> [MyTree]
56 toTree lt vs m = map toMyTree $ unfoldForest buildNode roots
58 buildNode r = maybe ((r, value r),[])
59 (\x -> ((r, value r), unNgramsTerm <$> (mSetToList $ _nre_children x)))
62 value l = maybe 0 (fromIntegral . Set.size) $ Map.lookup l vs
64 rootsCandidates :: [NgramsTerm]
65 rootsCandidates = catMaybes
67 $ map (\(c, c') -> case _nre_root c' of
68 Nothing -> Just $ NgramsTerm c
69 _ -> _nre_root c') (Map.toList m)
72 $ filter (\(_,l) -> l == lt)
74 $ map (\c -> (,) <$> Just c <*> (_nre_list <$> Map.lookup c m))
75 $ (unNgramsTerm <$> rootsCandidates)