File: vis.py

package info (click to toggle)
python-petl 1.7.17-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,224 kB
  • sloc: python: 22,617; makefile: 109; xml: 9
file content (610 lines) | stat: -rw-r--r-- 16,764 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
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
from __future__ import absolute_import, print_function, division


import locale
from itertools import islice
from collections import defaultdict
from petl.compat import numeric_types, text_type


from petl import config
from petl.util.base import Table
from petl.io.sources import MemorySource
from petl.io.html import tohtml


def look(table, limit=0, vrepr=None, index_header=None, style=None,
         truncate=None, width=None):
    """
    Format a portion of the table as text for inspection in an interactive
    session. E.g.::

        >>> import petl as etl
        >>> table1 = [['foo', 'bar'],
        ...           ['a', 1],
        ...           ['b', 2]]
        >>> etl.look(table1)
        +-----+-----+
        | foo | bar |
        +=====+=====+
        | 'a' |   1 |
        +-----+-----+
        | 'b' |   2 |
        +-----+-----+

        >>> # alternative formatting styles
        ... etl.look(table1, style='simple')
        ===  ===
        foo  bar
        ===  ===
        'a'    1
        'b'    2
        ===  ===

        >>> etl.look(table1, style='minimal')
        foo  bar
        'a'    1
        'b'    2

        >>> # any irregularities in the length of header and/or data
        ... # rows will appear as blank cells
        ... table2 = [['foo', 'bar'],
        ...           ['a'],
        ...           ['b', 2, True]]
        >>> etl.look(table2)
        +-----+-----+------+
        | foo | bar |      |
        +=====+=====+======+
        | 'a' |     |      |
        +-----+-----+------+
        | 'b' |   2 | True |
        +-----+-----+------+

    Three alternative presentation styles are available: 'grid', 'simple' and
    'minimal', where 'grid' is the default. A different style can be specified
    using the `style` keyword argument. The default style can also be changed
    by setting ``petl.config.look_style``.

    """

    # determine defaults
    if limit == 0:
        limit = config.look_limit
    if vrepr is None:
        vrepr = config.look_vrepr
    if index_header is None:
        index_header = config.look_index_header
    if style is None:
        style = config.look_style
    if width is None:
        width = config.look_width

    return Look(table, limit=limit, vrepr=vrepr, index_header=index_header,
                style=style, truncate=truncate, width=width)


Table.look = look


class Look(object):

    def __init__(self, table, limit, vrepr, index_header, style, truncate,
                 width):
        self.table = table
        self.limit = limit
        self.vrepr = vrepr
        self.index_header = index_header
        self.style = style
        self.truncate = truncate
        self.width = width

    def __repr__(self):

        # determine if table overflows limit
        table, overflow = _vis_overflow(self.table, self.limit)

        # construct output
        style = self.style
        vrepr = self.vrepr
        index_header = self.index_header
        truncate = self.truncate
        width = self.width
        if style == 'simple':
            output = _look_simple(table, vrepr=vrepr,
                                  index_header=index_header,
                                  truncate=truncate, width=width)
        elif style == 'minimal':
            output = _look_minimal(table, vrepr=vrepr,
                                   index_header=index_header,
                                   truncate=truncate, width=width)
        else:
            output = _look_grid(table, vrepr=vrepr, index_header=index_header,
                                truncate=truncate, width=width)

        # add overflow indicator
        if overflow:
            output += '...\n'

        return output

    __str__ = __repr__
    __unicode__ = __repr__


def _table_repr(table):
    return str(look(table))


Table.__repr__ = _table_repr


def lookall(table, **kwargs):
    """
    Format the entire table as text for inspection in an interactive session.

    N.B., this will load the entire table into memory.

    See also :func:`petl.util.vis.look` and :func:`petl.util.vis.see`.

    """

    kwargs['limit'] = None
    return look(table, **kwargs)


def lookstr(table, limit=0, **kwargs):
    """Like :func:`petl.util.vis.look` but use str() rather than repr() for data
    values.

    """

    kwargs['vrepr'] = str
    return look(table, limit=limit, **kwargs)


Table.lookstr = lookstr


