File: lazy-parquet-with-form.py

package info (click to toggle)
python-awkward 2.6.5-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 23,088 kB
  • sloc: python: 148,689; cpp: 33,562; sh: 432; makefile: 21; javascript: 8
file content (311 lines) | stat: -rw-r--r-- 11,214 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
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
import json

import numpy as np
import awkward as ak
import pyarrow.parquet

_from_arrow = ak.operations.convert._from_arrow
_from_parquet_key = ak.operations.convert._from_parquet_key


def _parquet_schema_to_form(schema):
    def lst(path):
        return "lst:" + ".".join(path)

    def col(path):
        return "col:" + ".".join(path)

    def maybe_nullable(field, content):
        if field.nullable:
            return ak.forms.ByteMaskedForm(
                "i8",
                content.with_form_key(None),
                valid_when=True,
                form_key=content.form_key,
            )
        else:
            return content

    def contains_record(form):
        if isinstance(form, ak.forms.RecordForm):
            return True
        elif isinstance(form, ak.forms.ListOffsetForm):
            return contains_record(form.content)
        else:
            return False

    def recurse(arrow_type, path):
        if isinstance(arrow_type, pyarrow.StructType):
            names = []
            contents = []
            for index in range(arrow_type.num_fields):
                field = arrow_type[index]
                names.append(field.name)
                content = maybe_nullable(
                    field, recurse(field.type, path + (field.name,))
                )
                contents.append(ak.forms.VirtualForm(content, has_length=True))
            assert len(contents) != 0
            return ak.forms.RecordForm(contents, names)

        elif isinstance(arrow_type, pyarrow.ListType):
            field = arrow_type.value_field
            content = maybe_nullable(
                field, recurse(field.type, path + ("list", "item"))
            )
            form_key = None if contains_record(content) else lst(path)
            return ak.forms.ListOffsetForm("i32", content, form_key=form_key)

        elif isinstance(arrow_type, pyarrow.LargeListType):
            field = arrow_type.value_field
            content = maybe_nullable(
                field, recurse(field.type, path + ("list", "item"))
            )
            form_key = None if contains_record(content) else lst(path)
            return ak.forms.ListOffsetForm("i64", content, form_key=form_key)

        elif arrow_type == pyarrow.string():
            return ak.forms.ListOffsetForm(
                "i32",
                ak.forms.NumpyForm((), 1, "B", parameters={"__array__": "char"}),
                parameters={"__array__": "string"},
                form_key=col(path),
            )

        elif arrow_type == pyarrow.large_string():
            return ak.forms.ListOffsetForm(
                "i64",
                ak.forms.NumpyForm((), 1, "B", parameters={"__array__": "char"}),
                parameters={"__array__": "string"},
                form_key=col(path),
            )

        elif arrow_type == pyarrow.binary():
            return ak.forms.ListOffsetForm(
                "i32",
                ak.forms.NumpyForm((), 1, "B", parameters={"__array__": "byte"}),
                parameters={"__array__": "bytestring"},
                form_key=col(path),
            )

        elif arrow_type == pyarrow.large_binary():
            return ak.forms.ListOffsetForm(
                "i64",
                ak.forms.NumpyForm((), 1, "B", parameters={"__array__": "byte"}),
                parameters={"__array__": "bytestring"},
                form_key=col(path),
            )

        elif isinstance(arrow_type, pyarrow.DataType):
            dtype = np.dtype(arrow_type.to_pandas_dtype())
            return ak.forms.Form.from_numpy(dtype).with_form_key(col(path))

        else:
            raise NotImplementedError(
                "cannot convert {0}.{1} to an equivalent Awkward Form".format(
                    type(arrow_type).__module__, type(arrow_type).__name__
                )
            )

    schema = schema.to_arrow_schema()
    contents = []
    for index, name in enumerate(schema.names):
        field = schema.field(index)
        content = maybe_nullable(field, recurse(field.type, (name,)))
        contents.append(ak.forms.VirtualForm(content, has_length=True))
    assert len(contents) != 0
    return ak.forms.RecordForm(contents, schema.names)


class AlgebraicEffect(Exception):
    def __init__(self, state):
        self.state = state

    def __call__(self):
        globals().update(self.state)


