forked from modin-project/modin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.py
596 lines (543 loc) · 19.9 KB
/
io.py
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
# Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under
# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific language
# governing permissions and limitations under the License.
"""
Module houses ``HdkOnNativeIO`` class.
``HdkOnNativeIO`` is used for storing IO functions implementations with HDK storage format and Native engine.
"""
from csv import Dialect
from typing import Union, Sequence, Callable, Dict, Tuple
import inspect
import os
from modin.experimental.core.storage_formats.hdk.query_compiler import (
DFAlgQueryCompiler,
)
from modin.core.io import BaseIO
from modin.experimental.core.execution.native.implementations.hdk_on_native.dataframe.dataframe import (
HdkOnNativeDataframe,
)
from modin.error_message import ErrorMessage
from modin.core.io.text.text_file_dispatcher import TextFileDispatcher
from pyarrow.csv import read_csv, ParseOptions, ConvertOptions, ReadOptions
import pyarrow as pa
import pandas
import pandas._libs.lib as lib
from pandas.io.common import is_url
ReadCsvKwargsType = Dict[
str,
Union[
str,
int,
bool,
dict,
object,
Sequence,
Callable,
Dialect,
None,
],
]
class ArrowEngineException(Exception):
"""Exception raised in case of Arrow engine-specific incompatibilities are found."""
class HdkOnNativeIO(BaseIO, TextFileDispatcher):
"""Class contains IO functions implementations with HDK storage format and Native engine."""
frame_cls = HdkOnNativeDataframe
query_compiler_cls = DFAlgQueryCompiler
arg_keys = [
"filepath_or_buffer",
"sep",
"delimiter",
"header",
"names",
"index_col",
"usecols",
"squeeze",
"prefix",
"mangle_dupe_cols",
"dtype",
"engine",
"converters",
"true_values",
"false_values",
"skipinitialspace",
"skiprows",
"nrows",
"na_values",
"keep_default_na",
"na_filter",
"verbose",
"skip_blank_lines",
"parse_dates",
"infer_datetime_format",
"keep_date_col",
"date_parser",
"dayfirst",
"cache_dates",
"iterator",
"chunksize",
"compression",
"thousands",
"decimal",
"lineterminator",
"quotechar",
"quoting",
"escapechar",
"comment",
"encoding",
"encoding_errors",
"dialect",
"error_bad_lines",
"warn_bad_lines",
"on_bad_lines",
"skipfooter",
"doublequote",
"delim_whitespace",
"low_memory",
"memory_map",
"float_precision",
"storage_options",
]
unsupported_args = [
"decimal",
"thousands",
"index_col",
"prefix",
"converters",
"skipfooter",
"nrows",
"skipinitialspace",
"squeeze",
"mangle_dupe_cols",
"na_values",
"keep_default_na",
"na_filter",
"verbose",
"infer_datetime_format",
"keep_date_col",
"date_parser",
"dayfirst",
"cache_dates",
"iterator",
"chunksize",
"encoding",
"encoding_errors",
"lineterminator",
"dialect",
"quoting",
"comment",
"warn_bad_lines",
"error_bad_lines",
"on_bad_lines",
"low_memory",
"memory_map",
"float_precision",
"storage_options",
]
@classmethod
def read_csv(
cls,
filepath_or_buffer,
sep=",",
delimiter=None,
header="infer",
names=lib.no_default,
index_col=None,
usecols=None,
squeeze=False,
prefix=lib.no_default,
mangle_dupe_cols=True,
dtype=None,
engine=None,
converters=None,
true_values=None,
false_values=None,
skipinitialspace=False,
skiprows=None,
nrows=None,
na_values=None,
keep_default_na=True,
na_filter=True,
verbose=False,
skip_blank_lines=True,
parse_dates=False,
infer_datetime_format=False,
keep_date_col=False,
date_parser=None,
dayfirst=False,
cache_dates=True,
iterator=False,
chunksize=None,
compression="infer",
thousands=None,
decimal=".",
lineterminator=None,
quotechar='"',
quoting=0,
escapechar=None,
comment=None,
encoding=None,
encoding_errors="strict",
dialect=None,
error_bad_lines=None,
warn_bad_lines=None,
on_bad_lines=None,
skipfooter=0,
doublequote=True,
delim_whitespace=False,
low_memory=True,
memory_map=False,
float_precision=None,
storage_options=None,
): # noqa: PR01
"""
Read data from `filepath_or_buffer` according to the passed `kwargs` parameters.
For parameters description please refer to pandas API.
Returns
-------
BaseQueryCompiler
Query compiler with imported data for further processing.
Notes
-----
Reading performed by using of `pyarrow.read_csv` function.
"""
items = locals().copy()
mykwargs = {k: items[k] for k in items if k in cls.arg_keys}
eng = str(engine).lower().strip()
try:
if eng in ["pandas", "c"]:
return super().read_csv(**mykwargs)
cls._validate_read_csv_kwargs(mykwargs)
use_modin_impl, error_message = cls._read_csv_check_support(
mykwargs,
)
if not use_modin_impl:
raise ArrowEngineException(error_message)
if isinstance(dtype, dict):
column_types = {c: cls._dtype_to_arrow(t) for c, t in dtype.items()}
else:
column_types = cls._dtype_to_arrow(dtype)
if (type(parse_dates) is list) and type(column_types) is dict:
for c in parse_dates:
column_types[c] = pa.timestamp("s")
if names not in [lib.no_default, None] and header == 0:
skiprows = skiprows + 1 if skiprows is not None else 1
if delimiter is None and sep is not lib.no_default:
delimiter = sep
usecols_md = cls._prepare_pyarrow_usecols(mykwargs)
po = ParseOptions(
delimiter="\\s+" if delim_whitespace else delimiter,
quote_char=quotechar,
double_quote=doublequote,
escape_char=escapechar,
newlines_in_values=False,
ignore_empty_lines=skip_blank_lines,
)
co = ConvertOptions(
check_utf8=None,
column_types=column_types,
null_values=None,
# we need to add default true/false_values like Pandas does
true_values=true_values + ["TRUE", "True", "true"]
if true_values is not None
else true_values,
false_values=false_values + ["False", "FALSE", "false"]
if false_values is not None
else false_values,
# timestamp fields should be handled as strings if parse_dates
# didn't passed explicitly as an array or a dict
timestamp_parsers=[""] if isinstance(parse_dates, bool) else None,
strings_can_be_null=None,
include_columns=usecols_md,
include_missing_columns=None,
auto_dict_encode=None,
auto_dict_max_cardinality=None,
)
ro = ReadOptions(
use_threads=True,
block_size=None,
skip_rows=skiprows,
column_names=names if names is not lib.no_default else None,
autogenerate_column_names=None,
)
at = read_csv(
filepath_or_buffer,
read_options=ro,
parse_options=po,
convert_options=co,
)
if len(set(at.schema.names)) < len(at.schema.names):
ErrorMessage.default_to_pandas("`read_csv`")
return super().read_csv(**mykwargs)
return cls.from_arrow(at)
except (
pa.ArrowNotImplementedError,
pa.ArrowInvalid,
NotImplementedError,
ArrowEngineException,
):
if eng in ["arrow"]:
raise
ErrorMessage.default_to_pandas("`read_csv`")
return super().read_csv(**mykwargs)
@classmethod
def _dtype_to_arrow(cls, dtype):
"""
Convert `pandas.read_csv` `dtype` parameter into PyArrow compatible type.
Parameters
----------
dtype : str, pandas extension or NumPy dtype
Data type for data or columns, `pandas.read_csv` `dtype` parameter.
Returns
-------
pa.DataType or pa.DictionaryType
PyArrow compatible type.
"""
if dtype is None:
return None
tname = dtype if isinstance(dtype, str) else dtype.name
if tname == "category":
return pa.dictionary(index_type=pa.int32(), value_type=pa.string())
elif tname == "string":
return pa.string()
else:
return pa.from_numpy_dtype(tname)
@classmethod
def _prepare_pyarrow_usecols(cls, read_csv_kwargs):
"""
Define `usecols` parameter in the way PyArrow can process it.
Parameters
----------
read_csv_kwargs : dict
Parameters of read_csv.
Returns
-------
list
Redefined `usecols` parameter.
"""
usecols = read_csv_kwargs.get("usecols", None)
engine = read_csv_kwargs.get("engine", None)
usecols_md, usecols_names_dtypes = cls._validate_usecols_arg(usecols)
if usecols_md:
empty_pd_df = pandas.read_csv(
**dict(
read_csv_kwargs,
nrows=0,
skipfooter=0,
usecols=None,
engine=None if engine == "arrow" else engine,
)
)
column_names = empty_pd_df.columns
if usecols_names_dtypes == "string":
if usecols_md.issubset(set(column_names)):
# columns should be sorted because pandas doesn't preserve columns order
usecols_md = [
col_name for col_name in column_names if col_name in usecols_md
]
else:
raise NotImplementedError(
"values passed in the `usecols` parameter don't match columns names"
)
elif usecols_names_dtypes == "integer":
# columns should be sorted because pandas doesn't preserve columns order
usecols_md = sorted(usecols_md)
if len(column_names) < usecols_md[-1]:
raise NotImplementedError(
"max usecols value is higher than the number of columns"
)
usecols_md = [column_names[i] for i in usecols_md]
elif callable(usecols_md):
usecols_md = [
col_name for col_name in column_names if usecols_md(col_name)
]
else:
raise NotImplementedError("unsupported `usecols` parameter")
return usecols_md
read_csv_unsup_defaults = {}
for k, v in inspect.signature(read_csv.__func__).parameters.items():
if v.default is not inspect.Parameter.empty and k in unsupported_args:
read_csv_unsup_defaults[k] = v.default
@classmethod
def _read_csv_check_support(
cls,
read_csv_kwargs: ReadCsvKwargsType,
) -> Tuple[bool, str]:
"""
Check if passed parameters are supported by current ``modin.pandas.read_csv`` implementation.
Parameters
----------
read_csv_kwargs : dict
Parameters of read_csv function.
Returns
-------
bool
Whether passed parameters are supported or not.
str
Error message that should be raised if user explicitly set `engine="arrow"`.
"""
filepath_or_buffer = read_csv_kwargs.get("filepath_or_buffer", None)
header = read_csv_kwargs.get("header", "infer")
names = read_csv_kwargs.get("names", None)
engine = read_csv_kwargs.get("engine", None)
skiprows = read_csv_kwargs.get("skiprows", None)
delimiter = read_csv_kwargs.get("delimiter", None)
parse_dates = read_csv_kwargs.get("parse_dates", False)
if read_csv_kwargs.get("compression", "infer") != "infer":
return (
False,
"read_csv with 'arrow' engine doesn't support explicit compression parameter, compression"
+ " must be inferred automatically (supported compression types are gzip and bz2)",
)
if isinstance(filepath_or_buffer, str):
if not os.path.exists(filepath_or_buffer):
if cls.file_exists(filepath_or_buffer) or is_url(filepath_or_buffer):
return (
False,
"read_csv with 'arrow' engine supports only local files",
)
else:
raise FileNotFoundError("No such file or directory")
elif not cls.pathlib_or_pypath(filepath_or_buffer):
if hasattr(filepath_or_buffer, "read"):
return (
False,
"read_csv with 'arrow' engine doesn't support file-like objects",
)
else:
raise ValueError(
f"Invalid file path or buffer object type: {type(filepath_or_buffer)}"
)
for arg, def_value in cls.read_csv_unsup_defaults.items():
if read_csv_kwargs[arg] != def_value:
return (
False,
f"read_csv with 'arrow' engine doesn't support {arg} parameter",
)
if delimiter is not None and read_csv_kwargs.get("delim_whitespace", False):
raise ValueError(
"Specified a delimiter with both sep and delim_whitespace=True; you can only specify one."
)
parse_dates_unsupported = isinstance(parse_dates, dict) or (
isinstance(parse_dates, list)
and any(not isinstance(date, str) for date in parse_dates)
)
if parse_dates_unsupported:
return (
False,
(
"read_csv with 'arrow' engine supports only bool and "
+ "flattened list of string column names for the "
+ "'parse_dates' parameter"
),
)
if names and names != lib.no_default:
if header not in [None, 0, "infer"]:
return (
False,
"read_csv with 'arrow' engine and provided 'names' parameter supports only 0, None and "
+ "'infer' header values",
)
if isinstance(parse_dates, list) and not set(parse_dates).issubset(names):
raise ValueError("Missing column provided to 'parse_dates'")
empty_pandas_df = pandas.read_csv(
**dict(
read_csv_kwargs,
nrows=0,
skiprows=None,
skipfooter=0,
usecols=None,
index_col=None,
names=None,
parse_dates=None,
engine=None if engine == "arrow" else engine,
),
)
columns_number = len(empty_pandas_df.columns)
if columns_number != len(names):
return (
False,
"read_csv with 'arrow' engine doesn't support names parameter, which length doesn't match "
+ "with actual number of columns",
)
else:
if header not in [0, "infer"]:
return (
False,
"read_csv with 'arrow' engine without 'names' parameter provided supports only 0 and 'infer' "
+ "header values",
)
if isinstance(parse_dates, list):
empty_pandas_df = pandas.read_csv(
**dict(
read_csv_kwargs,
nrows=0,
skiprows=None,
skipfooter=0,
usecols=None,
index_col=None,
engine=None if engine == "arrow" else engine,
),
)
if not set(parse_dates).issubset(empty_pandas_df.columns):
raise ValueError("Missing column provided to 'parse_dates'")
if not read_csv_kwargs.get("skip_blank_lines", True):
# in some corner cases empty lines are handled as '',
# while pandas handles it as NaNs - issue #3084
return (
False,
"read_csv with 'arrow' engine doesn't support skip_blank_lines = False parameter",
)
if skiprows is not None and not isinstance(skiprows, int):
return (
False,
"read_csv with 'arrow' engine doesn't support non-integer skiprows parameter",
)
return True, None
@classmethod
def _validate_read_csv_kwargs(
cls,
read_csv_kwargs: ReadCsvKwargsType,
):
"""
Validate `read_csv` keyword arguments.
Should be done to mimic `pandas.read_csv` behavior.
Parameters
----------
read_csv_kwargs : dict
Parameters of `read_csv` function.
"""
delimiter = read_csv_kwargs.get("delimiter", None)
sep = read_csv_kwargs.get("sep", lib.no_default)
on_bad_lines = read_csv_kwargs.get("on_bad_lines", "error")
error_bad_lines = read_csv_kwargs.get("error_bad_lines", None)
warn_bad_lines = read_csv_kwargs.get("warn_bad_lines", None)
delim_whitespace = read_csv_kwargs.get("delim_whitespace", False)
if delimiter and (sep is not lib.no_default):
raise ValueError(
"Specified a sep and a delimiter; you can only specify one."
)
# Alias sep -> delimiter.
if delimiter is None:
delimiter = sep
if delim_whitespace and (delimiter is not lib.no_default):
raise ValueError(
"Specified a delimiter with both sep and "
+ "delim_whitespace=True; you can only specify one."
)
if on_bad_lines is not None:
if error_bad_lines is not None or warn_bad_lines is not None:
raise ValueError(
"Both on_bad_lines and error_bad_lines/warn_bad_lines are set. "
+ "Please only set on_bad_lines."
)
if on_bad_lines not in ["error", "warn", "skip", None]:
raise ValueError(f"Argument {on_bad_lines} is invalid for on_bad_lines.")