File: xbb_search.py

package info (click to toggle)
python-biopython 1.78%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 65,756 kB
  • sloc: python: 221,141; xml: 178,777; ansic: 13,369; sql: 1,208; makefile: 131; sh: 70
file content (196 lines) | stat: -rw-r--r-- 6,056 bytes parent folder | download
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
#!/usr/bin/env python
# Copyright 2000 by Thomas Sicheritz-Ponten.
# Copyrigth 2016 by Markus Piotrowski.
# All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license.  Please see the LICENSE file that should have been included
# as part of this package.

# Created: Sun Dec  3 13:38:52 2000
# thomas@cbs.dtu.dk, http://www.cbs.dtu.dk/thomas

"""Search code for graphical Xbbtools tool."""

import re
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import colorchooser

from Bio.Data.IUPACData import ambiguous_dna_values
from Bio.Seq import reverse_complement

import xbb_widget


class DNAsearch:
    """Class to search a DNA sequence."""

    def __init__(self):
        """Set up the alphabet."""
        self.init_alphabet()
        self.sequence = ""

    def init_alphabet(self):
        """Expand alphabet values for ambiguous codes."""
        self.alphabet = ambiguous_dna_values
        other = "".join(self.alphabet)
        self.alphabet["N"] = self.alphabet["N"] + other
        for key in self.alphabet:
            if key == "N":
                continue
            if key in self.alphabet[key]:
                continue
            self.alphabet[key] = self.alphabet[key] + key

    def SetSeq(self, seq):
        """Set sequence."""
        self.sequence = seq

    def SetPattern(self, pattern):
        """Convert search pattern to regular expression."""
        self.pattern = pattern
        self.rx_pattern = self.IUPAC2regex(pattern)
        self.rx = re.compile(self.rx_pattern)

    def IUPAC2regex(self, s):
        """Translate search text into pattern."""
        rx = ""
        for i in s:
            r = self.alphabet.get(i, i)
            if len(r) > 1:
                rx = f"{rx}[{r}]"
            else:
                rx += r
        return rx

    def _Search(self, start=0):
        """Search and return MatchObject (PRIVAT)."""
        # Only called from SearchAll. Is it used?
        pos = self.rx.search(self.sequence, start)
        return pos

    def Search(self, start=0):
        """Search for query sequence and return position."""
        pos = self.rx.search(self.sequence, start)
        if pos:
            return pos.start()
        else:
            return -1

    def SearchAll(self):
        """Search the whole sequence."""
        # Doesn't seem to be used...
        pos = -1
        positions = []
        while True:
            m = self._Search(pos + 1)
            if not m:
                break
            pos = m.start()
            if pos == -1:
                break

            positions.append(pos)
        return positions


class XDNAsearch(tk.Toplevel, DNAsearch):
    """Graphical tools to perform the DNA search."""

    def __init__(self, seq="", master=None, highlight=0):
        """Initialize the search GUI."""
        DNAsearch.__init__(self)
        self.master = master
        self.highlight = highlight
        self.colors = []
        self.init_graphics()
        self.sequence = seq
        self.cur_pos = 0

    def init_graphics(self):
        """Build the search window."""
        tk.Toplevel.__init__(self, self.master)
        self.frame = ttk.Frame(self)
        self.frame.pack(fill=tk.BOTH, expand=1)

        self.search_entry = ttk.Entry(self.frame)
        self.search_entry.pack(fill=tk.BOTH, expand=1)

        f2 = ttk.Frame(self.frame)
        f2.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        f = f2
        self.forward = ttk.Button(f, text="Search +", command=self.do_search)
        self.forward.pack(side=tk.LEFT)
        self.forward = ttk.Button(
            f, text="Search -", command=lambda x=self.do_search: x(other_strand=1)
        )
        self.forward.pack(side=tk.LEFT)
        self.cancel = ttk.Button(f, text="Cancel", command=self.exit)
        self.cancel.pack(side=tk.LEFT)
        self.current_color = "cyan"
        self.colorb = ttk.Button(f, text="Color", command=self.change_color)
        self.colorb.pack(side=tk.LEFT)
        self.config_color(self.current_color)

    def config_color(self, color=None):
        """Set color for found sequence tag."""
        if not self.highlight:
            return
        if not color:
            color = colorchooser.askcolor()[1]
            if not color:
                color = "cyan"
        self.current_color = color
        self.current_tag = f"searched_{self.current_color}"
        self.master.tag_config(self.current_tag, background=self.current_color)
        self.master.tag_config(
            self.current_tag + "R", background=self.current_color, underline=1
        )
        self.colors.append(color)

    def change_color(self):
        """Call back for color button."""
        self.config_color()

    def get_pattern(self):
        """Retrieve query sequence."""
        pattern = self.search_entry.get()
        return pattern

    def do_search(self, other_strand=0):
        """Start the search."""
        pattern = self.get_pattern()
        if other_strand:
            pattern = reverse_complement(pattern)
        self.SetPattern(pattern)
        pos = self.Search(self.cur_pos)
        self.cur_pos = pos + 1
        w = self.master
        if pos != -1:
            if self.highlight:
                start, stop = pos, pos + len(self.pattern)
                if other_strand:
                    w.tag_add(self.current_tag + "R", f"1.{start:d}", f"1.{stop}")
                else:
                    w.tag_add(self.current_tag, f"1.{start:d}", f"1.{stop}")
                w.see(f"1.{start:d}")

    def exit(self):
        """Clean up on exit."""
        for c in self.colors:
            self.master.tag_remove(f"searched_{c}", 1.0, tk.END)
            self.master.tag_remove(f"searched_{c}R", 1.0, tk.END)
        self.destroy()
        del self


if __name__ == "__main__":
    win = tk.Tk()
    xbbtools = xbb_widget.xbb_widget()

    seq = "ATGGTGTGTGTGTACGATCGCCCCCCCCAGTCGATCGATGCATCGTA"
    xbbtools.insert_sequence(("Test_seq", seq))
    xbbtools.search()

    win.mainloop()