Skip to content
Snippets Groups Projects
ClassesGenofig.py 43.2 KiB
Newer Older
Copyright 2023 INRAE, Université de Tours
requests at: sebastien.leclercq@inrae.fr

This file is part of GenoFig.

GenoFig 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.

Genofig 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.
A copy of the GNU General Public License is available in the COPYING file. If not, see <https://www.gnu.org/licenses/>
This script may use some code adapted from Easyfig v2.1.1 written by Mitchell Sullivan and licensed under GNU GPLv3 (http://mjsull.github.io/Easyfig/files.html - Legacy versions)
'''


# Gtk modules
Sebastien Leclercq's avatar
Sebastien Leclercq committed
from gi.repository import Gtk,GObject

# BioPython modules
from Bio import SeqIO
from Bio.SeqFeature import FeatureLocation

import re
import copy
import tempfile


# Parse the Input File (Fasta or Genbank) to extract and store information
#--------------------------------------------------------------------------
def parseSeqFile(filename,outtype):
        ftype=filename[filename.rfind('.')+1:]

        parsed=None

        # Detect the format from the file extension
        if re.match(r'fa|fna',ftype):
          parsed = SeqIO.parse(filename, "fasta")
    
        if re.match(r'gb|genbank',ftype):
          parsed = SeqIO.parse(filename, "genbank")

        # Try to detect the format without an obvious file extension
        if parsed == None:
          filein = open(filename)
          line=filein.read(10)         
          if line.startswith('>'):
             parsed = SeqIO.parse(filename, "fasta")
          if line.startswith('LOCUS'):
             parsed = SeqIO.parse(filename, "genbank")
Sebastien Leclercq's avatar
Sebastien Leclercq committed

        # return a list of seqentries, with a postreatment on their accession.
        if outtype == "L":
          filelist= []
          for seqentry in parsed:
           filelist.append([getSeqname(seqentry),seqentry])
          return filelist

        # return a dictionary of seqEntries, matching to their accesssion in the input (have to be unique)
        if outtype == "D":
          filelist= {}
          for seqentry in parsed:
           filelist[getSeqname(seqentry)] = seqentry
          return filelist


# Get the sequence ACCESSION ID
#--------------------------------------------------------------------------
def getSeqname(record):
        componame = record.name.split("|")

        # Depends if its a fasta or a genbank
        if len(componame) > 3:  
             shortname= componame[3].split(".")[0]
        elif len(componame) > 2:  
             shortname= componame[1].split(".")[0] + componame[2]
        else: 
             shortname=componame[0]

        return shortname

################################################################################################
#
# This is a custom class to insert colored buttons (with icons only) into the sequence and feature table 
#
#######################################################text#########################################
class CellRendererButton( Gtk.CellRendererPixbuf ):
        __gproperties__ = { "callable": ( GObject.TYPE_PYOBJECT,
                                      "callable property",
                                      "callable property",
                                      GObject.PARAM_READWRITE ) }
        _button_width = 2
        _button_height = 1

        def __init__( self ):
#                self.__GObject_init__()
                Gtk.CellRendererPixbuf.__init__( self )
                self.set_property( "xalign", 0.5 )
                self.set_property( "mode", Gtk.CellRendererMode.ACTIVATABLE )
                self.set_property('cell-background-set' , True) 
                self.activatable = True
                self.callable = None
                self.table = None


        def do_get_property( self, pspec ):
                if pspec.name == "callable":
                        return self.callable
                else:
                        raise AttributeError( "Unknown property %s" % pspec.name )
 
        def do_set_property( self, pspec, value ):
                if pspec.name == "callable":
                        if callable( value ):
                                self.callable = value
                        else:
                                raise TypeError( "callable property must be callable!" )
                else:
                        raise AttributeError( "Unknown property %s" % pspec.name )


        def do_get_size( self, wid, cell_area ):
                xpad = self.get_property( "xpad" )
                ypad = self.get_property( "ypad" )

                if not cell_area:
                        x, y = 0, 0
                        w = 2 * xpad + self._button_width
                        h = 2 * ypad + self._button_height
                else:
                        w = 2 * xpad + cell_area.width
                        h = 2 * ypad + cell_area.height

                        xalign = self.get_property( "xalign" )
                        yalign = self.get_property( "yalign" )

                        x = max( 0, xalign * ( cell_area.width - w ) )
                        y = max( 0, yalign * ( cell_area.height - h ) )

                return ( x, y, w, h )

        def do_render( self, window, wid, bg_area, cell_area, flags ):
                if not window:
                        return


                flags = flags & Gtk.CellRendererState.SELECTED
                Gtk.CellRendererPixbuf.do_render( self, window, wid, bg_area,
                                                              cell_area, flags )

        def do_activate( self, event, wid, path, bg_area, cell_area, flags ):
                cb = self.get_property( "callable" )
                if cb != None :
                        cb (path)
                return True
                
        def set_color(self,colRGBA):
                self.set_property("cell-background-rgba",colRGBA)
# _CellRendererButton




################################################################################################
#
# This is a custom ListStore class which exclude the first line from the drag and drop
#
################################################################################################
class ListStoreDnd(Gtk.ListStore):
        def __init__(*args):
           Gtk.ListStore.__init__(*args)
         

        # To forbid movements of the [two] first rows 
        def do_row_draggable(self,path):
          if str(path) == '0' :
             return False
          else:
             return True

        # Avoid drag and drop before the [two] first row
        def do_row_drop_possible(self, dest, selection_data):
          if ':' in str(dest) or str(dest) == '0': 
            return False
          else:
            return True 

        def saveinfasta(self):
         Ffile = tempfile.NamedTemporaryFile(mode='w',delete=False)
         viewedNames={} # to avoid multiple copies of the same sequence being blasted 
         for s in self.return_seqEntries():
           if not s.bname in viewedNames.keys():
              Ffile.write(">" + s.bname + "\n" + str(s.record.seq) + "\n")
              viewedNames[s.bname]=1
         return Ffile.name


        # Transform the ListStore as a list of SeqEntries, more convenient to be handled in the Drawing script 
        def return_seqEntries(self):
          seqs = []

          # Skip the first row which is the general sequence information        
          S = self.get_iter_first()
          S = self.iter_next(S)
          while S != None:
            entry = SeqEntry(self.get_value(S,3),self.get_value(S,5).bname,self.get_value(S,5).record)
            entry.gp['file'] = self.get_value(S,5).file # get the original file path for save/reload purpose
            entry.gp['sel'] = int(self.get_value(S,6))
            entry.gp['height'] = self.get_value(S,7)
            entry.gp['lwidth'] = self.get_value(S,8)
            entry.gp['inspace'] = self.get_value(S,9)
            entry.gp['lcol'] = self.get_value(S,12)
            entry.gp['spos'] = self.get_value(S,13)
            entry.gp['sxpos'] = self.get_value(S,11)
            entry.gp['min'] = self.get_value(S,14)
            entry.gp['max'] = self.get_value(S,15)
            entry.gp['rev'] = self.get_value(S,16)

            entry.gp['slabsel'] = self.get_value(S,17)
            entry.gp['slabid'] = self.get_value(S,18)
            entry.gp['slabpos'] = self.get_value(S,19)
            entry.gp['slaboffset'] = self.get_value(S,30)
            entry.gp['slabcol'] = self.get_value(S,21)
            entry.gp['slabsize'] = self.get_value(S,22)
            entry.gp['slabbold'] = self.get_value(S,32)
            entry.gp['slabital'] = self.get_value(S,33)

            entry.gp['flabsel'] = self.get_value(S,23)
            entry.gp['flabval'] = self.get_value(S,24)
            entry.gp['flabpos'] = self.get_value(S,25)
            entry.gp['flabcol'] = self.get_value(S,27)
            entry.gp['flabsize'] = self.get_value(S,28)
            entry.gp['flabrot'] = self.get_value(S,29)
            
            entry.gp['ID'] = self.get_value(S,31)


            seqs.append(entry)
            S = self.iter_next(S)
          return seqs


        # Transform the ListStore as a list Feature dictionaries, more convenient to be handled in the Drawing script 
        def return_featDictionary(self):
          feats = []

          F = self.get_iter_first()
          F = self.iter_next(F)
          while F != None:
            entry = {}
            entry['id'] = self.get_value(F,3)
            entry['sel'] = int(self.get_value(F,4))
            entry['flegsel'] = int(self.get_value(F,26))

            entry['feat'] = self.get_value(F,5)
            entry['strand'] = self.get_value(F,6)
            entry['shape'] = self.get_value(F,7)
            entry['hatching'] = self.get_value(F,8)
            entry['height'] = self.get_value(F,9)

            entry['col'] = self.get_value(F,11)
            entry['fill'] = int(self.get_value(F,12))
            entry['stroke'] = self.get_value(F,13)
            entry['strokecol'] = self.get_value(F,15)

            entry['filter'] = self.get_value(F,16)
            entry['field'] = self.get_value(F,17)

            entry['flabsel'] = self.get_value(F,19)
            entry['flabval'] = self.get_value(F,20)
            entry['flabpos'] = self.get_value(F,21)
            entry['flabbold'] = self.get_value(F,27)
            entry['flabital'] = self.get_value(F,28)
            entry['flabcol'] = self.get_value(F,23)
            entry['flabsize'] = self.get_value(F,24)
            entry['flabrot'] = self.get_value(F,25)


            feats.append(entry)
            F = self.iter_next(F)
          return feats

        # Transform the ListStore as a list Decoration dictionaries, more convenient to be handled in the Drawing script 
        def return_decoDictionary(self):
          decoration = []

          D = self.get_iter_first()
          D = self.iter_next(D)
          while D != None:
            entry = {}
            entry['id'] = self.get_value(D,4)
            entry['select'] = int(self.get_value(D,5))
            entry['type'] = self.get_value(D,6)
            entry['step'] = int(self.get_value(D,7))
            entry['window'] = int(self.get_value(D,8))

            entry['pos'] = self.get_value(D,9)
            entry['heightR'] = self.get_value(D,10)
            entry['linewidth'] = self.get_value(D,11)
            entry['linecolor'] = self.get_value(D,13)
            entry['reverse'] = self.get_value(D,14)
            entry['labelprint'] = self.get_value(D,15)

            entry['labelcolor'] = self.get_value(D,17)
            entry['labelsize'] = self.get_value(D,18)
            entry['labelpos'] = self.get_value(D,19)
            entry['labelgbkpos'] = self.get_value(D,21)
Sebastien Leclercq's avatar
Sebastien Leclercq committed

            decoration.append(entry)
            D = self.iter_next(D)
          return decoration

################################################################################################
#
# Transfer Class to copy the information from the Dndlistbox sequence type
# for use in the Drawing command
#
################################################################################################
class SeqEntry:

    #--------------------------------------------------------------------------
    def __init__(self,seqname,bname,rec):

      self.record = copy.deepcopy(rec)
      self.bname = bname

      self.gp = {}
      self.gp['name'] = seqname

      # Drawing parameters
      self.xpos  = 0
      self.ypos  = 0
      self.length  = len(self.record.seq)
      self.lengthO = self.length

      # Set the record name if necessary
      if self.record.name == '<unknown name>': self.record.name = seqname



################################################################################################
#
# Small class to store the BioSeq record into the ListStore
#
################################################################################################
class BioSeqobj(GObject.GObject):

    def __init__(self,rec,afile):
        GObject.GObject.__init__(self)
        self.file = afile
        self.record = rec

        # create a unique name including Accession + reverse compl. and region information when necessary
        self.bname = self.record.name
        if 'accessions' in self.record.annotations.keys() and 'REGION:' in self.record.annotations['accessions']:
          R = self.record.annotations['accessions'][2].replace("complement(","c").replace(")","")
          self.bname += "_"+R

    def length(self):
        return self.record.__len__()

    def getfile(self):
        return self.file


    # to get general infos for dialog box
    def getinfo(self):
        infos = ""
        infos = infos + "name:\t"+self.record.name+"\n"

        if 'accessions' in self.record.annotations.keys():
          infos = infos + "accession:\t"+self.record.annotations['accessions'][0]+"\n"
          if 'REGION:' in self.record.annotations['accessions']:
           infos = infos + "position in accession:\t"+self.record.annotations['accessions'][2]+"\n"

        if 'source' in self.record.annotations.keys():
          infos = infos + "source:\t"+self.record.annotations['source']+"\n"
        if 'organism' in self.record.annotations.keys():
          infos = infos + "organism:\t"+self.record.annotations['organism']+"\n"

        if len(self.record.features) > 0 and ("strain" in self.record.features[0].qualifiers.keys()): 
          infos = infos + "strain:\t"+self.record.features[0].qualifiers["strain"][0]+"\n"

Sebastien Leclercq's avatar
Sebastien Leclercq committed
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 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
        infos = infos + "description:\t"+self.record.description+"\n"
        infos = infos + "size:\t"+str(self.length())+" bp\n"
        infos = infos + "filename:\t"+self.file

        return infos


    def getFeattypes(self):
        featslist = {}
        for feat in self.record.features:
            if feat.type != "source":
             featslist[feat.type] = 0
        return featslist.keys()




################################################################################################
#
# This is a custom Dialog class to ask for a custom x position for sequences
#
################################################################################################
class DialogXpos(Gtk.Dialog):

    def __init__(self,parent,seqname,xval):
        Gtk.Dialog.__init__(self,"custom position",parent)


        self.set_default_size(170, 50)

        labelX = Gtk.Label("x position for "+seqname+":")
        self.entryX = Gtk.Entry()
        self.entryX.set_text(xval)
        self.entryX.connect("activate", self.on_entry_edited)

        contentbox = self.get_content_area()
        contentbox.add(labelX)
        contentbox.add(self.entryX)
        self.show_all()

    def on_entry_edited(self,widget):
        self.response(Gtk.ResponseType.OK)



################################################################################################
#
# This is a custom Entry class to set up directly the size and the default value
#
################################################################################################
class EntrySmall(Gtk.Entry):

    def __init__(self,size,value, minval, maxval):
        Gtk.Entry.__init__(self)

        self.min = minval
        self.max = maxval
        self.savedval = value

        self.set_width_chars(size)
        self.set_max_width_chars(size)
        self.set_text(value)

        # to check the value integrity after modification
        self.connect("focus-out-event",self.checkvalue)
    

    # Automatically check whether the value is integer and in the range of min-max value
    def checkvalue(self,entry,val2):
       text = entry.get_text()

       try: int(text)
       except: entry.set_text(self.savedval)
       else:
         if   int(text) < self.min: entry.set_text(str(self.min))
         elif int(text) > self.max: entry.set_text(str(self.max))
         else: 
           entry.set_text(text)
           self.savedval = text



################################################################################################
#
# A child of EntrySmall class to deal with float values
#
################################################################################################
class EntrySmallFloat(EntrySmall):

    def __init__(self,size,value, minval, maxval):
        EntrySmall.__init__(self,size,value, minval, maxval)  


    # Automatically check whether the value is float and in the range of min-max value
    def checkvalue(self,entry,val2):
       text = entry.get_text()

       try: float(text)
       except: entry.set_text(self.savedval)
       else:
         if   float(text) < self.min: entry.set_text(str(self.min))
         elif float(text) > self.max: entry.set_text(str(self.max))
         else: 
           entry.set_text(text)
           self.savedval = text
 
################################################################################################
#
# A child of EntrySmall class to deal with "-" values
#
################################################################################################
class EntrySmallSameAs(EntrySmall):

    def __init__(self,size,value, minval, maxval):
        EntrySmall.__init__(self,size,value, minval, maxval)  


    # Automatically check whether the value is float and in the range of min-max value
    def checkvalue(self,entry,val2):
       text = entry.get_text()

       if text=='' or text==' ' or text=='-':
         entry.set_text("-")
         self.savedval = "-"
         return 1

       try: float(text)
       except: entry.set_text(self.savedval)
       else:
         if   float(text) < self.min: entry.set_text(str(self.min))
         elif float(text) > self.max: entry.set_text(str(self.max))
         else: 
           entry.set_text(text)
           self.savedval = text
 
      

################################################################################################
#
# This is a custom CellCombo class to set up directly the model and other properties
#
################################################################################################
class CellRendererComboNoEntry(Gtk.CellRendererCombo):

    def __init__(self,liststore):
        Gtk.CellRendererCombo.__init__(self)

        self.set_property("editable", True)
        self.set_property("has-entry", False)
        self.set_property("text-column",0)
        self.set_property("model",liststore)


################################################################################################
#
# This is a custom Dialog class to create the custom blast selection
#
################################################################################################
class DialogCustomBlast(Gtk.Dialog):

    #------------------------------------------------------
    def __init__(self, parent, blasttype, listseqs, listchecked):
        Gtk.Dialog.__init__(self, title="Custom matches selection for "+blasttype, parent=parent, modal=True)
        self.add_buttons(Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)

        self.nbseqs = len(listseqs)

        self.set_default_size(150, 150)
        self.set_modal(False)

        # Avoid the destruction of the window
        self.connect('delete-event', lambda w, e: w.hide() or True)
        self.connect('response', lambda w, e: w.hide() or True)


        # Box including a grid displaying the cross-sequence selection
        self.boxBlastSel = Gtk.Box(Gtk.Orientation.VERTICAL,3)
        self.boxBlastSel.set_property("margin-bottom",20)
        self.gridBlastSel = Gtk.Grid()


        # create labels for the selection
        for i in range(0,self.nbseqs):
           labnby = Gtk.Label(str(i+1)+". ")
           labely = Gtk.Button(listseqs[i])
           labely.connect("clicked",self.on_click_Name,i)
           labnby.set_xalign(1)         
           labely.set_property("margin-end",4)

           # print the number and sequence name in lines
           self.gridBlastSel.attach(labnby,0,i,1,1)
           self.gridBlastSel.attach(labely,1,i,1,1)

           # print the number in columns, but skip the last sequence
           if i < self.nbseqs-1:
            self.gridBlastSel.attach(Gtk.Label(str(i+1)+"."),i+2,self.nbseqs,1,1)

        # create the checkboxes
        for i in range(0,self.nbseqs):
           seq1 = self.gridBlastSel.get_child_at(1,i)
           for j in range(0,i):
              checkb = Gtk.CheckButton()

              # test if it was checked previously
              if listchecked != None:
               seq2 = self.gridBlastSel.get_child_at(1,j)
               for cc in listchecked:
                if seq1.get_label() in cc and seq2.get_label() in cc: # here is the real check test
                 checkb.set_active(True)
                 listchecked.remove(cc)

              # insert the checkbox in that grid
              self.gridBlastSel.attach(checkb,j+2,i,1,1)


        # create buttons
        self.labbb = Gtk.Label("Select:", name="label-blast")
        self.labbb.set_xalign(0)         
        self.butAdj = Gtk.Button("Adjacent")
        self.butAdj.connect("clicked",self.on_click_Adj)
        self.butNoAdj = Gtk.Button("No Adj.")
        self.butNoAdj.connect("clicked",self.on_click_NoAdj)
        self.butAll = Gtk.Button("All")
        self.butAll.connect("clicked",self.on_click_All)
        self.butClear = Gtk.Button("Clear")
        self.butClear.connect("clicked",self.on_click_Clear)


        self.boxBlastSel.pack_start(self.labbb,False,True,0)
        self.boxBlastSel.pack_start(self.butAdj,False,True,0)
        self.boxBlastSel.pack_start(self.butNoAdj,False,True,0)
        self.boxBlastSel.pack_start(self.butAll,False,True,0)
        self.boxBlastSel.pack_start(self.butClear,False,True,0)

        scrolledwindow = Gtk.ScrolledWindow()
        scrolledwindow.set_policy(Gtk.PolicyType.AUTOMATIC,Gtk.PolicyType.AUTOMATIC)
        scrolledwindow.set_min_content_height(600)
        scrolledwindow.add(self.gridBlastSel)

        box = self.get_content_area()
        box.add(self.boxBlastSel)
        box.add(scrolledwindow)
        box.set_property("margin",10)
        box.show_all()


    # return the list of checked combinations
    #------------------------------------------------------
    def get_checked(self):
        print("look at checked")
        listchecked = []

        # pass all the checkboxes
        for i in range(0,self.nbseqs):
         for j in range(0,i):
           check = self.gridBlastSel.get_child_at(j+2,i)
           # store when active
           if check.get_active():
            seq1 = self.gridBlastSel.get_child_at(1,j)
            seq2 = self.gridBlastSel.get_child_at(1,i)
            listchecked.append([seq1.get_label(),seq2.get_label()])

        return listchecked

    # return the matrix of checked combinations
    #------------------------------------------------------
    def get_checkedMatrix(self):
        mxchecked = []

        # pass all the checkboxes
        for i in range(0,self.nbseqs):
         mxchecked.append([])
         for j in range(0,i):
           check = self.gridBlastSel.get_child_at(j+2,i)
           # store 1 when active, 0 otherwise
           if check.get_active():
            mxchecked[i].append(1)
           else:
            mxchecked[i].append(0)

        return mxchecked


    # various selection actions
    #------------------------------------------------------
    def on_click_Adj(self,button):
        for i in range(2,self.nbseqs+1):
         check = self.gridBlastSel.get_child_at(i,i-1)
         check.set_active(True)

    def on_click_NoAdj(self,button):
        for i in range(2,self.nbseqs+1):
         check = self.gridBlastSel.get_child_at(i,i-1)
         check.set_active(False)

    def on_click_All(self,button):
        for i in range(2,self.nbseqs+1):
         for j in range(2,i+1):
           check = self.gridBlastSel.get_child_at(j,i-1)
           check.set_active(True)

    def on_click_Clear(self,button):
        for i in range(2,self.nbseqs+1):
         for j in range(2,i+1):
           check = self.gridBlastSel.get_child_at(j,i-1)
           check.set_active(False)

    def on_click_Name(self,button,pos):
       for i in range(2,pos+2):
            check = self.gridBlastSel.get_child_at(i,pos)
            check.set_active(True)
       for i in range(pos+1,self.nbseqs):
            check = self.gridBlastSel.get_child_at(pos+2,i)
            check.set_active(True)


################################################################################################
#
# This is a custom Filechooser dialog class for sequence selection
# -> to avoid core dumped errors linked to python library bugs not fixed
#
################################################################################################
class SeqFileChooserDialog(Gtk.FileChooserDialog):
    #------------------------------------------------------
    def __init__(self, parent, title,action):
        Gtk.FileChooserDialog.__init__(self,title="Please choose a sequence file", parent=parent, action=Gtk.FileChooserAction.OPEN)
        
        # Avoid the destruction of the window to avoid Segmentation fault
        self.connect('delete-event', lambda k, e: k.hide() or True)
        self.connect('response', lambda k, e: k.hide() or True)


################################################################################################
#
# This is a custom Dialog class to create the custom decoration selection
#
################################################################################################
class DialogCustomDecoration(Gtk.Dialog):

    #------------------------------------------------------
    def __init__(self, parent, seqslist):
        Gtk.Dialog.__init__(self, title="Custom sequences display for Decoration", parent=parent, modal=True)
        #self.add_buttons(Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)
        
        self.seqIDlist = [a[0] for a in seqslist]
        self.seqNamelist = [a[1] for a in seqslist]
        self.nbseqs = len(seqslist)

        self.set_default_size(400, 350)
        self.set_modal(False)

        # Avoid the destruction of the window
        self.connect('delete-event', lambda w, e: w.hide() or True)
        self.connect('response', lambda w, e: w.hide() or True)


        self.gridDecoSel = Gtk.Grid()
 
        self.scrolledwindow = Gtk.ScrolledWindow()
        self.scrolledwindow.set_policy(Gtk.PolicyType.NEVER,Gtk.PolicyType.AUTOMATIC)
        self.scrolledwindow.set_min_content_height(350)
        self.scrolledwindow.add(self.gridDecoSel)

        self.butValidate = Gtk.Button(label="Validate")
        self.butValidate.connect("clicked", self.on_validate_customSeq, parent)

        self.decoNameLabel = Gtk.Label()

        self.box = self.get_content_area()
        self.box.add(self.decoNameLabel)
        self.box.add(self.scrolledwindow)
        self.box.add(self.butValidate)
        self.box.set_property("margin",10)
        self.box.show_all()

    def update_seqslist(self, seqslist, decoName):
        self.seqIDlist = [a[0] for a in seqslist]
        self.seqNamelist = [a[1] for a in seqslist]
        self.nbseqs = len(seqslist)
        
        self.decoNameLabel.set_text(decoName)

        while True:
            if self.gridDecoSel.get_child_at(0,1)!= None:
                self.gridDecoSel.remove_row(1)
            else:
                break

        checkAll = Gtk.Button(label="Check All")
        checkAll.connect('clicked', self.check_all)
        self.gridDecoSel.attach(checkAll,0,0,2,1)
        uncheckAll = Gtk.Button(label="Uncheck All")
        uncheckAll.connect('clicked', self.uncheck_all)
        self.gridDecoSel.attach(uncheckAll,3,0,2,1)

        # create labels for the selection
        for i in range(0,self.nbseqs):
            label = Gtk.Label(str(self.seqNamelist[i]))
            labely = Gtk.Switch()
            labely.set_active(False)
            label.set_xalign(1)         

            # print the number and sequence name in lines
            self.gridDecoSel.attach(label,0,i+1,2,1)
            self.gridDecoSel.attach(Gtk.Label(label=" "),2,i+1,2,1)
            self.gridDecoSel.attach(labely,4,i+1,1,1)

            self.gridDecoSel.show_all()

    def on_validate_customSeq(self, widget, parent):
        parent.DecorationSequences[self.decoNameLabel.get_text()] = self.get_checked()
        self.hide()

    
    # return the list of checked combinations
    #------------------------------------------------------
    def get_checked(self):
        listchecked = dict()
        for i in range(0,max(self.seqIDlist)):
            try:
                switch = self.gridDecoSel.get_child_at(4,i+1)
                if switch.get_active():
                    listchecked[self.seqIDlist[i]] = 1
                else:
                    listchecked[self.seqIDlist[i]] = 0
            except:
                continue
        return listchecked

    def update_check_from_values(self, values):
        for i in range(0,max(self.seqIDlist)):
            try:
                switch = self.gridDecoSel.get_child_at(4,i+1)
                if values[self.seqIDlist[i]] == 1:
                    switch.set_active(True)
                else:
                    switch.set_active(False)
            except:
                continue

    
    def check_all(self, widget):
        for i in range(0,self.nbseqs):
            switch = self.gridDecoSel.get_child_at(4,i+1)
            switch.set_active(True)

    def uncheck_all(self, widget):
        for i in range(0,self.nbseqs):
            switch = self.gridDecoSel.get_child_at(4,i+1)
            switch.set_active(False)


################################################################################################
#
# Blast table data Class
#
################################################################################################
class BlastTable:
    #--------------------------------------------------------------------------
    def __init__(self, nbseq, hashseq, minlength, maxeval, minident):

        # get the filter parameters
        self.hashseq = hashseq
        self.minlength = int(minlength)
        self.maxeval = float(maxeval)
        self.minident = float(minident)

        # initialize the blast table 
        # with the number of row and column equal to the number of sequences
        self.Btable = []

        for i in range(0,nbseq):
         self.Btable.append(list())
         for j in range(0,nbseq):
          self.Btable[i].append(list())
       

    # gets all blast hits length > minlength and e value < mineval and identity > minident
    #--------------------------------------------------------------------------
    def readBlast(self,filename):

       # Test for Blast file presence
       if filename == '':
        return None

       # Get Blast Information
       blast = open(filename)

       lineI= blast.readline().rstrip()
       if lineI.find("\t") > 0: spchar = "\t" 
       elif lineI.find(",") > 0: spchar = "," 
       elif lineI.find(" ") > 0: spchar = " " 

       blast.seek(0,0)

       for line in blast:

        # empty line
        if len(line) == 1 : continue
        

        # define a new blast hit 
        (query, ref, ident, length, mismatch, gaps, qStart, qEnd, rStart, rEnd, eValue, bitscore) = tuple(line.split(spchar))
        blstHit=BlastHit(query, ref, ident, length, mismatch, gaps, qStart, qEnd, rStart, rEnd, eValue, bitscore)        

        # Test for match on existing sequences
        if blstHit.query not in self.hashseq.keys() or blstHit.ref not in self.hashseq.keys():
             continue
 
        # Test for length and identity filters
        if blstHit.length >= self.minlength and blstHit.eValue <= self.maxeval and blstHit.ident >= self.minident:

            # save hits for all pairs of sequences matching this hit (one same sequences can be found several times in the figure)
            for i in self.hashseq[blstHit.query]:
             for j in self.hashseq[blstHit.ref]:
               self.Btable[i][j].append(blstHit.qr())


    # get all hits for a given pairwise comparison
    #--------------------------------------------------------------------------
    def hits(self,i,j):
       return self.Btable[i][j]

    # remove all hits for a given pairwise comparison
    #--------------------------------------------------------------------------
    def removehits(self,i,j):
       self.Btable[i][j]=list()


    # Fill empty table entries in case of non symetrical blast files
    #--------------------------------------------------------------------------
    def mirroring(self):
       for i in range(0,len(self.hashseq)-1):
         for j in range(i+1,len(self.hashseq)):

             if len(self.Btable[i][j]) == 0 and len(self.Btable[j][i]) > 0:

               # copy all hits but by reverting query and reference
               for h in self.Btable[j][i]:
                  self.Btable[i][j].append({'qStart':h['rStart'],
                                            'qEnd':h['rEnd'], 
                                            'rStart':h['qStart'],
                                            'rEnd':h['qEnd'],
                                            'ident':h['ident']})


    # return ALL displayed hits as a new global list with the length as an aditional parameter
    # Used for the 'best blast' positionning option
    #--------------------------------------------------------------------------
    def returnhits(self):
       table = []
       for i in range(0,len(self.hashseq)-1):
         for j in range(i+1,len(self.hashseq)):
           for h in self.Btable[i][j]:
             table.append((i,j, abs(h['qEnd']-h['qStart'])+1, h))

#       return(sorted(table,key=lambda seqpair: seqpair[2]))
       return(table)


    # for debugging purpose
    #--------------------------------------------------------------------------
    def printT(self):
       print("\n\n Btable:\n")
       for i in range(0,len(self.hashseq)):
         for j in range(0,len(self.hashseq)):
           for h in self.Btable[i][j]:
             print("hit "+str(i)+" vs "+str(j)+":  "+str(h['qStart'])+":"+str(h['qEnd'])+" -> "+str(h['rStart'])+":"+str(h['rEnd']))


    # select hits which match the subregions selected for the sequences n and m
    #--------------------------------------------------------------------------
    def filterHits(self,n,m,pmin1,pmax1,pmin2,pmax2):
       i=0
       while i < len(self.Btable[n][m]):
        hit=self.Btable[n][m][i]

        # Invert Start and End positions of the query if necessary
        if (hit['qStart'] > hit['qEnd']):
           qtmp=hit['qStart']
           rtmp=hit['rStart']
           hit['qStart']=hit['qEnd'] 
           hit['rStart']=hit['rEnd']
           hit['qEnd']=qtmp
           hit['rEnd']=rtmp

        # Get ref hit orientation
        if (hit['rStart'] <= hit['rEnd']): o=1
        else: o=-1

        # Get real min and max positions for the ref
        rS = min(hit['rStart'],hit['rEnd'])
        rE = max(hit['rStart'],hit['rEnd'])

        # condition to be in the selected regions
        if (hit['qEnd'] > pmin1) and (hit['qStart'] < pmax1) and (rE > pmin2) and (rS < pmax2) :

          # Define the new coordinates on the ref, according to the query position in the subset
          # An offset is necessary when the subsequence ends in a middle of a hit
          offset = 0
          if hit['qStart'] < pmin1: offset = pmin1 - hit['qStart']
          temprS=hit['rStart'] - pmin2 + offset*o

          offset = 0
          if hit['qEnd'] > pmax1: offset = hit['qEnd'] - pmax1
          temprE=hit['rEnd'] - pmin2 - offset*o


          # Define the new coordinates on the query, according to the ref position
          offset = 0
          if hit['rStart'] < pmin2:
            offset = pmin2 - hit['rStart']
          elif hit['rStart'] > pmax2: