Debian Codegraph @

petl/io/bcolz.py

raw
1 # -*- coding: utf-8 -*-
2 from __future__ import absolute_import, print_function, division
3 import itertools
4
5
6 from petl.compat import string_types, text_type
7 from petl.util.base import Table, iterpeek
8 from petl.io.numpy import construct_dtype
9
10
11 def frombcolz(source, expression=None, outcols=None, limit=None, skip=0):
12 """Extract a table from a bcolz ctable, e.g.::
13
14 >>> import petl as etl
15 >>>
16 >>> def example_from_bcolz():
17 ... import bcolz
18 ... cols = [
19 ... ['apples', 'oranges', 'pears'],
20 ... [1, 3, 7],
21 ... [2.5, 4.4, .1]
22 ... ]
23 ... names = ('foo', 'bar', 'baz')
24 ... ctbl = bcolz.ctable(cols, names=names)
25 ... return etl.frombcolz(ctbl)
26 >>>
27 >>> example_from_bcolz() # doctest: +SKIP
28 +-----------+-----+-----+
29 | foo | bar | baz |
30 +===========+=====+=====+
31 | 'apples' | 1 | 2.5 |
32 +-----------+-----+-----+
33 | 'oranges' | 3 | 4.4 |
34 +-----------+-----+-----+
35 | 'pears' | 7 | 0.1 |
36 +-----------+-----+-----+
37
38 If `expression` is provided it will be executed by bcolz and only
39 matching rows returned, e.g.::
40
41 >>> tbl2 = etl.frombcolz(ctbl, expression='bar > 1') # doctest: +SKIP
42 >>> tbl2 # doctest: +SKIP
43 +-----------+-----+-----+
44 | foo | bar | baz |
45 +===========+=====+=====+
46 | 'oranges' | 3 | 4.4 |
47 +-----------+-----+-----+
48 | 'pears' | 7 | 0.1 |
49 +-----------+-----+-----+
50
51 .. versionadded:: 1.1.0
52
53 """
54
55 return BcolzView(source, expression=expression, outcols=outcols,
56 limit=limit, skip=skip)
57
58
59 class BcolzView(Table):
60
61 def __init__(self, source, expression=None, outcols=None, limit=None,
62 skip=0):
63 self.source = source
64 self.expression = expression
65 self.outcols = outcols
66 self.limit = limit
67 self.skip = skip
68
69 def __iter__(self):
70
71 # obtain ctable
72 if isinstance(self.source, string_types):
73 import bcolz
74 ctbl = bcolz.open(self.source, mode='r')
75 else:
76 # assume bcolz ctable
77 ctbl = self.source
78
79 # obtain header
80 if self.outcols is None:
81 header = tuple(ctbl.names)
82 else:
83 header = tuple(self.outcols)
84 assert all(h in ctbl.names for h in header), 'invalid outcols'
85 yield header
86
87 # obtain iterator
88 if self.expression is None:
89 it = ctbl.iter(outcols=self.outcols, skip=self.skip,
90 limit=self.limit)
91 else:
92 it = ctbl.where(self.expression, outcols=self.outcols, skip=self.skip,
93 limit=self.limit)
94
95 for row in it:
96 yield row
97
98
99 def tobcolz(table, dtype=None, sample=1000, **kwargs):
100 """Load data into a bcolz ctable, e.g.::
101
102 >>> import petl as etl
103 >>>
104 >>> def example_to_bcolz():
105 ... table = [('foo', 'bar', 'baz'),
106 ... ('apples', 1, 2.5),
107 ... ('oranges', 3, 4.4),
108 ... ('pears', 7, .1)]
109 ... return etl.tobcolz(table)
110 >>>
111 >>> ctbl = example_to_bcolz() # doctest: +SKIP
112 >>> ctbl # doctest: +SKIP
113 ctable((3,), [('foo', '<U7'), ('bar', '<i8'), ('baz', '<f8')])
114 nbytes: 132; cbytes: 1023.98 KB; ratio: 0.00
115 cparams := cparams(clevel=5, shuffle=1, cname='lz4', quantize=0)
116 [('apples', 1, 2.5) ('oranges', 3, 4.4) ('pears', 7, 0.1)]
117 >>> ctbl.names # doctest: +SKIP
118 ['foo', 'bar', 'baz']
119 >>> ctbl['foo'] # doctest: +SKIP
120 carray((3,), <U7)
121 nbytes := 84; cbytes := 511.98 KB; ratio: 0.00
122 cparams := cparams(clevel=5, shuffle=1, cname='lz4', quantize=0)
123 chunklen := 18724; chunksize: 524272; blocksize: 0
124 ['apples' 'oranges' 'pears']
125
126 Other keyword arguments are passed through to the ctable constructor.
127
128 .. versionadded:: 1.1.0
129
130 """
131
132 import bcolz
133 import numpy as np
134
135 it = iter(table)
136 peek, it = iterpeek(it, sample)
137 hdr = next(it)
138 # numpy is fussy about having tuples, need to make sure
139 it = (tuple(row) for row in it)
140 flds = list(map(text_type, hdr))
141 dtype = construct_dtype(flds, peek, dtype)
142
143 # create ctable
144 kwargs.setdefault('expectedlen', 1000000)
145 kwargs.setdefault('mode', 'w')
146 ctbl = bcolz.ctable(np.array([], dtype=dtype), **kwargs)
147
148 # fill chunk-wise
149 chunklen = sum(ctbl.cols[name].chunklen
150 for name in ctbl.names) // len(ctbl.names)
151 while True:
152 data = list(itertools.islice(it, chunklen))
153 data = np.array(data, dtype=dtype)
154 ctbl.append(data)
155 if len(data) < chunklen:
156 break
157
158 ctbl.flush()
159 return ctbl
160
161
162 def appendbcolz(table, obj, check_names=True):
163 """Append data into a bcolz ctable. The `obj` argument can be either an
164 existing ctable or the name of a directory were an on-disk ctable is
165 stored.
166
167 .. versionadded:: 1.1.0
168
169 """
170
171 import bcolz
172 import numpy as np
173
174 if isinstance(obj, string_types):
175 ctbl = bcolz.open(obj, mode='a')
176 else:
177 assert hasattr(obj, 'append') and hasattr(obj, 'names'), \
178 'expected rootdir or ctable, found %r' % obj
179 ctbl = obj
180
181 # setup
182 dtype = ctbl.dtype
183 it = iter(table)
184 hdr = next(it)
185 flds = list(map(text_type, hdr))
186
187 # check names match
188 if check_names:
189 assert tuple(flds) == tuple(ctbl.names), 'column names do not match'
190
191 # fill chunk-wise
192 chunklen = sum(ctbl.cols[name].chunklen
193 for name in ctbl.names) // len(ctbl.names)
194 while True:
195 data = list(itertools.islice(it, chunklen))
196 data = np.array(data, dtype=dtype)
197 ctbl.append(data)
198 if len(data) < chunklen:
199 break
200
201 ctbl.flush()
202 return ctbl