PhyloExport.hs 20.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
{-|
Module      : Gargantext.Viz.Phylo.PhyloExport
Description : Exportation module of a Phylo
Copyright   : (c) CNRS, 2017-Present
License     : AGPL + CECILL v3
Maintainer  : team@gargantext.org
Stability   : experimental
Portability : POSIX
-}

{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE FlexibleContexts  #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE MultiParamTypeClasses #-}
15 16
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances    #-}
17

18 19
module Gargantext.Viz.Phylo.PhyloExport where

qlobbe's avatar
qlobbe committed
20 21
import Data.Map (Map, fromList, empty, fromListWith, insert, (!), elems, unionWith, findWithDefault, toList)
import Data.List ((++), sort, nub, concat, sortOn, reverse, groupBy, union, (\\), (!!), init, partition, unwords, nubBy)
22 23
import Data.Vector (Vector)

qlobbe's avatar
qlobbe committed
24
import Prelude (writeFile)
25 26 27 28
import Gargantext.Prelude
import Gargantext.Viz.AdaptativePhylo
import Gargantext.Viz.Phylo.PhyloTools 

29
import Control.Lens
qlobbe's avatar
qlobbe committed
30
import Data.GraphViz hiding (DotGraph, Order)
31
import Data.GraphViz.Types.Generalised (DotGraph)
qlobbe's avatar
qlobbe committed
32 33
import Data.GraphViz.Attributes.Complete hiding (EdgeType, Order) 
import Data.GraphViz.Types.Monadic
qlobbe's avatar
qlobbe committed
34 35 36
import Data.Text.Lazy (fromStrict, pack, unpack)
import System.FilePath
import Debug.Trace (trace)
qlobbe's avatar
qlobbe committed
37 38

import qualified Data.Text as Text
qlobbe's avatar
qlobbe committed
39 40
import qualified Data.Text.Lazy as Lazy
import qualified Data.GraphViz.Attributes.HTML as H
41 42 43 44 45

--------------------
-- | Dot export | --
--------------------

qlobbe's avatar
qlobbe committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
dotToFile :: FilePath -> DotGraph DotId -> IO ()
dotToFile filePath dotG = writeFile filePath $ dotToString dotG

dotToString :: DotGraph DotId  -> [Char]
dotToString dotG = unpack (printDotGraph dotG)

dynamicToColor :: Double -> H.Attribute
dynamicToColor d 
  | d == 0    = H.BGColor (toColor LightCoral)
  | d == 1    = H.BGColor (toColor Khaki)
  | d == 2    = H.BGColor (toColor SkyBlue)
  | otherwise = H.Color   (toColor Black)

pickLabelColor :: [Double] -> H.Attribute
pickLabelColor lst
  | elem 0 lst = dynamicToColor 0
  | elem 2 lst = dynamicToColor 2
  | elem 1 lst = dynamicToColor 1
  | otherwise  = dynamicToColor 3  
65

qlobbe's avatar
qlobbe committed
66 67 68
toDotLabel :: Text.Text -> Label
toDotLabel lbl = StrLabel $ fromStrict lbl

qlobbe's avatar
qlobbe committed
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
toAttr :: AttributeName -> Lazy.Text -> CustomAttribute
toAttr k v = customAttribute k v

metaToAttr :: Map Text.Text [Double] -> [CustomAttribute]
metaToAttr meta = map (\(k,v) -> toAttr (fromStrict k) $ (pack . unwords) $ map show v) $ toList meta

groupIdToDotId :: PhyloGroupId -> DotId
groupIdToDotId (((d,d'),lvl),idx) = (fromStrict . Text.pack) $ ("group" <> (show d) <> (show d') <> (show lvl) <> (show idx))

branchIdToDotId :: PhyloBranchId -> DotId
branchIdToDotId bId = (fromStrict . Text.pack) $ ("branch" <> show (snd bId))

periodIdToDotId :: PhyloPeriodId -> DotId
periodIdToDotId prd = (fromStrict . Text.pack) $ ("period" <> show (fst prd) <> show (snd prd))

groupToTable :: Vector Ngrams -> PhyloGroup -> H.Label
groupToTable fdt g = H.Table H.HTable
                    { H.tableFontAttrs = Just [H.PointSize 14, H.Align H.HLeft]
                    , H.tableAttrs = [H.Border 0, H.CellBorder 0, H.BGColor (toColor White)]
                    , H.tableRows = [header]
                                 <> [H.Cells [H.LabelCell [H.Height 10] $ H.Text [H.Str $ fromStrict ""]]]
                                 <> ( map ngramsToRow $ splitEvery 4 
                                    $ reverse $ sortOn (snd . snd)
                                    $ zip (ngramsToText fdt (g ^. phylo_groupNgrams)) 
                                    $ zip ((g ^. phylo_groupMeta) ! "dynamics") ((g ^. phylo_groupMeta) ! "inclusion"))}
    where
        --------------------------------------
        ngramsToRow :: [(Ngrams,(Double,Double))] -> H.Row
        ngramsToRow ns = H.Cells $ map (\(n,(d,_)) -> 
                            H.LabelCell [H.Align H.HLeft,dynamicToColor d] $ H.Text [H.Str $ fromStrict n]) ns
        --------------------------------------
        header :: H.Row
        header = 
            H.Cells [ H.LabelCell [pickLabelColor ((g ^. phylo_groupMeta) ! "dynamics")] 
                    $ H.Text [H.Str $ (((fromStrict . Text.toUpper) $ g ^. phylo_groupLabel)
                                   <> (fromStrict " ( ")
                                   <> (pack $ show (fst $ g ^. phylo_groupPeriod))
                                   <> (fromStrict " , ")
                                   <> (pack $ show (snd $ g ^. phylo_groupPeriod))
                                   <> (fromStrict " ) "))]] 
        --------------------------------------

branchToDotNode :: PhyloBranch -> Dot DotId
branchToDotNode b = 
    node (branchIdToDotId $ b ^. branch_id)
         ([FillColor [toWColor CornSilk], FontName "Arial", FontSize 40, Shape Egg, Style [SItem Bold []], Label (toDotLabel $ b ^. branch_label)]
         <> (metaToAttr $ b ^. branch_meta)
         <> [ toAttr "nodeType" "branch"
117
            , toAttr "branchId" (pack $ unwords (map show $ snd $ b ^. branch_id)) ])
qlobbe's avatar
qlobbe committed
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
 
periodToDotNode :: (Date,Date) -> Dot DotId
periodToDotNode prd =
    node (periodIdToDotId prd)
         ([Shape Square, FontSize 50, Label (toDotLabel $ Text.pack (show (fst prd) <> " " <> show (snd prd)))]
         <> [ toAttr "nodeType" "period" 
            , toAttr "from" (fromStrict $ Text.pack $ (show $ fst prd))
            , toAttr "to"   (fromStrict $ Text.pack $ (show $ snd prd))])


groupToDotNode :: Vector Ngrams -> PhyloGroup -> Dot DotId
groupToDotNode fdt g = 
    node (groupIdToDotId $ getGroupId g)
                     ([FontName "Arial", Shape Square, toLabel (groupToTable fdt g)]
                      <> [ toAttr "nodeType" "group"
                         , toAttr "from" (pack $ show (fst $ g ^. phylo_groupPeriod))
                         , toAttr "to"   (pack $ show (snd $ g ^. phylo_groupPeriod))
135 136
                         , toAttr "branchId" (pack $ unwords (init $ map show $ snd $ g ^. phylo_groupBranchId))
                         , toAttr "support" (pack $ show (g ^. phylo_groupSupport))])  
qlobbe's avatar
qlobbe committed
137 138 139


toDotEdge :: DotId -> DotId -> Text.Text -> EdgeType -> Dot DotId
qlobbe's avatar
qlobbe committed
140
toDotEdge source target lbl edgeType = edge source target
qlobbe's avatar
qlobbe committed
141
    (case edgeType of
qlobbe's avatar
qlobbe committed
142
        GroupToGroup   -> [ Width 10, Color [toWColor Black], Constraint True
qlobbe's avatar
qlobbe committed
143 144 145 146 147 148 149 150 151 152
                          , Label (StrLabel $ fromStrict lbl)]
        BranchToGroup  -> [ Width 3, Color [toWColor Black], ArrowHead (AType [(ArrMod FilledArrow RightSide,DotArrow)])
                          , Label (StrLabel $ fromStrict lbl)]
        BranchToBranch -> [ Width 2, Color [toWColor Black], Style [SItem Dashed []], ArrowHead (AType [(ArrMod FilledArrow BothSides,DotArrow)])
                          , Label (StrLabel $ fromStrict lbl)]
        PeriodToPeriod -> [ Width 5, Color [toWColor Black]])


mergePointers :: [PhyloGroup] -> Map (PhyloGroupId,PhyloGroupId) Double
mergePointers groups = 
qlobbe's avatar
qlobbe committed
153 154
    let toChilds  = fromList $ concat $ map (\g -> map (\(target,w) -> ((getGroupId g,target),w)) $ g ^. phylo_groupPeriodChilds) groups
        toParents = fromList $ concat $ map (\g -> map (\(target,w) -> ((target,getGroupId g),w)) $ g ^. phylo_groupPeriodParents) groups
qlobbe's avatar
qlobbe committed
155 156
    in  unionWith (\w w' -> max w w') toChilds toParents

qlobbe's avatar
qlobbe committed
157 158 159

exportToDot :: Phylo -> PhyloExport -> DotGraph DotId
exportToDot phylo export = 
160 161
    trace ("\n-- | Convert " <> show(length $ export ^. export_branches) <> " branches and "
         <> show(length $ export ^. export_groups) <> " groups to a dot file\n") $
qlobbe's avatar
qlobbe committed
162 163
    digraph ((Str . fromStrict) $ (phyloName $ getConfig phylo)) $ do 

qlobbe's avatar
qlobbe committed
164 165 166 167
        -- | 1) init the dot graph
        graphAttrs ( [ Label (toDotLabel $ (phyloName $ getConfig phylo))]
                  <> [ FontSize 30, LabelLoc VTop, NodeSep 1, RankSep [1], Rank SameRank, Splines SplineEdges, Overlap ScaleOverlaps
                     , Ratio FillRatio
qlobbe's avatar
qlobbe committed
168 169 170 171 172 173 174 175
                     , Style [SItem Filled []],Color [toWColor White]]
                  -- | home made attributes
                  <> [(toAttr (fromStrict "nbDocs") $ pack $ show (sum $ elems $ phylo ^. phylo_timeDocs))
                     ,(toAttr (fromStrict "proxiName") $ pack $ show (getProximityName $ phyloProximity $ getConfig phylo))
                     ,(toAttr (fromStrict "proxiInit") $ pack $ show (getProximityInit $ phyloProximity $ getConfig phylo))
                     ,(toAttr (fromStrict "proxiStep") $ pack $ show (getProximityStep $ phyloProximity $ getConfig phylo))
                     ,(toAttr (fromStrict "quaFactor") $ pack $ show (_qua_relevance $ phyloQuality $ getConfig phylo))
                     ])
qlobbe's avatar
qlobbe committed
176 177 178


 -- toAttr (fromStrict k) $ (pack . unwords) $ map show v
qlobbe's avatar
qlobbe committed
179 180 181 182 183 184 185

        -- | 2) create a layer for the branches labels
        subgraph (Str "Branches peaks") $ do 

            graphAttrs [Rank SameRank]

            -- | 3) group the branches by hierarchy
