-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_handler.py
671 lines (550 loc) · 22.7 KB
/
file_handler.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
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
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 9 11:52:46 2023
@author: jcutern-imchugh
"""
import numpy as np
import pandas as pd
import file_io as io
import file_concatenators as fc
###############################################################################
### CLASSES ###
###############################################################################
#------------------------------------------------------------------------------
class DataHandler():
#--------------------------------------------------------------------------
def __init__(self, file, concat_files=False):
"""
Set attributes of handler.
Parameters
----------
file : str or pathlib.Path
Absolute path to file for which to create the handler.
concat_files : Boolean or list, optional
If False, the content of the passed file is parsed in isolation.
If True, any available backup (TOA5) or string-matched EddyPro
files stored in the same directory are concatenated.
If list, the files contained therein will be concatenated with the
main file.
The default is False.
Returns
-------
None.
"""
rslt = _get_handler_elements(file=file, concat_files=concat_files)
for key, value in rslt.items():
setattr(self, key, value)
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
def get_conditioned_data(self,
usecols=None, output_format=None, drop_non_numeric=False,
monotonic_index=False, resample_intvl=None,
raise_if_dupe_index=False
):
"""
Generate a conditioned version of the data. Duplicate data are dropped.
Parameters
----------
usecols : list or dict, optional
The columns to include in the output. If a dict is passed, then
the columns are renamed, with the mapping from existing to new
defined by the key (old name): value (new_name) pairs.
The default is None.
output_format : str, optional
The format for data output (None, TOA5 or EddyPro).
The default is None.
drop_non_numeric : bool, optional
Purge the non-numeric columns from the conditioned data. If false,
the non-numeric columns will be included even if excluded from
usecols. If true they will be dropped even if included in usecols.
The default is False.
monotonic_index : bool, optional
Align the data to a monotonic index. The default is False.
resample_intvl : date_offset, optional
The time interval to which the data should be resampled.
The default is None.
raise_if_dupe_index : bool, optional
Raise an error if duplicate indices are found with non-duplicate
data. The default is False.
Raises
------
RuntimeError
Raised if duplicate indices are found with non-duplicate data.
Returns
-------
pd.core.frame.DataFrame
Dataframe with altered data.
"""
# Apply column subset and rename
subset_list, rename_dict = self._subset_or_translate(usecols=usecols)
output_data = self.data[subset_list].rename(rename_dict, axis=1)
# Apply duplicate mask
dupe_records = self.get_duplicate_records()
dupe_indices = self.get_duplicate_indices()
if any(dupe_indices) and raise_if_dupe_index:
raise RuntimeError(
'Duplicate indices with non-duplicate data!'
)
dupes_mask = dupe_indices | dupe_records
output_data = output_data.loc[~dupes_mask]
# Do the resampling
if monotonic_index and not resample_intvl:
resample_intvl = f'{self.interval}T'
if resample_intvl:
output_data = output_data.resample(resample_intvl).asfreq()
# If platform-specific formatting not requested, drop non-numerics
# (if requested) and return
if output_format is None:
if drop_non_numeric:
for var in self._configs['non_numeric_cols']:
try:
output_data.drop(var, axis=1, inplace=True)
except KeyError:
pass
return output_data
# Format and return data
return io.reformat_data(
data=output_data,
output_format=output_format
)
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
def get_conditioned_headers(
self, usecols=None, output_format=None, drop_non_numeric=False
):
"""
Parameters
----------
usecols : list or dict, optional
The columns to include in the output. If a dict is passed, then
the columns are renamed, with the mapping from existing to new
defined by the key (old name): value (new_name) pairs.
The default is None.
output_format : str, optional
The format for header output (None, TOA5 or EddyPro).
The default is None.
drop_non_numeric : bool, optional
Purge the non-numeric headers from the conditioned data. If false,
the non-numeric headers will be included even if excluded from
usecols. If true they will be dropped even if included in usecols.
The default is False.
Returns
-------
output_headers : pd.core.frame.DataFrame
Dataframe with altered headers.
"""
# Apply column subset and rename
subset_list, rename_dict = self._subset_or_translate(usecols=usecols)
output_headers = self.headers.loc[subset_list].rename(rename_dict)
# If platform-specific formatting not requested, drop non-numerics
# (if requested) and return
if output_format is None:
if drop_non_numeric:
for var in self._configs['non_numeric_cols']:
try:
output_headers.drop(var, inplace=True)
except KeyError:
pass
return output_headers
# Format and return data
return io.reformat_headers(
headers=output_headers,
output_format=output_format
)
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
def get_duplicate_records(self, as_dates=False):
"""
Get a representation of duplicate records (boolean pandas Series).
Parameters
----------
as_dates : bool, optional
Output just the list of dates for which duplicate records occur.
The default is False.
Returns
-------
series or list
Output boolean series indicating duplicates, or list of dates.
"""
records = self.data.reset_index().duplicated().set_axis(self.data.index)
if as_dates:
return self.data[records].index.to_pydatetime().tolist()
return records
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
def get_duplicate_indices(self, as_dates=False):
"""
Get a representation of duplicate indices (boolean pandas Series).
Parameters
----------
as_dates : bool, optional
Output just the list of dates for which duplicate indices occur.
The default is False.
Returns
-------
series or list
Output boolean series indicating duplicates, or list of dates.
"""
records = self.get_duplicate_records()
indices = ~records & self.data.index.duplicated()
if as_dates:
return self.data[indices].index.to_pydatetime().tolist()
return indices
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
def get_missing_records(self, raise_if_single_record=False):
"""
Get simple statistics for missing records
Returns
-------
dict
Dictionary containing the number of missing cases, the % of missing
cases and the distribution of gap sizes.
"""
data = self._get_non_duplicate_data()
complete_index = pd.date_range(
start=data.index[0],
end=data.index[-1],
freq=f'{self.interval}T'
)
n_missing = len(complete_index) - len(data)
return {
'n_missing': n_missing,
'%_missing': round(n_missing / len(complete_index) * 100, 2),
}
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
def get_gap_bounds(self):
data, gap_series = self._init_gap_analysis()
return pd.concat(
[
gap_series.reset_index().n_records,
pd.DataFrame(
data=[
data.iloc[x-1: x+1].astype(str).tolist()
for x in gap_series.index
],
columns=['last_preceding', 'first_succeeding']
)
],
axis=1
)
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
def get_gap_distribution(self):
gap_series = self._init_gap_analysis()[1]
unique_gaps = gap_series.unique()
counts = [len(gap_series[gap_series==x]) for x in unique_gaps]
return (
pd.DataFrame(
data=zip(unique_gaps - 1, counts),
columns=['n_records', 'count']
)
.set_index(keys='n_records')
.sort_index()
)
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
def _init_gap_analysis(self):
# If file is TOA5, it will have a column AND an index named TIMESTAMP,
# so dump the variable if so
data = self._get_non_duplicate_data()
try:
data = data.drop('TIMESTAMP', axis=1)
except KeyError:
pass
# Get instances of duplicate indices OR records, and remove
data = data.reset_index()['DATETIME']
# Get gaps as n_records (exclude gaps equal to measurement interval!)
gap_series = (
(data - data.shift())
.astype('timedelta64[s]')
.replace(self.interval, np.nan)
.dropna()
.apply(lambda x: x.total_seconds() / (60 * self.interval))
.astype(int)
.rename('n_records')
)
gap_series = gap_series[gap_series!=1]
return data, gap_series
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
def _get_non_duplicate_data(self):
if self.interval is None:
raise TypeError('Analysis not applicable to single record!')
dupes = self.get_duplicate_indices() | self.get_duplicate_records()
return self.data[~dupes]
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
def get_date_span(self):
"""
Get start and end dates
Returns
-------
dict
Dictionary containing start and end dates (keys "start" and "end").
"""
return {
'start_date': self.data.index[0].to_pydatetime(),
'end_date': self.data.index[-1].to_pydatetime()
}
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
def get_non_numeric_variables(self):
return self._configs['non_numeric_cols']
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
def get_numeric_variables(self):
return [
col for col in self.data.columns if not col in
self.get_non_numeric_variables()
]
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
def get_variable_list(self):
"""
Gets the list of variables in the TOA5 header line
Returns
-------
list
The list.
"""
return self.headers.index.tolist()
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
def get_variable_units(self, variable):
"""
Gets the units for a given variable
Parameters
----------
variable : str
The variable for which to return the units.
Returns
-------
str
The units.
"""
return self.headers.loc[variable, 'units']
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
def map_variable_units(self):
"""
Get a dictionary cross-referencing all variables in file to their units
Returns
-------
dict
With variables (keys) and units (values).
"""
return dict(zip(
self.headers.index.tolist(),
self.headers.units.tolist()
))
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
def map_sampling_units(self):
"""
Get a dictionary cross-referencing all variables in file to their
sampling methods
Returns
-------
dict
With variables (keys) and sampling (values).
"""
if self.file_type == 'EddyPro':
raise NotImplementedError(
f'No station info available for file type "{self.file_type}"')
return dict(zip(
self.headers.index.tolist(),
self.headers.sampling.tolist()
))
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
def write_concatenation_report(self, abs_file_path):
"""
Write the concatenation report to file.
Parameters
----------
abs_file_path : str or pathlib.Path
Absolute path to the file.
Raises
------
TypeError
Raised if no concatenated files.
Returns
-------
None.
"""
if not self.concat_report:
raise TypeError(
'Cannot write a concatenation report if there are no '
'concatenated files!'
)
fc._write_text_to_file(
line_list=self.concat_report,
abs_file_path=abs_file_path
)
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
def write_conditioned_data(
self, abs_file_path, usecols=None, output_format=None,
drop_non_numeric=False, **kwargs
):
if output_format is None:
output_format = self.file_type
io.write_data_to_file(
headers=self.get_conditioned_headers(
usecols=usecols,
output_format=output_format,
drop_non_numeric=drop_non_numeric,
),
data=self.get_conditioned_data(
usecols=usecols,
output_format=output_format,
drop_non_numeric=drop_non_numeric,
**kwargs
),
abs_file_path=abs_file_path,
output_format=output_format,
info=self.file_info
)
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
def _subset_or_translate(self, usecols):
# Set the subsetting list and rename dict, depending on type
if usecols is None:
subset_list, rename_dict = self.data.columns, {}
elif isinstance(usecols, dict):
subset_list, rename_dict = list(usecols.keys()), usecols.copy()
elif isinstance(usecols, list):
subset_list, rename_dict = usecols.copy(), {}
else:
raise TypeError('usecols arg must be None, list or dict')
# Return the subset list and the renaming dictionary
return subset_list, rename_dict
#--------------------------------------------------------------------------
#------------------------------------------------------------------------------
###############################################################################
### BEGIN INIT FUNCTIONS ###
###############################################################################
#------------------------------------------------------------------------------
def _get_handler_elements(file, concat_files=False):
"""
Get elements required to populate file handler for either single file or
multi-file concatenated data.
Parameters
----------
file : str or pathlib.Path
Absolute path to master file.
concat_files : boolean or list
See concat_files description in __init__ docstring for DataHandler.
Returns
-------
dict
Contains data (key 'data'), headers (key 'headers') and concatenation
report (key 'concat_report').
"""
# Set an emptry concatenation list
concat_list = []
# If boolean passed...
if concat_files is True:
concat_list = io.get_eligible_concat_files(file=file)
# If list passed...
if isinstance(concat_files, list):
concat_list = concat_files
# If concat_list has no elements, get single file data
if len(concat_list) == 0:
fallback = False if not concat_files else True
data_dict = _get_single_file_data(file=file, fallback=fallback)
# If concat_list has elements, use the concatenator
if len(concat_list) > 0:
data_dict = _get_concatenated_file_data(
file=file,
concat_list=concat_list
)
# Get file interval regardless of provenance (single or concatenated)
data_dict.update(
{'interval': io.get_datearray_interval(
datearray=np.array(data_dict['data'].index.to_pydatetime())
)
}
)
# Return the dictionary
return data_dict
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
def _get_concatenated_file_data(file, concat_list):
file_type = io.get_file_type(file=file)
configs = io.get_file_type_configs(file_type=file_type)
concatenator = fc.FileConcatenator(
master_file=file,
file_type=file_type,
concat_list=concat_list
)
return {
'file_type': file_type,
'file_info': io.get_file_info(
file=file, file_type=file_type, dummy_override=True
),
'data': concatenator.get_concatenated_data(),
'headers': concatenator.get_concatenated_header(),
'concat_list': concat_list,
'concat_report': concatenator.get_concatenation_report(as_text=True),
'_configs': configs
}
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
def _get_single_file_data(file, fallback=False):
file_type = io.get_file_type(file=file)
configs = io.get_file_type_configs(file_type=file_type)
return {
'file_type': file_type,
'file_info': io.get_file_info(file=file, file_type=file_type),
'data': io.get_data(file=file, file_type=file_type),
'headers': io.get_header_df(file=file, file_type=file_type),
'concat_list': [],
'concat_report': [] if not fallback else ['No eligible files found!'],
'_configs': configs
}
#------------------------------------------------------------------------------
###############################################################################
### END INIT FUNCTIONS ###
###############################################################################
###############################################################################
### BEGIN PUBLIC FUNCTIONS ###
###############################################################################
#------------------------------------------------------------------------------
def merge_data(
files: list | dict, concat_files: bool=False
) -> pd.core.frame.DataFrame:
"""
Merge and align data from different files.
Args:
files: the absolute path of the files to parse.
If a list, all variables returned; if a dict, file is value, and key
is passed to the file_handler. That key can be a list of variables, or
a dictionary mapping translation of variable names (see file handler
documentation).
Returns:
merged data.
"""
df_list = []
for file in files:
try:
usecols = files[file]
except TypeError:
usecols = None
data_handler = DataHandler(file=file, concat_files=concat_files)
df_list.append(
data_handler.get_conditioned_data(
usecols=usecols, drop_non_numeric=True,
monotonic_index=True
)
)
return (
pd.concat(df_list, axis=1)
.rename_axis('time')
)
#------------------------------------------------------------------------------
###############################################################################
### END PUBLIC FUNCTIONS ###
###############################################################################