visualization.ml 30.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 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 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 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 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 392 393 394 395 396 397 398 399 400 401 402 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 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
(*
 *  ENIAM: Categorial Syntactic-Semantic Parser for Polish
 *  Copyright (C) 2016 Wojciech Jaworski <wjaworski atSPAMfree mimuw dot edu dot pl>
 *  Copyright (C) 2016 Institute of Computer Science Polish Academy of Sciences
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *)

open LCGtypes
open Xstd
open Printf
open PreTypes

let string_of_interps interps =
      String.concat "|" (Xlist.map interps (fun interp ->
        (String.concat ":" (Xlist.map interp (fun interp2 ->
          (String.concat "." interp2))))))

let rec string_of_token = function
    PreTypes.SmallLetter orth -> sprintf "SmallLetter(%s)" orth
  | PreTypes.CapLetter(orth,lc) -> sprintf "CapLetter(%s,%s)" orth lc
  | PreTypes.AllSmall orth -> sprintf "AllSmall(%s)" orth
  | PreTypes.AllCap(orth,lc,lc2) -> sprintf "AllCap(%s,%s,%s)" orth lc lc2
  | PreTypes.FirstCap(orth,lc,cl,ll) -> sprintf "FirstCap(%s,%s,%s,%s)" orth lc cl ll
  | PreTypes.SomeCap orth -> sprintf "SomeCap(%s)" orth
  | PreTypes.RomanDig(v,t) -> sprintf "RomanDig(%s,%s)" v t
  | PreTypes.Interp orth -> sprintf "Interp(%s)" orth
  | PreTypes.Symbol orth  -> sprintf "Symbol(%s)" orth
  | PreTypes.Dig(v,t) -> sprintf "Dig(%s,%s)" v t
  | PreTypes.Other2 orth  -> sprintf "Other(%s)" orth
  | PreTypes.Lemma(lemma,cat,interps) -> sprintf "Lemma(%s,%s,%s)" lemma cat (string_of_interps interps)
  | PreTypes.Proper(lemma,cat,interps,senses) -> sprintf "Proper(%s,%s,%s,%s)" lemma cat (string_of_interps interps) (String.concat "|" senses)
  | PreTypes.Compound(sense,l) -> sprintf "Compound(%s,[%s])" sense (String.concat ";" (Xlist.map l string_of_token))

let rec spaces i =
  if i = 0 then "" else "  " ^ spaces (i-1)

let rec string_of_tokens i = function
    PreTypes.Token t -> sprintf "%s{orth=%s;beg=%d;len=%d;next=%d;token=%s;id=%d;weight=%.2f;attrs=[%s];\n%s senses=[%s];\n%s valence=[%s];\n%s simple_valence=[%s];lroles=%s,%s}" (spaces i) t.PreTypes.orth t.PreTypes.beg t.PreTypes.len t.PreTypes.next (string_of_token t.PreTypes.token)
      t.PreTypes.id t.PreTypes.weight (String.concat ";" t.PreTypes.attrs) (spaces i) (String.concat ";" (Xlist.map t.PreTypes.senses (fun (sense,hipero,weight) -> sprintf "%s[%s]%.2f" sense (String.concat "," hipero) weight)))
      (spaces i) (String.concat ";" (Xlist.map t.PreTypes.valence (WalStringOf.fnum_frame ""))) (spaces i) (String.concat ";" (Xlist.map t.PreTypes.simple_valence (WalStringOf.fnum_frame ""))) (fst t.lroles) (snd t.lroles)
  | PreTypes.Variant l -> sprintf "%sVariant[\n%s]" (spaces i) (String.concat ";\n" (Xlist.map l (string_of_tokens (i+1))))
  | PreTypes.Seq l -> sprintf "%sSeq[\n%s]" (spaces i) (String.concat ";\n" (Xlist.map l (string_of_tokens (i+1))))

let paths_to_string_indexed (paths,last,next_id) =
  String.concat "\n" (Xlist.map paths (fun (i,j,t) ->
    Printf.sprintf "%2d %2d %s" i j (string_of_tokens 0 (PreTypes.Token t))))
  ^ Printf.sprintf "\nlast=%d next_id=%d" last next_id

