teixml.py 37.1 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 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
#-*- coding:utf-8 -*-
from semantics.models import LexicalUnitExamples

#Copyright (c) 2015, Bartłomiej Nitoń
#All rights reserved.

#Redistribution and use in source and binary forms, with or without modification, are permitted provided 
#that the following conditions are met:

#    Redistributions of source code must retain the above copyright notice, this list of conditions and 
#    the following disclaimer.
#    Redistributions in binary form must reproduce the above copyright notice, this list of conditions 
#    and the following disclaimer in the documentation and/or other materials provided with the distribution.

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED 
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
# POSSIBILITY OF SUCH DAMAGE.

'''
File with functions responsible for creating TEI xml.
'''

import codecs
import datetime
import operator

from lxml import etree
from xml.sax.saxutils import escape

from dictionary.models import Atribute_Model, Frame_Opinion_Value, \
                              Frame_Char_Model, PositionCategory, \
                              Argument_Model, \
                              sortArguments, sortatributes, sortPositions
from dictionary.common_func import getArgsList

XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'
                                       

def createteixml(outpath, lemmas, sort_reflex_vals,
                   sort_aspect_vals, sort_neg_vals, sort_pred_vals, frame_char_models,
                   form_dict, q_frame_opinions, real_arg_models):
    root = write_root()
    write_header(root)
    write_entries(root, lemmas, sort_reflex_vals, 
                  sort_aspect_vals, sort_neg_vals, sort_pred_vals, frame_char_models, 
                  form_dict, q_frame_opinions, real_arg_models)
    with codecs.open(outpath, 'wt', 'utf-8') as output_file:
        output_file.write(etree.tostring(root, pretty_print = True))
        
def write_root():
    root = etree.Element('TEI')
    root.attrib[etree.QName(XML_NAMESPACE, 'lang')] = 'pl'
    root.attrib['xmlns'] = 'http://www.tei-c.org/ns/1.0'
    return root
    
def write_header(root):
    tei_header = etree.SubElement(root, 'teiHeader')
    file_desc = etree.SubElement(tei_header, 'fileDesc')
    
    title_stmt = etree.SubElement(file_desc, 'titleStmt')
    title = etree.SubElement(title_stmt, 'title')
    title.text = 'Polish Valence Dictionary (Walenty)'
#    
    publication_stmt = etree.SubElement(file_desc, 'publicationStmt')
    publisher = etree.SubElement(publication_stmt, 'publisher')
    publisher.text = 'IPI PAN ZIL'
    date = etree.SubElement(publication_stmt, 'date')
    date.attrib['when'] = datetime.datetime.now().strftime('%Y-%m-%d')
    
    source_desc = etree.SubElement(file_desc, 'sourceDesc')
    p = etree.SubElement(source_desc, 'p')
    p.text = 'File generated using Slowal. Mentioned tool available at: walenty.ipipan.waw.pl.'
    
def write_entries(root, lemmas, sort_reflex_vals, 
                   sort_aspect_vals, sort_neg_vals, sort_pred_vals, frame_char_models, 
                   form_dict, q_frame_opinions, real_arg_models):
    text = etree.SubElement(root, 'text')
    body = etree.SubElement(text, 'body')
    for lemma in lemmas:
        frame_opinions = None
        if q_frame_opinions:
            frame_opinions = lemma.frame_opinions.filter(reduce(operator.or_, q_frame_opinions))
        write_entry(body, lemma, sort_reflex_vals, 
                    sort_aspect_vals, sort_neg_vals, sort_pred_vals, frame_char_models,
                    form_dict, frame_opinions, real_arg_models)
        
def write_entry(body_elem, lemma, sort_reflex_vals, 
                 sort_aspect_vals, sort_neg_vals, sort_pred_vals, 
                 frame_char_models, form_dict, frame_opinions, real_arg_models):
    entry_xml_id = 'wal_%s-ent' % str(lemma.entry_obj.id)
    entry_elem = etree.SubElement(body_elem, 'entry')
    entry_elem.attrib[etree.QName(XML_NAMESPACE, 'id')] = entry_xml_id
    
    form_elem = etree.SubElement(entry_elem, 'form')
    orth_elem = etree.SubElement(form_elem, 'orth')
    orth_elem.text = lemma.entry
    pos_elem = etree.SubElement(form_elem, 'pos')
    pos_elem.text = lemma.entry_obj.pos.tag
    
    write_syntactic_layer(entry_elem, lemma, form_dict,
                          sort_reflex_vals, sort_aspect_vals, 
                          sort_neg_vals, sort_pred_vals,
                          frame_opinions, real_arg_models)
    write_examples_layer(entry_elem, lemma)
    write_semantic_layer(entry_elem, lemma)
    write_meanings_layer(entry_elem, lemma)
    write_connections_layer(entry_elem, lemma)
    