qlobbe's avatar
qlobbe committed
186 187 188
            -- mapM (\branches -> 
            --         subgraph (Str "Branches clade") $ do
            --             graphAttrs [Rank SameRank]
qlobbe's avatar
qlobbe committed
189

qlobbe's avatar
qlobbe committed
190 191 192 193 194
            --             -- | 4) create a node for each branch
            --             mapM branchToDotNode branches
            --     ) $ elems $ fromListWith (++) $ map (\b -> ((init . snd) $ b ^. branch_id,[b])) $ export ^. export_branches

            mapM branchToDotNode $ export ^. export_branches
qlobbe's avatar
qlobbe committed
195 196

        -- | 5) create a layer for each period
qlobbe's avatar
qlobbe committed
197
        _ <- mapM (\period ->
qlobbe's avatar
qlobbe committed
198 199 200 201 202 203 204 205 206
                subgraph ((Str . fromStrict . Text.pack) $ ("Period" <> show (fst period) <> show (snd period))) $ do 
                    graphAttrs [Rank SameRank]
                    periodToDotNode period

                    -- | 6) create a node for each group 
                    mapM (\g -> groupToDotNode (getRoots phylo) g) (filter (\g -> g ^. phylo_groupPeriod == period) $ export ^. export_groups)
            ) $ getPeriodIds phylo

        -- | 7) create the edges between a branch and its first groups