let rec xml_of_graph = function
    Node t -> Xml.Element("node",["pred",t.pred;"cat",t.cat;"weight",string_of_float t.weight;"id",string_of_int t.id],[
          Xml.Element("gs",[],[xml_of_graph t.gs]);
          Xml.Element("agf",[],[Xml.PCData (WalStringOf.gf t.agf)]);
          Xml.Element("amorf",[],[Xml.PCData (WalStringOf.morf t.amorf)]);
          Xml.Element("attrs",[],Xlist.map t.attrs (fun (e,t) -> Xml.Element("attr",["label",e],[xml_of_graph t])));
          Xml.Element("args",[],[xml_of_graph t.args])])
  | Concept c -> Xml.Element("concept",["var",fst c.c_variable ^ snd c.c_variable;"pos",string_of_int c.c_pos],[
      Xml.Element("sense",[],[xml_of_graph c.c_sense]);
      Xml.Element("quant",["local",if c.c_local_quant then "t" else "f"],[xml_of_graph c.c_quant]);
      Xml.Element("relations",[],[xml_of_graph c.c_relations])])
  | Context c -> Xml.Element("context",["var",fst c.cx_variable ^ snd c.cx_variable;"pos",string_of_int c.cx_pos],[
      Xml.Element("sense",[],[xml_of_graph c.cx_sense]);
      Xml.Element("contents",[],[xml_of_graph c.cx_contents]);
      Xml.Element("relations",[],[xml_of_graph c.cx_relations])])
  | Relation(r,a,t) -> Xml.Element("relation",[],[
      Xml.Element("role",[],[xml_of_graph r]);
      Xml.Element("role_attr",[],[xml_of_graph r]);
      xml_of_graph t])
  | RevRelation(r,a,t) -> Xml.Element("revrelation",[],[
      Xml.Element("role",[],[xml_of_graph r]);
      Xml.Element("role_attr",[],[xml_of_graph r]);
      xml_of_graph t])
  | SingleRelation(r) -> Xml.Element("singlerelation",[],[xml_of_graph r])
  | Tuple l -> Xml.Element("tuple",[],Xlist.map l xml_of_graph)
  | Val s -> Xml.Element("val",[],[Xml.PCData s])
  | Variant(e,l) -> Xml.Element("variants",["label",e],Xlist.map l (fun (i,t) ->
          Xml.Element("variant",["id",i],[xml_of_graph t])))
  | Dot -> Xml.Element("dot",[],[])
  | Ref i -> Xml.Element("ref",["id",string_of_int i],[])
  | Morf _ -> Xml.Element("dot",[],[]) (* FIXME!!! *)
  | t -> failwith ("xml_of_graph: " ^ LCGstringOf.linear_term 0 t)

let print_xml_graph path name references =
  let l = Int.fold 0 (Array.length references - 1) [] (fun l i ->
    (i, xml_of_graph references.(i)) :: l) in
  let xml = Xml.Element("graph",[],Xlist.rev_map l (fun (i,xml) ->
    Xml.Element("graph_node",["id",string_of_int i],[xml]))) in
  File.file_out (path ^ name ^ ".xml") (fun file ->
    fprintf file "%s\n" (Xml.to_string_fmt xml))

let print_xml_tree path name tree =
  let xml = xml_of_graph tree in
  File.file_out (path ^ name ^ ".xml") (fun file ->
    fprintf file "%s\n" (Xml.to_string_fmt xml))



let rec get_refs rev = function
    Ref i -> i :: rev
  | Tuple l -> Xlist.fold l rev get_refs
  | Variant(e,l) -> Xlist.fold l rev (fun rev (i,t) -> get_refs rev t)
  | Dot -> rev
  | _ -> (*failwith*)print_endline "get_refs"; rev

let escape_string s =
  Int.fold 0 (String.length s - 1) "" (fun t i ->
    match String.sub s i 1 with
       "<" -> t ^ "〈"
     | ">" -> t ^ "〉"
     | c -> t ^ c)

let string_of_node t =
  let l = [
    "PRED",Val t.pred;"CAT",Val t.cat;"ID",Val (string_of_int t.id);"WEIGHT",Val (string_of_float t.weight);"GS",t.gs;
    "AGF",Gf t.agf;"AMORF",Morf t.amorf;"AROLE",Val t.arole;"AROLE-ATTR",Val t.arole_attr;
    "MEANING",Val t.meaning;"HIPERO",Tuple(Xlist.map (StringSet.to_list t.hipero) (fun s -> Val s));"MEANING-WEIGHT",Val (string_of_float t.meaning_weight);
    "ROLE",Val t.position.WalTypes.role;"ROLE-ATTR",Val t.position.WalTypes.role_attr;"SEL-PREFS",Tuple(Xlist.map t.position.WalTypes.sel_prefs (fun s -> Val s));
    "GF",Gf t.position.WalTypes.gf] @ t.attrs in
  "{ " ^ String.concat " | " (Xlist.map l (fun (e,t) -> "{ " ^ e ^ " | " ^ escape_string (LCGstringOf.linear_term 0 t) ^ " }")) ^ " }"

let single_rel_id_count = ref 0

let get_single_rel_id () =
  let id = !single_rel_id_count in
  incr single_rel_id_count;
  "s" ^ string_of_int id