def write_syntactic_layer(entry_elem, lemma, form_dict,
                             sort_reflex_vals, sort_aspect_vals, 
                             sort_neg_vals, sort_pred_vals,
                             frame_opinions, real_arg_models):
    synt_layer_fs_elem = etree.SubElement(entry_elem, 'fs')
    synt_layer_fs_elem.attrib['type'] = 'syntacticLayer'
    schemata_f_elem =  etree.SubElement(synt_layer_fs_elem, 'f')
    schemata_f_elem.attrib['name'] = 'schemata'
    vColl_elem = etree.SubElement(schemata_f_elem, 'vColl')
    vColl_elem.attrib['org'] = 'list'
    
    for reflex_val in sort_reflex_vals:
        for neg_val in sort_neg_vals:
            for pred_val in sort_pred_vals:
                for aspect_val in sort_aspect_vals:
                    matchingframes = lemma.get_frames_by_char_values(reflex_val=reflex_val, 
                                                                     neg_val=neg_val, 
                                                                     pred_val=pred_val, 
                                                                     aspect_val=aspect_val).order_by('text_rep')
                    for frame in matchingframes:
                        if not form_dict['frame_opinions'] or (frame_opinions and frame_opinions.filter(frame=frame).count() > 0):  
                            write_schema(vColl_elem, frame, lemma, real_arg_models)
        
def write_schema(parent_elem, schema, lemma, real_arg_models):
    
    schema_xml_id = 'wal_%s.%s-sch' % (str(lemma.entry_obj.id), str(schema.id))
    
    schema_fs_elem = etree.SubElement(parent_elem, 'fs')
    schema_fs_elem.attrib[etree.QName(XML_NAMESPACE, 'id')] = schema_xml_id
    schema_fs_elem.attrib['type'] = 'schema'
    # opinia o ramce
    try:  
        schema_opinion = lemma.frame_opinions.filter(frame=schema).all()[0].value.short
    except IndexError:
        schema_opinion = 'unk'
    opinion_f_elem = etree.SubElement(schema_fs_elem, 'f')
    opinion_f_elem.attrib['name'] = 'opinion'
    opinion_symbol = etree.SubElement(opinion_f_elem, 'symbol')
    opinion_symbol.attrib['value'] = schema_opinion
    
    # zwrotnosc
    reflex = 'false'
    if schema.characteristics.filter(type=u'ZWROTNOŚĆ', value__value=u'się').exists():
        reflex = 'true'
    selfmark_f_elem = etree.SubElement(schema_fs_elem, 'f')
    selfmark_f_elem.attrib['name'] = 'selfMark'
    selfmark_binary = etree.SubElement(selfmark_f_elem, 'binary')
    selfmark_binary.attrib['value'] = reflex
    
    # aspekt
    aspect = schema.characteristics.get(type=u'ASPEKT').value.value
    aspect_f_elem = etree.SubElement(schema_fs_elem, 'f')
    aspect_f_elem.attrib['name'] = 'aspect'
    if aspect:
        aspect_symbol = etree.SubElement(aspect_f_elem, 'symbol')
        aspect_symbol.attrib['value'] = aspect
    
    # negatywnosc
    negativity = schema.characteristics.get(type=u'NEGATYWNOŚĆ').value.value
    negativity_f_elem = etree.SubElement(schema_fs_elem, 'f')
    negativity_f_elem.attrib['name'] = 'negativity'
    if negativity:
        negativity_symbol = etree.SubElement(negativity_f_elem, 'symbol')
        negativity_symbol.attrib['value'] = negativity
    
    # predykatywnosc     
    predicativity = schema.characteristics.get(type=u'PREDYKATYWNOŚĆ').value.value
    predicativity_f_elem = etree.SubElement(schema_fs_elem, 'f')
    predicativity_f_elem.attrib['name'] = 'predicativity'
    if predicativity:
        predicativity_symbol = etree.SubElement(predicativity_f_elem, 'symbol')
        predicativity_symbol.attrib['value'] = predicativity
    
    # pozycje składniowe
    write_positions_feature(schema, schema_xml_id, schema_fs_elem, real_arg_models)
    
def write_positions_feature(schema, schema_xml_id, parent_elem, real_arg_models):
    sorted_pos_dict = sortPositions(schema.positions.all())
    if sorted_pos_dict:
        positions_f_elem = etree.SubElement(parent_elem, 'f')
        positions_f_elem.attrib['name'] = 'positions'
        vColl_elem = etree.SubElement(positions_f_elem, 'vColl')
        vColl_elem.attrib['org'] = 'list'
        for position in sorted_pos_dict:
            write_position_elem(vColl_elem, schema_xml_id, position['position'], real_arg_models)
        
def write_position_elem(parent_elem, schema_xml_id, position, real_arg_models):
    position_xml_id = schema_xml_id.replace(u'-sch', '.%d-psn' % position.id)
    
    position_fs_elem = etree.SubElement(parent_elem, 'fs')
    position_fs_elem.attrib[etree.QName(XML_NAMESPACE, 'id')] = position_xml_id
    position_fs_elem.attrib['type'] = 'position'

    functions = position.categories.filter(control=False)
    if functions.exists():
        function_f_elem = etree.SubElement(position_fs_elem, 'f')
        function_f_elem.attrib['name'] = 'function'
        function_symbol_elem = etree.SubElement(function_f_elem, 'symbol')
        function_symbol_elem.attrib['value'] = functions[0].category
    
    write_control_features(position_fs_elem, position)
    write_phrases_feature(position_fs_elem, position, position_xml_id, real_arg_models)
    
