File: PrintFormat.py

package info (click to toggle)
python-biopython 1.68%2Bdfsg-3~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 46,856 kB
  • sloc: python: 160,306; xml: 93,216; ansic: 9,118; sql: 1,208; makefile: 155; sh: 63
file content (426 lines) | stat: -rw-r--r-- 14,066 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/env python
#
#      Restriction Analysis Libraries.
#      Copyright (C) 2004. Frederic Sohm.
#
# 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.
#
r"""Print the results of restriction enzyme analysis.

PrintFormat prints the results from restriction analysis in 3 different
format: list, column or map.

The easiest way to use it is:

    >>> from Bio.Restriction.PrintFormat import PrintFormat
    >>> from Bio.Restriction.Restriction import AllEnzymes
    >>> from Bio import Entrez
    >>> from Bio import SeqIO
    >>> handle = Entrez.efetch(db="nucleotide", rettype="fasta", id="SYNPBR322")
    >>> pBR322 = SeqIO.read(handle, "fasta")
    >>> handle.close()
    >>> dct = AllEnzymes.search(pBR322.seq)
    >>> new = PrintFormat()
    >>> new.print_that(dct, 'My pBR322 analysis:\n', 'No site:\n')
    My pBR322 analysis:
    AasI       :  2169, 2582.
    AatII      :  4289.
    ...
    ZraI       :  4287.
    ZrmI       :  3847.
    No site:
    AarI      AatI      Acc65I    AcsI      AcvI      AdeI      AflII     AgeI
    ...
    Vha464I   XapI      XbaI      XcmI      XhoI      XmaCI     XmaI      XmaJI
    Zsp2I
    >>> new.sequence = pBR322.seq
    >>> new.print_as("map")
    >>> new.print_that(dct)
    ...

Some of the methods of PrintFormat are meant to be overridden by derived
class.
"""

from __future__ import print_function

import re

from Bio._py3k import range

from Bio.Restriction import RanaConfig as RanaConf


class PrintFormat(object):
    """PrintFormat allow the printing of results of restriction analysis."""

    ConsoleWidth = RanaConf.ConsoleWidth
    NameWidth = RanaConf.NameWidth
    MaxSize = RanaConf.MaxSize
    Cmodulo = ConsoleWidth % NameWidth
    PrefWidth = ConsoleWidth - Cmodulo
    Indent = RanaConf.Indent
    linesize = PrefWidth - NameWidth

    def __init__(self):
        """PrintFormat() -> new PrintFormat Instance"""
        pass

    def print_as(self, what='list'):
        """PF.print_as([what='list']) -> print the results as specified.

        Valid format are:
            'list'      -> alphabetical order
            'number'    -> number of sites in the sequence
            'map'       -> a map representation of the sequence with the sites.

        If you want more flexibility over-ride the virtual method make_format.
        """
        if what == 'map':
            self.make_format = self._make_map
        elif what == 'number':
            self.make_format = self._make_number
        else:
            self.make_format = self._make_list

        return

    def print_that(self, dct, title='', s1=''):
        """PF.print_that(dct, [title[, s1]]) -> Print dct nicely formatted.

        Arguments:
         - dct is a dictionary as returned by a RestrictionBatch.search()
         - title is the title of the map.
           It must be a formatted string, i.e. you must include the line break.
         - s1 is the title separating the list of enzymes that have sites from
           those without sites.
         - s1 must be a formatted string as well.

        The format of print_that is a list."""
        if not dct:
            dct = self.results
        ls, nc = [], []
        for k, v in dct.items():
            if v:
                ls.append((k, v))
            else:
                nc.append(k)
        print(self.make_format(ls, title, nc, s1))
        return

    def make_format(self, cut=(), title='', nc=(), s1=''):
        """PF.make_format(cut, nc, title, s) -> string

        Virtual method.
        Here to be pointed to one of the _make_* methods.
        You can as well create a new method and point make_format to it.
        """
        return self._make_list(cut, title, nc, s1)