class _ParquetState(object):
    def __init__(self, file):
        self.file = file

    def __call__(self, row_group, unpack, length, form, lazy_cache, lazy_cache_key):
        if form.form_key is None:
            if isinstance(form, ak.forms.RecordForm):
                contents = []
                recordlookup = []
                for i in range(form.numfields):
                    name = form.key(i)
                    subform = form.content(i).form
                    generator = ak.layout.ArrayGenerator(
                        self,
                        (
                            row_group,
                            unpack + (name,),
                            length,
                            subform,
                            lazy_cache,
                            lazy_cache_key,
                        ),
                        length=length,
                        form=subform,
                    )
                    if subform.form_key is None:
                        field_cache = None
                        cache_key = None
                    else:
                        field_cache = lazy_cache
                        cache_key = "{0}:{1}[{2}]".format(
                            lazy_cache_key, subform.form_key, row_group
                        )
                    contents.append(
                        ak.layout.VirtualArray(generator, field_cache, cache_key)
                    )
                    recordlookup.append(name)
                return ak.layout.RecordArray(contents, recordlookup, length)

            elif isinstance(form, ak.forms.ListOffsetForm):
                struct_only = [x for x in unpack[:0:-1] if x is not None]
                sampleform = _ParquetState_first_column(form, struct_only)
                sample = self.get(row_group, unpack, sampleform, struct_only)

                offsets = [sample.offsets]
                sublength = offsets[-1][-1]
                sample = sample.content
                recordform = form.content
                unpack = unpack + (None,)
                while not isinstance(recordform, ak.forms.RecordForm):
                    offsets.append(sample.offsets)
                    sublength = offsets[-1][-1]
                    sample = sample.content
                    recordform = recordform.content
                    unpack = unpack + (None,)

                out = self(
                    row_group, unpack, sublength, recordform, lazy_cache, lazy_cache_key
                )
                for off in offsets[::-1]:
                    if isinstance(off, ak.layout.Index32):
                        out = ak.layout.ListOffsetArray32(off, out)
                    elif isinstance(off, ak.layout.Index64):
                        out = ak.layout.ListOffsetArray64(off, out)
                    else:
                        raise AssertionError("unexpected Index type: {0}".format(off))
                return out

            else:
                raise AssertionError("unexpected Form: {0}".format(type(form)))

        else:
            assert form.form_key.startswith("col:") or form.form_key.startswith("lst:")
            column_name = form.form_key[4:]
            masked = isinstance(form, ak.forms.ByteMaskedForm)
            if masked:
                form = form.content
            table = self.file.read_row_group(row_group, [column_name])
            struct_only = [column_name.split(".")[-1]]
            struct_only.extend([x for x in unpack[:0:-1] if x is not None])
            return _ParquetState_arrow_to_awkward(table, struct_only, masked, unpack)

    def get(self, row_group, unpack, form, struct_only):
        assert form.form_key.startswith("col:") or form.form_key.startswith("lst:")
        column_name = form.form_key[4:]
        masked = isinstance(form, ak.forms.ByteMaskedForm)
        if masked:
            form = form.content
        table = self.file.read_row_group(row_group, [column_name])
        return _ParquetState_arrow_to_awkward(table, struct_only, masked, unpack)


def _ParquetState_first_column(form, struct_only):
    if isinstance(form, ak.forms.VirtualForm):
        return _ParquetState_first_column(form.form, struct_only)
    elif isinstance(form, ak.forms.RecordForm):
        assert form.numfields != 0
        struct_only.insert(0, form.key(0))
        return _ParquetState_first_column(form.content(0), struct_only)
    elif isinstance(form, ak.forms.ListOffsetForm):
        return _ParquetState_first_column(form.content, struct_only)
    else:
        return form


def _ParquetState_arrow_to_awkward(table, struct_only, masked, unpack):
    out = _from_arrow(table, False, struct_only=struct_only, highlevel=False)
    for item in unpack:
        if item is None:
            out = out.content
        else:
            out = out.field(item)
    if masked and not isinstance(out, ak.layout.ByteMaskedArray):
        out = out.toByteMaskedArray()
    return out


def from_parquet(source):
    file = pyarrow.parquet.ParquetFile(source)
    form = _parquet_schema_to_form(file.schema)
    all_columns = form.keys()
    columns = all_columns

    length = file.metadata.row_group(0).num_rows

    cache = {}
    hold_cache = ak._util.MappingProxy.maybe_wrap(cache)
    lazy_cache = ak.layout.ArrayCache(hold_cache)
    state = _ParquetState(file)

    lazy_cache_key = None
    if lazy_cache_key is None:
        lazy_cache_key = "ak.from_parquet:{0}".format(_from_parquet_key())

    row_group = 0
    fields = []
    names = []
    for column in columns:
        subform = form.contents[column].form
        generator = ak.layout.ArrayGenerator(
            state,
            (
                row_group,
                (column,),
                length,
                subform,
                lazy_cache,
                lazy_cache_key,
            ),
            length=length,
            form=form.contents[column].form,
        )
        if subform.form_key is None:
            field_cache = None
            cache_key = None
        else:
            field_cache = lazy_cache
            cache_key = "{0}:{1}[{2}]".format(
                lazy_cache_key, subform.form_key, row_group
            )
        fields.append(ak.layout.VirtualArray(generator, field_cache, cache_key))
        names.append(column)

    return ak.Array(ak.layout.RecordArray(fields, names))


ak.to_parquet(
    ak.Array(
        [
    {"x": [{"y": {"q": 1}, "z": 1.1}]},
    {"x": [{"y": {"q": 1}, "z": 1.1}, {"y": {"q": 2}, "z": 2.2}]},
    {"x": [{"y": {"q": 1}, "z": 1.1}, {"y": {"q": 2}, "z": 2.2}, {"y": {"q": 3}, "z": 3.3}]},
        ]
    ),
    "tmp.parquet",
)

array = from_parquet("tmp.parquet")

# try:
#     array.layout.field("x").array
# except AlgebraicEffect as effect:
#     print("AlgebraicEffect")
#     effect()