import Data.List (tails)
import Data.List (sort)

data Concept = Top
             | Atomic ConceptName
             | Not Concept
             | Concept `And` Concept
             | Concept `Or` Concept
             | Exists RoleName Concept
             | All RoleName Concept
             | AtLeast Int RoleName
             | AtMost Int RoleName
             deriving (Eq, Ord, Show)

type ConceptName = String
type RoleName = String

infixl 5 `Or`
infixl 6 `And`

data Tableau = Tableau { nodes :: [Node],
                         edges :: [Edge],
                         tboxConcept :: Concept,
                         nextId :: Id,
                         ineqs :: [(Id,Id)]
                       } deriving (Eq, Show)

type Id = Int

data Node = Node { nid :: Id,
                   concepts :: [Concept]
                 } deriving (Eq, Ord, Show)

data Edge = Edge { parentId :: Id,
                   role :: RoleName,
                   childId :: Id
                 } deriving (Eq, Ord, Show)

-- nnf c = the negation normal form of the concept c.
nnf :: Concept -> Concept
nnf (Not (Not c)) = nnf c
nnf (Not (c1 `And` c2)) = nnf (Not c1) `Or`  nnf (Not c2)
nnf (Not (c1 `Or`  c2)) = nnf (Not c1) `And` nnf (Not c2)
nnf (Not (Exists r c))  = All r (nnf (Not c))
nnf (Not (All r c))     = Exists r (nnf (Not c))
nnf (Not (AtMost k r))  = AtLeast (k + 1) r
nnf (Not (AtLeast k r)) = if k > 0 then AtMost (k - 1) r
                          else Not Top
nnf (c1 `And` c2) = nnf c1 `And` nnf c2
nnf (c1 `Or` c2)  = nnf c1 `Or` nnf c2
nnf (Exists r c)  = Exists r (nnf c)
nnf (All r c)     = All r (nnf c)
nnf c = c

infixl 4 `Implies`
data Axiom = Concept `Implies` Concept

-- axiomConcept a = the concept derived from the axiom a.
axiomConcept :: Axiom -> Concept
axiomConcept (Top `Implies` c) = c
axiomConcept (c1 `Implies` c2) = Not c1 `Or` c2

-- tboxInternalise tbox = the concept derived from the list of
-- axioms tbox representing a TBox.
tboxInternalise :: [Axiom] -> Concept
tboxInternalise [] = Top
tboxInternalise tbox = nnf (foldl1 And cs)
      where cs = map axiomConcept tbox

-- initTableau c tbox = the initial tableau state
-- for checking the satisfiability of the concept c
-- w.r.t. the TBox, whose internalisation is the concept tbox.
initTableau :: Concept -> Concept -> [Tableau]
initTableau c tbox = [Tableau [n] [] ntbox 1 []]
    where n = Node 0 [nnf c,ntbox]
          ntbox = nnf tbox

-- models c tbox = the list of complete and clash-free tableau
-- states representing models of the concept c w.r.t. TBox tbox.
models :: Concept -> [Axiom] -> [Tableau]
models c tbox = tableau (initTableau c (tboxInternalise tbox))

-- satisfiable c tbox = True iff the concept c
-- is satisfiable w.r.t. TBox tbox.
satisfiable :: Concept -> [Axiom] -> Bool
satisfiable c tbox = not (null (models c tbox))

-- subsumes c1 c2 tbox = True iff concept c1 subsumes
-- concept c2 w.r.t. the TBox tbox.
subsumes :: Concept -> Concept -> [Axiom] -> Bool
subsumes c1 c2 tbox = not (satisfiable (Not c1 `And` c2) tbox)

type TableauTransformation = Tableau -> [Tableau]