let print_edge file label upper id =
  if upper <> "" then
    if label = "" then fprintf file "  %s -> %s\n" upper id
    else fprintf file "  %s -> %s  [label=\"%s\"]\n" upper id label

(*let rec print_graph_rec2 file edge upper = function
    Tuple l -> Xlist.iter l (print_graph_rec2 file edge upper)
  | Node t ->
          let id = get_single_rel_id () in
          fprintf file "  %s [label=\"%s\"]\n" id (string_of_node t);
          print_edge file edge upper id;
          print_graph_rec2 file "" id t.args
  | Concept t ->
          let id = get_single_rel_id () in
          fprintf file "  %s [shape=box,label=\"%s %s\"]\n" id
            (LCGchart.string_of_linear_term 0 t.c_sense)
            (if t.c_name=Dot then "" else "„" ^ LCGchart.string_of_linear_term 0 t.c_name ^ "”"); (* FIXME *)
          print_edge file edge upper id;
          print_graph_rec2 file "" id t.c_relations
  | SingleRelation(role) ->
          let id = get_single_rel_id () in
          fprintf file "  %s [shape=circle,label=\"%s\"]\n" id (LCGchart.string_of_linear_term 0 role);
          if upper <> "" then fprintf file "  %s -> %s\n" upper id
  | Variant(e,l) ->
          fprintf file "  %s [shape=diamond]\n" e;
          print_edge file edge upper e;
          Xlist.iter l (fun (i,t) -> print_graph_rec2 file i e t)
  | Dot -> ()
  | Ref i -> print_edge file edge upper ("x" ^ string_of_int i)
  | t -> failwith ("print_graph_rec2: " ^ LCGchart.string_of_linear_term 0 t)    *)

let rec string_of_quant_rec quant = function
    Tuple l -> Xlist.fold l quant string_of_quant_rec
  | Variant(e,l) -> (LCGstringOf.linear_term 0 (Variant(e,l))) :: quant
  | Dot -> quant
  | Val s -> s :: quant
  | _ -> failwith "string_of_quant_rec"

let string_of_quant t =
  let l = string_of_quant_rec [] t in
  let s = String.concat " " l in
  if s = "" then "" else "<I>" ^ s ^ "</I> "

let rec print_graph_rec file edge upper id = function
    Node t ->
          fprintf file "  %s [label=\"%s\"]\n" id (string_of_node t);
          print_edge file edge upper id;
          print_graph_rec2 file "" id t.args
  | Concept t ->
          fprintf file "  %s [shape=box,label=<%s%s %s>]\n" id
            (string_of_quant t.c_quant)
            (LCGstringOf.linear_term 0 t.c_sense)
            (if t.c_name=Dot then "" else "„" ^ LCGstringOf.linear_term 0 t.c_name ^ "”"); (* FIXME *)
          print_edge file edge upper id;
          print_graph_rec2 file "" id t.c_relations
  | Context t ->
          if t.cx_sense = Dot then fprintf file "  %s [shape=Msquare,label=\"\"]\n" id
          else fprintf file "  %s [shape=Msquare,label=\"%s\"]\n" id (LCGstringOf.linear_term 0 t.cx_sense);
          print_edge file edge upper id;
          print_graph_rec2 file "" id t.cx_contents;
          print_graph_rec2 file "" id t.cx_relations;
  | Relation(role,role_attr,t) ->
          fprintf file "  %s [shape=circle,label=\"%s\\n%s\"]\n" id (LCGstringOf.linear_term 0 role) (LCGstringOf.linear_term 0 role_attr);
          print_edge file edge upper id;
          print_graph_rec2 file "" id t
  | RevRelation(role,role_attr,t) -> (* FIXME: odwrócenie strzałek *)
          fprintf file "  %s [shape=circle,label=\"%s\\n%s\"]\n" id (LCGstringOf.linear_term 0 role) (LCGstringOf.linear_term 0 role_attr);
          print_edge file edge upper id;
          print_graph_rec2 file "" id t
  | SingleRelation(role) ->
          fprintf file "  %s [shape=circle,label=\"%s\"]\n" id (LCGstringOf.linear_term 0 role);
          print_edge file edge upper id
  | AddRelation(t,role,role_attr,s) ->
          fprintf file "  %s [shape=circle,label=\"AddRelation\\n%s\\n%s\"]\n" id role role_attr;
          print_edge file edge upper id;
          print_graph_rec2 file "" id t;
          print_graph_rec2 file "" id s;
  | SetContextName(s,t) ->
          fprintf file "  %s [shape=circle,label=\"SetContextName\\n%s\"]\n" id s;
          print_edge file edge upper id;
          print_graph_rec2 file "" id t
  | RemoveRelation t ->
          fprintf file "  %s [shape=circle,label=\"RemoveRelation\"]\n" id;
          print_edge file edge upper id;
          print_graph_rec2 file "" id t
  | Variant(e,l) ->
          fprintf file "  %s [shape=diamond,label=\"%s\"]\n" id e;
          print_edge file edge upper id;
          Xlist.iter l (fun (i,t) -> print_graph_rec2 file i id t)
  | Choice choice ->
          fprintf file "  %s [shape=Mdiamond,label=\"%s\"]\n" id "";
          print_edge file edge upper id;
          StringMap.iter choice (fun ei t -> print_graph_rec2 file ei id t)
  | Val s ->
          fprintf file "  %s [shape=box,label=\"%s\"]\n" id s;
          print_edge file edge upper id
  | Dot -> ()