# _make_* methods to be used with the virtual method make_format

    def _make_list(self, ls, title, nc, s1):
        """PF._make_number(ls,title, nc,s1) -> string.

        return a string of form::

            title.

            enzyme1     :   position1, position2.
            enzyme2     :   position1, position2, position3.

        Arguments:
         - ls is a tuple or list of cutting enzymes.
         - title is the title.
         - nc is a tuple or list of non cutting enzymes.
         - s1 is the sentence before the non cutting enzymes.
        """
        return self._make_list_only(ls, title) + self._make_nocut_only(nc, s1)

    def _make_map(self, ls, title, nc, s1):
        """PF._make_number(ls,title, nc,s1) -> string.

        return a string of form::

            | title.
            |
            |     enzyme1, position
            |     |
            | AAAAAAAAAAAAAAAAAAAAA...
            | |||||||||||||||||||||
            | TTTTTTTTTTTTTTTTTTTTT...

        Arguments:
         - ls is a list of cutting enzymes.
         - title is the title.
         - nc is a list of non cutting enzymes.
         - s1 is the sentence before the non cutting enzymes.
        """
        return self._make_map_only(ls, title) + self._make_nocut_only(nc, s1)

    def _make_number(self, ls, title, nc, s1):
        """PF._make_number(ls,title, nc,s1) -> string.

        Returns a string in the form::

            title.

            enzyme which cut 1 time:

            enzyme1     :   position1.

            enzyme which cut 2 times:

            enzyme2     :   position1, position2.
            ...

        Arguments:
         - ls is a list of cutting enzymes.
         - title is the title.
         - nc is a list of non cutting enzymes.
         - s1 is the sentence before the non cutting enzymes.
        """
        return self._make_number_only(ls, title) + self._make_nocut_only(nc, s1)

    def _make_nocut(self, ls, title, nc, s1):
        """PF._make_nocut(ls,title, nc,s1) -> string.

        return a formatted string of the non cutting enzymes.

        ls is a list of cutting enzymes -> will not be used.
        Here for compatibility with make_format.

        Arguments:
         - title is the title.
         - nc is a list of non cutting enzymes.
         - s1 is the sentence before the non cutting enzymes.
        """
        return title + self._make_nocut_only(nc, s1)

    def _make_nocut_only(self, nc, s1, ls=(), title=''):
        """PF._make_nocut_only(nc, s1) -> string.

        return a formatted string of the non cutting enzymes.

        Arguments:
         - nc is a tuple or list of non cutting enzymes.
         - s1 is the sentence before the non cutting enzymes.
        """
        if not nc:
            return s1
        st = ''
        stringsite = s1 or '\n   Enzymes which do not cut the sequence.\n\n'
        Join = ''.join
        for key in sorted(nc):
            st = Join((st, str.ljust(str(key), self.NameWidth)))
            if len(st) > self.linesize:
                stringsite = Join((stringsite, st, '\n'))
                st = ''
        stringsite = Join((stringsite, st, '\n'))
        return stringsite

    def _make_list_only(self, ls, title, nc=(), s1=''):
        """PF._make_list_only(ls, title) -> string.

        return a string of form::

            title.

            enzyme1     :   position1, position2.
            enzyme2     :   position1, position2, position3.
            ...

        Arguments:
         - ls is a tuple or list of results.
         - title is a string.
         - Non cutting enzymes are not included.
        """
        if not ls:
            return title
        return self.__next_section(ls, title)

    def _make_number_only(self, ls, title, nc=(), s1=''):
        """PF._make_number_only(ls, title) -> string.

        return a string of form::

            title.

            enzyme which cut 1 time:

            enzyme1     :   position1.

            enzyme which cut 2 times:

            enzyme2     :   position1, position2.
            ...

        Arguments:
         - ls is a list of results.
         - title is a string.
         - Non cutting enzymes are not included.
        """
        if not ls:
            return title
        # TODO: Use key to sort!
        ls.sort(lambda x, y: cmp(len(x[1]), len(y[1])))
        iterator = iter(ls)
        cur_len = 1
        new_sect = []
        for name, sites in iterator:
            l = len(sites)
            if l > cur_len:
                title += "\n\nenzymes which cut %i times :\n\n" % cur_len
                title = self.__next_section(new_sect, title)
                new_sect, cur_len = [(name, sites)], l
                continue
            new_sect.append((name, sites))
        title += "\n\nenzymes which cut %i times :\n\n" % cur_len
        return self.__next_section(new_sect, title)

    def _make_map_only(self, ls, title, nc=(), s1=''):
        """PF._make_map_only(ls, title) -> string.

        return a string of form::

            | title.
            |
            |     enzyme1, position
            |     |
            | AAAAAAAAAAAAAAAAAAAAA...
            | |||||||||||||||||||||
            | TTTTTTTTTTTTTTTTTTTTT...

        Arguments:
         - ls is a list of results.
         - title is a string.
         - Non cutting enzymes are not included.
        """
        if not ls:
            return title
        resultKeys = sorted(str(x) for x, y in ls)
        map = title or ''
        enzymemap = {}
        for (enzyme, cut) in ls:
            for c in cut:
                if c in enzymemap:
                    enzymemap[c].append(str(enzyme))
                else:
                    enzymemap[c] = [str(enzyme)]
        mapping = sorted(enzymemap.keys())
        cutloc = {}
        x, counter, length = 0, 0, len(self.sequence)
        for x in range(60, length, 60):
            counter = x - 60
            l = []
            cutloc[counter] = l
            remaining = []
            for key in mapping:
                if key <= x:
                    l.append(key)
                else:
                    remaining.append(key)
            mapping = remaining
        cutloc[x] = mapping
        sequence = str(self.sequence)
        revsequence = str(self.sequence.complement())
        a = '|'
        base, counter = 0, 0
        emptyline = ' ' * 60
        Join = ''.join
        for base in range(60, length, 60):
            counter = base - 60
            line = emptyline
            for key in cutloc[counter]:
                s = ''
                if key == base:
                    for n in enzymemap[key]:
                        s = ' '.join((s, n))
                    l = line[0:59]
                    lineo = Join((l, str(key), s, '\n'))
                    line2 = Join((l, a, '\n'))
                    linetot = Join((lineo, line2))
                    map = Join((map, linetot))
                    break
                for n in enzymemap[key]:
                    s = ' '.join((s, n))
                k = key % 60
                lineo = Join((line[0:(k - 1)], str(key), s, '\n'))
                line = Join((line[0:(k - 1)], a, line[k:]))
                line2 = Join((line[0:(k - 1)], a, line[k:], '\n'))
                linetot = Join((lineo, line2))
                map = Join((map, linetot))
            mapunit = '\n'.join((sequence[counter: base], a * 60,
                                 revsequence[counter: base],
                                 Join((str.ljust(str(counter + 1), 15), ' ' * 30,
                                       str.rjust(str(base), 15), '\n\n'))
                                 ))
            map = Join((map, mapunit))
        line = ' ' * 60
        for key in cutloc[base]:
            s = ''
            if key == length:
                for n in enzymemap[key]:
                    s = Join((s, ' ', n))
                l = line[0:(length - 1)]
                lineo = Join((l, str(key), s, '\n'))
                line2 = Join((l, a, '\n'))
                linetot = Join((lineo, line2))
                map = Join((map, linetot))
                break
            for n in enzymemap[key]:
                s = Join((s, ' ', n))
            k = key % 60
            lineo = Join((line[0:(k - 1)], str(key), s, '\n'))
            line = Join((line[0:(k - 1)], a, line[k:]))
            line2 = Join((line[0:(k - 1)], a, line[k:], '\n'))
            linetot = Join((lineo, line2))
            map = Join((map, linetot))
        mapunit = ''
        mapunit = Join((sequence[base: length], '\n'))
        mapunit = Join((mapunit, a * (length - base), '\n'))
        mapunit = Join((mapunit, revsequence[base:length], '\n'))
        mapunit = Join((mapunit, Join((str.ljust(str(base + 1), 15), ' ' * (
            length - base - 30), str.rjust(str(length), 15),
            '\n\n'))))
        map = Join((map, mapunit))
        return map

# private method to do lists:

    def __next_section(self, ls, into):
        """FP.__next_section(ls, into) -> string.

        Arguments:
         - ls is a tuple/list of tuple (string, [int, int]).
         - into is a string to which the formatted ls will be added.

        Format ls as a string of lines:
        The form is::

            enzyme1     :   position1.
            enzyme2     :   position2, position3.

        then add the formatted ls to tot
        return tot.
        """
        indentation = '\n' + (self.NameWidth + self.Indent) * ' '
        linesize = self.linesize - self.MaxSize
        pat = re.compile("([\w,\s()]){1,%i}[,\.]" % linesize)
        several, Join = '', ''.join
        for name, sites in sorted(ls):
            stringsite = ''
            l = Join((', '.join(str(site) for site in sites), '.'))
            if len(l) > linesize:
                #
                #   cut where appropriate and add the indentation
                #
                l = [x.group() for x in re.finditer(pat, l)]
                stringsite = indentation.join(l)
            else:
                stringsite = l
            into = Join((into,
                         str(name).ljust(self.NameWidth), ' :  ', stringsite, '\n'))
        return into