def _table_str(table):
    return str(lookstr(table))


Table.__str__ = _table_str
Table.__unicode__ = _table_str


def lookallstr(table, **kwargs):
    """
    Like :func:`petl.util.vis.lookall` but use str() rather than repr() for data
    values.

    """

    kwargs['vrepr'] = str
    return lookall(table, **kwargs)


Table.lookallstr = lookallstr


Table.lookall = lookall


def _look_grid(table, vrepr, index_header, truncate, width):
    it = iter(table)

    # fields representation
    try:
        hdr = next(it)
    except StopIteration:
        return ''
    flds = list(map(text_type, hdr))
    if index_header:
        fldsrepr = ['%s|%s' % (i, r) for (i, r) in enumerate(flds)]
    else:
        fldsrepr = flds

    # rows representations
    rows = list(it)
    rowsrepr = [[vrepr(v) for v in row] for row in rows]

    # find maximum row length - may be uneven
    rowlens = [len(hdr)]
    rowlens.extend([len(row) for row in rows])
    maxrowlen = max(rowlens)

    # pad short fields and rows
    if len(hdr) < maxrowlen:
        fldsrepr.extend([''] * (maxrowlen - len(hdr)))
    for valsrepr in rowsrepr:
        if len(valsrepr) < maxrowlen:
            valsrepr.extend([''] * (maxrowlen - len(valsrepr)))

    # truncate
    if truncate:
        fldsrepr = [x[:truncate] for x in fldsrepr]
        rowsrepr = [[x[:truncate] for x in valsrepr]
                    for valsrepr in rowsrepr]

    # find longest representations so we know how wide to make cells
    colwidths = [0] * maxrowlen  # initialise to 0
    for i, fr in enumerate(fldsrepr):
        colwidths[i] = len(fr)
    for valsrepr in rowsrepr:
        for i, vr in enumerate(valsrepr):
            if len(vr) > colwidths[i]:
                colwidths[i] = len(vr)

    # construct a line separator
    sep = '+'
    for w in colwidths:
        sep += '-' * (w + 2)
        sep += '+'
    if width:
        sep = sep[:width]
    sep += '\n'

    # construct a header separator
    hedsep = '+'
    for w in colwidths:
        hedsep += '=' * (w + 2)
        hedsep += '+'
    if width:
        hedsep = hedsep[:width]
    hedsep += '\n'

    # construct a line for the header row
    fldsline = '|'
    for i, w in enumerate(colwidths):
        f = fldsrepr[i]
        fldsline += ' ' + f
        fldsline += ' ' * (w - len(f))  # padding
        fldsline += ' |'
    if width:
        fldsline = fldsline[:width]
    fldsline += '\n'

    # construct a line for each data row
    rowlines = list()
    for vals, valsrepr in zip(rows, rowsrepr):
        rowline = '|'
        for i, w in enumerate(colwidths):
            vr = valsrepr[i]
            if i < len(vals) and isinstance(vals[i], numeric_types) \
                    and not isinstance(vals[i], bool):
                # left pad numbers
                rowline += ' ' * (w + 1 - len(vr))  # padding
                rowline += vr + ' |'
            else:
                # right pad everything else
                rowline += ' ' + vr
                rowline += ' ' * (w - len(vr))  # padding
                rowline += ' |'
        if width:
            rowline = rowline[:width]
        rowline += '\n'
        rowlines.append(rowline)

    # put it all together
    output = sep + fldsline + hedsep
    for line in rowlines:
        output += line + sep

    return output


