This repository was archived by the owner on Feb 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathdataframe_constructor.py
More file actions
383 lines (305 loc) · 16.1 KB
/
dataframe_constructor.py
File metadata and controls
383 lines (305 loc) · 16.1 KB
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
# *****************************************************************************
# Copyright (c) 2020, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# *****************************************************************************
import numba
from numba.core import cgutils, types
from numba.core.rewrites import (register_rewrite, Rewrite)
from numba.core.ir_utils import (guard, find_callname)
from numba.core.ir import (Expr)
from numba.extending import overload
from numba.core.extending import intrinsic
from numba.core.typing import signature
from numba.core.target_extension import current_target, resolve_dispatcher_from_str
import numpy as np
from pandas import DataFrame
from sys import modules
from textwrap import dedent
from sdc.rewrites.ir_utils import (find_operations, is_dict,
get_tuple_items, get_dict_items, remove_unused_recursively,
get_call_parameters,
declare_constant,
import_function, make_call,
insert_before)
from sdc.hiframes import pd_dataframe_ext as pd_dataframe_ext_module
from sdc.hiframes.pd_dataframe_type import DataFrameType, ColumnLoc
from sdc.hiframes.pd_dataframe_ext import get_structure_maps, init_dataframe_internal
from sdc.hiframes.api import fix_df_array, fix_df_index
from sdc.str_ext import string_type
from sdc.extensions.indexes.empty_index_ext import init_empty_index
from sdc.datatypes.indexes.empty_index_type import EmptyIndexType
from sdc.utilities.sdc_typing_utils import TypeChecker, SDCLimitation
from sdc.str_arr_type import StringArrayType
from sdc.functions.tuple_utils import sdc_tuple_map, sdc_tuple_zip
from sdc.datatypes.indexes.positional_index_type import PositionalIndexType
from sdc.utilities.utils import sdc_overload
from sdc.utilities.sdc_typing_utils import get_nbtype_literal_values, sdc_pandas_index_types
@register_rewrite('before-inference')
class RewriteDataFrame(Rewrite):
"""
Searches for calls of pandas.DataFrame and replace it with calls of init_dataframe.
"""
_pandas_dataframe = ('DataFrame', 'pandas')
_df_arg_list = ('data', 'index', 'columns', 'dtype', 'copy')
def __init__(self, pipeline):
self._pipeline = pipeline
super().__init__(pipeline)
self._reset()
def match(self, func_ir, block, typemap, calltypes):
self._reset()
self._block = block
self._func_ir = func_ir
self._calls_to_rewrite = set()
for stmt in find_operations(block=block, op_name='call'):
expr = stmt.value
fdef = guard(find_callname, func_ir, expr)
if fdef == self._pandas_dataframe:
args = get_call_parameters(call=expr, arg_names=self._df_arg_list)
if self._match_dict_case(args, func_ir):
self._calls_to_rewrite.add(stmt)
else:
pass # Forward this case to pd_dataframe_overload which will handle it
return len(self._calls_to_rewrite) > 0
def apply(self):
for stmt in self._calls_to_rewrite:
args = get_call_parameters(call=stmt.value, arg_names=self._df_arg_list)
old_data = args['data']
args['data'], args['columns'] = self._extract_dict_args(args, self._func_ir)
args_len = len(args['data'])
func_name = f'init_dataframe_{args_len}'
# injected_module = modules[pd_dataframe_ext_module.__name__]
init_df = getattr(pd_dataframe_ext_module, func_name, None)
if init_df is None:
init_df_text = gen_init_dataframe_text(func_name, args_len)
init_df = gen_init_dataframe_func(
func_name,
init_df_text,
{
'numba': numba,
'cgutils': cgutils,
'signature': signature,
'types': types,
'get_structure_maps': get_structure_maps,
'intrinsic': intrinsic,
'DataFrameType': DataFrameType,
'ColumnLoc': ColumnLoc,
'string_type': string_type,
'intrinsic': intrinsic,
'fix_df_array': fix_df_array,
'fix_df_index': fix_df_index,
'init_empty_index': init_empty_index,
'EmptyIndexType': EmptyIndexType
})
setattr(pd_dataframe_ext_module, func_name, init_df)
init_df.__module__ = pd_dataframe_ext_module.__name__
init_df._defn.__module__ = pd_dataframe_ext_module.__name__
init_df_stmt = import_function(init_df, self._block, self._func_ir)
self._replace_call(stmt, init_df_stmt.target, args, self._block, self._func_ir)
remove_unused_recursively(old_data, self._block, self._func_ir)
self._pipeline.typingctx.refresh()
return self._block
def _reset(self):
self._block = None
self._func_ir = None
self._calls_to_rewrite = None
@staticmethod
def _match_dict_case(args, func_ir):
if 'data' in args and is_dict(args['data'], func_ir) and 'columns' not in args:
return True
return False
@staticmethod
def _extract_tuple_args(args, block, func_ir):
data_args = get_tuple_items(args['data'], block, func_ir) if 'data' in args else None
columns_args = get_tuple_items(args['columns'], block, func_ir) if 'columns' in args else None
return data_args, columns_args
@staticmethod
def _extract_dict_args(args, func_ir):
dict_items = get_dict_items(args['data'], func_ir)
data_args = [item[1] for item in dict_items]
columns_args = [item[0] for item in dict_items]
return data_args, columns_args
@staticmethod
def _replace_call(stmt, new_call, args, block, func_ir):
func = stmt.value
data_args = args['data']
columns_args = args['columns']
index_args = args.get('index')
if index_args is None: # index arg was omitted
none_stmt = declare_constant(None, block, func_ir, stmt.loc)
index_args = none_stmt.target
index_args = [index_args]
all_args = data_args + index_args + columns_args
call = Expr.call(new_call, all_args, {}, func.loc)
stmt.value = call
def gen_init_dataframe_text(func_name, n_cols):
args_col_data = ['c' + str(i) for i in range(n_cols)]
args_col_names = ['n' + str(i) for i in range(n_cols)]
params = ', '.join(args_col_data + ['index'] + args_col_names)
suffix = ('' if n_cols == 0 else ', ')
func_text = dedent(
f'''
@intrinsic
def {func_name}(typingctx, {params}):
"""Create a DataFrame with provided columns data and index values.
Takes 2n+1 args: n columns data, index data and n column names.
Each column data is passed as separate argument to have compact LLVM IR.
Used as as generic constructor for native DataFrame objects, which
can be used with different input column types (e.g. lists), and
resulting DataFrameType is deduced by applying transform functions
(fix_df_array and fix_df_index) to input argument types.
"""
n_cols = {n_cols}
is_df_empty = {n_cols == 0}
input_data_typs = ({', '.join(args_col_data) + suffix})
fnty = typingctx.resolve_value_type(fix_df_array)
fixed_col_sigs = []
for i in range({n_cols}):
to_sig = fnty.get_call_type(typingctx, (input_data_typs[i],), {{}})
fixed_col_sigs.append(to_sig)
data_typs = tuple(fixed_col_sigs[i].return_type for i in range({n_cols}))
need_fix_cols = tuple(data_typs[i] != input_data_typs[i] for i in range({n_cols}))
input_index_typ = index
fnty = typingctx.resolve_value_type(fix_df_index)
fixed_index_sig = fnty.get_call_type(typingctx,
(input_index_typ, {'data_typs[0]' if n_cols > 0 else ''}), {{}})
index_typ = fixed_index_sig.return_type
need_fix_index = index_typ != input_index_typ
column_names = tuple(a.literal_value for a in ({', '.join(args_col_names) + suffix}))
column_loc, data_typs_map, types_order = get_structure_maps(data_typs, column_names)
col_needs_transform = tuple(not isinstance(data_typs[i], types.Array) for i in range(len(data_typs)))
def codegen(context, builder, sig, args):
{params}, = args
data_arrs = [{', '.join(args_col_data) + suffix}]
data_arrs_transformed = []
for i, arr in enumerate(data_arrs):
if need_fix_cols[i] == False:
data_arrs_transformed.append(arr)
else:
res = context.compile_internal(builder, lambda a: fix_df_array(a), fixed_col_sigs[i], [arr])
data_arrs_transformed.append(res)
# create dataframe struct and store values
dataframe = cgutils.create_struct_proxy(
sig.return_type)(context, builder)
data_list_type = [types.List(typ) for typ in types_order]
data_lists = []
for typ_id, typ in enumerate(types_order):
data_arrs_of_typ = [data_arrs_transformed[data_id] for data_id in data_typs_map[typ][1]]
data_list_typ = context.build_list(builder, data_list_type[typ_id], data_arrs_of_typ)
data_lists.append(data_list_typ)
data_tup = context.make_tuple(
builder, types.Tuple(data_list_type), data_lists)
if need_fix_index == True:
if is_df_empty == True:
first_col_data = context.get_dummy_value()
else:
first_col_data = data_arrs_transformed[0]
index = context.compile_internal(builder,
lambda a, d: fix_df_index(a, d),
fixed_index_sig,
[index, first_col_data])
dataframe.data = data_tup
dataframe.index = index
dataframe.parent = context.get_constant_null(types.pyobject)
# increase refcount of stored values
if context.enable_nrt:
context.nrt.incref(builder, index_typ, index)
for var, typ in zip(data_arrs_transformed, data_typs):
context.nrt.incref(builder, typ, var)
return dataframe._getvalue()
ret_typ = DataFrameType(data_typs, index_typ, column_names, column_loc=column_loc)
sig = signature(ret_typ, {params})
return sig, codegen
''')
return func_text
def gen_init_dataframe_func(func_name, func_text, global_vars):
loc_vars = {}
exec(func_text, global_vars, loc_vars)
return loc_vars[func_name]
@sdc_overload(DataFrame)
def pd_dataframe_overload(data, index=None, columns=None, dtype=None, copy=False):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.DataFrame
Limitations
-----------
- Parameters `dtype` and `copy` are currently unsupported by Intel Scalable Dataframe Compiler.
"""
ty_checker = TypeChecker('Method DataFrame')
if not (isinstance(data, (types.DictType, types.LiteralStrKeyDict))
or isinstance(data, types.Array) and data.ndim == 2 and isinstance(data.dtype, types.Number)):
ty_checker.raise_exc(data, 'dict or 2d numeric array', 'data')
accepted_index_types = (types.Omitted, types.NoneType, types.ListType, types.List) + sdc_pandas_index_types
if not (isinstance(index, accepted_index_types) or index is None):
ty_checker.raise_exc(index, 'array-like', 'index')
if not (isinstance(columns, (types.Omitted, types.NoneType, types.Tuple, types.UniTuple)) or columns is None):
ty_checker.raise_exc(columns, 'tuple of strings', 'columns')
if not (isinstance(dtype, (types.Omitted, types.NoneType)) or dtype is None):
ty_checker.raise_exc(dtype, 'None', 'dtype')
if not (isinstance(copy, (types.Omitted, types.NoneType)) or copy is False):
ty_checker.raise_exc(copy, 'False', 'copy')
if isinstance(data, types.Array):
# case of homogenous DF columns, is special as we can use views to input data
# when creating internal DF structure and avoid penalty in boxing DF as
# pd.DataFrame can be created from 2d array without copy
nb_col_names = None
try:
nb_col_names = tuple(get_nbtype_literal_values(columns))
except AssertionError:
ty_checker.raise_exc(columns, 'tuple of literal strings', 'columns')
n_cols = len(columns)
if index is None and n_cols == 0:
# DataFrame index type cannot be defined unless columns argument is provided
# as it depends on the runtime number of columns in data
raise SDCLimitation("pd.DataFrame constructor from np.ndarray " \
f"requires columns argument. Given columns={columns}.")
# FIXME: there should be more accurate way to write this layout definition
if data.layout in ('C', 'A'):
col_type = types.Array(data.dtype, 1, 'A')
else:
col_type = types.Array(data.dtype, 1, 'C')
nb_col_types = tuple([col_type, ] * n_cols)
column_loc, _, _ = get_structure_maps(nb_col_types, nb_col_names)
typingctx = resolve_dispatcher_from_str(current_target()).targetdescr.typing_context
fnty = typingctx.resolve_value_type(fix_df_index)
nb_index_type = types.none if index is None else index
fixed_index_sig = fnty.get_call_type(typingctx, (nb_index_type, nb_col_types[0]), {}) ### FIXME: need add column argument
fixed_index_typ = fixed_index_sig.return_type
need_fix_index = fixed_index_typ != index
df_type = DataFrameType(nb_col_types, fixed_index_typ, nb_col_names, column_loc=column_loc)
def pd_dataframe_2d_array_impl(data, index=None, columns=None, dtype=None, copy=False):
data_as_columns = np.transpose(data)
df_columns_list = []
if n_cols != data.shape[1]:
raise AssertionError("Number of columns must match data shape")
for i in range(n_cols):
df_columns_list.append(data_as_columns[i])
data_tup = (df_columns_list, )
if need_fix_index == True: # noqa
new_index = fix_df_index(index, df_columns_list[0])
else:
new_index = index
return init_dataframe_internal(data_tup, new_index, df_type)
return pd_dataframe_2d_array_impl
return None