-
Notifications
You must be signed in to change notification settings - Fork 1
/
extract.py
344 lines (278 loc) · 11.1 KB
/
extract.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
r"""
Provides a command line interface for transforming .json data files
into .csv files.
By default, the command expects to find the .json files in the current
working directory. A basic example would look something like this. You
have run some local experiment sessions. Now you have an experiment directory
that looks something like this::
data/
save/
exp/
2021-04-27_12.03.58_data_0f278318f0bb4ea6b8cb6a58e8a5afc3.json
2021-04-27_13.06.01_data_d06249f45d66494192aca0cc7b91b54d.json
2021-04-29_12.08.59_data_5999f44eaea0447ca0abbf079824b9ce.json
log/
script.py
config.conf
The .json files in the directory ``save/exp/`` hold data of *individual sessions*.
We want to combine them into a .csv file for further data anaylsis. Usually,
alfred3 will do this automatically for you after each experiment run and
save the result in the ``data/`` directory, but lets assume that this
does not work in our case. To transform the data, we follow these steps:
**1. Open up a terminal.**
On Mac, this is just the *Terminal* app. On Windows,
this is the command line application. If you are using an IDE like PyCharm,
there is most likely a terminal integrated into the user interface.
**2. Make sure that you are in the correct working directory.**
You can go to a specific directory by running the following code::
$ cd path/to/directory
Replace ``path/to/directory`` with your actual full path to the ``save/exp/``
directory of your experiment.
Note that, on Windows, you probably need to use backshlashes (\) instead
of ordinary slashes (/) in the path.
**3. Run the command in the terminal**
Run the following command::
$ alfred3 json-to-csv
Et voilà! This will place the .csv file inside the current directory.
If you run into problem at this point, make sure that you have alfred3
installed in your current environment. If you are usually working in a
virtual environment, you may need to activate that environment.
You can access the full manual to all available options of the ``json-to-csv``
command by executing::
$ alfred3 json-to-csv --help
The current version is::
Usage: alfred3 json-to-csv [OPTIONS]
Options:
--dtype TEXT The data type to extratct form .json files. Can be
'exp_data', 'codebook', 'move_history', and
'unlinked_data'. [default: exp_data]
--in_path TEXT Path to directory containing json files. If None
(default), the current working directory will be used.
--out_path TEXT Path to directory in which the output csv file will be
place. If None (default), the current working directory
will be used.
--exp_version TEXT The experiment version for which codebook data should be
extracted. Only relevant for codebook data.
--delimiter TEXT Delimiter to use in the resulting csv file. Defaults to
';'
--help Show this message and exit.
"""
from itertools import chain
from pathlib import Path
import click
from alfred3.data_manager import DataManager
from alfred3.export import Exporter, find_unique_name
class Extractor:
"""
Turns uncurated alfred data from json format into csv format.
Args:
in_path (str): Path to directory containing json files. If None
(default), the current working directory will be used.
out_path (str): Path to directory in which the output csv file
will be place. If None (default), the current working
directory will be used.
delimiter (str): Delimiter to use in the resulting csv file.
Defaults to ";"
Examples:
The extractor is used by calling one of its four methods. The
following python code can be used to turn all alfred json
datasets in the current working directory into a nice csv file.
>>> from alfred3.export import Extractor
>>> ex = Extractor()
>>> ex.extract_exp_data()
"""
def __init__(self, in_path: str = None, out_path: str = None, delimiter: str = ";"):
self.in_path = Path(in_path) if in_path is not None else Path.cwd()
self.out_path = Path(out_path) if out_path is not None else Path.cwd()
self.delimiter = delimiter
def extract_exp_data(self):
"""
Extracts the main experiment data from json files in the
Extractors *in_path*.
Examples:
Turn all alfred json datasets in the current working
directory into a nice csv file.
>>> from alfred3.cli.extract import Extractor
>>> ex = Extractor()
>>> ex.extract_exp_data()
"""
data = list(
DataManager.iterate_local_data(
data_type=DataManager.EXP_DATA, directory=self.in_path
)
)
fieldnames = DataManager.extract_ordered_fieldnames(data)
alldata = [DataManager.flatten(d) for d in data]
csvname = find_unique_name(directory=self.out_path, filename="exp_data.csv")
Exporter.write(
data=alldata,
fieldnames=fieldnames,
path=self.out_path / csvname,
delimiter=self.delimiter,
)
return csvname
def extract_unlinked_data(self):
"""
Extracts unlinked data from json files in the Extractors
*in_path*.
Examples:
Turn all alfred json datasets in the current working
directory into a nice csv file.
>>> from alfred3.cli.extract import Extractor
>>> ex = Extractor()
>>> ex.extract_unlinked_data()
"""
existing_data = list(
DataManager.iterate_local_data(
data_type=DataManager.UNLINKED_DATA, directory=self.in_path
)
)
data = [DataManager.flatten(d) for d in existing_data]
fieldnames = DataManager.extract_fieldnames(data)
csvname = find_unique_name(directory=self.out_path, filename="unlinked.csv")
Exporter.write(
data=data,
fieldnames=fieldnames,
path=self.out_path / csvname,
delimiter=self.delimiter,
)
return csvname
def extract_codebook(self, exp_version: str):
"""
Extracts codebook data from json files in the Extractors
*in_path*.
Args:
exp_version (str): Experiment version. Codebook data must
be exported for specific experiment versions.
Examples:
Get a nice csv codebook for the json data in the current
working directory.
>>> from alfred3.cli.extract import Extractor
>>> ex = Extractor()
>>> ex.extract_codebook("1.0")
"""
cursor = DataManager.iterate_local_data(
data_type=DataManager.EXP_DATA,
directory=self.in_path,
exp_version=exp_version,
)
cursor_unlinked = DataManager.iterate_local_data(
data_type=DataManager.UNLINKED_DATA,
directory=self.in_path,
exp_version=exp_version,
)
# extract individual codebooks for each experimen session
cbdata_collection = []
for entry in cursor:
cb = DataManager.extract_codebook_data(entry)
cbdata_collection.append(cb)
for entry in cursor_unlinked:
cb = DataManager.extract_codebook_data(entry)
cbdata_collection.append(cb)
# combine them to a single dictionary, overwriting old values
# with newer ones
data = {}
for entry in cbdata_collection:
data.update(entry)
fieldnames = DataManager.extract_fieldnames(data.values())
fieldnames = DataManager.sort_codebook_fieldnames(fieldnames)
csvname = find_unique_name(
directory=self.out_path, filename=f"codebook_{exp_version}.csv"
)
Exporter.write(
data=data.values(),
fieldnames=fieldnames,
path=self.out_path / csvname,
delimiter=self.delimiter,
)
return csvname
def extract_move_history(self):
"""
Extracts movement data from json files in the Extractors
*in_path*.
Examples:
Get a nice csv of movement data for json data in the
current working directory.
>>> from alfred3.cli.extract import Extractor
>>> ex = Extractor()
>>> ex.extract_move_history()
"""
existing_data = DataManager.iterate_local_data(
data_type=DataManager.EXP_DATA, directory=self.in_path
)
history = [d["exp_move_history"] for d in existing_data]
fieldnames = DataManager.extract_fieldnames(chain(*history))
history = chain(*history)
csvname = find_unique_name(directory=self.out_path, filename="move_history.csv")
Exporter.write(
data=history,
fieldnames=fieldnames,
path=self.out_path / csvname,
delimiter=self.delimiter,
)
return csvname
@click.command()
@click.option(
"--dtype",
default="exp_data",
help=(
"The data type to extratct form .json files. Can be 'exp_data', 'codebook',"
" 'move_history', and 'unlinked_data'."
),
show_default=True,
)
@click.option(
"--in_path",
default=None,
help=(
"Path to directory containing json files. If None (default), the current"
" working directory will be used."
),
)
@click.option(
"--out_path",
default=None,
help=(
"Path to directory in which the output csv file will be place. If None"
" (default), the current working directory will be used."
),
)
@click.option(
"--exp_version",
default=None,
help=(
"The experiment version for which codebook data should be extracted. Only"
" relevant for codebook data."
),
)
@click.option(
"--delimiter",
default=";",
help="Delimiter to use in the resulting csv file. Defaults to ';'",
)
def json_to_csv(dtype, in_path, out_path, exp_version, delimiter):
extractor = Extractor(in_path=in_path, out_path=out_path, delimiter=delimiter)
if dtype == "exp_data":
csvname = extractor.extract_exp_data()
elif dtype == "codebook":
if exp_version is None:
raise ValueError(
"You must specify an experiment version for codebook extraction. See"
" 'alfred3 json-to-csv --help' for more."
)
csvname = extractor.extract_codebook(exp_version=exp_version)
elif dtype == "move_history":
csvname = extractor.extract_move_history()
elif dtype == "unlinked_data":
csvname = extractor.extract_unlinked_data()
else:
msg = (
f"Value {dtype} for option '--dtype' is not valid. See 'alfred3 json-to-csv"
" --help' for more."
)
raise ValueError(msg)
msg = (
f"Data transformed to csv. File '{csvname}' was placed in directory"
f" '{extractor.out_path}'"
)
click.echo(msg)