update GArrowTikZ.hs; still not finished, though
[coq-hetmet.git] / examples / GArrowTikZ.hs
1 {-# OPTIONS_GHC -XModalTypes -XMultiParamTypeClasses -XNoMonoPatBinds -XKindSignatures -XGADTs -XFlexibleContexts -XFlexibleInstances -XTypeOperators -XUndecidableInstances #-}
2 --module GArrowTikZ
3 --where
4 import Prelude hiding ( id, (.), lookup )
5 import Control.Category
6 import GHC.HetMet.GArrow
7 import Data.List hiding (lookup, insert)
8 import Data.Map hiding (map, (!))
9 import Unify
10
11
12 {-
13 TO DO:
14     - have "resolve" turn a (Diagram UnifVal) into (Diagram Int)
15     - custom rendering
16     - bias right now is for all edges to be uppermost; try for bias
17       towards smallest nodes?
18     - curvy boxes (like XOR gates)
19 -}
20
21
22 -- a unification value is basically a LISP-ish expression
23 data UVal =
24    UVVar  UVar
25  | UVVal  [UVal]
26
27 instance Unifiable UVal where
28   unify' (UVVal vl1) (UVVal vl2)
29       | length vl1 /= length vl2  = error "length mismatch during unification"
30       | otherwise                 = foldr mergeU emptyUnifier (map (\(x,y) -> unify x y) $ zip vl1 vl2)
31   unify' _ _                      = error "impossible"
32   inject                          = UVVar
33   project (UVVar v)               = Just v
34   project _                       = Nothing
35   occurrences (UVVar v)           = [v]
36   occurrences (UVVal vl)          = concatMap occurrences vl
37
38 -- | Resolves a unification variable; the answer to this query will change if subsequent unifications are performed
39 getU' :: Unifier UVal -> UVal -> UVal
40 getU' u (UVVal vl)    = UVVal $ map (getU' u) vl
41 getU' u x@(UVVar v)   = case Unify.getU u v  of
42                                      Nothing -> x
43                                      Just x' -> getU' u x'
44
45
46
47
48 --
49 -- | Render a fully-polymorphic GArrow term as a boxes-and-wires diagram using TikZ
50 --
51
52 type Constraints = [(UVal, Int, UVal)]
53
54 -- the unification monad
55 data UyM t a = UyM (([UVar],Unifier UVal,Constraints) -> ([UVar],Unifier UVal,Constraints,a))
56 instance Monad (UyM t)
57  where
58   return x      = UyM $ \(i,u,k) -> (i,u,k,x)
59   (UyM f) >>= g = UyM $ \(i,u,k) -> let (i',u',k',x) = f (i,u,k) in let UyM g' = g x in g' (i',u',k')
60
61
62 getU        = UyM $ \(i,u,k) -> (i,u,k,u)
63 getM    v   = UyM $ \(i,u,k) -> (i,u,k,getU' u v)
64 occursU v x = UyM $ \(i,u,k) -> (i,u,k,occurs u v x)
65 unifyM :: Eq t => UVal -> UVal -> UyM t ()
66 unifyM v1 v2 = UyM $ \(i,u,k) -> (i,mergeU u (unify v1 v2),k,())
67 freshU :: UyM t UVar
68 freshU = UyM $ \(i:is,u,k) -> (is,u,k,i)
69 constrain :: UVal -> Int -> UVal -> UyM t ()
70 constrain v1 d v2 = UyM $ \(i,u,k) -> (i,u,((v1,d,v2):k),())
71 getK :: UyM t [(UVal, Int, UVal)]
72 getK = UyM $ \(i,u,k) -> (i,u,k,k)
73 runU :: UyM t a -> ([UVar],Unifier UVal,Constraints,a)
74 runU (UyM f) = (f (uvarSupply,emptyUnifier,[]))
75
76 data GArrowTikZ :: * -> * -> *
77  where
78   TikZ_id        ::                                     GArrowTikZ x x
79   TikZ_comp      :: GArrowTikZ y z -> GArrowTikZ x y -> GArrowTikZ x z
80   TikZ_first     :: GArrowTikZ x y                   -> GArrowTikZ (x**z)  (y**z)
81   TikZ_second    :: GArrowTikZ x y                   -> GArrowTikZ (z**x)  (z**y)
82   TikZ_cancell   ::                                     GArrowTikZ (()**x) x
83   TikZ_cancelr   ::                                     GArrowTikZ (x**()) x
84   TikZ_uncancell ::                                     GArrowTikZ x (()**x)
85   TikZ_uncancelr ::                                     GArrowTikZ x (x**())
86   TikZ_assoc     ::                                     GArrowTikZ ((x**y)**z) (x**(y**z))
87   TikZ_unassoc   ::                                     GArrowTikZ (x**(y**z)) ((x**y)**z)
88   TikZ_drop      ::                                     GArrowTikZ x         ()
89   TikZ_copy      ::                                     GArrowTikZ x         (x**x)
90   TikZ_swap      ::                                     GArrowTikZ (x**y)     (y**x)
91   TikZ_merge     ::                                     GArrowTikZ (x**y)     z
92   TikZ_loopl     ::           GArrowTikZ (x**z) (y**z) -> GArrowTikZ x y
93   TikZ_loopr     ::           GArrowTikZ (z**x) (z**y) -> GArrowTikZ x y
94
95 --
96 -- Technically this instance violates the laws (and RULEs) for
97 -- Control.Category; the compiler might choose to optimize (f >>> id)
98 -- into f, and this optimization would produce a change in behavior
99 -- below.  In practice this means that the user must be prepared for
100 -- the rendered TikZ diagram to be merely *equivalent to* his/her
101 -- term, rather than structurally exactly equal to it.
102 --
103 instance Category GArrowTikZ where
104   id           = TikZ_id
105   (.)          = TikZ_comp
106
107 instance GArrow GArrowTikZ (**) () where
108   ga_first     = TikZ_first
109   ga_second    = TikZ_second
110   ga_cancell   = TikZ_cancell
111   ga_cancelr   = TikZ_cancelr
112   ga_uncancell = TikZ_uncancell
113   ga_uncancelr = TikZ_uncancelr
114   ga_assoc     = TikZ_assoc
115   ga_unassoc   = TikZ_unassoc
116
117 instance GArrowDrop GArrowTikZ (**) () where
118   ga_drop      = TikZ_drop
119
120 instance GArrowCopy GArrowTikZ (**) () where
121   ga_copy      = TikZ_copy
122
123 instance GArrowSwap GArrowTikZ (**) () where
124   ga_swap      = TikZ_swap
125
126 instance GArrowLoop GArrowTikZ (**) () where
127   ga_loopl     = TikZ_loopl
128   ga_loopr     = TikZ_loopr
129
130 name :: GArrowTikZ a b -> String
131 name TikZ_id              = "id"
132 name (TikZ_comp      _ _) = "comp"
133 name (TikZ_first     _  ) = "first"
134 name (TikZ_second    _  ) = "second"
135 name TikZ_cancell         = "cancell"
136 name TikZ_cancelr         = "cancelr"
137 name TikZ_uncancell       = "uncancell"
138 name TikZ_uncancelr       = "uncancelr"
139 name TikZ_drop            = "drop"
140 name TikZ_copy            = "copy"
141 name TikZ_swap            = "swap"
142 name (TikZ_loopl     _ )  = "loopl"
143 name (TikZ_loopr     _ )  = "loopr"
144 name TikZ_assoc           = "assoc"
145 name TikZ_unassoc         = "unassoc"
146
147 fresh1 :: UyM () Ports
148 fresh1 = do { x <- freshU
149             ; return $ UVVar x
150             }
151
152 fresh2 :: UyM () (Ports,Ports)
153 fresh2 = do { x <- freshU
154             ; y <- freshU
155             ; constrain (UVVar x) 1 (UVVar y)
156             ; return $ (UVVar x,UVVar y)
157             }
158
159 fresh3 :: UyM () (Ports,Ports,Ports)
160 fresh3 = do { x <- freshU
161             ; y <- freshU
162             ; z <- freshU
163             ; constrain (UVVar x) 1 (UVVar y)
164             ; constrain (UVVar y) 1 (UVVar z)
165             ; return $ (UVVar x,UVVar y,UVVar z)
166             }
167
168 fresh4 :: UyM () (Ports,Ports,Ports,Ports)
169 fresh4 = do { x1 <- freshU
170             ; x2 <- freshU
171             ; x3 <- freshU
172             ; x4 <- freshU
173             ; constrain (UVVar x1) 1 (UVVar x2)
174             ; constrain (UVVar x2) 1 (UVVar x3)
175             ; constrain (UVVar x3) 1 (UVVar x4)
176             ; return $ (UVVar x1,UVVar x2,UVVar x3,UVVar x4)
177             }
178
179 fresh5 :: UyM () (Ports,Ports,Ports,Ports,Ports)
180 fresh5 = do { x1 <- freshU
181             ; x2 <- freshU
182             ; x3 <- freshU
183             ; x4 <- freshU
184             ; x5 <- freshU
185             ; constrain (UVVar x1) 1 (UVVar x2)
186             ; constrain (UVVar x2) 1 (UVVar x3)
187             ; constrain (UVVar x3) 1 (UVVar x4)
188             ; constrain (UVVar x4) 1 (UVVar x5)
189             ; return $ (UVVar x1,UVVar x2,UVVar x3,UVVar x4,UVVar x5)
190             }
191
192
193
194
195 example = ga_first ga_drop >>> ga_cancell >>> ga_first id >>> ga_swap >>> ga_first id >>> TikZ_merge
196 --example :: forall x y z. forall g. (GArrow g (,) (), GArrowCopy g (,) (), GArrowSwap g (,) ()) => g x ((x,x),x)
197 --example = ga_copy >>> ga_second ga_copy >>> ga_second (ga_first id) >>> ga_unassoc >>> ga_first ga_swap
198 --example = ga_copy >>> ga_second ga_copy >>> ga_second (ga_second id) >>> ga_unassoc >>> ga_first id >>> ga_first ga_swap
199 --example :: forall x. forall g. (GArrow g (,) (), GArrowCopy g (,) (), GArrowSwap g (,) ()) => g x x
200 --example = id >>> id
201
202 data Diagram p = DiagramComp      (Diagram p) (Diagram p)
203                | DiagramPrim      String p p p p (String -> Int -> Int -> Int -> p -> p -> Int -> String)
204                | DiagramBypassTop p (Diagram p)
205                | DiagramBypassBot (Diagram p) p
206                -- | DiagramLoopTop   Diagram
207                -- | DiagramLoopBot   Diagram
208
209 type Ports = UVal
210
211 getOut :: Diagram Ports -> Ports
212 getOut (DiagramComp f g)                     = getOut g
213 getOut (DiagramPrim s ptop pin pout pbot _)  = pout
214 getOut (DiagramBypassTop p f)                = UVVal [p, (getOut f)]
215 getOut (DiagramBypassBot f p)                = UVVal [(getOut f), p]
216
217 getIn :: Diagram Ports -> Ports
218 getIn (DiagramComp f g)                      = getIn f
219 getIn (DiagramPrim s ptop pin pout pbot _)   = pin
220 getIn (DiagramBypassTop p f)                 = UVVal [p, (getIn f)]
221 getIn (DiagramBypassBot f p)                 = UVVal [(getIn f), p]
222
223 -- constrain that Ports is at least Int units above the topmost portion of Diagram
224 constrainTop :: Ports -> Int -> Diagram Ports -> UyM () ()
225 constrainTop v i (DiagramComp d1 d2)                  = do { constrainTop v i d1 ; constrainTop v i d2 ; return () }
226 constrainTop v i (DiagramBypassTop p d)               = constrain v 2 p
227 constrainTop v i (DiagramBypassBot d p)               = constrainTop v (i+1) d
228 constrainTop v i (DiagramPrim s ptop pin pout pbot _) = constrain v i ptop
229
230 -- constrain that Ports is at least Int units below the bottommost portion of Diagram
231 constrainBot :: Diagram Ports -> Int -> Ports -> UyM () ()
232 constrainBot (DiagramComp d1 d2)                  i v = do { constrainBot d1 i v ; constrainBot d2 i v ; return () }
233 constrainBot (DiagramBypassTop p d)               i v = constrainBot d (i+1) v
234 constrainBot (DiagramBypassBot d p)               i v = constrain p 2 v
235 constrainBot (DiagramPrim s ptop pin pout pbot _) i v = constrain pbot i v
236
237 ga2diag :: GArrowTikZ a b -> UyM () (Diagram Ports)
238 ga2diag (TikZ_id           ) = do { (top,x,bot) <- fresh3 ; return $ DiagramPrim "id" top x x bot defren }
239 ga2diag (TikZ_comp      g f) = do { f' <- ga2diag f
240                                   ; g' <- ga2diag g
241                                   ; unifyM (getOut f') (getIn g')
242                                   ; return $ DiagramComp f' g' }
243 ga2diag (TikZ_first  f)=do { x <- fresh1; f' <- ga2diag f ; constrainBot f' 1 x  ; return $ DiagramBypassBot f' x  }
244 ga2diag (TikZ_second f)=do { x <- fresh1; f' <- ga2diag f ; constrainTop x  1 f' ; return $ DiagramBypassTop x f'  }
245 ga2diag TikZ_cancell  = do { (top,x,y  ,bot) <- fresh4  ; return $ DiagramPrim   "cancell" top (UVVal [x,y]) y bot defren }
246 ga2diag TikZ_cancelr  = do { (top,x,y  ,bot) <- fresh4  ; return $ DiagramPrim   "cancelr" top (UVVal [x,y]) x bot defren }
247 ga2diag TikZ_uncancell= do { (top,x,y  ,bot) <- fresh4  ; return $ DiagramPrim "uncancell" top y (UVVal [x,y]) bot defren }
248 ga2diag TikZ_uncancelr= do { (top,x,y  ,bot) <- fresh4  ; return $ DiagramPrim "uncancelr" top x (UVVal [x,y]) bot defren }
249 ga2diag TikZ_drop     = do { (top,x    ,bot) <- fresh3  ; return $ DiagramPrim      "drop" top x x bot defren }
250 ga2diag TikZ_copy     = do { (top,x,y,z,bot) <- fresh5
251                            ; return $ DiagramPrim      "copy" top y (UVVal [x,z]) bot defren }
252 ga2diag TikZ_merge    = do { (top,x,y,z,bot) <- fresh5
253                            ; return $ DiagramPrim      "merge" top (UVVal [x,z]) y bot defren }
254 ga2diag TikZ_swap     = do { (top,x,y  ,bot) <- fresh4
255                            ; return $ DiagramPrim      "swap" top (UVVal [x,y]) (UVVal [x,y]) bot defren }
256 ga2diag TikZ_assoc    = do { (top,x,y,z,bot) <- fresh5
257                            ; return $ DiagramPrim  "assoc" top (UVVal [UVVal [x,y],z])(UVVal [x,UVVal [y,z]]) bot defren }
258 ga2diag TikZ_unassoc  = do { (top,x,y,z,bot) <- fresh5
259                            ; return $ DiagramPrim "unassoc" top (UVVal [x,UVVal [y,z]])(UVVal [UVVal [x,y],z]) bot defren }
260 ga2diag (TikZ_loopl f) = error "not implemented"
261 ga2diag (TikZ_loopr f) = error "not implemented"
262
263 defren :: String -> Int -> Int -> Int -> Ports -> Ports -> Int -> String
264 defren s x w top p1 p2 bot
265       = drawBox x top (x+w) bot "black" s
266 --        ++ wires (x-1) p1  x    "green"
267 --        ++ wires  (x+w) p2 (x+w+1) "red"
268
269 xscale = 1
270 yscale = 1
271
272 textc x y text color = 
273     "\\node[anchor=center,color="++color++"] at ("++show (x*xscale)++"cm,"++show (y*yscale)++"cm) "++
274     "{{\\tt{"++text++"}}};\n"
275
276 drawBox x1 y1 x2 y2 color text =
277     "\\node[anchor=north west] at ("++show (x1*xscale)++"cm,"++show (y1*yscale)++"cm) "++
278     "{{\\tt{"++text++"}}};\n"
279     ++
280     "\\path[draw,color="++color++"]"++
281        " ("++show (x1*xscale)++","++show (y1*yscale)++") rectangle ("++
282            show (x2*xscale)++","++show (y2*yscale)++");\n"
283
284 drawLine x1 y1 x2 y2 color style =
285   "\\path[draw,color="++color++","++style++"] "++
286   "("++show (x1*xscale)++","++show (y1*yscale)++") -- " ++
287   "("++show (x2*xscale)++","++show (y2*yscale)++");\n"
288
289 width :: Diagram Ports -> Int
290 width (DiagramComp d1 d2)         = (width d1) + 1 + (width d2)
291 width (DiagramPrim s _ p1 p2 _ _) = 2
292 width (DiagramBypassTop p d)      = (width d) + 2
293 width (DiagramBypassBot d p)      = (width d) + 2
294
295 (!) :: Map UVar Int -> UVar -> Int
296 m ! x = case lookup x m of
297           Nothing -> 0
298           Just y -> y
299
300 tikZ :: Map UVar Int ->
301         Diagram Ports ->
302         Int ->                -- horizontal position
303         String
304 tikZ m = tikZ'
305  where
306   tikZ'  d@(DiagramComp d1 d2)    x = tikZ' d1 x
307                                       ++ wires (x+width d1) (getOut d1) (x+width d1+1) "black"
308                                       ++ tikZ' d2 (x + width d1 + 1)
309   tikZ' d'@(DiagramBypassTop p d) x = let top = getTop d' in
310                                       let bot = getBot d' in
311                                       drawBox  x top (x+width d') bot "gray!50" "second"
312                                       ++ drawLine x (top+1) (x+width d') (top+1) "black" "->"
313                                       ++ wires x (getIn d) (x+1) "black"
314                                       ++ tikZ' d (x+1)
315                                       ++ wires (x+1+width d) (getOut d) (x+1+width d+1) "black"
316   tikZ' d'@(DiagramBypassBot d p) x = let top = getTop d' in
317                                       let bot = getBot d' in
318                                       drawBox  x top (x+width d') bot "gray!50" "first"
319                                       ++ drawLine x (bot-1) (x+width d') (bot-1) "black" "->"
320                                       ++ wires x (getIn d) (x+1) "black"
321                                       ++ tikZ' d (x+1)
322                                       ++ wires (x+1+width d) (getOut d) (x+1+width d+1) "black"
323   tikZ'  d@(DiagramPrim s (UVVar top) p1 p2 (UVVar bot) r)  x = r s x (width d) (m ! top) p1 p2 (m ! bot)
324
325   wires :: Int -> Ports -> Int -> String -> String
326   wires x1 (UVVar v)    x2 color = drawLine x1 (m ! v) x2 (m ! v) color "->"
327                                   -- ++ textc ((x1+x2) `div` 2) (m!v) (show v) "purple"
328   wires x1 (UVVal vl) x2 color = foldr (\x y -> x ++ " " ++ y) [] (map (\v -> wires x1 v x2 color) vl)
329
330   getTop :: Diagram Ports -> Int
331   getTop (DiagramComp d1 d2)                = min (getTop d1) (getTop d2)
332   getTop (DiagramBypassTop p d)             = (m ! getleft p) - 1
333   getTop (DiagramBypassBot d p)             = getTop d - 1
334   getTop (DiagramPrim s (UVVar ptop) _ _ _ _)  = m ! ptop
335
336   getBot :: Diagram Ports -> Int
337   getBot (DiagramComp d1 d2)                = max (getBot d1) (getBot d2)
338   getBot (DiagramBypassTop p d)             = getBot d + 1
339   getBot (DiagramBypassBot d p)             = (m ! getright p) + 1
340   getBot (DiagramPrim s _ _ _ (UVVar pbot) _)  = m ! pbot
341
342 resolve' (DiagramComp d1 d2)    = do { d1' <- resolve' d1 ; d2' <- resolve' d2 ; return $ DiagramComp d1' d2'    }
343 resolve' (DiagramBypassTop p d) = do { p'  <- getM p     ; d'  <- resolve' d  ; return $ DiagramBypassTop p' d' }
344 resolve' (DiagramBypassBot d p) = do { p'  <- getM p     ; d'  <- resolve' d  ; return $ DiagramBypassBot d' p' }
345 resolve' (DiagramPrim s ptop pin pout pbot r) 
346     = do { ptop' <- getM ptop
347          ; pbot' <- getM pbot
348          ; pin'  <- getM pin
349          ; pout' <- getM pout
350          ; return $ DiagramPrim s ptop' pin' pout' pbot' r }
351
352 getleft (UVVar   v)  = v
353 getleft (UVVal  vl) = getleft (head vl)
354
355 getright (UVVar   v)  = v
356 getright (UVVal  vl) = getright (last vl)
357
358 strip :: [(Ports,Int,Ports)] -> [(UVar,Int,UVar)]
359 strip = map (\(v1,x,v2) -> (getright v1, x, getleft v2))
360
361
362 -- must use bubblesort because the ordering isn't transitive
363 sortit :: [(UVar,Int,UVar)] -> [(UVar,Int,UVar)]
364 sortit x = stupidSort x []
365  where
366   stupidSort []    x = x
367   stupidSort (h:t) x = stupidSort t (stupidInsert h x)
368
369   stupidInsert t []    = [t]
370   stupidInsert t@(_,_,t') ((a@(_,_,a')):b) = if cmp' x t' a' == LT
371                                              then t:a:b
372                                              else a:(stupidInsert t b)
373   
374   cmp' :: [(UVar,Int,UVar)] -> UVar -> UVar -> Ordering
375   cmp' [] a b = EQ -- compare a b
376   cmp' ((v1,_,v2):r) a b = if a == v1 && b==v2
377                            then LT
378                            else if a == v2 && b==v1
379                                 then GT
380                                 else cmp' r a b
381
382 lookup'' :: Map UVar Int -> UVar -> Int
383 lookup'' m x = case lookup x m of
384                  Nothing -> 0
385                  Just y -> y
386
387 valuatit :: Map UVar Int -> [(UVar,Int,UVar)] -> Map UVar Int
388 valuatit m []            = m
389 valuatit m ((v1,k,v2):r) = valuatit m' r
390                             where
391                               m'  = insert v2 v2' m
392                               v2' = max (lookup'' m v2) (k+(lookup'' m v1))
393
394 resolve'k :: UyM () [(Ports,Int,Ports)]
395 resolve'k = do { k  <- getK
396               ; k' <- mapM (\(v1,x,v2) -> do { v1' <- getM v1 ; v2' <- getM v2 ; return (v1',x,v2') }) k
397               ; return k'
398               }
399
400 toTikZ :: GArrowTikZ a b -> String
401 toTikZ g = tikZ m d 0
402             where
403               (_,_,_,(d,k)) = runU $ do { d <- ga2diag g
404                                         ; d' <- resolve' d
405                                         ; k' <- resolve'k
406                                         ; return (d',k') }
407               s = sortit (strip k)
408               m = valuatit empty s
409 toTikZ' :: GArrowTikZ a b -> String
410 toTikZ' g = foldr (\x y -> x++"\\\\\n"++y) [] (map foo s)
411              where
412                (_,_,_,k) = runU $ ga2diag g >>= resolve' >>= \_ -> resolve'k
413                foo (v1,v,v2) = "x_{"++show v1++"} + "++show v++" \\leq x_{"++show v2++"} = " ++ (show $ lookup'' m v2)
414                s = sortit (strip k)
415                m = valuatit empty s
416
417 main = do putStrLn "\\documentclass{article}"
418           putStrLn "\\usepackage[landscape,paperheight=20in,textwidth=19in]{geometry}"
419           putStrLn "\\usepackage{tikz}"
420           putStrLn "\\usepackage{amsmath}"
421           putStrLn "\\begin{document}"
422           putStrLn $ "\\begin{tikzpicture}[every on chain/.style={join=by ->},yscale=-1]"
423           putStrLn (toTikZ example)
424           putStrLn "\\end{tikzpicture}"
425 --          putStrLn "\\begin{align*}"
426 --          putStr   (toTikZ' example)
427 --          putStrLn "\\end{align*}"
428           putStrLn "\\end{document}"