(*          fprintf file "  %s [shape=box,label=\"Dot\"]\n" id;
          print_edge file edge upper id*)
  | Ref i -> print_edge file edge upper ("x" ^ string_of_int i)
  | t -> failwith ("print_graph_rec: " ^ LCGstringOf.linear_term 0 t)

and print_graph_rec2 file edge upper = function
    Tuple l -> Xlist.iter l (print_graph_rec2 file edge upper)
  | t -> print_graph_rec file edge upper (get_single_rel_id ()) t

(*let rec print_graph_rec file is_rev upper i = function  (* FIXME: dokończyć is_rev *)
    Node t ->
 (*         let orth = if t.id = 0 then "" else.(t.id).PreTypes.orth in
          fprintf file "  %s [label=\"%s\\n%s\\n%s:%s\"]\n" i (LCGstringOf.linear_term 0 t.gs) orth t.pred t.cat;*)
          fprintf file "  %s [label=\"%s\"]\n" i (string_of_node t);
          if upper <> "" then
            if is_rev then fprintf file "  %s -> %s\n" i upper
            else fprintf file "  %s -> %s\n" upper i;
          print_graph_rec file false i i t.args
  | Concept t ->
          fprintf file "  %s [shape=box,label=\"%s %s\"]\n" ("c" ^ i)
            (LCGstringOf.linear_term 0 t.c_sense)
            (if t.c_name=Dot then "" else "„" ^ LCGstringOf.linear_term 0 t.c_name ^ "”"); (* FIXME *)
          if upper <> "" then
            if is_rev then fprintf file "  %s -> %s\n" ("c" ^ i) upper
            else fprintf file "  %s -> %s\n" upper ("c" ^ i);
          print_graph_rec file false ("c" ^ i) i t.c_relations
  | Context t ->
          fprintf file "  %s [shape=Msquare,label=\"\"]\n" ("i" ^ i);
          if upper <> "" then
            if is_rev then fprintf file "  %s -> %s\n" ("i" ^ i) upper
            else fprintf file "  %s -> %s\n" upper ("i" ^ i);
          print_graph_rec file false ("i" ^ i) i t.cx_contents
  | SingleRelation(role) ->
          let id = get_single_rel_id () in
          fprintf file "  %s [shape=circle,label=\"%s\"]\n" id (LCGstringOf.linear_term 0 role);
          if upper <> "" then fprintf file "  %s -> %s\n" upper id
  | Relation(role,role_attr,t) ->
          fprintf file "  %s [shape=circle,label=\"%s\\n%s\"]\n" i (LCGstringOf.linear_term 0 role) (LCGstringOf.linear_term 0 role_attr);
          if upper <> "" then fprintf file "  %s -> %s\n" upper i;
          print_graph_rec file false i i t
  | RevRelation(role,role_attr,t) ->
          fprintf file "  %s [shape=circle,label=\"%s\\n%s\"]\n" i (LCGstringOf.linear_term 0 role) (LCGstringOf.linear_term 0 role_attr);
          if upper <> "" then fprintf file "  %s -> %s\n" i upper;
          print_graph_rec file true i i t
  | Tuple l -> Xlist.iter l (print_graph_rec file is_rev upper i)
  | Variant(e,l) ->
          fprintf file "  %s [shape=diamond]\n" e;
          if upper <> "" then fprintf file "  %s -> %s\n" upper e;
          Xlist.iter l (fun (i2,t) -> print_graph_rec file false e ("x" ^ i ^ "y" ^ i2) t)
  | Dot -> ()
  | Ref i2 -> fprintf file "  %s -> %d\n" upper i2
  | t -> failwith ("print_graph_rec: " ^ LCGstringOf.linear_term 0 t)*)