def _look_simple(table, vrepr, index_header, truncate, width):
    it = iter(table)

    # fields representation
    try:
        hdr = next(it)
    except StopIteration:
        return ''
    flds = list(map(text_type, hdr))
    if index_header:
        fldsrepr = ['%s|%s' % (i, r) for (i, r) in enumerate(flds)]
    else:
        fldsrepr = flds

    # rows representations
    rows = list(it)
    rowsrepr = [[vrepr(v) for v in row] for row in rows]

    # find maximum row length - may be uneven
    rowlens = [len(hdr)]
    rowlens.extend([len(row) for row in rows])
    maxrowlen = max(rowlens)

    # pad short fields and rows
    if len(hdr) < maxrowlen:
        fldsrepr.extend([''] * (maxrowlen - len(hdr)))
    for valsrepr in rowsrepr:
        if len(valsrepr) < maxrowlen:
            valsrepr.extend([''] * (maxrowlen - len(valsrepr)))

    # truncate
    if truncate:
        fldsrepr = [x[:truncate] for x in fldsrepr]
        rowsrepr = [[x[:truncate] for x in valsrepr]
                    for valsrepr in rowsrepr]

    # find longest representations so we know how wide to make cells
    colwidths = [0] * maxrowlen  # initialise to 0
    for i, fr in enumerate(fldsrepr):
        colwidths[i] = len(fr)
    for valsrepr in rowsrepr:
        for i, vr in enumerate(valsrepr):
            if len(vr) > colwidths[i]:
                colwidths[i] = len(vr)

    # construct a header separator
    hedsep = '  '.join('=' * w for w in colwidths)
    if width:
        hedsep = hedsep[:width]
    hedsep += '\n'

    # construct a line for the header row
    fldsline = '  '.join(f.ljust(w) for f, w in zip(fldsrepr, colwidths))
    if width:
        fldsline = fldsline[:width]
    fldsline += '\n'

    # construct a line for each data row
    rowlines = list()
    for vals, valsrepr in zip(rows, rowsrepr):
        rowline = ''
        for i, w in enumerate(colwidths):
            vr = valsrepr[i]
            if i < len(vals) and isinstance(vals[i], numeric_types) \
                    and not isinstance(vals[i], bool):
                # left pad numbers
                rowline += vr.rjust(w)
            else:
                # right pad everything else
                rowline += vr.ljust(w)
            if i < len(colwidths) - 1:
                rowline += '  '
        if width:
            rowline = rowline[:width]
        rowline += '\n'
        rowlines.append(rowline)

    # put it all together
    output = hedsep + fldsline + hedsep
    for line in rowlines:
        output += line
    output += hedsep

    return output


def _look_minimal(table, vrepr, index_header, truncate, width):
    it = iter(table)

    # fields representation
    try:
        hdr = next(it)
    except StopIteration:
        return ''
    flds = list(map(text_type, hdr))
    if index_header:
        fldsrepr = ['%s|%s' % (i, r) for (i, r) in enumerate(flds)]
    else:
        fldsrepr = flds

    # rows representations
    rows = list(it)
    rowsrepr = [[vrepr(v) for v in row] for row in rows]

    # find maximum row length - may be uneven
    rowlens = [len(hdr)]
    rowlens.extend([len(row) for row in rows])
    maxrowlen = max(rowlens)

    # pad short fields and rows
    if len(hdr) < maxrowlen:
        fldsrepr.extend([''] * (maxrowlen - len(hdr)))
    for valsrepr in rowsrepr:
        if len(valsrepr) < maxrowlen:
            valsrepr.extend([''] * (maxrowlen - len(valsrepr)))

    # truncate
    if truncate:
        fldsrepr = [x[:truncate] for x in fldsrepr]
        rowsrepr = [[x[:truncate] for x in valsrepr]
                    for valsrepr in rowsrepr]

    # find longest representations so we know how wide to make cells
    colwidths = [0] * maxrowlen  # initialise to 0
    for i, fr in enumerate(fldsrepr):
        colwidths[i] = len(fr)
    for valsrepr in rowsrepr:
        for i, vr in enumerate(valsrepr):
            if len(vr) > colwidths[i]:
                colwidths[i] = len(vr)

    # construct a line for the header row
    fldsline = '  '.join(f.ljust(w) for f, w in zip(fldsrepr, colwidths))
    if width:
        fldsline = fldsline[:width]
    fldsline += '\n'

    # construct a line for each data row
    rowlines = list()
    for vals, valsrepr in zip(rows, rowsrepr):
        rowline = ''
        for i, w in enumerate(colwidths):
            vr = valsrepr[i]
            if i < len(vals) and isinstance(vals[i], numeric_types) \
                    and not isinstance(vals[i], bool):
                # left pad numbers
                rowline += vr.rjust(w)
            else:
                # right pad everything else
                rowline += vr.ljust(w)
            if i < len(colwidths) - 1:
                rowline += '  '
        if width:
            rowline = rowline[:width]
        rowline += '\n'
        rowlines.append(rowline)

    # put it all together
    output = fldsline
    for line in rowlines:
        output += line

    return output


