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 | class SignalsDataset:
DEFAULT_CACHE_DIR = Path(appdirs.user_cache_dir('news-signals/datasets'))
def __init__(self, signals=None, metadata=None):
if metadata is None:
metadata = {
# default dataset name
'name': 'News Signals Dataset'
}
else:
assert 'name' in metadata, 'Dataset metadata must specify a name.'
self.metadata = metadata
if signals is None:
signals = {}
if type(signals) is not dict:
signals = {s.id: s for s in signals}
assert len(set([s.ts_column for s in signals.values()])) == 1, \
'All signals in a dataset must have the same `ts_column` attribute.'
self.signals = signals
def update(self):
raise NotImplementedError
@classmethod
def load(cls, dataset_path, cache_dir=None):
# handle downloading from urls
if type(dataset_path) is str \
and (dataset_path.startswith('https://drive.google.com') or dataset_path.startswith('gs://')):
basename = base64.b64encode(dataset_path.encode()).decode()
if cache_dir is None:
cache_dir = cls.DEFAULT_CACHE_DIR
else:
cache_dir = Path(cache_dir)
local_dataset_dir = cache_dir / basename
if not local_dataset_dir.exists():
if dataset_path.startswith('https://drive.google.com'):
# folder vs file download from gdrive
if 'folders' in dataset_path:
local_dataset_dir = Path(cache_dir) / basename
local_dataset_dir.mkdir(parents=True, exist_ok=True)
logger.info(f'Downloading dataset from {dataset_path} to {local_dataset_dir}.')
status = gdown.download_folder(
url=dataset_path,
output=str(local_dataset_dir),
remaining_ok=True
)
dataset_path = local_dataset_dir
else:
local_dataset_path = Path(str(local_dataset_dir) + '.tar.gz')
logger.info(f'Downloading dataset from {dataset_path} to {local_dataset_path}.')
status = gdown.download(url=dataset_path, output=str(local_dataset_path))
assert status is not None, 'Download as file failed.'
dataset_path = local_dataset_path
elif dataset_path.startswith('gs://'):
assert dataset_path.endswith('.tar.gz'), \
'Datasets stored in GCS currently must be in .tar.gz format'
local_dataset_path = Path(str(local_dataset_dir) + '.tar.gz')
bucket_name, blob_name = dataset_path.replace("gs://", "").split("/", 1)
ds_cache_dir = Path(os.path.dirname(local_dataset_path))
ds_cache_dir.mkdir(parents=True, exist_ok=True)
load_from_gcs(
bucket_name=bucket_name,
blob_name=blob_name,
local_dataset_path=local_dataset_path
)
dataset_path = local_dataset_path
else:
logger.info(f'Using cached dataset at {local_dataset_dir}.')
dataset_path = local_dataset_dir
# handle decompressing tar.gz
dataset_path = Path(dataset_path)
if str(dataset_path).endswith('.tar.gz') or dataset_path.with_suffix('.tar.gz').exists():
# add .tar.gz suffix if dataset_path doesn't already have it
if not str(dataset_path).endswith('.tar.gz'):
dataset_path = dataset_path.with_suffix('.tar.gz')
# check if dataset_path exists without .tar.gz suffix
expected_dataset_path = Path(str(dataset_path).replace('.tar.gz', ''))
# already decompressed
if os.path.exists(expected_dataset_path):
logger.info(f'Found decompressed dataset at {expected_dataset_path}, '
'not decompressing again.')
else:
# extract tar.gz to the same directory as the tar.gz is in
with tarfile.open(dataset_path, 'r:gz') as tar:
common_path = os.path.commonpath(tar.getnames())
expected_dataset_path = dataset_path.parent / common_path
print(f'Extracting dataset to {expected_dataset_path}')
if not expected_dataset_path.exists():
tar.extractall(path=dataset_path.parent)
dataset_path = expected_dataset_path
dataset_signals = signals.Signal.load(dataset_path)
if (dataset_path / 'metadata.json').is_file():
metadata = read_json(dataset_path / 'metadata.json')
else:
metadata = None
return cls(
signals=dataset_signals,
metadata=metadata
)
def save(self, dataset_path, compress=True, overwrite=False, gcs_bucket_name=None):
if gcs_bucket_name is not None:
assert compress, 'Datasets uploaded to GCS must be compressed.'
dataset_path = Path(dataset_path)
if (overwrite and dataset_path.exists()) and not dataset_path.is_dir():
dataset_path.unlink()
dataset_path.mkdir(parents=True, exist_ok=overwrite)
for signal in self.signals.values():
signal.save(dataset_path)
write_json(
self.metadata,
dataset_path / 'metadata.json'
)
if compress:
shutil.make_archive(
base_name=str(dataset_path),
root_dir=dataset_path.parent,
base_dir=dataset_path.name,
format='gztar'
)
if dataset_path.exists():
shutil.rmtree(dataset_path)
logger.info(f'Saved compressed dataset to {dataset_path}.tar.gz')
if gcs_bucket_name is not None:
save_to_gcs(
bucket_name=gcs_bucket_name,
source_file_name=f'{dataset_path}.tar.gz',
destination_blob_name=f'{dataset_path.name}.tar.gz'
)
return f'{dataset_path}.tar.gz'
else:
logger.info(
f'Saved {len(self.signals)} signals in dataset to {dataset_path}.'
)
return dataset_path
def aggregate_signal(self, name=None):
if name is None:
name = self.metadata['name']
return signals.AggregateSignal(
name=name,
components=list(self.signals.values())
)
def plot(self, savedir=None, **kwargs):
plot = self.aggregate_signal().plot(**kwargs)
if savedir is not None:
savedir = Path(savedir)
savedir.mkdir(parents=True, exist_ok=True)
fig = plot.get_figure()
plot_file = savedir / f'{self.metadata["name"]}.png'
fig.savefig(plot_file)
logger.info(f"Saved plot to {plot_file}.")
return plot
def df(self, axis=0):
"""
Return a long form view of all the signals in the dataset.
TODO: memoize when signals are the same between calls
"""
return pd.concat(
[s.df for s in self.signals.values()],
axis=axis
)
def corr(self, **kwargs):
"""
Compute pairwise correlation of signals in the dataset.
"""
return self.aggregate_signal().corr(**kwargs)
def __getattr__(self, name):
"""
Try to delegate to pandas if the attribute is not found on SignalsDataset.
"""
try:
df = self.df(axis=0)
return getattr(df, name)
except AttributeError as e:
raise AttributeError(
f"type object 'SignalsDataset' has no attribute '{name}'"
)
def generate_report(self):
"""
Generate a report containing summary statistics about the dataset.
"""
pass
def __len__(self):
return len(self.signals)
def __getitem__(self, key):
return self.signals[key]
def __iter__(self):
return iter(self.signals)
def __contains__(self, key):
return key in self.signals
def __repr__(self):
return f"SignalsDataset({self.signals})"
def __str__(self):
return f"SignalsDataset({self.signals})"
def items(self):
return self.signals.items()
def keys(self):
return self.signals.keys()
def values(self):
return self.signals.values()
def map(self, func):
"""
Note this is embarassingly parallel, should
be done multithreaded
"""
logger.info(
f'applying function to {len(self)} signals in dataset'
)
for k, v in tqdm.tqdm(self.signals.items(), total=len(self)):
self.signals[k] = func(v)
|