forked from childmindresearch/bids2table
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_table.py
More file actions
245 lines (209 loc) · 6.68 KB
/
test_table.py
File metadata and controls
245 lines (209 loc) · 6.68 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
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
import pandas as pd
import pytest
from bids2table import bids2table
from bids2table.table import (
ENTITY_NAMES_TO_KEYS,
BIDSTable,
flat_to_multi_columns,
join_bids_path,
multi_to_flat_columns,
)
BIDS_EXAMPLES = Path(__file__).parent.parent / "bids-examples"
@pytest.fixture(scope="module")
def tab() -> BIDSTable:
tab = bids2table(BIDS_EXAMPLES / "ds001")
# sort rows to get deterministic order
tab = tab.sort_values("finfo__file_path", ignore_index=True)
return tab
@pytest.fixture(scope="module")
def tab_no_meta() -> BIDSTable:
tab = bids2table(BIDS_EXAMPLES / "ds001", with_meta=False)
# sort rows to get deterministic order
tab = tab.sort_values("finfo__file_path", ignore_index=True)
return tab
def test_table(tab: BIDSTable):
assert tab.shape == (128, len(ENTITY_NAMES_TO_KEYS) + 8)
groups = tab.nested.columns.unique(0).tolist()
assert groups == ["ds", "ent", "meta", "finfo"]
assert tab.ds.shape == (128, 4)
assert tab.ent.shape == (128, len(ENTITY_NAMES_TO_KEYS))
assert tab.meta.shape == (128, 1)
assert tab.flat_meta.shape == (128, 2)
assert tab.finfo.shape == (128, 3)
subtab: BIDSTable = tab.iloc[:10]
assert subtab.ds.shape == (10, 4)
assert len(tab.datatypes) == 2
assert set(tab.modalities).issuperset(
{
"T1w",
"inplaneT2",
"bold",
}
)
assert len(tab.subjects) == 16
assert len(tab.entities) == 3
def test_table_files(tab: BIDSTable):
files = tab.files
assert len(files) == 128
file = files[2]
assert file.dataset == "ds001"
assert file.path.exists()
assert (file.root / file.relative_path).exists()
assert file.path.name == "sub-01_task-balloonanalogrisktask_run-01_bold.nii.gz"
assert file.metadata == {
"RepetitionTime": 2.0,
"TaskName": "balloon analog risk task",
}
ents = file.entities
assert (ents.sub, ents.task, ents.run) == ("01", "balloonanalogrisktask", 1)
@pytest.mark.parametrize(
"key,filter,expected_count",
[
("sub", {"value": "04"}, 8),
("subject", {"value": "04"}, 8),
("RepetitionTime", {"value": 2.0}, 48),
("subject", {"value": "04"}, 8),
("sub", {"items": ["04", "06"]}, 16),
("sub", {"contains": "4"}, 16),
("sub", {"regex": "0[456]"}, 24),
("RepetitionTime", {"func": lambda v: v <= 2.0}, 48),
],
)
def test_table_filter(
tab: BIDSTable, key: str, filter: Dict[str, Any], expected_count: int
):
subtab = tab.filter(key, **filter)
assert isinstance(subtab, BIDSTable)
assert len(subtab) == expected_count
@pytest.mark.parametrize(
"filters,expected_count",
[
(
{
"dataset": "ds001",
"sub": {"items": ["04", "06"]},
"RepetitionTime": {"value": 2.0},
},
6,
)
],
)
def test_table_filter_multi(
tab: BIDSTable, filters: Dict[str, Any], expected_count: int
):
subtab = tab.filter_multi(**filters)
assert isinstance(subtab, BIDSTable)
assert len(subtab) == expected_count
@pytest.mark.parametrize("inplace", [True, False])
@pytest.mark.parametrize("by", ["sub", ["subject"], ["dataset", "sub"]])
def test_table_sort_entities(tab: BIDSTable, by: Union[str, List[str]], inplace: bool):
tab = tab.copy()
sort_tab = tab.sort_entities(by, inplace=inplace)
assert isinstance(sort_tab, BIDSTable)
assert len(sort_tab) == len(tab)
assert sort_tab.subjects == sorted(tab.subjects)
def test_table_with_meta(tab_no_meta: BIDSTable):
tab_no_meta = tab_no_meta.copy()
tab_with_meta = tab_no_meta.with_meta(inplace=False)
assert tab_no_meta["meta__json"].isna().all()
assert not tab_with_meta["meta__json"].isna().all()
tab_with_meta = tab_no_meta.with_meta(inplace=True)
assert not tab_no_meta["meta__json"].isna().all()
@pytest.mark.parametrize("sep", ["__", "."])
def test_flat_to_multi_columns(sep: str):
df = pd.DataFrame(
{
f"A{sep}a": [1, 2, 3],
f"A{sep}b": ["a", "b", "c"],
f"B{sep}a": [4, 5, 6],
f"B{sep}b": ["d", "e", "f"],
}
)
multi_index = pd.MultiIndex.from_product([["A", "B"], ["a", "b"]])
df_multi = flat_to_multi_columns(df, sep=sep)
assert df_multi.columns.equals(multi_index)
df_flat = multi_to_flat_columns(df_multi, sep=sep)
assert df_flat.equals(df)
@pytest.mark.parametrize(
"entities,prefix,valid_only,expected",
[
(
{"sub": "A01", "ses": "b", "run": 2, "suffix": "bold", "ext": ".json"},
None,
False,
"sub-A01/ses-b/sub-A01_ses-b_run-2_bold.json",
),
(
{"sub": "A01", "ses": "b", "run": 2, "suffix": "bold", "ext": ".json"},
"dataset",
False,
"dataset/sub-A01/ses-b/sub-A01_ses-b_run-2_bold.json",
),
(
{
"sub": "A01",
"ses": "b",
"run": 2,
"extraKey": 1,
"suffix": "bold",
"ext": ".json",
},
None,
False,
"sub-A01/ses-b/sub-A01_ses-b_run-2_extraKey-1_bold.json",
),
(
{
"sub": "A01",
"ses": "b",
"run": 2,
"extraKey": 1,
"suffix": "bold",
"ext": ".json",
},
None,
True,
"sub-A01/ses-b/sub-A01_ses-b_run-2_bold.json",
),
(
pd.Series(
{
"sub": "A01",
"ses": "b",
"run": 2,
"suffix": "bold",
"ext": ".json",
}
),
None,
False,
"sub-A01/ses-b/sub-A01_ses-b_run-2_bold.json",
),
# Make sure it still works if applied to the raw df
(
{
"ds__dataset": "ds001",
"ent__sub": "A01",
"ent__ses": "b",
"ent__run": 2,
"suffix": "bold",
"ext": ".json",
},
None,
False,
"sub-A01/ses-b/sub-A01_ses-b_run-2_bold.json",
),
],
)
def test_join_bids_path(
entities: Union[Dict[str, Any], pd.Series],
prefix: Optional[str],
valid_only: bool,
expected: str,
):
path = join_bids_path(entities, prefix=prefix, valid_only=valid_only)
assert Path(path).as_posix() == expected
if __name__ == "__main__":
pytest.main([__file__])