let print_graph path name references =
  single_rel_id_count := 0;
  File.file_out (path ^ name ^ ".gv") (fun file ->
    fprintf file "digraph G {\n  node [shape=record]\n";
    Int.iter 0 (Array.length references - 1) (fun i -> print_graph_rec file (*false*) "" "" ("x" ^ string_of_int i) references.(i));
(*    Int.iter 0 (Array.length references - 1) (fun i ->
      match references.(i) with
        Node t ->
          fprintf file "  %d [label=\"%s\"]\n" i (string_of_node t);
          let refs = get_refs [] t.args in
          Xlist.iter refs (fun r ->
            fprintf file "  %d -> %d\n" i r)
      | t -> failwith ("print_graph: " ^ LCGstringOf.linear_term 0 t));*)
    fprintf file "}\n");
  Sys.chdir path;
  ignore (Sys.command ("dot -Tpng " ^ name ^ ".gv -o " ^ name ^ ".png"));
  Sys.chdir ".."

let id_counter = ref 0

let print_edge2 file edge_rev edge_label edge_head edge_tail upper id =
  let edge_head,edge_tail,upper,id = if edge_rev then edge_tail,edge_head,id,upper else edge_head,edge_tail,upper,id in
  let l =
    (if edge_label = "" then [] else ["label=\"" ^ edge_label ^ "\""]) @
    (if edge_head = "" then [] else ["ltail=\"" ^ edge_head ^ "\""]) @
    (if edge_tail = "" then [] else ["lhead=\"" ^ edge_tail ^ "\""]) in
  if upper <> 0 then
    if l = [] then fprintf file "  %d -> %d\n" upper id
    else fprintf file "  %d -> %d  [%s]\n" upper id (String.concat "," l)