-- tableau ts = the list of complete and clash-free tableaux
-- which can be derived from the elements of the input
-- tableau list ts by repeatedly applying transformation rules.
tableau :: [Tableau] -> [Tableau]
tableau ts = applyTransformations transformations ts
 where -- applyTransformations fs ts = the result of executing the
       -- tableau algorithm on the tableau list ts, assuming
       -- that only the transformations in fs can be used to
       -- process the first element of ts.
       applyTransformations _ [] = []
       applyTransformations [] (t : ts) = t : tableau ts
       applyTransformations (f : fs) (t : ts) =
                       if c then tableau ts'
                       else applyTransformations fs (t : ts)
           where -- c is true if the firing condition of the
                 -- transformation rule f holds, i.e. new
                 -- tableau state(s) are formed.
                 -- ts' denotes the list of states obtained
                 -- from the successful application of
                 -- the rule f for the tableau t, prepended
                 -- to the list ts.
                 (c,ts') = apply f t ts
       transformations = [clash,applyAnd,applyAll,applyAtMost,
                          applyOr,applyExists,applyAtLeast]

-- apply r t ts = a pair (b,ts'), where the Boolean value b is
-- True iff the transformation rule r fires for the tableau t;
-- the list ts' contains the transformed tableaux produced
-- by the rule r, prepended to the list ts.
apply :: (TableauTransformation -> Tableau ->
          [Tableau] -> (Bool,[Tableau]))
apply r t ts =
    (changed transformed_tableaux, transformed_tableaux ++ ts)
    where transformed_tableaux = r t
          changed [t'] = t /= t'
          changed _ = True

-- clash t = [] if tableau state t contains a clash,
--           [t] if t is clash-free.
clash :: TableauTransformation
clash t = if any check (nodes t) then [] else [t]

-- check n = True, if any of the clash conditions is met
-- in the label of node n, False otherwise.
check :: Node -> Bool
check n = (Not Top) `elem` cs ||
          any checkPair [(c1,c2) |
                         (c1 : c2s) <- tails cs, c2 <- c2s
                        ]
    where cs = concepts n
          checkPair (a,Not b) = a == b
          checkPair (Not b,a) = a == b
          checkPair (AtLeast k1 r1,AtMost k2 r2) =
              r1 == r2 && k1 > k2
          checkPair (AtMost k1 r1,AtLeast k2 r2) =
              r1 == r2 && k2 > k1
          checkPair _ = False


-- applyAnd t = [t'], where tableau t' is derived from t by
-- applying the intersection rule to each node of t, i.e.
-- unfolding each and-visible concept in the node.
applyAnd :: TableauTransformation
applyAnd t = [t {nodes = map andRule (nodes t)}]

-- andRule n = a node obtained from n by extending the
-- label of n with the and-visible components of its
-- intersection concepts.
andRule :: Node -> Node
andRule n = n {concepts = usort (andRule' (concepts n))}
  where -- andRule' cs = the list of non-intersection concepts
        -- and and-visible concepts found in cs.
        andRule' [] = []
        andRule' (c:cs) = c : unfold c (andRule' cs)
          where -- unfold c as = the list of and-visible
                -- components of c prepended to as
                unfold (c1 `And` c2) as = unfold c1 (unfold c2 as)
                unfold c as = c : as

-- applyAll t = [t'] where t' is a tableau state not more
-- constrained than t that contains all the possible changes
-- resulting from the application of the "forall" rule.
applyAll :: TableauTransformation
applyAll t = [t {nodes = allRule (nodes t) (edges t)}]

-- findNode ns id = the list of nodes that contains those
-- elements of the node list ns, whose identifier is id.
findNode :: [Node] -> Id -> [Node]
findNode ns id = filter f ns
   where f n = nid n == id

-- removeNode ns id = the list of nodes obtained from ns by
-- omitting the nodes with identifier id.
removeNode :: [Node] -> Id -> [Node]
removeNode ns id = filter f ns
   where f n = nid n /= id

-- allRule ns es = the list of nodes obtained by applying
-- the value restriction rule to all "forall" concepts in
-- all nodes of the tableau whose list of nodes is ns
-- and whose list of edges is es.
allRule :: [Node] -> [Edge] -> [Node]
allRule ns es = if null toDo then ns else allRule ns' es
 where -- toDo = the list of firings of the rule.
       toDo = [x | e <- es, n <- ns,
                   parentNode n e, x <- needAll e n]
       -- parentNode n e = true, iff the node n is the starting
       -- point of the directed edge e.
       parentNode n e = nid n == parentId e
       -- needAll e n = list of (id,c) pairs specifying that the
       -- concept c has to be added to the label of the node with
       -- identifier id. The identifier points to the end point
       -- of edge e.
       needAll e n = [(cid,d) | c <- concepts n, d <- match e c,
                                d `notElem` ccs]
          where cid = childId e
                ccs = concepts (head (findNode ns cid))
       -- match e c = [d], if c is a concept of the form
       -- (All r d), where role r is the label of edge e,
       -- [] otherwise.
       match e (All r d) = if r == role e then [d] else []
       match _ _ = []
       -- ns' = the list of nodes ns with the concepts
       -- specified in toDo added to the corresponding labels.
       ns' = foldl op ns toDo
       op ns idC = map (insert idC) ns
       -- insert (id,c) n = if the identifier of node n is id,
       -- then insert the concept c into n's label, otherwise
       -- leave n unchanged. Return the possibly modified node.
       insert (id,c) n0 = if nid n0 == id
                          then n0 {concepts = c : concepts n0}
                          else n0

-- successors pid r t = the list of node identifiers in
-- the tableau t that are the r-successors of the node with
-- identifier pid ("parent identifier").
successors :: Int -> RoleName -> Tableau -> [Id]
successors pid r t =
               [childId e | e <- edges t, match e]
    where match (Edge pid' r' _) = pid == pid' && r == r'

-- identifyNodes id1 id2 t = a pair (id,t'), where t' is the
-- tableau obtained from t by identifying nodes specified by
-- id1 and id2, and id is the identifier of the new node.
identifyNodes :: Id -> Id -> Tableau -> (Id,Tableau)
identifyNodes id1 id2 t =
          (id1,t {nodes = n : ns',
                  edges = usort (map modifyEdge (edges t)),
                  ineqs = usort (map modifyIneq (ineqs t))})
    where -- n = The node obtained by identifying n1 and n2.
          n = n1 {concepts = usort (concepts n1 ++ concepts n2)}
          -- n1, n2: the nodes with identifiers id1 and id2.
          ([n1],[n2]) = (findNode ns id1,findNode ns id2)
          ns = nodes t
          ns' = removeNode (removeNode ns id2) id1
          -- modifyEdge e = if either end of the edge is the node
          -- with identifier id2, then it is replaced by id1 in
          -- the return value. Otherwise the return value
          -- equals e.
          modifyEdge :: Edge -> Edge
          modifyEdge e =
             if      parentId e == id2 then e {parentId = id1}
             else if childId  e == id2 then e {childId = id1}
                  else e
          -- modifyIneq (x,y): if one of the elements of (x,y)
          -- is id2, then it is changed to id1, and the elements
          -- are swapped if necessary to have the smaller value
          -- in the first place.
          modifyIneq :: (Id,Id) -> (Id,Id)
          modifyIneq (x,y) =
              if x == id2 then pair id1 y
              else if y == id2 then pair id1 x else (x,y)

-- pair x y = the pair containing x and y such that the first
-- element of the pair is not greater than the second element.
pair :: Id -> Id -> (Id,Id)
pair x y = if x < y then (x,y) else (y,x)

-- identifyNodeList t ids = a tableau derived from t by
-- identifying the nodes specified by list of identifiers ids.
identifyNodeList :: Tableau -> [Id] -> Tableau
identifyNodeList t [] = t
identifyNodeList t (id : ids) = t'
    where (_,t') = foldl op (id,t) ids
          op (id1,t) id2 = identifyNodes id1 id2 t

-- applyAtMost t = the list of tableau states derived from t
-- by applying an at-most transformation, which results in
-- the least number of non-deterministic branches.
applyAtMost :: TableauTransformation
applyAtMost t = if null toDo then [t]
                else if any null toDo then []
                     else atMostRule (minimum (map lpair toDo))
    where toDo = foldl needAtMost [] [(nid n,k,r) |
                                      n <- nodes t,
                                      AtMost k r <- concepts n
                                     ]
          -- needAtMost ccs (id,k,r) = a list of colouring choices
          -- which includes the list ccs, as well as the
          -- colouring choice obtained for the k-colouring of the
          -- r-successors of node id in the tableau t, if the
          -- number of r-successors of node id is more than k.
          needAtMost ccs (id,k,r) =
             if length rss <= k then ccs
             else (colourings k rss (ineqs t)) : ccs
               where rss = successors id r t
          -- lpair lst = a pair whose first element is the length
          -- of the list lst and its second element is lst itself.
          lpair lst = (length lst,lst)
          -- atMostRule (l,cc) = list of tableau states derived
          -- from tableau t by applying the node identification
          -- transformations specified by each colouring
          -- in the colouring choice cc
          atMostRule (_,cc) = map (foldl identifyNodeList t) cc

-- applyOr t = the list of tableau states derived from t by
-- a single application of the union rule, if possible.
applyOr :: TableauTransformation
applyOr t = transform toDo
  where toDo = [(n,c) | n <- nodes t,
                c <- concepts n, orConcept c (concepts n)
               ]
        -- Verify the firing conditions of the union rule.
        orConcept (c1 `Or` c2) cs =
            (c1 `notElem` cs) && (c2 `notElem` cs)
        orConcept _ _ = False
        -- Perform a single union rule, if applicable.
        transform [] = [t]
        transform ((n,c1 `Or` c2) : _) =
          [t {nodes = n1 : nodes'}, t {nodes = n2 : nodes'}]
          where n1 = n {concepts = c1 : cs}
                n2 = n {concepts = c2 : cs}
                cs = concepts n
                nodes' = removeNode (nodes t) (nid n)

-- newEdge t dnodes pid r c = the tableau derived from t by adding
-- a new r-successor to the node with the identifier pid, where
-- the label of the r-successor contains the concept c. Also,
-- the list of the inequalities of the tableau is extended so
-- that the new node is distinct from any of the nodes
-- whose identifiers are supplied in the list dnodes.
newEdge ::
    Tableau -> [Id] -> Id -> RoleName -> Concept -> Tableau
newEdge t dnodes pid r c =
   t {nodes = n : nodes t, edges = e : edges t,
      nextId = newid + 1, ineqs = ineqs'
     }
   where n = Node newid [c,tboxConcept t]
         e = Edge pid r newid
         newid = nextId t
         -- The list of inequalities of the tableau t is extended
         -- with pairs (newid,id'), for each id' in dnodes.
         ineqs' = addIneqs newid (ineqs t) dnodes

-- addIneqs id ieqs ids = inequalities ieqs extended with all
-- (id,id') pairs where id' is an arbitrary element of ids.
addIneqs :: Id -> [(Id,Id)] -> [Id] -> [(Id,Id)]
addIneqs id = foldl op
   where op x id' = (id',id) : x

-- applyExists t = a list containing a single tableau state
-- derived from t by applying the exists rule at all nodes
-- where the rule is applicable.
applyExists :: TableauTransformation
applyExists t = [foldl makeEdgeAndNode t toDo]
  where ns = nodes t
        es = edges t
        -- toDo = a list of pairs (id,exc), where id is
        -- the identifier of a node whose label contains
        -- the existential concept exc, for which
        -- the exists rule has to be applied.
        toDo = [(nid n,c) | n <- ns, nonBlocked n ns es,
                c <- concepts n, match n c
               ]
        -- match n c = true iff the exist rule fires for
        -- the concept c appearing in the label of node n.
        match :: Node -> Concept -> Bool
        match n (Exists r c1) =
              all (notElem c1)
                  [(concepts node) |
                   id' <- successors (nid n) r t,
                   node <- findNode ns id'
                  ]
        match _ _ = False
        -- makeEdgeAndNode t (id,exc) = the tableau derived
        -- from t by the application of the exists rule for
        -- the concept exc and the node with the identifier id.
        makeEdgeAndNode t (id,Exists r c) =
            newEdge t [] id r c

-- applyAtLeast t = a list containing a single tableau state
-- derived from t by applying the at-least restriction
-- rule everywhere possible
applyAtLeast :: TableauTransformation
applyAtLeast t = [foldl (addEdge []) t toDo]
    where ns = nodes t
          es = edges t
          -- toDo = the list of the successor nodes to create,
          -- each as a triple (identifier,edge label,count)
          toDo = [(nid n,r,k) |
                  n <- ns, nonBlocked n ns es,
                  AtLeast k r <- concepts n,
                  k > length (successors (nid n) r t)
                 ]
          -- addEdge dnodes t (pid,r,k) =
          -- tableau t after adding k successor nodes that
          -- are connected to the node with identifier pid by
          -- edges with r in their label. The new nodes are
          -- pairwise distinct and also distinct from all the
          -- nodes in the list dnodes.
          addEdge dnodes t (pid,r,k) =
              if k < 1 then t
              else addEdge (nextId t : dnodes) t' (pid,r,k - 1)
              where t' = newEdge t dnodes pid r Top

-- ancestors n ns es = the list of ancestors of n
-- in the tableau specified by ns and es.
ancestors :: Node -> [Node] -> [Edge] -> [Node]
ancestors n ns es = [anc | ancid <- ancestorIds (nid n),
                           anc <- findNode ns ancid
                    ]
 where -- ancestorIds id = the list of identifiers of the
       -- ancestor nodes of the node with the identifier id.
       ancestorIds id = if null pids then []
                        else pid : ancestorIds pid
             where -- pids = the singleton list containing the
                   -- identifier of the parent of the node with
                   -- the identifier id;
                   -- or [], if no such parent exists.
                   pids = [parentId e | e <- es, childId e == id]
                   pid = head pids

-- nonBlocked n ns es = node n is not blocked by
-- any of its ancestors in the tableau
-- specified by ns and es.
nonBlocked :: Node -> [Node] -> [Edge] -> Bool
nonBlocked n ns es =
        not (any (blocks (concepts n)) (ancestors n ns es))
  where -- blocks cs anc = True if, and only if, every
        -- concept in the list cs is also found in
        -- the label of the node anc.
        blocks cs anc = all isIn cs
          where isIn x = x `elem` (concepts anc)


-- unique lst = the list obtained from lst by replacing
-- any maximal sequence of equal elements by a single
-- member of the sequence.
unique :: Eq a => [a] -> [a]
unique (x : y : lst) = if x == y then unique (y : lst)
                   else x:unique (y : lst)
unique lst = lst

-- usort lst = a sorted list containing the
-- distinct elements of lst.
usort :: Ord a => [a] -> [a]
usort = unique . sort

type Partition = [Int]
type Colouring = [Partition]

-- colourings k ns es = the list of all colourings, using
-- exactly k colours, of the graph whose set of
-- nodes and edges is ns and es, respectively.
colourings :: Int -> [Int] -> [(Int,Int)] -> [Colouring]
colourings k ns es = map first (pcolourings ns pcs0)
    where pcs0 = [([],k,length ns)]
          first (a,_,_) = a
          pcolourings [] pcs = pcs
          pcolourings (n : ns) pcs =
                   pcolourings ns
                               [pc' | pc <- pcs,
                                      pc' <- colourNode pc n es
                               ]

type PartialColouring = ([Partition],Int,Int)

-- select lst = the list of all pairs (e,lst') where e is
-- an element of lst and lst' is obtained from lst by removing e.
select :: [a] -> [(a,[a])]
select [] = []
select (head : tail) = (head,tail) : map sel (select tail)
   where sel (elem,lst) = (elem,head : lst)

-- noEdge id ids es = True iff the node with identifier id
-- does not share an edge with any of the nodes in ids,
-- given the list of edges es.
noEdge :: Id -> [Id] -> [(Id,Id)] -> Bool
noEdge id ids es = all noEdge' ids
   where noEdge' id' = (pair id id') `notElem` es

-- colourNode pc0 n es = the list of all partial colourings that
-- can be derived from pc0 by colouring the node n, observing
-- the constraints given by graph edges es.
colourNode ::
   PartialColouring -> Int -> [(Int,Int)] -> [PartialColouring]
colourNode pc0 n es =
       -- We have less nodes than colours available,
       -- thus the graph cannot be coloured:
       if (an < ac) then []
       -- Colours and nodes available are equal in number,
       -- so we have to put n into a new partition:
       else if (an == ac) then [newp]
            -- We still have colours to use, so we can start a
            -- new partition, or extend an existing one:
            else if (ac > 0) then newp:exps
                 -- There are no more colours to use,
                 -- we have to extend an existing partition:
                 else exps
   where (cps,ac,an) = pc0
         -- newp = pc0 extended with a new singleton
         -- partition [n].
         newp = ([n] : cps,ac - 1,an - 1)
         -- exps = the list of all possible partial colourings
         -- where n is put into an existing partition of pc0.
         exps = foldl ins [] (select cps)
         -- ins exps (cp,cps) = add the partial colouring
         -- in which n is put into the partition cp to the list
         -- exps, if this partial colouring is allowed.
         -- Otherwise return exps unchanged.
         ins exps0 (cp,cps) =
              -- If n does not share any edge with any other node
              -- in cp, given the edge list es,
              if noEdge n cp es
              -- then build a new partial colouring,
              -- where n is put into the partition cp,
              -- and prepend it to exps0;
              then ((n : cp) : cps,ac,an - 1) : exps0
              -- otherwise return exps0 itself.
              else exps0