def see(table, limit=0, vrepr=None, index_header=None):
    """
    Format a portion of a table as text in a column-oriented layout for
    inspection in an interactive session. E.g.::

        >>> import petl as etl
        >>> table = [['foo', 'bar'], ['a', 1], ['b', 2]]
        >>> etl.see(table)
        foo: 'a', 'b'
        bar: 1, 2

    Useful for tables with a larger number of fields.


    """

    # determine defaults
    if limit == 0:
        limit = config.see_limit
    if vrepr is None:
        vrepr = config.see_vrepr
    if index_header is None:
        index_header = config.see_index_header

    return See(table, limit=limit, vrepr=vrepr, index_header=index_header)


class See(object):

    def __init__(self, table, limit, vrepr, index_header):
        self.table = table
        self.limit = limit
        self.vrepr = vrepr
        self.index_header = index_header

    def __repr__(self):

        # determine if table overflows limit
        table, overflow = _vis_overflow(self.table, self.limit)

        vrepr = self.vrepr
        index_header = self.index_header

        # construct output
        output = ''
        it = iter(table)
        try:
            flds = next(it)
        except StopIteration:
            return ''
        cols = defaultdict(list)
        for row in it:
            for i, f in enumerate(flds):
                try:
                    cols[str(i)].append(vrepr(row[i]))
                except IndexError:
                    cols[str(f)].append('')
        for i, f in enumerate(flds):
            if index_header:
                f = '%s|%s' % (i, f)
            output += '%s: %s' % (f, ', '.join(cols[str(i)]))
            if overflow:
                output += '...\n'
            else:
                output += '\n'

        return output

    __str__ = __repr__
    __unicode__ = __repr__


Table.see = see


def _vis_overflow(table, limit):
    overflow = False
    if limit:
        # try reading one more than the limit, to see if there are more rows
        table = list(islice(table, 0, limit+2))
        if len(table) > limit+1:
            overflow = True
            table = table[:-1]
    return table, overflow


def _display_html(table, limit=0, vrepr=None, index_header=None, caption=None,
                  tr_style=None, td_styles=None, encoding=None,
                  truncate=None, epilogue=None):

    # determine defaults
    if limit == 0:
        limit = config.display_limit
    if vrepr is None:
        vrepr = config.display_vrepr
    if index_header is None:
        index_header = config.display_index_header
    if encoding is None:
        encoding = locale.getpreferredencoding()

    table, overflow = _vis_overflow(table, limit)
    buf = MemorySource()
    tohtml(table, buf, encoding=encoding, index_header=index_header,
           vrepr=vrepr, caption=caption, tr_style=tr_style,
           td_styles=td_styles, truncate=truncate)
    output = text_type(buf.getvalue(), encoding)

    if epilogue:
        output += '<p>%s</p>' % epilogue
    elif overflow:
        output += '<p><strong>...</strong></p>'

    return output


Table._repr_html_ = _display_html


def display(table, limit=0, vrepr=None, index_header=None, caption=None,
            tr_style=None, td_styles=None, encoding=None, truncate=None,
            epilogue=None):
    """
    Display a table inline within an IPython notebook.

    """

    from IPython.core.display import display_html
    html = _display_html(table, limit=limit, vrepr=vrepr,
                         index_header=index_header, caption=caption,
                         tr_style=tr_style, td_styles=td_styles,
                         encoding=encoding, truncate=truncate,
                         epilogue=epilogue)
    display_html(html, raw=True)


Table.display = display


def displayall(table, **kwargs):
    """
    Display **all rows** from a table inline within an IPython notebook (use
    with caution, big tables will kill your browser).

    """

    kwargs['limit'] = None
    display(table, **kwargs)


Table.displayall = displayall