def write_control_features(parent_elem, position):
    controls1 = position.categories.filter(control=True).exclude(category__endswith='2')
    if controls1.exists():
        control = controls1[0].category
        control1_f_elem = etree.SubElement(parent_elem, 'f')
        control1_f_elem.attrib['name'] = 'control1'
        control1_symbol_elem = etree.SubElement(control1_f_elem, 'symbol')
        control1_symbol_elem.attrib['value'] = control
           
    controls2 = position.categories.filter(control=True, category__endswith='2')
    if controls2.exists():
        control = controls2[0].category
        control2_f_elem = etree.SubElement(parent_elem, 'f')
        control2_f_elem.attrib['name'] = 'control2'
        control2_symbol_elem = etree.SubElement(control2_f_elem, 'symbol')
        control2_symbol_elem.attrib['value'] = control
        
def write_phrases_feature(parent_elem, position, position_xml_id, real_arg_models):
    sorted_phrases = sortArguments(getArgsList(position.arguments.all(), real_arg_models))
    if sorted_phrases:
        phrases_f_elem = etree.SubElement(parent_elem, 'f')
        phrases_f_elem.attrib['name'] = 'phrases'
        vColl_elem = etree.SubElement(phrases_f_elem, 'vColl')
        vColl_elem.attrib['org'] = 'list'
        for phrase in sorted_phrases:
            write_phrase(vColl_elem, phrase, position_xml_id)
    
def write_phrase(parent_elem, phrase, position_xml_id):
    phrase_xml_id = position_xml_id.replace(u'-psn', '.%d-phr' % phrase.id)
    phrase_fs_elem = etree.SubElement(parent_elem, 'fs')
    phrase_fs_elem.attrib[etree.QName(XML_NAMESPACE, 'id')] = phrase_xml_id
    phrase_fs_elem.attrib['type'] = phrase.type
    
#    text_rep_elem = etree.SubElement(phrase_fs_elem, 'f')
#    text_rep_elem.attrib['name'] = 'text_rep' 
#    string_elem = etree.SubElement(text_rep_elem, 'string')
#    string_elem.text = phrase.text_rep
    
    write_attributes(phrase_fs_elem, phrase)
        
def write_attributes(parent_elem, phrase):
    attributes = sortatributes(phrase)
    for attribute in attributes:
        writeattribute(parent_elem, attribute)
        
def writeattribute(parent_elem, attribute):
    attribute_model = Atribute_Model.objects.get(atr_model_name=attribute.type)
    attr_f_elem = etree.SubElement(parent_elem, 'f')
    attr_f_elem.attrib['name'] = attribute_model.sym_name
    attr_f_elem.text = unicode(attribute)
    
#    if attribute_model.type.sym_name == 'parameter': # mamy problem, nie moze byc symbol, bo takie comprepnp np. ma spacje
#        symbol_elem = etree.SubElement(attr_f_elem, 'symbol')
#        symbol_elem.attrib['value'] = unicode(attribute)
#    elif attribute_model.type.sym_name == 'text':
#        string_elem = etree.SubElement(attr_f_elem, 'string')
#    else:
    
    
def write_examples_layer(parent_elem, lemma):
    examples_layer_elem = etree.SubElement(parent_elem, 'fs')
    examples_layer_elem.attrib['type'] = 'examplesLayer'
    
    examples_f_elem = etree.SubElement(examples_layer_elem, 'f')
    examples_f_elem.attrib['name'] = 'examples'
    
    vColl_elem = etree.SubElement(examples_f_elem, 'vColl')
    vColl_elem.attrib['org'] = 'list'
    
    write_examples_feature(vColl_elem, lemma)
    
def write_examples_feature(parent_elem, lemma):
    entry = lemma.entry_obj
    for example in lemma.nkjp_examples.order_by('opinion__priority').all():
        write_example(parent_elem, entry, example)  
    for example in lemma.lemma_nkjp_examples.order_by('opinion__priority').all():
        write_example(parent_elem, entry, example)
        
def write_example(parent_elem, entry, example):
    example_xml_id = u'wal_%s.%s-exm' % (str(entry.id), str(example.id))
    
    example_fs_elem = etree.SubElement(parent_elem, 'fs')
    example_fs_elem.attrib[etree.QName(XML_NAMESPACE, 'id')] = example_xml_id
    example_fs_elem.attrib['type'] = 'example'
    
    get_and_write_meaning_link(example_fs_elem, entry, example)
    write_phrases_links(example_fs_elem, entry, example)
    
    sentence_f_elem = etree.SubElement(example_fs_elem, 'f')
    sentence_f_elem.attrib['name'] = 'sentence'
    sentence_content_elem = etree.SubElement(sentence_f_elem, 'string')
    sentence_content_elem.text = escape(example.sentence)
    
    # trzeba do zrodel dodac nazwy symboliczne
    source_f_elem = etree.SubElement(example_fs_elem, 'f')
    source_f_elem.attrib['name'] = 'source'
    source_symbol_elem = etree.SubElement(source_f_elem, 'symbol')
    source_symbol_elem.attrib['value'] = example.source.sym_name
    
    opinion_f_elem = etree.SubElement(example_fs_elem, 'f')
    opinion_f_elem.attrib['name'] = 'opinion'
    opinion_symbol_elem = etree.SubElement(opinion_f_elem, 'symbol')
    opinion_symbol_elem.attrib['value'] = example.opinion.opinion
    
    note_f_elem = etree.SubElement(example_fs_elem, 'f')
    note_f_elem.attrib['name'] = 'note'
    note_content_elem = etree.SubElement(note_f_elem, 'string')
    note_content_elem.text = escape(example.comment)
    
