forked from cpp-lln-lab/bidsMReye
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualize.py
More file actions
479 lines (410 loc) · 11.8 KB
/
visualize.py
File metadata and controls
479 lines (410 loc) · 11.8 KB
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
from __future__ import annotations
import json
from datetime import datetime
from pathlib import Path
from typing import Any
import numpy as np
import pandas as pd
import plotly.graph_objs as go
from plotly.subplots import make_subplots
from bidsmreye._version import __version__
from bidsmreye.bids_utils import get_dataset_layout, list_subjects
from bidsmreye.configuration import Config
from bidsmreye.logger import bidsmreye_log
from bidsmreye.utils import check_if_file_found, set_this_filter
LINE_WIDTH = 3
FONT_SIZE = {"size": 14}
GRID_COLOR = "grey"
LINE_COLOR = "rgb(0, 150, 175)"
BG_COLOR = "rgb(255,255,255)"
HEAT_MAP_COLOR = "gnbu"
MARKER_SIZE = 10
TICK_FONT = {"family": "arial", "color": "black", "size": 14}
X_POSITION_1 = 1
X_POSITION_2 = 1.5
X_POSITION_3 = 2
X_POSITION = [X_POSITION_1, X_POSITION_2, X_POSITION_3]
COLOR_1 = "rgba(30, 120, 180, 0.6)"
COLOR_2 = "rgba(255, 130, 15, 0.6)"
COLOR_3 = "rgba(45, 160, 45, 0.6)"
COLORS = [COLOR_1, COLOR_2, COLOR_3]
log = bidsmreye_log(name="bidsmreye")
def collect_group_qc_data(cfg: Config) -> pd.DataFrame | None:
"""Collect QC metrics data from all subjects json in a BIDS dataset.
:param input_dir:
:type input_dir: str | Path
:return:
:rtype: pd.DataFrame
"""
layout = get_dataset_layout(cfg.output_dir, use_database=False)
subjects = list_subjects(cfg, layout)
this_filter = set_this_filter(cfg, subjects, "eyetrack_qc")
bf = layout.get(
regex_search=True,
**this_filter,
)
check_if_file_found(bf, this_filter, layout)
qc_data = None
for i, file in enumerate(bf):
log.info(f"Processing file: {file.path}")
entities = layout.parse_file_entities(file.path)
with open(file.path) as f:
data = json.loads(f.read())
df = pd.json_normalize(data)
df["filename"] = Path(file.path).name
df["subject"] = entities["subject"]
qc_data = df if i == 0 else pd.concat([qc_data, df], sort=False)
if qc_data is None:
return None
cols = [
"subject",
"filename",
"NbDisplacementOutliers",
"NbXOutliers",
"NbYOutliers",
"XVar",
"YVar",
]
try:
qc_data = qc_data[cols]
except KeyError:
log.error(f"""Sidecar files seem to be missing the keys: {cols}.
To fix try to run the qc at the participant level first.""")
return None
return qc_data
def plot_group_boxplot(
fig: Any,
qc_data: pd.DataFrame,
row: int,
col: int,
column_names: list[str],
trace_names: list[str],
ticktext: list[str],
yaxes_title: str,
) -> None:
nb_data_points = qc_data.shape[0]
for i, this_column in enumerate(column_names):
fig.add_trace(
go.Box(
x=np.ones(nb_data_points) * X_POSITION[i],
y=qc_data[this_column],
marker={"size": MARKER_SIZE, "color": COLORS[i]},
name=trace_names[i],
),
row=row,
col=col,
)
fig.update_xaxes(
row=row,
col=col,
tickvals=X_POSITION[: len(column_names)],
ticktext=ticktext,
)
fig.update_yaxes(
row=row,
col=col,
title={"text": yaxes_title, "font": FONT_SIZE},
)
def group_report(cfg: Config) -> None:
"""Create a group level report figure for eyetracking data.
:return: Figure object
:rtype: Any
"""
qc_data = collect_group_qc_data(cfg)
if qc_data is None:
log.warning("No data found.")
return
fig = go.FigureWidget(
make_subplots(
rows=2,
cols=3,
horizontal_spacing=0.2,
vertical_spacing=0.1,
specs=[
[{"rowspan": 1, "colspan": 3}, None, None],
[{"rowspan": 1, "colspan": 2}, None, None],
],
)
)
row = 1
col = 1
plot_group_boxplot(
fig,
qc_data=qc_data,
row=row,
col=col,
column_names=["NbDisplacementOutliers", "NbXOutliers", "NbYOutliers"],
trace_names=["displacement", "x gaze<br>position", "Y gaze<br>position"],
ticktext=["Disp", "X", "Y"],
yaxes_title="number of outliers",
)
row = 2
col = 1
plot_group_boxplot(
fig,
qc_data=qc_data,
row=row,
col=col,
column_names=["XVar", "YVar"],
trace_names=["x gaze<br>position", "Y gaze<br>position"],
ticktext=["X", "Y"],
yaxes_title="variance (degrees<sup>2</sup>)",
)
fig.update_yaxes(
title={"standoff": 0, "font": FONT_SIZE},
showline=True,
linewidth=LINE_WIDTH - 1,
linecolor="black",
gridcolor=GRID_COLOR,
griddash="dot",
gridwidth=0.5,
tickfont=TICK_FONT,
)
fig.update_xaxes(
showline=True,
linewidth=LINE_WIDTH - 1,
linecolor="black",
ticks="outside",
tickangle=-45,
ticklen=5,
tickwidth=2,
tickcolor="black",
tickfont=TICK_FONT,
)
fig.update_traces(
boxpoints="all",
jitter=0.3,
pointpos=2,
boxmean=True,
width=0.2,
hovertext=qc_data["filename"],
marker={"size": MARKER_SIZE},
fillcolor="rgb(200, 200, 200)",
line={"color": "black"},
)
fig.update_layout(
showlegend=False,
plot_bgcolor=BG_COLOR,
paper_bgcolor=BG_COLOR,
height=800,
width=800,
title={
"text": f"""<b>bidsmreye: group report</b><br>
<b>Summary</b><br>
- Date and time: {datetime.now():%Y-%m-%d, %H:%M}<br>
- bidsmreye version: {__version__}<br>
""",
"x": 0.05,
"y": 0.95,
"font": {"size": 19, "color": "black"},
},
margin={"t": 150, "b": 10, "l": 100, "r": 10, "pad": 0},
)
fig.show()
group_report_file = cfg.output_dir / "group_eyetrack.html"
fig.write_html(group_report_file)
qc_data_file = cfg.output_dir / "group_eyetrack.tsv"
qc_data.to_csv(qc_data_file, sep="\t", index=False)
def value_range(X: pd.Series) -> list[float]:
return [-X.max() * 1.2, X.max() * 1.2]
def time_range(time_stamps: pd.Series) -> list[float]:
return [time_stamps.min() - 3, time_stamps.max() + 3]
def visualize_eye_gaze_data(
eye_gaze_data: pd.DataFrame,
) -> Any:
fig = go.FigureWidget(
make_subplots(
rows=3,
cols=4,
shared_xaxes=True,
horizontal_spacing=0.1,
vertical_spacing=0.05,
specs=[
[{"colspan": 2}, None, {"rowspan": 2, "colspan": 2}, None],
[{"colspan": 2}, None, None, None],
[{"colspan": 2}, None, None, None],
],
)
)
# Plot input signal together with split output signal (X & Y)
plot_time_series(fig, eye_gaze_data, title_text="X", row=1, col=1)
plot_time_series(fig, eye_gaze_data, title_text="Y", row=2, col=1)
plot_time_series(
fig,
eye_gaze_data,
title_text="displacement",
row=3,
col=1,
plotting_range=[-0.1, eye_gaze_data["displacement"].max() * 1.1],
line_color="grey",
)
fig.update_xaxes(
row=3,
col=1,
title={"text": "Time (s)", "standoff": 16, "font": FONT_SIZE},
tickfont=TICK_FONT,
)
plot_heat_map(fig, eye_gaze_data)
return fig
def plot_time_series(
fig: Any,
eye_gaze_data: pd.DataFrame,
title_text: str,
row: int,
col: int,
plotting_range: list[float] | None = None,
line_color: str = LINE_COLOR,
) -> None:
outliers = None
values_to_plot = eye_gaze_data["x_coordinate"]
outliers = eye_gaze_data["x_outliers"]
outlier_color = "orange"
if title_text == "Y":
values_to_plot = eye_gaze_data["y_coordinate"]
outliers = eye_gaze_data["y_outliers"]
elif title_text == "displacement":
values_to_plot = eye_gaze_data["displacement"]
outliers = eye_gaze_data["displacement_outliers"]
outlier_color = "red"
if plotting_range is None:
plotting_range = value_range(values_to_plot)
fig.add_trace(
go.Scatter(
x=time_range(eye_gaze_data["timestamp"]),
y=[0, 0],
mode="lines",
line_color="black",
line_width=LINE_WIDTH - 1,
),
row=row,
col=col,
)
fig.add_trace(
go.Scatter(
x=eye_gaze_data["timestamp"],
y=values_to_plot,
mode="lines",
line_color=line_color,
line_width=LINE_WIDTH,
),
row=row,
col=col,
)
if outliers is not None:
fig.add_trace(
go.Scatter(
x=eye_gaze_data["timestamp"][outliers == 1],
y=values_to_plot[outliers == 1],
mode="markers",
marker_color=outlier_color,
marker_size=MARKER_SIZE,
),
row=row,
col=col,
)
fig.update_xaxes(
range=time_range(eye_gaze_data["timestamp"]),
row=row,
col=col,
gridcolor=GRID_COLOR,
griddash="dot",
gridwidth=0.5,
tickfont=TICK_FONT,
)
fig.update_yaxes(
range=plotting_range,
row=row,
col=col,
gridcolor=GRID_COLOR,
griddash="dot",
gridwidth=0.5,
ticksuffix="°",
title={"text": title_text, "standoff": 0, "font": FONT_SIZE},
tickfont=FONT_SIZE,
)
fig.update_layout(
showlegend=False,
plot_bgcolor=BG_COLOR,
paper_bgcolor=BG_COLOR,
)
def plot_heat_map(fig: Any, eye_gaze_data: pd.DataFrame) -> None:
X = eye_gaze_data["x_coordinate"]
Y = eye_gaze_data["y_coordinate"]
x_range = value_range(X)
y_range = value_range(Y)
fig.add_trace(
go.Histogram2dContour(x=X, y=Y, colorscale=HEAT_MAP_COLOR),
row=1,
col=3,
)
fig.add_trace(
go.Scatter(
x=x_range,
y=[0, 0],
mode="lines",
line_color="black",
line_width=LINE_WIDTH - 2,
),
row=1,
col=3,
)
fig.add_trace(
go.Scatter(
x=[0, 0],
y=y_range,
mode="lines",
line_color="black",
line_width=LINE_WIDTH - 2,
),
row=1,
col=3,
)
fig.add_trace(
go.Scatter(
x=X,
y=Y,
opacity=0.4,
line={"color": "black", "width": 1, "dash": "dash"},
),
row=1,
col=3,
)
outliers = eye_gaze_data["x_outliers"]
outlier_color = "orange"
add_outliers_to_heatmap(fig, X, Y, outliers, outlier_color)
outliers = eye_gaze_data["y_outliers"]
add_outliers_to_heatmap(fig, X, Y, outliers, outlier_color)
outliers = eye_gaze_data["displacement_outliers"]
outlier_color = "red"
add_outliers_to_heatmap(fig, X, Y, outliers, outlier_color)
fig.update_xaxes(
row=1,
col=3,
range=value_range(X),
ticksuffix="°",
title={"text": "X", "standoff": 16, "font": FONT_SIZE},
tickfont=TICK_FONT,
)
fig.update_yaxes(
row=1,
col=3,
range=value_range(Y),
ticksuffix="°",
title={"text": "Y", "standoff": 16, "font": FONT_SIZE},
tickfont=TICK_FONT,
)
fig.update_layout(showlegend=False)
def add_outliers_to_heatmap(
fig: Any, X: pd.Series, Y: pd.Series, outliers: pd.Series, outlier_color: str
) -> None:
fig.add_trace(
go.Scatter(
x=X[outliers == 1],
y=Y[outliers == 1],
mode="markers",
marker_color=outlier_color,
marker_size=MARKER_SIZE / 2,
),
row=1,
col=3,
)