-
Notifications
You must be signed in to change notification settings - Fork 89
/
_data_loaders.py
1200 lines (1062 loc) · 45.6 KB
/
_data_loaders.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
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 os
import re
import shutil
import tempfile
import urllib
import zipfile
from datetime import datetime
from distutils.util import strtobool
from urllib.request import urlretrieve
import numpy as np
import pandas as pd
import aeon
from aeon.datasets.dataset_collections import (
list_downloaded_tsc_tsr_datasets,
list_downloaded_tsf_datasets,
)
from aeon.utils.validation.collection import convert_collection
DIRNAME = "data"
MODULE = os.path.join(os.path.dirname(aeon.__file__), "datasets")
__all__ = [ # Load functions
"load_from_tsfile",
"load_from_tsf_file",
"load_from_arff_file",
"load_from_tsv_file",
"load_classification",
"load_forecasting",
"load_regression",
"download_all_regression",
]
# Return appropriate return_type in case an alias was used
def _alias_datatype_check(return_type):
if return_type in ["numpy2d", "np2d", "np2D", "numpyflat"]:
return_type = "numpy2D"
if return_type in ["numpy3d", "np3d", "np3D"]:
return_type = "numpy3D"
return return_type
def _load_header_info(file):
"""Load the meta data from a .ts file and advance file to the data.
Parameters
----------
file : stream.
input file to read header from, assumed to be just opened
Returns
-------
meta_data : dict.
dictionary with the data characteristics stored in the header.
"""
meta_data = {
"problemname": "none",
"timestamps": False,
"missing": False,
"univariate": True,
"equallength": True,
"classlabel": True,
"targetlabel": False,
"class_values": [],
}
boolean_keys = ["timestamps", "missing", "univariate", "equallength", "targetlabel"]
for line in file:
line = line.strip().lower()
line = re.sub(r"\s+", " ", line)
if line and not line.startswith("#"):
tokens = line.split(" ")
token_len = len(tokens)
key = tokens[0][1:]
if key == "data":
if line != "@data":
raise IOError("data tag should not have an associated value")
return meta_data
if key in meta_data.keys():
if key in boolean_keys:
if token_len != 2:
raise IOError(f"{tokens[0]} tag requires a boolean value")
if tokens[1] == "true":
meta_data[key] = True
elif tokens[1] == "false":
meta_data[key] = False
elif key == "problemname":
meta_data[key] = tokens[1]
elif key == "classlabel":
if tokens[1] == "true":
meta_data["classlabel"] = True
if token_len == 2:
raise IOError(
"if the classlabel tag is true then class values "
"must be supplied"
)
elif tokens[1] == "false":
meta_data["classlabel"] = False
else:
raise IOError("invalid class label value")
meta_data["class_values"] = [token.strip() for token in tokens[2:]]
if meta_data["targetlabel"]:
meta_data["classlabel"] = False
return meta_data
def _get_channel_strings(line, target=True, missing="NaN"):
"""Split a string with timestamps into separate csv strings."""
channel_strings = re.sub(r"\s", "", line)
channel_strings = channel_strings.split("):")
c = len(channel_strings)
if target:
c = c - 1
for i in range(c):
channel_strings[i] = channel_strings[i] + ")"
numbers = re.findall(r"\d+\.\d+|" + missing, channel_strings[i])
channel_strings[i] = ",".join(numbers)
return channel_strings
def _load_data(file, meta_data, replace_missing_vals_with="NaN"):
"""Load data from a file with no header.
this assumes each time series has the same number of channels, but allows unequal
length series between cases.
Parameters
----------
file : stream, input file to read data from, assume no comments or header info
meta_data : dict.
with meta data in the file header loaded with _load_header_info
Returns
-------
data: list[np.ndarray].
list of numpy arrays of floats: the time series
y_values : np.ndarray.
numpy array of strings: the class/target variable values
meta_data : dict.
dictionary of characteristics enhanced with number of channels and series length
"problemname" (string), booleans: "timestamps", "missing", "univariate",
"equallength", "classlabel", "targetlabel" and "class_values": [],
"""
data = []
n_cases = 0
n_channels = 0 # Assumed the same for all
current_channels = 0
series_length = 0
y_values = []
target = False
if meta_data["classlabel"] or meta_data["targetlabel"]:
target = True
for line in file:
line = line.strip().lower()
line = line.replace("nan", replace_missing_vals_with)
line = line.replace("?", replace_missing_vals_with)
if "timestamps" in meta_data and meta_data["timestamps"]:
channels = _get_channel_strings(line, target, replace_missing_vals_with)
else:
channels = line.split(":")
n_cases += 1
current_channels = len(channels)
if target:
current_channels -= 1
if n_cases == 1: # Find n_channels and length from first if not unequal
n_channels = current_channels
if meta_data["equallength"]:
series_length = len(channels[0].split(","))
else:
if current_channels != n_channels:
raise IOError(
f"Inconsistent number of dimensions in case {n_cases}. "
f"Expecting {n_channels} but have read {current_channels}"
)
if meta_data["univariate"]:
if current_channels > 1:
raise IOError(
f"Seen {current_channels} in case {n_cases}."
f"Expecting univariate from meta data"
)
if meta_data["equallength"]:
current_length = series_length
else:
current_length = len(channels[0].split(","))
np_case = np.zeros(shape=(n_channels, current_length))
for i in range(0, n_channels):
single_channel = channels[i].strip()
data_series = single_channel.split(",")
data_series = [float(x) for x in data_series]
if len(data_series) != current_length:
equal_length = meta_data["equallength"]
raise IOError(
f"channel {i} in case {n_cases} has a different number of "
f"observations to the other channels. "
f"Saw {current_length} in the first channel but"
f" {len(data_series)} in the channel {i}. The meta data "
f"specifies equal length == {equal_length}. But even if series "
f"length are unequal, all channels for a single case must be the "
f"same length"
)
np_case[i] = np.array(data_series)
data.append(np_case)
if target:
y_values.append(channels[n_channels])
if meta_data["equallength"]:
data = np.array(data)
return data, np.asarray(y_values), meta_data
def load_from_tsfile(
full_file_path_and_name,
replace_missing_vals_with="NaN",
return_meta_data=False,
return_type="auto",
):
"""Load time series .ts file into X and (optionally) y.
Parameters
----------
full_file_path_and_name : string
full path of the file to load, .ts extension is assumed.
replace_missing_vals_with : string, default="NaN"
issing values in the file are replaces with this value
return_meta_data : boolean, default=False
return a dictionary with the meta data loaded from the file
return_type : string, default = "auto"
data type to convert to.
If "auto", returns numpy3D for equal length and list of numpy2D for unequal.
If "numpy2D", will squash a univariate equal length into a numpy2D (n_cases,
n_timepoints). Other options are available but not supported medium term.
Returns
-------
data: Union[np.ndarray,list]
time series data, np.ndarray (n_cases, n_channels, series_length) if equal
length time series, list of [n_cases] np.ndarray (n_channels, n_timepoints)
if unequal length series.
y : target variable, np.ndarray of string or int
meta_data : dict (optional).
dictionary of characteristics, with keys
"problemname" (string), booleans: "timestamps", "missing", "univariate",
"equallength", "classlabel", "targetlabel" and "class_values": [],
Raises
------
IOError if the load fails.
"""
# Check file ends in .ts, if not, insert
if not full_file_path_and_name.endswith(".ts"):
full_file_path_and_name = full_file_path_and_name + ".ts"
# Open file
with open(full_file_path_and_name, "r", encoding="utf-8") as file:
# Read in headers
meta_data = _load_header_info(file)
# load into list of numpy
data, y, meta_data = _load_data(file, meta_data)
# if equal load to 3D numpy
if meta_data["equallength"]:
data = np.array(data)
if return_type == "numpy2D" and meta_data["univariate"]:
data = data.squeeze()
# If regression problem, convert y to float
if meta_data["targetlabel"]:
y = y.astype(float)
if return_meta_data:
return data, y, meta_data
return data, y
def _load_saved_dataset(
name,
split=None,
return_X_y=True,
return_type=None,
local_module=MODULE,
local_dirname=DIRNAME,
return_meta=False,
):
"""Load baked in time series classification datasets (helper function).
Loads data from the provided files from aeon/datasets/data only.
Parameters
----------
name : string, file name to load from
split: None or one of "TRAIN", "TEST", optional (default=None)
Whether to load the train or test instances of the problem.
By default it loads both train and test instances (in a single container).
return_X_y: bool, optional (default=True)
If True, returns (features, target) separately instead of a single
dataframe with columns for features and the target.
return_data_type : str, optional, default = None
"numpy3D"/"numpy3d"/"np3D": recommended for equal length series
"numpy2D"/"numpy2d"/"np2d": can be used for univariate equal length series,
although we recommend numpy3d, because some transformers do not work with
numpy2d. If None will load 3D numpy or list of numpy
local_module: default = os.path.dirname(__file__),
local_dirname: default = "data"
Raises
------
Raise ValueError if the requested return type is not supported
Returns
-------
X: Data stored in specified `return_type`
The time series data for the problem, with n instances
y: 1D numpy array of length n, only returned if return_X_y if True
The class labels for each time series instance in X
If return_X_y is False, y is appended to X instead.
"""
if isinstance(split, str):
split = split.upper()
# This is also called in load_from_tsfile, but we need the value here and it
# is required in load_from_tsfile since it is public
return_type = _alias_datatype_check(return_type)
if split in ("TRAIN", "TEST"):
fname = name + "_" + split + ".ts"
abspath = os.path.join(local_module, local_dirname, name, fname)
X, y, meta_data = load_from_tsfile(abspath, return_meta_data=True)
# if split is None, load both train and test set
elif split is None:
fname = name + "_TRAIN.ts"
abspath = os.path.join(local_module, local_dirname, name, fname)
X_train, y_train, meta_data = load_from_tsfile(abspath, return_meta_data=True)
fname = name + "_TEST.ts"
abspath = os.path.join(local_module, local_dirname, name, fname)
X_test, y_test, meta_data_test = load_from_tsfile(
abspath, return_meta_data=True
)
if meta_data["equallength"]:
X = np.concatenate([X_train, X_test])
else:
X = X_train + X_test
y = np.concatenate([y_train, y_test])
else:
raise ValueError("Invalid `split` value =", split)
if return_type is not None:
X = convert_collection(X, return_type)
if return_X_y:
if return_meta:
return X, y, meta_data
else:
return X, y
else:
combo = (X, y)
if return_meta:
return combo, meta_data
else:
return combo
def download_dataset(name, save_path=None):
"""
Download a dataset from the timeseriesclassification.com website.
Parameters
----------
name : string,
name of the dataset to download
safe_path : string, optional (default: None)
Path to the directory where the dataset is downloaded into.
Returns
-------
if successful, string containing the path of the saved file
Raises
------
ValueError if the dataset is not available on the website
or the extract path is invalid
"""
if save_path is None:
save_path = os.path.join(MODULE, "local_data")
if not os.path.exists(save_path):
os.makedirs(save_path)
if name not in list_downloaded_tsc_tsr_datasets(
save_path
) or name not in list_downloaded_tsf_datasets(save_path):
# Dataset is not already present in the datasets directory provided.
# If it is not there, download it.
url = f"https://timeseriesclassification.com/aeon-toolkit/{name}.zip"
try:
_download_and_extract(url, extract_path=save_path)
except zipfile.BadZipFile as e:
raise ValueError(
f"Invalid dataset name ={name} is not available on extract path ="
f"{save_path}. Nor is it available on "
f"https://timeseriesclassification.com/.",
) from e
return os.path.join(save_path, name)
def _download_and_extract(url, extract_path=None):
"""
Download and unzip datasets (helper function).
This code was modified from
https://github.com/tslearn-team/tslearn/blob
/775daddb476b4ab02268a6751da417b8f0711140/tslearn/datasets.py#L28
Parameters
----------
url : string
Url pointing to file to download
extract_path : string, optional (default: None)
path to extract downloaded zip to, None defaults
to aeon/datasets/data
Returns
-------
extract_path : string or None
if successful, string containing the path of the extracted file, None
if it wasn't successful
"""
file_name = os.path.basename(url)
dl_dir = tempfile.mkdtemp()
zip_file_name = os.path.join(dl_dir, file_name)
urlretrieve(url, zip_file_name)
if extract_path is None:
extract_path = os.path.join(MODULE, "local_data/%s/" % file_name.split(".")[0])
else:
extract_path = os.path.join(extract_path, "%s/" % file_name.split(".")[0])
try:
if not os.path.exists(extract_path):
os.makedirs(extract_path)
zipfile.ZipFile(zip_file_name, "r").extractall(extract_path)
shutil.rmtree(dl_dir)
return extract_path
except zipfile.BadZipFile:
shutil.rmtree(dl_dir)
if os.path.exists(extract_path):
shutil.rmtree(extract_path)
raise zipfile.BadZipFile(
"Could not unzip dataset. Please make sure the URL is valid."
)
def _load_tsc_dataset(
name, split, return_X_y=True, return_type=None, extract_path=None, return_meta=False
):
"""Load time series classification datasets (helper function).
Parameters
----------
name : string, file name to load from
split: None or one of "TRAIN", "TEST", optional (default=None)
Whether to load the train or test instances of the problem.
By default it loads both train and test instances (in a single container).
return_X_y: bool, optional (default=True)
If True, returns (features, target) separately instead of a single
dataframe with columns for features and the target.
return_data_type : str, optional, default = None
"numpy3D"/"numpy3d"/"np3D": recommended for equal length series
"numpy2D"/"numpy2d"/"np2d": can be used for univariate equal length series,
although we recommend numpy3d, because some transformers do not work with
numpy2d.
"np-list": for unequal length series that cannot be stored in numpy arrays
if None returns either numpy3D for equal length or "np-list" for unequal
extract_path : optional (default = None)
Path of the location for the data file. If none, data is written to
os.path.dirname(__file__)/data/
Raises
------
Raise ValueException if the requested return type is not supported
Returns
-------
X: Data stored in specified `return_type`
The time series data for the problem, with n instances
y: 1D numpy array of length n, only returned if return_X_y if True
The class labels for each time series instance in X
If return_X_y is False, y is appended to X instead.
"""
# Allow user to have non standard extract path
if extract_path is not None:
local_module = extract_path
local_dirname = ""
else:
local_module = MODULE
local_dirname = "data"
if not os.path.exists(os.path.join(local_module, local_dirname)):
os.makedirs(os.path.join(local_module, local_dirname))
if name not in list_downloaded_tsc_tsr_datasets(extract_path):
if extract_path is None:
local_dirname = "local_data"
if not os.path.exists(os.path.join(local_module, local_dirname)):
os.makedirs(os.path.join(local_module, local_dirname))
if name not in list_downloaded_tsc_tsr_datasets(
os.path.join(local_module, local_dirname)
):
# Dataset is not already present in the datasets directory provided.
# If it is not there, download and install it.
url = "https://timeseriesclassification.com/aeon-toolkit/%s.zip" % name
# This also tests the validitiy of the URL, can't rely on the html
# status code as it always returns 200
try:
_download_and_extract(
url,
extract_path=extract_path,
)
except zipfile.BadZipFile as e:
raise ValueError(
f"Invalid dataset name ={name} is not available on extract path ="
f"{extract_path}. Nor is it available on {url}",
) from e
return _load_saved_dataset(
name,
split=split,
return_X_y=return_X_y,
return_type=return_type,
local_module=local_module,
local_dirname=local_dirname,
return_meta=return_meta,
)
def load_from_arff_file(
full_file_path_and_name,
replace_missing_vals_with="NaN",
):
"""Load data from a classification/regression WEKA arff file to a 3D numpy array.
Parameters
----------
full_file_path_and_name: str
The full pathname of the .ts file to read.
replace_missing_vals_with: str
The value that missing values in the text file should be replaced
with prior to parsing.
Returns
-------
data: np.ndarray
time series data, np.ndarray (n_cases, n_channels, series_length)
y : target variable, np.ndarray of string or int
"""
instance_list = []
class_val_list = []
data_started = False
is_multi_variate = False
is_first_case = True
n_cases = 0
n_channels = 1
with open(full_file_path_and_name, "r", encoding="utf-8") as f:
for line in f:
if line.strip():
if (
is_multi_variate is False
and "@attribute" in line.lower()
and "relational" in line.lower()
):
is_multi_variate = True
if "@data" in line.lower():
data_started = True
continue
# if the 'data tag has been found, the header information
# has been cleared and now data can be loaded
if data_started:
line = line.replace("?", replace_missing_vals_with)
if is_multi_variate:
line, class_val = line.split("',")
class_val_list.append(class_val.strip())
channels = line.split("\\n")
channels[0] = channels[0].replace("'", "")
if is_first_case:
n_channels = len(channels)
n_timepoints = len(channels[0].split(","))
is_first_case = False
elif len(channels) != n_channels:
raise ValueError(
f" Number of channels not equal in "
f"dataset, first case had {n_channels} channel "
f"but case number {n_cases+1} has "
f"{len(channels)}"
)
inst = np.zeros(shape=(n_channels, n_timepoints))
for c in range(len(channels)):
split = channels[c].split(",")
inst[c] = np.array([float(i) for i in split])
else:
line_parts = line.split(",")
if is_first_case:
is_first_case = False
n_timepoints = len(line_parts) - 1
class_val_list.append(line_parts[-1].strip())
split = line_parts[: len(line_parts) - 1]
inst = np.zeros(shape=(n_channels, n_timepoints))
inst[0] = np.array([float(i) for i in split])
instance_list.append(inst)
return np.asarray(instance_list), np.asarray(class_val_list)
def load_from_tsv_file(full_file_path_and_name):
"""Load data from a .tsv file into a numpy array.
tsv files are simply csv files with the class value as the first value. They only
store equal length, univariate data, so are simple.
Parameters
----------
full_file_path_and_name: str
The full pathname of the .tsv file to read.
Returns
-------
data: np.ndarray
time series data, np.ndarray (n_cases, 1, series_length)
y : target variable, np.ndarray of string or int
"""
df = pd.read_csv(full_file_path_and_name, sep="\t", header=None)
y = df.pop(0).values
df.columns -= 1
X = df.to_numpy()
X = np.expand_dims(X, axis=1)
return X, y
def _convert_tsf_to_hierarchical(
data: pd.DataFrame,
metadata,
freq: str = None,
value_column_name: str = "series_value",
) -> pd.DataFrame:
"""Convert the data from default_tsf to pd_multiindex_hier.
Parameters
----------
data : pd.DataFrame
nested values dataframe
metadata : Dict
tsf file metadata
freq : str, optional
pandas compatible time frequency, by default None
if not specified it's automatically mapped from the tsf frequency to a pandas
frequency
value_column_name: str, optional
The name of the column that contains the values, by default "series_value"
Returns
-------
pd.DataFrame
aeon pd_multiindex_hier mtype
"""
df = data.copy()
if freq is None:
freq_map = {
"daily": "D",
"weekly": "W",
"monthly": "MS",
"yearly": "YS",
}
freq = freq_map[metadata["frequency"]]
# create the time index
if "start_timestamp" in df.columns:
df["timestamp"] = df.apply(
lambda x: pd.date_range(
start=x["start_timestamp"], periods=len(x[value_column_name]), freq=freq
),
axis=1,
)
drop_columns = ["start_timestamp"]
else:
df["timestamp"] = df.apply(
lambda x: pd.RangeIndex(start=0, stop=len(x[value_column_name])), axis=1
)
drop_columns = []
# pandas implementation of multiple column explode
# can be removed and replaced by explode if we move to pandas version 1.3.0
columns = [value_column_name, "timestamp"]
index_columns = [c for c in list(df.columns) if c not in drop_columns + columns]
result = pd.DataFrame({c: df[c].explode() for c in columns})
df = df.drop(columns=columns + drop_columns).join(result)
if df["timestamp"].dtype == "object":
df = df.astype({"timestamp": "int64"})
df = df.set_index(index_columns + ["timestamp"])
df = df.astype({value_column_name: "float"}, errors="ignore")
return df
def load_from_tsf_file(
full_file_path_and_name,
replace_missing_vals_with="NaN",
value_column_name="series_value",
return_type="tsf_default",
):
"""
Convert the contents in a .tsf file into a dataframe.
This code was extracted from
https://github.com/rakshitha123/TSForecasting/blob/master/utils/data_loader.py.
Parameters
----------
full_file_path_and_name : str
The full path to the .tsf file.
replace_missing_vals_with : str, default="NAN"
A term to indicate the missing values in series in the returning dataframe.
value_column_name : str, default="series_value"
Any name that is preferred to have as the name of the column containing series
values in the returning dataframe.
return_type : str - "pd_multiindex_hier" or "tsf_default" (default)
- "tsf_default" = container that faithfully mirrors tsf format from the original
implementation in: https://github.com/rakshitha123/TSForecasting/
blob/master/utils/data_loader.py.
Returns
-------
loaded_data : pd.DataFrame
The converted dataframe containing the time series.
metadata : dict
The metadata for the forecasting problem. The dictionary keys are:
"frequency", "forecast_horizon", "contain_missing_values",
"contain_equal_length"
"""
col_names = []
col_types = []
all_data = {}
line_count = 0
frequency = None
forecast_horizon = None
contain_missing_values = None
contain_equal_length = None
found_data_tag = False
found_data_section = False
started_reading_data_section = False
with open(full_file_path_and_name, "r", encoding="cp1252") as file:
for line in file:
# Strip white space from start/end of line
line = line.strip()
if line:
if line.startswith("@"): # Read meta-data
if not line.startswith("@data"):
line_content = line.split(" ")
if line.startswith("@attribute"):
if (
len(line_content) != 3
): # Attributes have both name and type
raise Exception("Invalid meta-data specification.")
col_names.append(line_content[1])
col_types.append(line_content[2])
else:
if (
len(line_content) != 2
): # Other meta-data have only values
raise Exception("Invalid meta-data specification.")
if line.startswith("@frequency"):
frequency = line_content[1]
elif line.startswith("@horizon"):
forecast_horizon = int(line_content[1])
elif line.startswith("@missing"):
contain_missing_values = bool(
strtobool(line_content[1])
)
elif line.startswith("@equallength"):
contain_equal_length = bool(strtobool(line_content[1]))
else:
if len(col_names) == 0:
raise Exception(
"Missing attribute section. "
"Attribute section must come before data."
)
found_data_tag = True
elif not line.startswith("#"):
if len(col_names) == 0:
raise Exception(
"Missing attribute section. "
"Attribute section must come before data."
)
elif not found_data_tag:
raise Exception("Missing @data tag.")
else:
if not started_reading_data_section:
started_reading_data_section = True
found_data_section = True
all_series = []
for col in col_names:
all_data[col] = []
full_info = line.split(":")
if len(full_info) != (len(col_names) + 1):
raise Exception("Missing attributes/values in series.")
series = full_info[len(full_info) - 1]
series = series.split(",")
if len(series) == 0:
raise Exception(
"A given series should contains a set "
"of comma separated numeric values."
"At least one numeric value should be there "
"in a series. "
"Missing values should be indicated with ? symbol"
)
numeric_series = []
for val in series:
if val == "?":
numeric_series.append(replace_missing_vals_with)
else:
numeric_series.append(float(val))
if numeric_series.count(replace_missing_vals_with) == len(
numeric_series
):
raise Exception(
"All series values are missing. "
"A given series should contains a set "
"of comma separated numeric values."
"At least one numeric value should be there "
"in a series."
)
all_series.append(pd.Series(numeric_series).array)
for i in range(len(col_names)):
att_val = None
if col_types[i] == "numeric":
att_val = int(full_info[i])
elif col_types[i] == "string":
att_val = str(full_info[i])
elif col_types[i] == "date":
att_val = datetime.strptime(
full_info[i], "%Y-%m-%d %H-%M-%S"
)
else:
# Currently, the code supports only
# numeric, string and date types.
# Extend this as required.
raise Exception("Invalid attribute type.")
if att_val is None:
raise Exception("Invalid attribute value.")
else:
all_data[col_names[i]].append(att_val)
line_count = line_count + 1
if line_count == 0:
raise Exception("Empty file.")
if len(col_names) == 0:
raise Exception("Missing attribute section.")
if not found_data_section:
raise Exception("Missing series information under data section.")
all_data[value_column_name] = all_series
loaded_data = pd.DataFrame(all_data)
# metadata dict
metadata = dict(
zip(
(
"frequency",
"forecast_horizon",
"contain_missing_values",
"contain_equal_length",
),
(
frequency,
forecast_horizon,
contain_missing_values,
contain_equal_length,
),
)
)
if return_type != "tsf_default":
loaded_data = _convert_tsf_to_hierarchical(
loaded_data, metadata, value_column_name=value_column_name
)
return loaded_data, metadata
def load_forecasting(name, extract_path=None, return_metadata=False):
"""Download/load forecasting problem from https://forecastingdata.org/.
Parameters
----------
name : string, file name to load from
extract_path : optional (default = None)
Path of the location for the data file. If none, data is written to
os.path.dirname(__file__)/data/
return_metadata : boolean, default = True
If True, returns a tuple (data, metadata)
Raises
------
Raise ValueException if the requested return type is not supported
Returns
-------
X: Data stored in a dataframe, each column a series
metadata: optional
returns the following meta data
frequency,forecast_horizon,contain_missing_values,contain_equal_length
Example
-------
>>> from aeon.datasets import load_forecasting
>>> X=load_forecasting("m1_yearly_dataset") # doctest: +SKIP
"""
# Allow user to have non standard extract path
from aeon.datasets.tsf_data_lists import tsf_all
if extract_path is not None:
local_module = extract_path
local_dirname = ""
else:
local_module = MODULE
local_dirname = "data"
if not os.path.exists(os.path.join(local_module, local_dirname)):
os.makedirs(os.path.join(local_module, local_dirname))
# Check if data already in extract path or, if extract_path None,
# in datasets/data directory
if name not in list_downloaded_tsf_datasets(extract_path):
# Dataset is not already present in the datasets directory provided.
# If it is not there, download and install it.
if name in tsf_all.keys():
id = tsf_all[name]
if extract_path is None:
local_dirname = "local_data"
if not os.path.exists(os.path.join(local_module, local_dirname)):
os.makedirs(os.path.join(local_module, local_dirname))
else:
raise ValueError(
f"File name {name} is not in the list of valid files to download"
)
if name not in list_downloaded_tsf_datasets(
os.path.join(local_module, local_dirname)
):
url = f"https://zenodo.org/record/{id}/files/{name}.zip"
file_save = f"{local_module}/{local_dirname}/{name}.zip"
if not os.path.exists(file_save):
try:
urllib.request.urlretrieve(url, file_save)
except Exception:
raise ValueError(
f"Invalid dataset name ={name} is not available on extract path"
f" {extract_path}.\n Nor is it available on "
f"https://forecastingdata.org/ via path {url}",
)
if not os.path.exists(
f"{local_module}/{local_dirname}/{name}/" f"{name}.tsf"
):
z = zipfile.ZipFile(file_save, "r")
z.extractall(f"{local_module}/{local_dirname}/{name}/")
full_name = f"{local_module}/{local_dirname}/{name}/{name}.tsf"
data, meta = load_from_tsf_file(full_file_path_and_name=full_name)
if return_metadata:
return data, meta
return data
def load_regression(name, split=None, extract_path=None, return_metadata=False):
"""Download/load regression problem from http://tseregression.org/.
If you want to load a problem from a local file, specify the
location in ``extract_path``. This function assumes the data is stored in format
<extract_path>/<name>/<name>_TRAIN.ts and <extract_path>/<name>/<name>_TEST.ts.
If you want to load a file directly from a full path, use the function
`load_from_tsfile`` directly. If you do not specify ``extract_path``, or if the
problem is not present in ``extract_path`` it will attempt to download the data
from http://tseregression.org/.
The list of problems this function can download from the website is in
``datasets/tser_lists.py``. This function can load timestamped data, but it does
not store the time stamps. The time stamp loading is fragile, it will only work