def get_and_write_meaning_link(parent_elem, entry, example):
    try:
        lex_unit_example = LexicalUnitExamples.objects.get(example=example,
                                                           lexical_unit__base=entry.name)
        meaning = lex_unit_example.lexical_unit
        meaning_xml_id = u'#wal_%s.%s-mng' % (str(entry.id), str(meaning.id))
        
        meaning_f_elem = etree.SubElement(parent_elem, 'f')
        meaning_f_elem.attrib['name'] = 'meaning'
        
        meaning_link_elem = etree.SubElement(meaning_f_elem, 'fs')
        meaning_link_elem.attrib['sameAs'] = meaning_xml_id
        meaning_link_elem.attrib['type'] = 'lexicalUnit'
    except LexicalUnitExamples.DoesNotExist:
        pass

def write_phrases_links(parent_elem, entry, example):
    phrases_f_elem = etree.SubElement(parent_elem, 'f')
    phrases_f_elem.attrib['name'] = 'phrases'
    
    vColl_elem = etree.SubElement(phrases_f_elem, 'vColl')
    vColl_elem.attrib['org'] = 'list'
    
    for phrase_selection in example.arguments.all():
        create_and_write_phrase_link(vColl_elem, entry, example, phrase_selection)
    
def create_and_write_phrase_link(parent_elem, entry, example, phrase_selection):
    link_base = u'#wal_%d.%d.%d.' % (entry.id, example.frame.id, phrase_selection.position.id)
    for phrase in phrase_selection.arguments.all():
        link_end = u'%d-phr' % phrase.id
        link = link_base + link_end
        phrase_link_elem = etree.SubElement(parent_elem, 'fs')
        phrase_link_elem.attrib['sameAs'] = link
        phrase_link_elem.attrib['type'] = 'phrase'

def write_semantic_layer(parent_elem, lemma):
    semantic_layer_elem = etree.SubElement(parent_elem, 'fs')
    semantic_layer_elem.attrib['type'] = 'semanticLayer'
    
    frames_f_elem = etree.SubElement(semantic_layer_elem, 'f')
    frames_f_elem.attrib['name'] = 'frames'
    
    vColl_elem = etree.SubElement(frames_f_elem, 'vColl')
    vColl_elem.attrib['org'] = 'list'
      
    write_frames(vColl_elem, lemma)
    
def write_frames(parent_elem, lemma):
    entry = lemma.entry_obj
    frames = entry.actual_frames()
    for frame in frames:
        write_frame_fs(parent_elem, entry, frame)
        
def write_frame_fs(parent_elem, entry, frame):
    frame_xml_id = u'wal_%d.%d-frm' % (entry.id, frame.id)
    
    frame_fs_elem = etree.SubElement(parent_elem, 'fs')
    frame_fs_elem.attrib[etree.QName(XML_NAMESPACE, 'id')] = frame_xml_id
    frame_fs_elem.attrib['type'] = 'frame'
    
    write_frame_meanings(frame_fs_elem, entry, frame)
    write_frame_arguments(frame_fs_elem, entry, frame)
    
def write_frame_meanings(parent_elem, entry, frame):
    meanings_f_elem = etree.SubElement(parent_elem, 'f')
    meanings_f_elem.attrib['name'] = 'meanings'
    
    vColl_elem = etree.SubElement(meanings_f_elem, 'vColl')
    vColl_elem.attrib['org'] = 'list'
    
    for meaning in frame.lexical_units.all():
        write_frame_meaning_link(vColl_elem, entry, meaning)
    
def write_frame_meaning_link(parent_elem, entry, meaning):
    link = u'#wal_%d.%d-mng' % (entry.id, meaning.id)
    lex_unit_link_elem = etree.SubElement(parent_elem, 'fs')
    lex_unit_link_elem.attrib['sameAs'] = link
    lex_unit_link_elem.attrib['type'] = 'lexicalUnit'
    
def write_frame_arguments(parent_elem, entry, frame):
    arguments_f_elem = etree.SubElement(parent_elem, 'f')
    arguments_f_elem.attrib['name'] = 'arguments'
    
    vColl_elem = etree.SubElement(arguments_f_elem, 'vColl')
    vColl_elem.attrib['org'] = 'list'
    
    for arg in frame.complements.all():
        write_frame_argument(vColl_elem, entry, frame, arg)
    
def write_frame_argument(parent_elem, entry, frame, arg):
    arg_base_id = u'wal_%d.%d' % (entry.id, frame.id)
    arg_xml_id = arg_base_id + u'.%d-arg' % arg.id
    
    argument_fs_elem = etree.SubElement(parent_elem, 'fs')
    argument_fs_elem.attrib[etree.QName(XML_NAMESPACE, 'id')] = arg_xml_id
    argument_fs_elem.attrib['type'] = 'argument'

    write_roles(argument_fs_elem, arg)
    write_selective_preferences(argument_fs_elem, arg, arg_base_id)
    