let rec print_graph2_rec file edge_rev edge_label edge_head upper = function
    Node t ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [label=\"%s\"]\n" id (string_of_node t);
          print_edge2 file edge_rev edge_label edge_head "" upper id;
          print_graph2_rec file false "" "" id t.args
  | Concept t ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [shape=box,label=<%s%s %s>]\n" id
            (string_of_quant t.c_quant)
            (LCGstringOf.linear_term 0 t.c_sense)
            (if t.c_name=Dot then "" else "„" ^ LCGstringOf.linear_term 0 t.c_name ^ "”"); (* FIXME *)
          print_edge2 file edge_rev edge_label edge_head "" upper id;
          print_graph2_rec file false "" "" id t.c_relations
  | Context t ->
          let id = !id_counter in
          incr id_counter;
          if t.cx_sense = Dot then fprintf file "  subgraph cluster%d {\nlabel=\"\"\n" id
          else fprintf file "  subgraph cluster%d {\nlabel=\"%s\"\n" id (LCGstringOf.linear_term 0 t.cx_sense);
          print_graph2_rec file false "" "" 0 t.cx_contents;
          fprintf file "  }\n";
          print_edge2 file edge_rev edge_label edge_head ("cluster" ^ string_of_int id) upper (id+1);
          print_graph2_rec file false "" ("cluster" ^ string_of_int id) (id+1) t.cx_relations;
  | Relation(role,role_attr,t) ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [shape=circle,label=\"%s\\n%s\"]\n" id (LCGstringOf.linear_term 0 role) (LCGstringOf.linear_term 0 role_attr);
          print_edge2 file false edge_label edge_head "" upper id;
          print_graph2_rec file false "" "" id t
  | RevRelation(role,role_attr,t) ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [shape=circle,label=\"%s\\n%s\"]\n" id (LCGstringOf.linear_term 0 role) (LCGstringOf.linear_term 0 role_attr);
          print_edge2 file true edge_label edge_head "" upper id;
          print_graph2_rec file true "" "" id t
  | SingleRelation(role) ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [shape=circle,label=\"%s\"]\n" id (LCGstringOf.linear_term 0 role);
          print_edge2 file false edge_label edge_head "" upper id
  | AddRelation(t,role,role_attr,s) ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [shape=circle,label=\"AddRelation\\n%s\\n%s\"]\n" id role role_attr;
          print_edge2 file edge_rev edge_label edge_head "" upper id;
          print_graph2_rec file false "" "" id t;
          print_graph2_rec file false "" "" id s
  | RemoveRelation t ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [shape=circle,label=\"RemoveRelation\"]\n" id;
          print_edge2 file edge_rev edge_label edge_head "" upper id;
          print_graph2_rec file false "" "" id t
  | SetContextName(s,t) ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [shape=circle,label=\"SetContextName\\n%s\"]\n" id s;
          print_edge2 file edge_rev edge_label edge_head "" upper id;
          print_graph2_rec file false "" "" id t;
  | Tuple l -> Xlist.iter l (print_graph2_rec file edge_rev edge_label edge_head upper)
  | Variant(e,l) ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [shape=diamond,label=\"%s\"]\n" id e;
          print_edge2 file edge_rev edge_label edge_head "" upper id;
          Xlist.iter l (fun (i,t) -> print_graph2_rec file edge_rev  i "" id t)
  | Val s ->
          let id = !id_counter in
          incr id_counter;
          fprintf file "  %d [shape=box,label=\"%s\"]\n" id s;
          print_edge2 file edge_rev edge_label edge_head "" upper id
  | Dot -> ()
  | t -> failwith ("print_graph_rec: " ^ LCGstringOf.linear_term 0 t)

let print_graph2 path name query t =
(*   print_endline  *)
  id_counter := 1;
  File.file_out (path ^ name ^ ".gv") (fun file ->
    fprintf file "digraph G {\n  compound=true\n  node [shape=record]\n";
    print_graph2_rec file false "" "" 0 t;
    fprintf file "label=\"%s\"\n  }\n" query);
(*   Sys.chdir path; *)
  ignore (Sys.command ("dot -Tpng " ^ path ^ name ^ ".gv -o " ^ path ^ name ^ ".png"))(*;
  Xlist.iter (Str.split (Str.regexp path) path) (fun _ -> Sys.chdir "..")*)

let rec get_lemma = function
    PreTypes.Interp orth -> orth
  | PreTypes.Lemma(lemma,cat,_) -> lemma ^ "\n" ^ cat
  | _ -> ""

let print_paths path name paths =
  File.file_out (path ^ name ^ ".gv") (fun file ->
    fprintf file "digraph G {\n";
    Array.iter (fun t ->
      let lemma = get_lemma t.PreTypes.token in
      if lemma <> "" then fprintf file "  %d -> %d [label=\"%s\\n%s\"]\n" t.PreTypes.beg t.PreTypes.next t.PreTypes.orth lemma) paths;
    fprintf file "}\n");
  Sys.chdir path;
  ignore (Sys.command ("dot -Tpng " ^ name ^ ".gv -o " ^ name ^ ".png"));
  Sys.chdir ".."

let rec print_tree_rec2 file paths edge upper = function
    Tuple l -> Xlist.iter l (print_tree_rec2 file paths edge upper)
  | Variant(e,l) ->
          fprintf file "  %s [shape=diamond]\n" e;
          print_edge file edge upper e;
          Xlist.iter l (fun (i,t) -> print_tree_rec2 file paths i e t)
  | Dot -> ()
  | Ref i -> print_edge file edge upper ("x" ^ string_of_int i)
  | t -> failwith ("print_tree_rec: " ^ LCGstringOf.linear_term 0 t)

let rec print_tree_rec file paths edge upper id = function
    Node t ->
          let orth = if t.id = 0 then "" else paths.(t.id).PreTypes.orth in
          fprintf file "  %s [label=\"%s\\n%s\\n%s:%s\\n%f\"]\n" id (LCGstringOf.linear_term 0 t.gs) orth t.pred t.cat t.weight;
          print_edge file edge upper id;
          print_tree_rec2 file paths "" id t.args
  | Variant(e,l) ->
          fprintf file "  %s [shape=diamond,label=\"%s\"]\n" id e;
          print_edge file edge upper id;
          Xlist.iter l (fun (i,t) -> print_tree_rec file paths i id (id ^ "y" ^ i) t)
  | Choice choice ->
          fprintf file "  %s [shape=Mdiamond,label=\"%s\"]\n" id "";
          print_edge file edge upper id;
          StringMap.iter choice (fun ei t -> print_tree_rec file paths ei id (id ^ "b" ^ ei) t)
  | Dot -> ()
  | t -> failwith ("print_tree_rec: " ^ LCGstringOf.linear_term 0 t)

let print_tree path name paths references =
  File.file_out (path ^ name ^ ".gv") (fun file ->
    fprintf file "digraph G {\n  node [shape=box]\n";
    Int.iter 0 (Array.length references - 1) (fun i -> print_tree_rec file paths "" "" ("x" ^ string_of_int i) references.(i));
(*      match references.(i) with
        Node t ->
          let orth = if t.id = 0 then "" else paths.(t.id).PreTypes.orth in
          fprintf file "  %d [label=\"%s\\n%s\\n%s:%s\"]\n" i (LCGstringOf.linear_term 0 t.gs) orth t.pred t.cat;
          let refs = get_refs [] t.args in
          Xlist.iter refs (fun r ->
            fprintf file "  %d -> %d\n" i r)
      | t -> failwith ("print_tree: " ^ LCGstringOf.linear_term 0 t));*)
    fprintf file "}\n");
  Sys.chdir path;
  ignore (Sys.command ("dot -Tpng " ^ name ^ ".gv -o " ^ name ^ ".png"));
  Sys.chdir ".."

(*let print_tree filename paths references =
  File.file_out filename (fun file ->
    fprintf file "digraph G {\n";
    let set = Xlist.fold paths IntSet.empty (fun set t ->
      IntSet.add (IntSet.add set t.PreTypes.beg) t.PreTypes.next) in
    IntSet.iter set (fun i -> fprintf file "  %d [width=0; height=0; label=\"\"]\n" i);
    Xlist.iter paths (fun t ->
      let lemma = get_lemma t.PreTypes.token in
      if lemma <> "" then (
        let s = if t.PreTypes.orth = "" then lemma else t.PreTypes.orth ^ "\n" ^ lemma in
        fprintf file "  %d -> i%d -> %d [arrowhead=none]\n" t.PreTypes.beg t.PreTypes.id t.PreTypes.next;
        fprintf file "  i%d [label=\"%s\"]\n" t.PreTypes.id s));
    fprintf file "}\n");
  Sys.chdir "results";
  ignore (Sys.command "dot -Tpng tree.gv -o tree.png");
  Sys.chdir ".."*)

(*let print_tree filename paths references =
  File.file_out filename (fun file ->
    fprintf file "digraph G {\n";
      fprintf file "  subgraph {\n  ordering=out\n";
      let same = Xlist.fold (Xlist.sort paths (fun s t -> compare s.PreTypes.beg t.PreTypes.beg)) [] (fun same t ->
        let lemma = get_lemma t.PreTypes.token in
        if lemma <> "" then (
          let s = if t.PreTypes.orth = "" then lemma else t.PreTypes.orth ^ "\n" ^ lemma in
          fprintf file "    i%d -> out [arrowhead=none]\n" t.PreTypes.id;
          fprintf file "    i%d [label=\"%s\"]\n" t.PreTypes.id s;
          t.PreTypes.id :: same)
        else same) in
      fprintf file "  }\n";
      fprintf file "  { rank = same; %s }\n" (String.concat "; " (Xlist.map same (fun i -> sprintf "\"i%d\"" i)));
    Int.iter 0 (Array.length references - 1) (fun i ->
      match references.(i) with
        Node t ->
          fprintf file "  %d [label=\"%s\"]\n" i t.pred;
          fprintf file "  %d -> i%d\n" i t.id;
          let refs = get_refs [] t.args in
          Xlist.iter refs (fun r ->
            fprintf file "  %d -> %d\n" i r)
      | _ -> failwith "print_graph");
    fprintf file "}\n");
  Sys.chdir "results";
  ignore (Sys.command "dot -Tpng tree.gv -o tree.png");
  Sys.chdir ".."*)

let rec schema_latex schema = 
  "\\begin{tabular}{l}" ^
  String.concat "\\\\" (Xlist.map schema (fun s ->
    LatexMain.escape_string (String.concat "," (
      (if s.WalTypes.gf = WalTypes.ARG then [] else [WalStringOf.gf s.WalTypes.gf])@
      (if s.WalTypes.role = "" then [] else [s.WalTypes.role])@
      (if s.WalTypes.role_attr = "" then [] else [s.WalTypes.role_attr])@
      s.WalTypes.sel_prefs@(WalStringOf.controllers s.WalTypes.cr)@(WalStringOf.controllees s.WalTypes.ce)) ^ WalStringOf.direction s.WalTypes.dir ^ "{" ^  String.concat ";" (Xlist.map s.WalTypes.morfs WalStringOf.morf) ^ "}"))) ^
  "\\end{tabular}"

let fnum_frame_latex = function
    fnum,WalTypes.Frame(atrs,s) ->
      Printf.sprintf "%d: %s: %s" fnum (LatexMain.escape_string (WalStringOf.frame_atrs atrs)) (schema_latex s)
  | fnum,WalTypes.LexFrame(id,p,r,s) ->
      Printf.sprintf "%d: %s: %s: %s: %s" fnum id (LatexMain.escape_string (WalStringOf.pos p)) (WalStringOf.restr r) (schema_latex s)
  | fnum,WalTypes.ComprepFrame(le,p,r,s) ->
      Printf.sprintf "%d: %s: %s: %s: %s" fnum le (LatexMain.escape_string (WalStringOf.pos p)) (WalStringOf.restr r) (schema_latex s)

let print_paths_latex name paths =
  LatexMain.latex_file_out "results/" name "a0" false (fun file ->
    fprintf file "\\begin{longtable}{|l|l|l|l|l|l|l|p{4cm}|l|l|l|l|}\n\\hline\north & beg & len & next & token & id & weight & attrs & lroles & senses & simple valence & valence\\\\\n";
    Int.iter 0 (Array.length paths - 1) (fun i ->
      let t = paths.(i) in
      fprintf file "%s & %d & %d & %d & %s & %d & %.4f & %s & %s %s &\\begin{tabular}{l|l|p{4cm}}%s\\end{tabular} &\\begin{tabular}{l}%s\\end{tabular} &\\begin{tabular}{l}%s\\end{tabular}\\\\\n\\hline\n"
        t.PreTypes.orth t.PreTypes.beg t.PreTypes.len t.PreTypes.next (LatexMain.escape_string (string_of_token t.PreTypes.token)) t.PreTypes.id t.PreTypes.weight
        (String.concat ";" t.PreTypes.attrs) (fst t.PreTypes.lroles) (snd t.PreTypes.lroles)
        (String.concat "\\\\\n" (Xlist.map t.PreTypes.senses (fun (sense,hipero,weight) -> sprintf "%s & %.2f & %s" sense weight (String.concat "," hipero))))
        (String.concat "\\\\\n\\hline\n" (Xlist.map t.PreTypes.simple_valence (fun x -> fnum_frame_latex x)))
        (String.concat "\\\\\n\\hline\n" (Xlist.map t.PreTypes.valence (fun x -> fnum_frame_latex x))));
    fprintf file "\\end{longtable}");
  LatexMain.latex_compile_and_clean "results/" name

let print_mml path name mml =
  File.file_out (path ^ name ^ ".mml") (fun file ->
    fprintf file "<!DOCTYPE math PUBLIC \"-//W3C//DTD MathML 2.0//EN\" \"http://www.w3.org/Math/DTD/mathml2/mathml2.dtd\">\n";
    fprintf file "%s\n" (Xml.to_string_fmt mml))

let page_header path =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
<html>
  <head>
	<META HTTP-EQUIV=\"CONTENT-TYPE\" CONTENT=\"text/html; charset=utf8\">
	<TITLE>ENIAM: Kategorialny Parser Składniowo-Semantyczny</TITLE>
	<META HTTP-EQUIV=\"Content-Language\" CONTENT=\"pl\">
  </head>

  <body>
 <center>
   <h1>ENIAM: Kategorialny Parser Składniowo-Semantyczny</h1>
    <h3>Podaj tekst:</h3>
    <form method=POST action=\"" ^ path ^ "parser.cgi\">
      <p><input type=\"text\" name=\"text0\" value=\"\" size=\"40\"></p>
      <p><input type=\"submit\" value=\"Analizuj\" size=\"60\"></p>
   </form>"

let page_trailer =
"<BR><BR>
<hr align=\"center\" size=\"2\" width=\"800\" />
Copyright &copy; 2016 Institute of Computer Science Polish Academy of Sciences<BR>
</center>
  </body>
</html>"

let print_webpage file cg_bin_path html_path id query n max_n mml =
  fprintf file "%s\n" (page_header cg_bin_path);
  fprintf file "\n<H3>%s</H3>\n" query;
  fprintf file "<P>%s %s\n"
    (if n = 1 then "" else sprintf "<A HREF=\"%spage%s_%d.html\">Poprzednia interpretacja</A>" html_path id (n-1))
    (if n = max_n then "" else sprintf "<A HREF=\"%spage%s_%d.html\">Następna interpretacja</A>" html_path id (n+1));
  fprintf file "<P><IMG SRC=\"%stree%s_%d.png\">\n" html_path id n;
  fprintf file "<P>%s\n" (Xml.to_string_fmt mml);
  fprintf file "<P><A HREF=\"%stree%s_%d.xml\">Graf w formacie XML</A>\n" html_path id n;
  fprintf file "<P><A HREF=\"%sformula%s_%d.mml\">Formuła w formacie MathML</A>\n" html_path id n;
  fprintf file "<P>%s %s\n"
    (if n = 1 then "" else sprintf "<A HREF=\"%spage%s_%d.html\">Poprzednia interpretacja</A>" html_path id (n-1))
    (if n = max_n then "" else sprintf "<A HREF=\"%spage%s_%d.html\">Następna interpretacja</A>" html_path id (n+1));
  fprintf file "%s\n" page_trailer

open ExecTypes

let generate_status_message result = function
    Idle -> "Server error: " ^ result.msg
  | PreprocessingError -> "Error during preprocessing: " ^ result.msg
  | LexiconError -> "Error during LCG lexicon generation: " ^ result.msg
  | ParseError -> "Error during parsing: " ^ result.msg
  | ParseTimeout -> "Parser timeout: " ^ result.msg
  | NotParsed -> "Unable to parse query"
  | ReductionError -> "Error during dependency tree generation: " ^ result.msg
  | TooManyNodes -> "Depencency tree is too big"
  | NotReduced -> "Unable to generate dependency tree"
  | SemError -> "Error during logical form generation: " ^ result.msg
  | NotTranslated -> "Unable to generate logical form"
  | Parsed -> "parsed"

let print_other_result file cg_bin_path query result =
  fprintf file "%s\n" (page_header cg_bin_path);
  fprintf file "\n<H3>%s</H3>\n" query;
  fprintf file "\n<P>%s\n" (generate_status_message result result.status);
  fprintf file "%s\n" page_trailer