This repository was archived by the owner on Mar 1, 2023. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathhiframes_typed.py
More file actions
2535 lines (2213 loc) · 110 KB
/
Copy pathhiframes_typed.py
File metadata and controls
2535 lines (2213 loc) · 110 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
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import operator
from collections import defaultdict, namedtuple
import re
import numpy as np
import pandas as pd
import warnings
import datetime
import numba
from numba import ir, ir_utils, types
from numba.ir_utils import (replace_arg_nodes, compile_to_numba_ir,
find_topo_order, gen_np_call, get_definition, guard,
find_callname, mk_alloc, find_const, is_setitem,
is_getitem, mk_unique_var, dprint_func_ir,
build_definitions, find_build_sequence)
from numba.extending import overload
from numba.inline_closurecall import inline_closure_call
from numba.typing.arraydecl import ArrayAttribute
from numba.typing.templates import Signature, bound_function, signature, infer_global, AbstractTemplate, signature
import hpat
from hpat.utils import (debug_prints, inline_new_blocks, ReplaceFunc,
is_whole_slice, is_array)
from hpat.str_ext import (string_type, unicode_to_std_str, std_str_to_unicode,
list_string_array_type)
from hpat.str_arr_ext import (string_array_type, StringArrayType,
is_str_arr_typ, pre_alloc_string_array, get_utf8_size)
from hpat import hiframes
from hpat.hiframes import series_kernels, split_impl
from hpat.hiframes.pd_series_ext import (SeriesType, is_str_series_typ,
series_to_array_type, is_dt64_series_typ,
if_series_to_array_type, is_series_type,
series_str_methods_type, SeriesRollingType, SeriesIatType,
explicit_binop_funcs, series_dt_methods_type)
from hpat.hiframes.pd_index_ext import DatetimeIndexType
from hpat.hiframes.rolling import get_rolling_setup_args
from hpat.hiframes.aggregate import Aggregate
from hpat.hiframes.series_kernels import series_replace_funcs
from hpat.hiframes.split_impl import (string_array_split_view_type,
StringArraySplitViewType, getitem_c_arr, get_array_ctypes_ptr,
get_split_view_index, get_split_view_data_ptr)
from hpat.io.pio_api import h5dataset_type
_dt_index_binops = ('==', '!=', '>=', '>', '<=', '<', '-',
operator.eq, operator.ne, operator.ge, operator.gt,
operator.le, operator.lt, operator.sub)
_string_array_comp_ops = ('==', '!=', '>=', '>', '<=', '<',
operator.eq, operator.ne, operator.ge, operator.gt,
operator.le, operator.lt)
_binop_to_str = {
operator.eq: '==',
operator.ne: '!=',
operator.ge: '>=',
operator.gt: '>',
operator.le: '<=',
operator.lt: '<',
operator.sub: '-',
operator.add: '+',
operator.mul: '*',
operator.truediv: '/',
operator.floordiv: '//',
operator.mod: '%',
operator.pow: '**',
'==': '==',
'!=': '!=',
'>=': '>=',
'>': '>',
'<=': '<=',
'<': '<',
'-': '-',
'+': '+',
'*': '*',
'/': '/',
'//': '//',
'%': '%',
'**': '**',
}
class HiFramesTyped(object):
"""Analyze and transform hiframes calls after typing"""
def __init__(self, func_ir, typingctx, typemap, calltypes):
self.func_ir = func_ir
self.typingctx = typingctx
self.typemap = typemap
self.calltypes = calltypes
# keep track of tuple variables change by to_const_tuple
self._type_changed_vars = []
def run(self):
blocks = self.func_ir.blocks
# topo_order necessary so Series data replacement optimization can be
# performed in one pass
topo_order = find_topo_order(blocks)
work_list = list((l, blocks[l]) for l in reversed(topo_order))
while work_list:
label, block = work_list.pop()
new_body = []
replaced = False
for i, inst in enumerate(block.body):
out_nodes = [inst]
if isinstance(inst, ir.Assign):
self.func_ir._definitions[inst.target.name].remove(inst.value)
out_nodes = self._run_assign(inst)
elif isinstance(inst, (ir.SetItem, ir.StaticSetItem)):
out_nodes = self._run_setitem(inst)
else:
if isinstance(inst, (Aggregate, hiframes.sort.Sort,
hiframes.join.Join, hiframes.filter.Filter,
hpat.io.csv_ext.CsvReader)):
out_nodes = self._handle_hiframes_nodes(inst)
if isinstance(out_nodes, list):
new_body.extend(out_nodes)
self._update_definitions(out_nodes)
if isinstance(out_nodes, ReplaceFunc):
rp_func = out_nodes
if rp_func.pre_nodes is not None:
new_body.extend(rp_func.pre_nodes)
self._update_definitions(rp_func.pre_nodes)
# replace inst.value to a call with target args
# as expected by inline_closure_call
inst.value = ir.Expr.call(
ir.Var(block.scope, "dummy", inst.loc),
rp_func.args, (), inst.loc)
block.body = new_body + block.body[i:]
inline_closure_call(self.func_ir, rp_func.glbls,
block, len(new_body), rp_func.func, self.typingctx,
rp_func.arg_types,
self.typemap, self.calltypes, work_list)
replaced = True
break
if isinstance(out_nodes, dict):
block.body = new_body + block.body[i:]
inline_new_blocks(self.func_ir, block, i, out_nodes, work_list)
replaced = True
break
if not replaced:
blocks[label].body = new_body
# XXX remove slice() of h5 read due to Numba's #3380 bug
self.func_ir.blocks = ir_utils.simplify_CFG(self.func_ir.blocks)
while ir_utils.remove_dead(self.func_ir.blocks, self.func_ir.arg_names,
self.func_ir, self.typemap):
pass
self.func_ir._definitions = build_definitions(self.func_ir.blocks)
dprint_func_ir(self.func_ir, "after hiframes_typed")
return
def _run_assign(self, assign):
lhs = assign.target.name
rhs = assign.value
# fix type of lhs if type of rhs has been changed
if isinstance(rhs, ir.Var) and rhs.name in self._type_changed_vars:
self.typemap.pop(lhs)
self.typemap[lhs] = self.typemap[rhs.name]
self._type_changed_vars.append(lhs)
if isinstance(rhs, ir.Expr):
if rhs.op == 'getattr':
return self._run_getattr(assign, rhs)
if rhs.op == 'binop':
return self._run_binop(assign, rhs)
# XXX handling inplace_binop similar to binop for now
# TODO handle inplace alignment similar to
# add_special_arithmetic_methods() in pandas ops.py
# TODO: inplace of str array?
if rhs.op == 'inplace_binop':
return self._run_binop(assign, rhs)
if rhs.op == 'unary':
return self._run_unary(assign, rhs)
# replace getitems on Series.iat
if rhs.op in ('getitem', 'static_getitem'):
return self._run_getitem(assign, rhs)
if rhs.op == 'call':
return self._run_call(assign, lhs, rhs)
return [assign]
def _run_getitem(self, assign, rhs):
nodes = []
# Series(bool) as index
if (rhs.op == 'getitem'
and self.typemap[rhs.index.name] == SeriesType(types.bool_)):
rhs.index = self._get_series_data(rhs.index, nodes)
if isinstance(self.typemap[rhs.value.name], SeriesIatType):
val_def = guard(get_definition, self.func_ir, rhs.value)
assert (isinstance(val_def, ir.Expr) and val_def.op == 'getattr'
and val_def.attr in ('iat', 'iloc', 'loc'))
series_var = val_def.value
rhs.value = series_var
# replace getitems on dt_index/dt64 series with Timestamp function
if is_dt64_series_typ(self.typemap[rhs.value.name]):
if rhs.op == 'getitem':
ind_var = rhs.index
else:
ind_var = rhs.index_var
in_arr = rhs.value
def f(_in_arr, _ind):
dt = _in_arr[_ind]
s = np.int64(dt)
return hpat.hiframes.pd_timestamp_ext.convert_datetime64_to_timestamp(s)
data = self._get_series_data(in_arr, nodes)
assert isinstance(self.typemap[ind_var.name],
(types.Integer, types.IntegerLiteral))
f_block = compile_to_numba_ir(f, {'numba': numba, 'np': np,
'hpat': hpat}, self.typingctx,
(self.typemap[data.name], types.intp),
self.typemap, self.calltypes).blocks.popitem()[1]
replace_arg_nodes(f_block, [data, ind_var])
nodes += f_block.body[:-2]
nodes[-1].target = assign.target
return nodes
if isinstance(self.typemap[rhs.value.name], SeriesType):
rhs.value = self._get_series_data(rhs.value, nodes)
self._convert_series_calltype(rhs)
lhs = assign.target
# convert output to Series from Array
if isinstance(self.typemap[lhs.name], SeriesType):
new_lhs = ir.Var(
lhs.scope, mk_unique_var(lhs.name + '_data'), lhs.loc)
self.typemap[new_lhs.name] = series_to_array_type(
self.typemap[lhs.name])
nodes.append(ir.Assign(rhs, new_lhs, lhs.loc))
return self._replace_func(
lambda A: hpat.hiframes.api.init_series(A), [new_lhs],
pre_nodes=nodes)
nodes.append(assign)
return nodes
nodes.append(assign)
return nodes
def _run_setitem(self, inst):
target_typ = self.typemap[inst.target.name]
# Series as index
# TODO: handle all possible cases
nodes = []
if (isinstance(inst, ir.SetItem)
and isinstance(self.typemap[inst.index.name], SeriesType)):
inst.index = self._get_series_data(inst.index, nodes)
if (isinstance(inst, ir.SetItem)
and isinstance(self.typemap[inst.value.name], SeriesType)):
inst.value = self._get_series_data(inst.value, nodes)
if target_typ == h5dataset_type:
return self._handle_h5_write(inst.target, inst.index, inst.value)
if isinstance(target_typ, SeriesIatType):
val_def = guard(get_definition, self.func_ir, inst.target)
assert (isinstance(val_def, ir.Expr) and val_def.op == 'getattr'
and val_def.attr in ('iat', 'iloc', 'loc'))
series_var = val_def.value
inst.target = series_var
target_typ = target_typ.stype
if isinstance(target_typ, SeriesType):
# TODO: handle index
data = self._get_series_data(inst.target, nodes)
inst.target = data
nodes.append(inst)
self._convert_series_calltype(inst)
return nodes
nodes.append(inst)
return nodes
def _run_getattr(self, assign, rhs):
rhs_type = self.typemap[rhs.value.name] # get type of rhs value "S"
# replace arr.dtype for dt64 since PA replaces with
# np.datetime64[ns] which invalid, TODO: fix PA
if (rhs.attr == 'dtype' and (is_series_type(rhs_type)
or isinstance(rhs_type, types.Array)) and isinstance(
rhs_type.dtype,
(types.NPDatetime, types.NPTimedelta))):
assign.value = ir.Global("numpy.datetime64", rhs_type.dtype, rhs.loc)
return [assign]
# replace arr.dtype since PA replacement inserts in the
# beginning of block, preventing fusion. TODO: fix PA
if (rhs.attr == 'dtype' and isinstance(
if_series_to_array_type(rhs_type), types.Array)):
typ_str = str(rhs_type.dtype)
assign.value = ir.Global("np.dtype({})".format(typ_str), np.dtype(typ_str), rhs.loc)
return [assign]
# PR135. This needs to be commented out
if isinstance(rhs_type, SeriesType) and rhs.attr == 'values':
# simply return the column
nodes = []
var = self._get_series_data(rhs.value, nodes)
assign.value = var
nodes.append(assign)
return nodes
# PR171. This needs to be commented out
# if isinstance(rhs_type, SeriesType) and rhs.attr == 'index':
# nodes = []
# assign.value = self._get_series_index(rhs.value, nodes)
# nodes.append(assign)
# return nodes
if isinstance(rhs_type, SeriesType) and rhs.attr == 'shape':
nodes = []
data = self._get_series_data(rhs.value, nodes)
return self._replace_func(
lambda A: (len(A),), [data], pre_nodes=nodes)
if isinstance(rhs_type, DatetimeIndexType) and rhs.attr == 'values':
# simply return the data array
nodes = []
var = self._get_dt_index_data(rhs.value, nodes)
assign.value = var
nodes.append(assign)
return nodes
if isinstance(rhs_type, DatetimeIndexType):
if rhs.attr in hpat.hiframes.pd_timestamp_ext.date_fields:
return self._run_DatetimeIndex_field(assign, assign.target, rhs)
if rhs.attr == 'date':
return self._run_DatetimeIndex_date(assign, assign.target, rhs)
if rhs_type == series_dt_methods_type:
dt_def = guard(get_definition, self.func_ir, rhs.value)
if dt_def is None: # TODO: check for errors
raise ValueError("invalid series.dt")
rhs.value = dt_def.value
if rhs.attr in hpat.hiframes.pd_timestamp_ext.date_fields:
return self._run_DatetimeIndex_field(assign, assign.target, rhs)
if rhs.attr == 'date':
return self._run_DatetimeIndex_date(assign, assign.target, rhs)
if isinstance(rhs_type, hpat.hiframes.pd_index_ext.TimedeltaIndexType):
if rhs.attr in hpat.hiframes.pd_timestamp_ext.timedelta_fields:
return self._run_Timedelta_field(assign, assign.target, rhs)
if isinstance(rhs_type, SeriesType) and rhs.attr == 'size':
# simply return the column
nodes = []
var = self._get_series_data(rhs.value, nodes)
rhs.value = var
nodes.append(assign)
return nodes
return [assign]
def _run_binop(self, assign, rhs):
res = self._handle_string_array_expr(assign, rhs)
if res is not None:
return res
if self._is_dt_index_binop(rhs):
return self._handle_dt_index_binop(assign, rhs)
arg1, arg2 = rhs.lhs, rhs.rhs
typ1, typ2 = self.typemap[arg1.name], self.typemap[arg2.name]
if not (isinstance(typ1, SeriesType) or isinstance(typ2, SeriesType)):
return [assign]
nodes = []
# TODO: support alignment, dt, etc.
# S3 = S1 + S2 ->
# S3_data = S1_data + S2_data; S3 = init_series(S3_data)
if isinstance(typ1, SeriesType):
arg1 = self._get_series_data(arg1, nodes)
if isinstance(typ2, SeriesType):
arg2 = self._get_series_data(arg2, nodes)
rhs.lhs, rhs.rhs = arg1, arg2
self._convert_series_calltype(rhs)
# output stays as Array in A += B where A is Array
if isinstance(self.typemap[assign.target.name], types.Array):
assert isinstance(self.calltypes[rhs].return_type, types.Array)
nodes.append(assign)
return nodes
out_data = ir.Var(
arg1.scope, mk_unique_var(assign.target.name + '_data'), rhs.loc)
self.typemap[out_data.name] = self.calltypes[rhs].return_type
nodes.append(ir.Assign(rhs, out_data, rhs.loc))
return self._replace_func(
lambda data: hpat.hiframes.api.init_series(data, None, None),
[out_data],
pre_nodes=nodes
)
def _run_unary(self, assign, rhs):
arg = rhs.value
typ = self.typemap[arg.name]
if isinstance(typ, SeriesType):
nodes = []
arg = self._get_series_data(arg, nodes)
rhs.value = arg
self._convert_series_calltype(rhs)
out_data = ir.Var(
arg.scope, mk_unique_var(assign.target.name + '_data'), rhs.loc)
self.typemap[out_data.name] = self.calltypes[rhs].return_type
nodes.append(ir.Assign(rhs, out_data, rhs.loc))
return self._replace_func(
lambda data: hpat.hiframes.api.init_series(data),
[out_data],
pre_nodes=nodes
)
return [assign]
def _run_call(self, assign, lhs, rhs):
fdef = guard(find_callname, self.func_ir, rhs, self.typemap)
if fdef is None:
from numba.stencil import StencilFunc
# could be make_function from list comprehension which is ok
func_def = guard(get_definition, self.func_ir, rhs.func)
if isinstance(func_def, ir.Expr) and func_def.op == 'make_function':
return [assign]
if isinstance(func_def, ir.Global) and isinstance(func_def.value, StencilFunc):
return [assign]
warnings.warn(
"function call couldn't be found for initial analysis")
return [assign]
else:
func_name, func_mod = fdef
if (isinstance(func_mod, ir.Var)
and self.typemap[func_mod.name]
== series_str_methods_type):
f_def = guard(get_definition, self.func_ir, rhs.func)
str_def = guard(get_definition, self.func_ir, f_def.value)
if str_def is None: # TODO: check for errors
raise ValueError("invalid series.str")
series_var = str_def.value
return self._run_series_str_method(assign, assign.target, series_var, func_name, rhs)
# replace _get_type_max_value(arr.dtype) since parfors
# arr.dtype transformation produces invalid code for dt64
# TODO: min
if fdef == ('_get_type_max_value', 'hpat.hiframes.hiframes_typed'):
if self.typemap[rhs.args[0].name] == types.DType(types.NPDatetime('ns')):
return self._replace_func(
lambda: hpat.hiframes.pd_timestamp_ext.integer_to_dt64(
numba.targets.builtins.get_type_max_value(
numba.types.int64)), [])
return self._replace_func(
lambda d: numba.targets.builtins.get_type_max_value(
d), rhs.args)
if fdef == ('h5_read_dummy', 'hpat.io.pio_api'):
ndim = guard(find_const, self.func_ir, rhs.args[1])
dtype_str = guard(find_const, self.func_ir, rhs.args[2])
index_var = rhs.args[3]
filter_read = False
func_text = "def _h5_read_impl(dset_id, ndim, dtype_str, index):\n"
if guard(is_whole_slice, self.typemap, self.func_ir, index_var):
func_text += " size_0 = hpat.io.pio_api.h5size(dset_id, np.int32(0))\n"
else:
# TODO: check index format for this case
filter_read = True
assert isinstance(self.typemap[index_var.name], types.BaseTuple)
func_text += " read_indices = hpat.io.pio_api.get_filter_read_indices(index[0])\n"
func_text += " size_0 = len(read_indices)\n"
for i in range(1, ndim):
func_text += " size_{} = hpat.io.pio_api.h5size(dset_id, np.int32({}))\n".format(i, i)
func_text += " arr_shape = ({},)\n".format(
", ".join(["size_{}".format(i) for i in range(ndim)]))
func_text += " zero_tup = ({},)\n".format(", ".join(["0"] * ndim))
func_text += " A = np.empty(arr_shape, np.{})\n".format(
dtype_str)
if filter_read:
func_text += " err = hpat.io.pio_api.h5read_filter(dset_id, np.int32({}),\n".format(ndim)
func_text += " zero_tup, arr_shape, 0, A, read_indices)\n"
else:
func_text += " err = hpat.io.pio_api.h5read(dset_id, np.int32({}),\n".format(ndim)
func_text += " zero_tup, arr_shape, 0, A)\n"
func_text += " return A\n"
loc_vars = {}
exec(func_text, {}, loc_vars)
_h5_read_impl = loc_vars['_h5_read_impl']
return self._replace_func(_h5_read_impl, rhs.args)
if fdef == ('DatetimeIndex', 'pandas'):
return self._run_pd_DatetimeIndex(assign, assign.target, rhs)
if fdef == ('Series', 'pandas'):
arg_typs = tuple(self.typemap[v.name] for v in rhs.args)
kw_typs = {name: self.typemap[v.name]
for name, v in dict(rhs.kws).items()}
impl = hpat.hiframes.pd_series_ext.pd_series_overload(
*arg_typs, **kw_typs)
return self._replace_func(impl, rhs.args,
pysig=self.calltypes[rhs].pysig, kws=dict(rhs.kws))
if func_mod == 'hpat.hiframes.api':
return self._run_call_hiframes(assign, assign.target, rhs, func_name)
if func_mod == 'hpat.hiframes.rolling':
return self._run_call_rolling(assign, assign.target, rhs, func_name)
if fdef == ('empty_like', 'numpy'):
return self._handle_empty_like(assign, lhs, rhs)
if (isinstance(func_mod, ir.Var)
and is_series_type(self.typemap[func_mod.name])):
return self._run_call_series(
assign, assign.target, rhs, func_mod, func_name)
if (isinstance(func_mod, ir.Var) and isinstance(
self.typemap[func_mod.name], SeriesRollingType)):
return self._run_call_series_rolling(
assign, assign.target, rhs, func_mod, func_name)
if (isinstance(func_mod, ir.Var)
and isinstance(
self.typemap[func_mod.name], DatetimeIndexType)):
return self._run_call_dt_index(
assign, assign.target, rhs, func_mod, func_name)
if (fdef == ('concat_dummy', 'hpat.hiframes.pd_dataframe_ext')
and isinstance(self.typemap[lhs], SeriesType)):
return self._run_call_concat(assign, lhs, rhs)
# handle sorted() with key lambda input
if fdef == ('sorted', 'builtins') and 'key' in dict(rhs.kws):
return self._handle_sorted_by_key(rhs)
if fdef == ('init_dataframe', 'hpat.hiframes.pd_dataframe_ext'):
return [assign]
# XXX sometimes init_dataframe() can't be resolved in dataframe_pass
# and there are get_dataframe_data() calls that could be optimized
# example: test_sort_parallel
if fdef == ('get_dataframe_data', 'hpat.hiframes.pd_dataframe_ext'):
df_var = rhs.args[0]
df_typ = self.typemap[df_var.name]
ind = guard(find_const, self.func_ir, rhs.args[1])
var_def = guard(get_definition, self.func_ir, df_var)
call_def = guard(find_callname, self.func_ir, var_def)
if call_def == ('init_dataframe', 'hpat.hiframes.pd_dataframe_ext'):
assign.value = var_def.args[ind]
if fdef == ('get_dataframe_index', 'hpat.hiframes.pd_dataframe_ext'):
df_var = rhs.args[0]
df_typ = self.typemap[df_var.name]
n_cols = len(df_typ.columns)
var_def = guard(get_definition, self.func_ir, df_var)
call_def = guard(find_callname, self.func_ir, var_def)
if call_def == ('init_dataframe', 'hpat.hiframes.pd_dataframe_ext'):
assign.value = var_def.args[n_cols]
# convert Series to Array for unhandled calls
# TODO check all the functions that get here and handle if necessary
nodes = []
new_args = []
for arg in rhs.args:
if isinstance(self.typemap[arg.name], SeriesType):
new_args.append(self._get_series_data(arg, nodes))
else:
new_args.append(arg)
self._convert_series_calltype(rhs)
rhs.args = new_args
# Second condition is to avoid chenging SeriesGroupBy class members
# test: python -m hpat.runtests hpat.tests.test_series.TestSeries.test_series_groupby_count
if isinstance(self.typemap[lhs], SeriesType) and not isinstance(func_mod, ir.Var):
scope = assign.target.scope
new_lhs = ir.Var(scope, mk_unique_var(lhs + '_data'), rhs.loc)
self.typemap[new_lhs.name] = self.calltypes[rhs].return_type
nodes.append(ir.Assign(rhs, new_lhs, rhs.loc))
def _replace_func_param_impl(A):
return hpat.hiframes.api.init_series(A)
return self._replace_func(_replace_func_param_impl, [new_lhs], pre_nodes=nodes)
nodes.append(assign)
return nodes
def _run_call_hiframes(self, assign, lhs, rhs, func_name):
if func_name in ('to_arr_from_series',):
assign.value = rhs.args[0]
return [assign]
# pd.DataFrame() calls init_series for even Series since it's untyped
# remove the call since it is invalid for analysis here
# XXX remove when df pass is typed? (test_pass_series2)
if func_name == 'init_series' and isinstance(
self.typemap[rhs.args[0].name], SeriesType):
assign.value = rhs.args[0]
return [assign]
if func_name == 'get_index_data':
# fix_df_array() calls get_index_data() for DatetimeIndex
# but it can be removed sometimes
var_def = guard(get_definition, self.func_ir, rhs.args[0])
call_def = guard(find_callname, self.func_ir, var_def)
if call_def == ('init_datetime_index', 'hpat.hiframes.api'):
assign.value = var_def.args[0]
return [assign]
if func_name == 'get_series_data':
# fix_df_array() calls get_series_data() (e.g. for dataframes)
# but it can be removed sometimes
var_def = guard(get_definition, self.func_ir, rhs.args[0])
call_def = guard(find_callname, self.func_ir, var_def)
if call_def == ('init_series', 'hpat.hiframes.api'):
assign.value = var_def.args[0]
return [assign]
if func_name in ('str_contains_regex', 'str_contains_noregex'):
return self._handle_str_contains(assign, lhs, rhs, func_name)
# arr = fix_df_array(col) -> arr=col if col is array
if func_name == 'fix_df_array':
in_typ = self.typemap[rhs.args[0].name]
impl = hpat.hiframes.api.fix_df_array_overload(in_typ)
return self._replace_func(impl, rhs.args)
# arr = fix_rolling_array(col) -> arr=col if col is float array
if func_name == 'fix_rolling_array':
in_arr = rhs.args[0]
if isinstance(self.typemap[in_arr.name].dtype, types.Float):
assign.value = rhs.args[0]
return [assign]
else:
def f(column): # pragma: no cover
a = column.astype(np.float64)
f_block = compile_to_numba_ir(f,
{'hpat': hpat, 'np': np}, self.typingctx,
(if_series_to_array_type(self.typemap[in_arr.name]),),
self.typemap, self.calltypes).blocks.popitem()[1]
replace_arg_nodes(f_block, [in_arr])
nodes = f_block.body[:-3]
nodes[-1].target = assign.target
return nodes
if func_name == 'series_filter_bool':
return self._handle_df_col_filter(assign, lhs, rhs)
if func_name == 'to_const_tuple':
tup = rhs.args[0]
tup_items = self._get_const_tup(tup)
new_tup = ir.Expr.build_tuple(tup_items, tup.loc)
assign.value = new_tup
# fix type and definition of lhs
self.typemap.pop(lhs.name)
self._type_changed_vars.append(lhs.name)
self.typemap[lhs.name] = types.Tuple(tuple(
self.typemap[a.name] for a in tup_items))
return [assign]
if func_name == 'series_tup_to_arr_tup':
in_typ = self.typemap[rhs.args[0].name]
assert isinstance(in_typ, types.BaseTuple), 'tuple expected'
series_vars = guard(get_definition, self.func_ir, rhs.args[0]).items
nodes = []
tup_items = [self._get_series_data(v, nodes) for v in series_vars]
new_tup = ir.Expr.build_tuple(tup_items, lhs.loc)
assign.value = new_tup
nodes.append(assign)
return nodes
if func_name == 'concat':
# concat() case where tuple type changes by to_const_type()
if any([a.name in self._type_changed_vars for a in rhs.args]):
argtyps = tuple(self.typemap[a.name] for a in rhs.args)
old_sig = self.calltypes.pop(rhs)
new_sig = self.typemap[rhs.func.name].get_call_type(
self.typingctx, argtyps, rhs.kws)
self.calltypes[rhs] = new_sig
# replace tuple of Series with tuple of Arrays
in_vars, _ = guard(find_build_sequence, self.func_ir, rhs.args[0])
nodes = []
s_arrs = [self._get_series_data(v, nodes) if isinstance(
self.typemap[v.name], SeriesType) else v for v in in_vars]
new_tup = ir.Expr.build_tuple(s_arrs, lhs.loc)
new_arg = ir.Var(lhs.scope, mk_unique_var(
rhs.args[0].name + '_arrs'), lhs.loc)
self.typemap[new_arg.name] = if_series_to_array_type(
self.typemap[rhs.args[0].name])
nodes.append(ir.Assign(new_tup, new_arg, lhs.loc))
rhs.args[0] = new_arg
nodes.append(assign)
self.calltypes.pop(rhs)
new_sig = self.typemap[rhs.func.name].get_call_type(
self.typingctx, (self.typemap[new_arg.name],), rhs.kws)
self.calltypes[rhs] = new_sig
return nodes
# replace isna early to enable more optimization in PA
# TODO: handle more types
if func_name == 'isna':
arr = rhs.args[0]
ind = rhs.args[1]
arr_typ = self.typemap[arr.name]
if isinstance(arr_typ, (types.Array, SeriesType)):
if isinstance(arr_typ.dtype, types.Float):
def func(arr, i):
return np.isnan(arr[i])
return self._replace_func(func, [arr, ind])
elif isinstance(
arr_typ.dtype, (types.NPDatetime, types.NPTimedelta)):
nat = arr_typ.dtype('NaT')
# TODO: replace with np.isnat
return self._replace_func(
lambda arr, i: arr[i] == nat, [arr, ind])
elif arr_typ.dtype != string_type:
return self._replace_func(lambda arr, i: False, [arr, ind])
if func_name == 'df_isin':
# XXX df isin is different than Series.isin, df.isin considers
# index but Series.isin ignores it (everything is set)
# TODO: support strings and other types
nodes = []
data, other = rhs.args
def _isin_series(A, B):
numba.parfor.init_prange()
n = len(A)
m = len(B)
S = np.empty(n, np.bool_)
for i in numba.parfor.internal_prange(n):
S[i] = (A[i] == B[i] if i < m else False)
return S
return self._replace_func(
_isin_series, [data, other], pre_nodes=nodes)
if func_name == 'df_isin_vals':
nodes = []
data = rhs.args[0]
def _isin_series(A, vals):
numba.parfor.init_prange()
n = len(A)
S = np.empty(n, np.bool_)
for i in numba.parfor.internal_prange(n):
S[i] = A[i] in vals
return S
return self._replace_func(
_isin_series, [data, rhs.args[1]], pre_nodes=nodes)
if func_name == 'flatten_to_series':
arg = rhs.args[0]
in_typ = self.typemap[arg.name]
nodes = []
if isinstance(in_typ, SeriesType):
arg = self._get_series_data(arg, nodes)
def _flatten_impl(A):
numba.parfor.init_prange()
flat_list = []
n = len(A)
for i in numba.parfor.internal_prange(n):
elems = A[i]
for s in elems:
flat_list.append(s)
return hpat.hiframes.api.init_series(
hpat.hiframes.api.parallel_fix_df_array(flat_list))
return self._replace_func(_flatten_impl, [arg], pre_nodes=nodes)
if func_name == 'to_numeric':
out_dtype = self.typemap[lhs.name].dtype
assert out_dtype == types.int64 or out_dtype == types.float64
# TODO: handle non-Series input
def _to_numeric_impl(A):
# TODO: fix distributed
numba.parfor.init_prange()
n = len(A)
B = np.empty(n, out_dtype)
for i in numba.parfor.internal_prange(n):
hpat.str_arr_ext.str_arr_item_to_numeric(B, i, A, i)
return hpat.hiframes.api.init_series(B)
nodes = []
data = self._get_series_data(rhs.args[0], nodes)
return self._replace_func(_to_numeric_impl, [data],
pre_nodes=nodes,
extra_globals={'out_dtype': out_dtype})
if func_name == 'parse_datetimes_from_strings':
nodes = []
data = self._get_series_data(rhs.args[0], nodes)
def parse_impl(data):
numba.parfor.init_prange()
n = len(data)
S = numba.unsafe.ndarray.empty_inferred((n,))
for i in numba.parfor.internal_prange(n):
S[i] = hpat.hiframes.pd_timestamp_ext.parse_datetime_str(data[i])
return S
return self._replace_func(parse_impl, [data], pre_nodes=nodes)
if func_name == 'get_itertuples':
nodes = []
new_args = []
for arg in rhs.args:
if isinstance(self.typemap[arg.name], SeriesType):
new_args.append(self._get_series_data(arg, nodes))
else:
new_args.append(arg)
self._convert_series_calltype(rhs)
rhs.args = new_args
nodes.append(assign)
return nodes
return self._handle_df_col_calls(assign, lhs, rhs, func_name)
def _run_call_series(self, assign, lhs, rhs, series_var, func_name):
# single arg functions
if func_name in ('sum', 'count', 'mean', 'var', 'min', 'max'):
if rhs.args or rhs.kws:
raise ValueError("HPAT pipeline does not support arguments for Series.{}()".format(func_name))
# TODO: handle skipna, min_count arguments
series_typ = self.typemap[series_var.name]
series_dtype = series_typ.dtype
func = series_replace_funcs[func_name]
if isinstance(func, dict):
func = func[series_dtype]
nodes = []
data = self._get_series_data(series_var, nodes)
return self._replace_func(func, [data], pre_nodes=nodes)
if func_name in ('std', 'nunique', 'describe',
'isnull', 'median', 'idxmin', 'idxmax', 'unique'):
if rhs.args or rhs.kws:
raise ValueError("unsupported Series.{}() arguments".format(
func_name))
func = series_replace_funcs[func_name]
# TODO: handle skipna, min_count arguments
nodes = []
if func_name == 'describe':
data = series_var
else:
data = self._get_series_data(series_var, nodes)
return self._replace_func(func, [data], pre_nodes=nodes)
if func_name == 'quantile':
nodes = []
data = self._get_series_data(series_var, nodes)
def run_call_series_quantile(A, q):
return hpat.hiframes.api.quantile(A, q)
def run_call_series_quantile_default(A):
return hpat.hiframes.api.quantile(A, 0.5)
if len(rhs.args) == 0:
args = [data]
replacement_func = run_call_series_quantile_default
else:
assert len(rhs.args) == 1, "invalid args for " + func_name
args = [data, rhs.args[0]]
replacement_func = run_call_series_quantile
return self._replace_func(replacement_func, args, pre_nodes=nodes)
if func_name == 'fillna':
return self._run_call_series_fillna(assign, lhs, rhs, series_var)
if func_name == 'dropna':
return self._run_call_series_dropna(assign, lhs, rhs, series_var)
if func_name == 'rename':
nodes = []
data = self._get_series_data(series_var, nodes)
index = self._get_series_index(series_var, nodes)
name = rhs.args[0]
return self._replace_func(
lambda data, index, name: hpat.hiframes.api.init_series(
data, index, name),
[data, index, name], pre_nodes=nodes)
if func_name == 'pct_change':
nodes = []
data = self._get_series_data(series_var, nodes)
# TODO: support default period argument
if len(rhs.args) == 0:
args = [data]
func = series_replace_funcs[func_name + "_default"]
else:
assert len(rhs.args) == 1, "invalid args for " + func_name
shift_const = rhs.args[0]
args = [data, shift_const]
func = series_replace_funcs[func_name]
return self._replace_func(func, args, pre_nodes=nodes)
if func_name in ('nlargest', 'nsmallest'):
# TODO: kws
nodes = []
data = self._get_series_data(series_var, nodes)
name = self._get_series_name(series_var, nodes)
if len(rhs.args) == 0 and not rhs.kws:
return self._replace_func(
series_replace_funcs[func_name + '_default'], [data, name],
extra_globals={'gt_f': series_kernels.gt_f,
'lt_f': series_kernels.lt_f},
pre_nodes=nodes)
n_arg = rhs.args[0]
func = series_replace_funcs[func_name]
return self._replace_func(func, [data, n_arg, name],
extra_globals={'gt_f': series_kernels.gt_f,
'lt_f': series_kernels.lt_f},
pre_nodes=nodes)
if func_name == 'head':
nodes = []
n_arg = self._get_arg('Series.head', rhs.args, dict(rhs.kws), 0,
'n', default=False) # TODO: proper default handling
if n_arg is False:
n_arg = ir.Var(lhs.scope, mk_unique_var('head_n'), lhs.loc)
# default is 5
self.typemap[n_arg.name] = types.IntegerLiteral(5)
nodes.append(ir.Assign(
ir.Const(5, lhs.loc), n_arg, lhs.loc))
data = self._get_series_data(series_var, nodes)
func = series_replace_funcs[func_name]
if self.typemap[series_var.name].index != types.none:
index = self._get_series_index(series_var, nodes)
func = series_replace_funcs['head_index']
else:
index = self._get_index_values(data, nodes)
name = self._get_series_name(series_var, nodes)
return self._replace_func(
func, (data, index, n_arg, name), pre_nodes=nodes)
if func_name in ('cov', 'corr'):
S2 = rhs.args[0]
func = series_replace_funcs[func_name]
return self._replace_func(func, [series_var, S2])
if func_name in ('argsort', 'sort_values'):
return self._handle_series_sort(
lhs, rhs, series_var, func_name == 'argsort')
if func_name == 'rolling':
# XXX: remove rolling setup call, assuming still available in definitions
self.func_ir._definitions[lhs.name].append(rhs)
return []
if func_name == 'combine':
return self._handle_series_combine(assign, lhs, rhs, series_var)
if func_name in ('map', 'apply'):
return self._handle_series_map(assign, lhs, rhs, series_var)
if func_name == 'append':
nodes = []
data = self._get_series_data(series_var, nodes)
other = rhs.args[0]
if isinstance(self.typemap[other.name], SeriesType):
func = series_replace_funcs['append_single']
other = self._get_series_data(other, nodes)
else:
func = series_replace_funcs['append_tuple']
return self._replace_func(func, [data, other], pre_nodes=nodes)
if func_name == 'notna':
# TODO: make sure this is fused and optimized properly
return self._replace_func(
lambda S: S.isna() == False, [series_var])