def write_roles(parent_elem, arg):
    for role in arg.roles.order_by('gradient'):
        if role.gradient:
            attribute_f_elem = etree.SubElement(parent_elem, 'f')
            attribute_f_elem.attrib['name'] = 'roleAttribute'
            attribute_symbol_elem = etree.SubElement(attribute_f_elem, 'symbol')
            attribute_symbol_elem.attrib['value'] = unicode(role)
        else:
            role_f_elem = etree.SubElement(parent_elem, 'f')
            role_f_elem.attrib['name'] = 'role'
            role_symbol_elem = etree.SubElement(role_f_elem, 'symbol')
            role_symbol_elem.attrib['value'] = unicode(role)
            
def write_selective_preferences(parent_elem, arg, arg_base_id):
    if(arg.selective_preference):
        sel_prefs_f_elem = etree.SubElement(parent_elem, 'f')
        sel_prefs_f_elem.attrib['name'] = 'selPrefs'
    
        sel_prefs_groups_fs_elem = etree.SubElement(sel_prefs_f_elem, 'fs')
        sel_prefs_groups_fs_elem.attrib['type'] = 'selPrefsGroups'
        
        write_synsets_sel_prefs(sel_prefs_groups_fs_elem, arg)
        write_predefined_sel_prefs(sel_prefs_groups_fs_elem, arg)
        write_relation_sel_prefs(sel_prefs_groups_fs_elem, arg, arg_base_id)
        write_synset_relation_sel_prefs(sel_prefs_groups_fs_elem, arg)
    
def write_synsets_sel_prefs(parent_elem, arg):
    synsets = arg.selective_preference.synsets
    if synsets.exists():
        synsets_f_elem = etree.SubElement(parent_elem, 'f')
        synsets_f_elem.attrib['name'] = 'synsets'
        
        vColl_elem = etree.SubElement(synsets_f_elem, 'vColl')
        vColl_elem.attrib['org'] = 'list'
        
        for synset in synsets.all():
            write_synset(vColl_elem, synset)
            
def write_synset(parent_elem, synset):
    synset_fs_elem = etree.SubElement(parent_elem, 'fs')
    synset_fs_elem.attrib['type'] = 'synset'
    
    plWN_id_elem = etree.SubElement(synset_fs_elem, 'f')
    plWN_id_elem.attrib['name'] = 'plwnid'
    
    id_numeric_elem = etree.SubElement(plWN_id_elem, 'numeric')
    id_numeric_elem.attrib['value'] = str(synset.id)
            
def write_predefined_sel_prefs(parent_elem, arg):
    generals = arg.selective_preference.generals
    if generals.exists():
        predefs_f_elem = etree.SubElement(parent_elem, 'f')
        predefs_f_elem.attrib['name'] = 'predefs'
        
        vColl_elem = etree.SubElement(predefs_f_elem, 'vColl')
        vColl_elem.attrib['org'] = 'list'
        
        for predef in generals.all():
            write_predef(vColl_elem, predef)
            
def write_predef(parent_elem, predef):
    predef_fs_elem = etree.SubElement(parent_elem, 'fs')
    predef_fs_elem.attrib['type'] = 'predef'
    
    name_f_elem = etree.SubElement(predef_fs_elem, 'f')
    name_f_elem.attrib['name'] = 'name'
    
    name_symbol_elem = etree.SubElement(name_f_elem, 'symbol')
    name_symbol_elem.attrib['value'] = predef.name
    
def write_relation_sel_prefs(parent_elem, arg, arg_base_id):
    relations = arg.selective_preference.relations
    if relations.exists():
        relations_f_elem = etree.SubElement(parent_elem, 'f')
        relations_f_elem.attrib['name'] = 'relations'
        
        vColl_elem = etree.SubElement(relations_f_elem, 'vColl')
        vColl_elem.attrib['org'] = 'list'
        
        for relation in relations.all():
            write_relation(vColl_elem, relation, arg_base_id)
            
def write_relation(parent_elem, relation, arg_base_id):
    relation_fs_elem = etree.SubElement(parent_elem, 'fs')
    relation_fs_elem.attrib['type'] = 'relation'
    
    relation_f_elem = etree.SubElement(relation_fs_elem, 'f')
    relation_f_elem.attrib['name'] = 'type'
    
    type_string_elem = etree.SubElement(relation_f_elem, 'string') # tak ni powinno byc
    type_string_elem.text = relation.relation.name
#    type_symbol_elem = etree.SubElement(relation_f_elem, 'symbol') # @todo: tak powinno byc zamiast stringa
#    type_symbol_elem.attrib['value'] = relation.relation.name
    
    to_f_elem = etree.SubElement(relation_fs_elem, 'f')
    to_f_elem.attrib['name'] = 'to'
    
    to_xml_link = '#%s.%d-arg' % (arg_base_id, relation.to.id)
    arg_link_elem = etree.SubElement(to_f_elem, 'fs')
    arg_link_elem.attrib['sameAs'] = to_xml_link
    arg_link_elem.attrib['type'] = 'argument'
    