qlobbe's avatar
qlobbe committed
207
        _ <- mapM (\(bId,groups) ->
qlobbe's avatar
qlobbe committed
208 209 210 211 212 213 214 215 216
                mapM (\g -> toDotEdge (branchIdToDotId bId) (groupIdToDotId $ getGroupId g) "" BranchToGroup) groups 
             )
           $ toList
           $ map (\groups -> head' "toDot" 
                           $ groupBy (\g g' -> g' ^. phylo_groupPeriod == g ^. phylo_groupPeriod)
                           $ sortOn (fst . _phylo_groupPeriod) groups) 
           $ fromListWith (++) $ map (\g -> (g ^. phylo_groupBranchId,[g])) $ export ^. export_groups

        -- | 8) create the edges between the groups
qlobbe's avatar
qlobbe committed
217
        _ <- mapM (\((k,k'),_) -> 
qlobbe's avatar
qlobbe committed
218 219 220 221
                toDotEdge (groupIdToDotId k) (groupIdToDotId k') "" GroupToGroup
            ) $ (toList . mergePointers) $ export ^. export_groups

        -- | 7) create the edges between the periods 
qlobbe's avatar
qlobbe committed
222
        _ <- mapM (\(prd,prd') ->
qlobbe's avatar
qlobbe committed
223 224 225 226
                toDotEdge (periodIdToDotId prd) (periodIdToDotId prd') "" PeriodToPeriod
            ) $ nubBy (\combi combi' -> fst combi == fst combi') $ listToCombi' $ getPeriodIds phylo

        -- | 8) create the edges between the branches 
qlobbe's avatar
qlobbe committed
227
        _ <- mapM (\(bId,bId') ->
qlobbe's avatar
qlobbe committed
228 229 230 231 232
                toDotEdge (branchIdToDotId bId) (branchIdToDotId bId') 
                (Text.pack $ show(branchIdsToProximity bId bId' 
                                    (getThresholdInit $ phyloProximity $ getConfig phylo)
                                    (getThresholdStep $ phyloProximity $ getConfig phylo))) BranchToBranch
            ) $ nubBy (\combi combi' -> fst combi == fst combi') $ listToCombi' $ map _branch_id $ export ^. export_branches
qlobbe's avatar
qlobbe committed
233 234 235 236


        graphAttrs [Rank SameRank]

qlobbe's avatar
qlobbe committed
237 238

        
qlobbe's avatar
qlobbe committed
239 240 241 242 243 244 245 246 247 248 249 250 251


----------------
-- | Filter | --
----------------

filterByBranchSize :: Double -> PhyloExport -> PhyloExport
filterByBranchSize thr export = 
    let branches' = partition (\b -> head' "filter" ((b ^. branch_meta) ! "size") >= thr) $ export ^. export_branches
    in  export & export_branches .~ (fst branches')
               & export_groups %~ (filter (\g -> not $ elem  (g ^. phylo_groupBranchId) (map _branch_id $ snd branches')))


252 253
processFilters :: [Filter] -> Quality -> PhyloExport -> PhyloExport
processFilters filters qua export = 
qlobbe's avatar
qlobbe committed
254
    foldl (\export' f -> case f of 
255 256 257
                ByBranchSize thr -> if (thr < (fromIntegral $ qua ^. qua_minBranch))
                                      then filterByBranchSize (fromIntegral $ qua ^. qua_minBranch) export'
                                      else filterByBranchSize thr export'  
qlobbe's avatar
qlobbe committed
258 259 260 261 262 263 264
        ) export filters

--------------
-- | Sort | --
--------------

sortByHierarchy :: Int -> [PhyloBranch] -> [PhyloBranch]
qlobbe's avatar
qlobbe committed
265 266 267 268 269
sortByHierarchy depth branches =
    if (length branches == 1)
        then branches
        else concat 
           $ map (\branches' ->
qlobbe's avatar
qlobbe committed
270 271 272
                    let partitions = partition (\b -> depth + 1 == ((length . snd) $ b ^. branch_id)) branches'
                    in  (sortOn (\b -> (b ^. branch_meta) ! "birth") (fst partitions))
                    ++  (sortByHierarchy (depth + 1) (snd partitions))) 
qlobbe's avatar
qlobbe committed
273 274
            $ groupBy (\b b' -> ((take depth . snd) $ b ^. branch_id) == ((take depth . snd) $ b' ^. branch_id) )
            $ sortOn (\b -> (take depth . snd) $ b ^. branch_id) branches
qlobbe's avatar
qlobbe committed
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289


sortByBirthDate :: Order -> PhyloExport -> PhyloExport
sortByBirthDate order export = 
    let branches  = sortOn (\b -> (b ^. branch_meta) ! "birth") $ export ^. export_branches
        branches' = case order of
                    Asc  -> branches
                    Desc -> reverse branches
    in  export & export_branches .~ branches'

processSort :: Sort -> PhyloExport -> PhyloExport
processSort sort' export = case sort' of
    ByBirthDate o -> sortByBirthDate o export 
    ByHierarchy   -> export & export_branches .~ sortByHierarchy 0 (export ^. export_branches)

290 291 292 293 294 295 296 297 298 299 300

-----------------
-- | Metrics | --
-----------------

-- | Return the conditional probability of i knowing j 
conditional :: Ord a => Map (a,a) Double -> a -> a -> Double
conditional m i j = (findWithDefault 0 (i,j) m) 
                  / (m ! (j,j))


qlobbe's avatar
qlobbe committed
301 302 303 304 305 306 307 308 309 310 311 312
-- | Return the genericity score of a given ngram
genericity :: Map (Int, Int) Double -> [Int] -> Int -> Double 
genericity m l i = ( (sum $ map (\j -> conditional m i j) l) 
                   - (sum $ map (\j -> conditional m j i) l)) / (fromIntegral $ (length l) + 1)


-- | Return the specificity score of a given ngram
specificity :: Map (Int, Int) Double -> [Int] -> Int -> Double 
specificity m l i = ( (sum $ map (\j -> conditional m j i) l)
                    - (sum $ map (\j -> conditional m i j) l)) / (fromIntegral $ (length l) + 1)                  


313 314 315 316 317 318
-- | Return the inclusion score of a given ngram
inclusion :: Map (Int, Int) Double -> [Int] -> Int -> Double 
inclusion m l i = ( (sum $ map (\j -> conditional m j i) l)
                  + (sum $ map (\j -> conditional m i j) l)) / (fromIntegral $ (length l) + 1)


qlobbe's avatar
qlobbe committed
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
ngramsMetrics :: PhyloExport -> PhyloExport
ngramsMetrics export =
    over ( export_groups
         .  traverse )
    (\g -> g & phylo_groupMeta %~ insert "genericity" 
                                  (map (\n -> genericity  (g ^. phylo_groupCooc) ((g ^. phylo_groupNgrams) \\ [n]) n) $ g ^. phylo_groupNgrams)
             & phylo_groupMeta %~ insert "specificity" 
                                  (map (\n -> specificity (g ^. phylo_groupCooc) ((g ^. phylo_groupNgrams) \\ [n]) n) $ g ^. phylo_groupNgrams)
             & phylo_groupMeta %~ insert "inclusion" 
                                  (map (\n -> inclusion   (g ^. phylo_groupCooc) ((g ^. phylo_groupNgrams) \\ [n]) n) $ g ^. phylo_groupNgrams)
        ) export


branchDating :: PhyloExport -> PhyloExport
branchDating export =
    over ( export_branches
         .  traverse )
    (\b -> 
        let groups = sortOn fst
                   $ foldl' (\acc g -> if (g ^. phylo_groupBranchId == b ^. branch_id)
                                      then acc ++ [g ^. phylo_groupPeriod]
                                      else acc ) [] $ export ^. export_groups
            birth = fst $ head' "birth" groups
            age   = (snd $ last' "age"  groups) - birth 
        in b & branch_meta %~ insert "birth" [fromIntegral birth] 
             & branch_meta %~ insert "age"   [fromIntegral age]
             & branch_meta %~ insert "size"  [fromIntegral $ length groups] ) export

processMetrics :: PhyloExport -> PhyloExport
processMetrics export = ngramsMetrics
                      $ branchDating export 


352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
-----------------
-- | Taggers | --
----------------- 

getNthMostMeta :: Int -> [Double] -> [Int] -> [Int]
getNthMostMeta nth meta ns = map (\(idx,_) -> (ns !! idx))
                           $ take nth
                           $ reverse
                           $ sortOn snd $ zip [0..] meta 


mostInclusive :: Int -> Vector Ngrams -> PhyloExport -> PhyloExport
mostInclusive nth foundations export =
    over ( export_branches
         .  traverse )
         (\b -> 
            let groups = filter (\g -> g ^. phylo_groupBranchId == b ^. branch_id) $ export ^. export_groups
                cooc   = foldl (\acc g -> unionWith (+) acc (g ^. phylo_groupCooc)) empty groups
                ngrams = sort $ foldl (\acc g -> union acc (g ^. phylo_groupNgrams)) [] groups
                inc    = map (\n -> inclusion cooc (ngrams \\ [n]) n) ngrams
                lbl    = ngramsToLabel foundations $ getNthMostMeta nth inc ngrams
            in b & branch_label .~ lbl ) export


mostEmergentInclusive :: Int -> Vector Ngrams -> PhyloExport -> PhyloExport
mostEmergentInclusive nth foundations export =
    over ( export_groups
         .  traverse ) 
         (\g -> 
            let lbl = ngramsToLabel foundations
                    $ take nth 
                    $ map (\(_,(_,idx)) -> idx)
                    $ concat
                    $ map (\groups -> sortOn (fst . snd) groups)
                    $ groupBy ((==) `on` fst) $ reverse $ sortOn fst                
                    $ zip ((g ^. phylo_groupMeta) ! "inclusion")
                    $ zip ((g ^. phylo_groupMeta) ! "dynamics") (g ^. phylo_groupNgrams)
            in g & phylo_groupLabel .~ lbl ) export


qlobbe's avatar
qlobbe committed
392
processLabels :: [PhyloLabel] -> Vector Ngrams -> PhyloExport -> PhyloExport
393 394 395 396 397 398 399 400 401
processLabels labels foundations export =
    foldl (\export' label -> 
                case label of
                    GroupLabel  tagger nth -> 
                        case tagger of
                            MostEmergentInclusive -> mostEmergentInclusive nth foundations export' 
                            _ -> panic "[ERR][Viz.Phylo.PhyloExport] unknown tagger"
                    BranchLabel tagger nth ->
                        case tagger of
qlobbe's avatar
qlobbe committed
402
                            MostInclusive -> mostInclusive nth foundations export'
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
                            _ -> panic "[ERR][Viz.Phylo.PhyloExport] unknown tagger" ) export labels 


------------------
-- | Dynamics | --
------------------ 


toDynamics :: Int -> [PhyloGroup] -> PhyloGroup -> Map Int (Date,Date) -> Double
toDynamics n parents group m = 
    let prd = group ^. phylo_groupPeriod
        end = last' "dynamics" (sort $ map snd $ elems m)
    in  if (((snd prd) == (snd $ m ! n)) && (snd prd /= end))
            -- | decrease
            then 2
        else if ((fst prd) == (fst $ m ! n))
            -- | recombination
            then 0
        else if isNew
            -- | emergence
            then 1
        else 3
    where
        -------------------------------------- 
        isNew :: Bool
        isNew = not $ elem n $ concat $ map _phylo_groupNgrams parents
429 430 431


processDynamics :: [PhyloGroup] -> [PhyloGroup]
432 433 434 435 436 437 438 439 440 441 442 443 444 445
processDynamics groups = 
    map (\g ->
        let parents = filter (\g' -> (g ^. phylo_groupBranchId == g' ^. phylo_groupBranchId)
                                  && ((fst $ g ^. phylo_groupPeriod) > (fst $ g' ^. phylo_groupPeriod))) groups
        in  g & phylo_groupMeta %~ insert "dynamics" (map (\n -> toDynamics n parents g mapNgrams) $ g ^. phylo_groupNgrams) ) groups
    where
        --------------------------------------
        mapNgrams :: Map Int (Date,Date)
        mapNgrams = map (\dates -> 
                        let dates' = sort dates
                        in (head' "dynamics" dates', last' "dynamics" dates'))
                  $ fromListWith (++)
                  $ foldl (\acc g -> acc ++ ( map (\n -> (n,[fst $ g ^. phylo_groupPeriod, snd $ g ^. phylo_groupPeriod])) 
                                            $ (g ^. phylo_groupNgrams))) [] groups
446 447 448 449 450 451 452 453


---------------------
-- | phyloExport | --
---------------------   


toPhyloExport :: Phylo -> DotGraph DotId
qlobbe's avatar
qlobbe committed
454
toPhyloExport phylo = exportToDot phylo
455
                    $ processFilters (exportFilter $ getConfig phylo) (phyloQuality $ getConfig phylo)
qlobbe's avatar
qlobbe committed
456 457 458
                    $ processSort    (exportSort   $ getConfig phylo)
                    $ processLabels  (exportLabel  $ getConfig phylo) (getRoots phylo)
                    $ processMetrics  export           
459 460 461 462 463
    where
        export :: PhyloExport
        export = PhyloExport groups branches
        --------------------------------------
        branches :: [PhyloBranch] 
qlobbe's avatar
qlobbe committed
464
        branches = traceExportBranches $ map (\bId -> PhyloBranch bId "" empty) $ nub $ map _phylo_groupBranchId groups
465
        --------------------------------------    
466
        groups :: [PhyloGroup]
qlobbe's avatar
qlobbe committed
467
        groups = processDynamics 
qlobbe's avatar
qlobbe committed
468 469 470
               $ getGroupsFromLevel (phyloLevel $ getConfig phylo) phylo


qlobbe's avatar
qlobbe committed
471 472
traceExportBranches :: [PhyloBranch] -> [PhyloBranch]
traceExportBranches branches = trace ("\n" <> "-- | Export " <> show(length branches) <> " branches") branches