def write_synset_relation_sel_prefs(parent_elem, arg):
    relations = arg.selective_preference.synset_relations
    if relations.exists():
        relations_f_elem = etree.SubElement(parent_elem, 'f')
        relations_f_elem.attrib['name'] = 'synsetRelations'
        
        vColl_elem = etree.SubElement(relations_f_elem, 'vColl')
        vColl_elem.attrib['org'] = 'list'
        
        for relation in relations.all():
            write_synset_relation(vColl_elem, relation)
            
def write_synset_relation(parent_elem, relation):
    relation_fs_elem = etree.SubElement(parent_elem, 'fs')
    relation_fs_elem.attrib['type'] = 'synsetRelation'
    
    relation_f_elem = etree.SubElement(relation_fs_elem, 'f')
    relation_f_elem.attrib['name'] = 'type'
    
    type_string_elem = etree.SubElement(relation_f_elem, 'string')
    type_string_elem.text = relation.relation.name
#    type_symbol_elem = etree.SubElement(relation_f_elem, 'symbol') # @todo: tak powinno byc zamiast stringa
#    type_symbol_elem.attrib['value'] = relation.relation.name
    
    to_f_elem = etree.SubElement(relation_fs_elem, 'f')
    to_f_elem.attrib['name'] = 'to'
    write_synset(to_f_elem, relation.to)
    
def write_meanings_layer(parent_elem, lemma):
    meanings_layer_elem = etree.SubElement(parent_elem, 'fs')
    meanings_layer_elem.attrib['type'] = 'meaningsLayer'
    
    meanings_f_elem = etree.SubElement(meanings_layer_elem, 'f')
    meanings_f_elem.attrib['name'] = 'meanings'
    
    vColl_elem = etree.SubElement(meanings_f_elem, 'vColl')
    vColl_elem.attrib['org'] = 'list'
      
    write_meanings(vColl_elem, lemma)
    
def write_meanings(parent_elem, lemma):
    entry = lemma.entry_obj
    lex_units = entry.lexical_units()
    for lex_unit in lex_units.all():
        write_meaning(parent_elem, entry, lex_unit)
        
def write_meaning(parent_elem, entry, lex_unit):
    meaning_xml_id = u'wal_%d.%d-mng' % (entry.id, lex_unit.id)
    
    meaning_fs_elem = etree.SubElement(parent_elem, 'fs')
    meaning_fs_elem.attrib[etree.QName(XML_NAMESPACE, 'id')] = meaning_xml_id
    meaning_fs_elem.attrib['type'] = 'lexicalUnit'
    
    name_f_elem = etree.SubElement(meaning_fs_elem, 'f')
    name_f_elem.attrib['name'] = 'name'
    name_content_elem = etree.SubElement(name_f_elem, 'string')
    name_content_elem.text = lex_unit.base
    
    variant_f_elem = etree.SubElement(meaning_fs_elem, 'f')
    variant_f_elem.attrib['name'] = 'variant'
    variant_symbol_elem = etree.SubElement(variant_f_elem, 'symbol')
    variant_symbol_elem.attrib['value'] = lex_unit.sense
    
    plwnluid_f_elem = etree.SubElement(meaning_fs_elem, 'f')
    plwnluid_f_elem.attrib['name'] = 'plwnluid'
    plwnluid_numeric_elem = etree.SubElement(plwnluid_f_elem, 'numeric')
    plwnluid_numeric_elem.attrib['value'] = str(lex_unit.luid)
    
    gloss_f_elem = etree.SubElement(meaning_fs_elem, 'f')
    gloss_f_elem.attrib['name'] = 'gloss'
    gloss_content_elem = etree.SubElement(gloss_f_elem, 'string')
    gloss_content_elem.text = lex_unit.glossa
    
def write_connections_layer(parent_elem, lemma):
    connections_layer_elem = etree.SubElement(parent_elem, 'fs')
    connections_layer_elem.attrib['type'] = 'connectionLayer'
    
    alternations_f_elem = etree.SubElement(connections_layer_elem, 'f')
    alternations_f_elem.attrib['name'] = 'alternations'
    
    vColl_elem = etree.SubElement(alternations_f_elem, 'vColl')
    vColl_elem.attrib['org'] = 'list'
      
    write_alternations(vColl_elem, lemma)
    
def write_alternations(parent_elem, lemma):
    entry = lemma.entry_obj
    frames = entry.actual_frames()
    
    for schema in lemma.frames.all():
        for frame in frames:
            matching_complements = frame.complements.filter(realizations__frame=schema).distinct()
            if matching_complements.filter(realizations__alternation=1).exists():
                alternation_fs_elem = etree.SubElement(parent_elem, 'fs')
                alternation_fs_elem.attrib['type'] = 'alternation'
                
                connections_f_elem = etree.SubElement(alternation_fs_elem, 'f')
                connections_f_elem.attrib['name'] = 'connections'
                
                vColl_elem = etree.SubElement(connections_f_elem, 'vColl')
                vColl_elem.attrib['org'] = 'list'
                
                for arg in frame.complements.all():
                    alt_realizations = arg.realizations.filter(frame=schema, alternation=1)
                    write_connection(vColl_elem, entry, frame, arg, alt_realizations)
            
            if matching_complements.filter(realizations__alternation=2).exists():
                alternation_fs_elem = etree.SubElement(parent_elem, 'fs')
                alternation_fs_elem.attrib['type'] = 'alternation'
                
                connections_f_elem = etree.SubElement(alternation_fs_elem, 'f')
                connections_f_elem.attrib['name'] = 'connections'
                
                vColl_elem = etree.SubElement(connections_f_elem, 'vColl')
                vColl_elem.attrib['org'] = 'list'
                      
                for arg in frame.complements.all():
                    alt_realizations = arg.realizations.filter(frame=schema, alternation=2)
                    write_connection(vColl_elem, entry, frame, arg, alt_realizations)
                    
def write_connection(parent_elem, entry, frame, arg, realizations):
    connection_fs_elem = etree.SubElement(parent_elem, 'fs')
    connection_fs_elem.attrib['type'] = 'connection'
    
    write_argument(connection_fs_elem, entry, frame, arg)
    write_phrases(connection_fs_elem, entry, realizations)
    
def write_argument(parent_elem, entry, frame, arg):
    arg_f_elem = etree.SubElement(parent_elem, 'f')
    arg_f_elem.attrib['name'] = 'argument'
    
    arg_link = u'#wal_%d.%d.%d-arg' % (entry.id, frame.id, arg.id)
    arg_link_fs_elem = etree.SubElement(arg_f_elem, 'fs')
    arg_link_fs_elem.attrib['sameAs'] = arg_link
    arg_link_fs_elem.attrib['type'] = 'argument'
    
def write_phrases(parent_elem, entry, realizations): 
    phrases_f_elem = etree.SubElement(parent_elem, 'f')
    phrases_f_elem.attrib['name'] = 'phrases'
    vColl_elem = etree.SubElement(phrases_f_elem, 'vColl')
    vColl_elem.attrib['org'] = 'list'
    
    for realization in realizations:
        phrase_xml_link = u'#wal_%d.%d.%d.%d-phr' % (entry.id, realization.frame.id,
                                                     realization.position.id, realization.argument.id)
        phrase_link_elem = etree.SubElement(vColl_elem, 'fs')
        phrase_link_elem.attrib['sameAs'] = phrase_xml_link
        phrase_link_elem.attrib['type'] = 'phrase'  


    
def writefsdecl(outfile):
    '''
    Write feature structures declarations
    '''
    outfile.write(u'  <encodingDesc>\n')
    outfile.write(u'    <fsdDecl>\n')

# syntacticBahaviour fs declaration
    outfile.write(u'      <fsDecl type="syntacticBehaviour">\n')
    outfile.write(u'        <fsDescr>Describes syntactic behaviour of entry</fsDescr>\n')
    outfile.write(u'        <fDecl name="frames">\n')
    outfile.write(u'          <fDescr>syntactic frames</fDescr>\n')    
    outfile.write(u'          <vRange>\n')  
    outfile.write(u'            <vColl org="list">\n')
    outfile.write(u'              <fs type="frame"/>\n')
    outfile.write(u'            </vColl>\n')
    outfile.write(u'          </vRange>\n')  
    outfile.write(u'        </fDecl>\n')    
    outfile.write(u'      </fsDecl>\n')
    
# frame fs declaration
    outfile.write(u'      <fsDecl type="frame">\n')
    outfile.write(u'        <fsDescr>Describes syntactic frame</fsDescr>\n')
    # frame opinion
    outfile.write(u'        <fDecl name="opinion">\n') 
    outfile.write(u'          <fDescr>frame opinion</fDescr>\n')  
    outfile.write(u'          <vRange>\n')
    outfile.write(u'            <vAlt>\n')   
    for alt in Frame_Opinion_Value.objects.order_by('priority'):
        outfile.write(u'              <symbol value="%s"/>\n' % alt.short)     
    outfile.write(u'            </vAlt>\n')   
    outfile.write(u'          </vRange>\n')       
    outfile.write(u'        </fDecl>\n')
    # reflex
    outfile.write(u'        <fDecl name="reflex">\n') 
    outfile.write(u'          <fDescr>frame reflexivity</fDescr>\n')  
    outfile.write(u'          <vRange>\n')
    outfile.write(u'            <vAlt>\n')   
    outfile.write(u'              <binary value="true"/>\n')   
    outfile.write(u'              <binary value="false"/>\n')        
    outfile.write(u'            </vAlt>\n')   
    outfile.write(u'          </vRange>\n')       
    outfile.write(u'        </fDecl>\n')  
    # aspect
    outfile.write(u'        <fDecl name="aspect">\n') 
    outfile.write(u'          <fDescr>frame aspect</fDescr>\n')  
    outfile.write(u'          <vRange>\n')
    outfile.write(u'            <vAlt>\n')
    aspect_obj = Frame_Char_Model.objects.get(model_name=u'ASPEKT')
    for alt in aspect_obj.frame_char_values.order_by('priority'):
        outfile.write(u'              <symbol value="%s"/>\n' % 
                      alt.value)        
    outfile.write(u'            </vAlt>\n')   
    outfile.write(u'          </vRange>\n')       
    outfile.write(u'        </fDecl>\n')    
    # negatywnosc
    outfile.write(u'        <fDecl name="negativity">\n') 
    outfile.write(u'          <fDescr>frame negativity</fDescr>\n')  
    outfile.write(u'          <vRange>\n')
    outfile.write(u'            <vAlt>\n')
    aspect_obj = Frame_Char_Model.objects.get(model_name=u'NEGATYWNOŚĆ')
    for alt in aspect_obj.frame_char_values.order_by('priority'):
        outfile.write(u'              <symbol value="%s"/>\n' % 
                      alt.value)        
    outfile.write(u'            </vAlt>\n')   
    outfile.write(u'          </vRange>\n')       
    outfile.write(u'        </fDecl>\n')   
    # predykatywnosc
    outfile.write(u'        <fDecl name="predicativity">\n') 
    outfile.write(u'          <fDescr>frame predicativity</fDescr>\n')  
    outfile.write(u'          <vRange>\n')
    outfile.write(u'            <vAlt>\n')
    aspect_obj = Frame_Char_Model.objects.get(model_name=u'PREDYKATYWNOŚĆ')
    for alt in aspect_obj.frame_char_values.order_by('priority'):
        outfile.write(u'              <symbol value="%s"/>\n' % 
                      alt.value)        
    outfile.write(u'            </vAlt>\n')   
    outfile.write(u'          </vRange>\n')       
    outfile.write(u'        </fDecl>\n') 
    # positions   
    outfile.write(u'        <fDecl name="positions">\n')
    outfile.write(u'          <fDescr>syntactic positions</fDescr>\n')    
    outfile.write(u'          <vRange>\n')  
    outfile.write(u'            <vColl org="list">\n')
    outfile.write(u'              <fs type="position"/>\n')
    outfile.write(u'            </vColl>\n')
    outfile.write(u'          </vRange>\n')  
    outfile.write(u'        </fDecl>\n')    
    outfile.write(u'      </fsDecl>\n')
    
# position fs declaration
    outfile.write(u'      <fsDecl type="position">\n')
    outfile.write(u'        <fsDescr>Describes syntactic position</fsDescr>\n')
    # position category
    outfile.write(u'        <fDecl name="category">\n') 
    outfile.write(u'          <fDescr>position category</fDescr>\n')  
    outfile.write(u'          <vRange>\n')
    outfile.write(u'            <vAlt>\n')   
    for alt in PositionCategory.objects.filter(control=False).order_by('priority'):
        outfile.write(u'              <symbol value="%s"/>\n' % alt.category)     
    outfile.write(u'            </vAlt>\n')   
    outfile.write(u'          </vRange>\n')       
    outfile.write(u'        </fDecl>\n')
    # position control
    outfile.write(u'        <fDecl name="control">\n') 
    outfile.write(u'          <fDescr>position category</fDescr>\n')  
    outfile.write(u'          <vRange>\n')
    outfile.write(u'            <vAlt>\n')   
    for alt in PositionCategory.objects.filter(control=True).order_by('priority'):
        outfile.write(u'              <symbol value="%s"/>\n' % alt.category)     
    outfile.write(u'            </vAlt>\n')   
    outfile.write(u'          </vRange>\n')       
    outfile.write(u'        </fDecl>\n')  
    # arguments   
    outfile.write(u'        <fDecl name="arguments">\n')
    outfile.write(u'          <fDescr>syntactic arguments</fDescr>\n')    
    outfile.write(u'          <vRange>\n')  
    outfile.write(u'            <vColl org="list">\n')
    outfile.write(u'              <fs type="argument"/>\n')
    outfile.write(u'            </vColl>\n')
    outfile.write(u'          </vRange>\n')  
    outfile.write(u'        </fDecl>\n')    
    outfile.write(u'      </fsDecl>\n')
    
# argument fs declaration
    outfile.write(u'      <fsDecl type="argument">\n')
    outfile.write(u'        <fsDescr>Describes syntactic argument</fsDescr>\n')
    # position category
    outfile.write(u'        <fDecl name="type">\n') 
    outfile.write(u'          <fDescr>type of argument</fDescr>\n')  
    outfile.write(u'          <vRange>\n')
    outfile.write(u'            <vAlt>\n')   
    for alt in Argument_Model.objects.order_by('priority'):
        outfile.write(u'              <symbol value="%s"/>\n' % alt.arg_model_name)     
    outfile.write(u'            </vAlt>\n')   
    outfile.write(u'          </vRange>\n')       
    outfile.write(u'        </fDecl>\n')
    #  attributes  
    outfile.write(u'        <fDecl name="attributes">\n')
    outfile.write(u'          <fDescr>argument attributes</fDescr>\n')    
    outfile.write(u'          <vRange>\n')  
    outfile.write(u'            <vColl org="list">\n')
    outfile.write(u'              <fs type="attribut"/>\n')
    outfile.write(u'            </vColl>\n')
    outfile.write(u'          </vRange>\n')  
    outfile.write(u'        </fDecl>\n')    
    outfile.write(u'      </fsDecl>\n')
    
    outfile.write(u'    </fsdDecl>\n')      
    outfile.write(u'  </encodingDesc>\n')