-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
164 lines (135 loc) · 5.19 KB
/
utils.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
import contextlib
import json
import warnings
from pathlib import Path
import pandas as pd
from heuristics import get_column_type
def output_dir() -> Path:
return Path(__file__).parent / "outputs"
def dt_inplace(df: pd.DataFrame) -> pd.DataFrame:
"""Automatically detect and convert (in place!) each dataframe column \
of datatype 'object' to a datetime just \
when ALL of its non-NaN values can be successfully parsed by pd.to_datetime().
Also returns a ref. to df for convenient use in an expression.
from :
https://towardsdatascience.com/auto-detect-and-set-the-date-datetime-datatypes-when-reading-csv-into-pandas-261746095361
"""
from pandas.errors import ParserError
for c in df.columns[df.dtypes == "object"]: # don't convert num
with contextlib.suppress(ParserError, ValueError, TypeError):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
df[c] = pd.to_datetime(df[c])
return df
def read_csv_autodetect_date(*args, **kwargs) -> pd.DataFrame:
"""Drop-in replacement for Pandas pd.read_csv.
It invokes pd.read_csv() (passing its arguments)
and then auto-matically detects and converts each column
whose datatype is 'object' to a datetime just when ALL of the column's
non-NaN values can be successfully parsed by pd.to_datetime(),
and returns the resulting dataframe.
from :
https://towardsdatascience.com/auto-detect-and-set-the-date-datetime-datatypes-when-reading-csv-into-pandas-261746095361
"""
return dt_inplace(pd.read_csv(*args, **kwargs))
def new_row_template(
dataset_name: str, nb_rows: int, include_levels: False
) -> dict[str, str | int | bool]:
if include_levels:
return {
"dataset": dataset_name,
"nb_rows": nb_rows,
"column": "n/a",
"type": "n/a",
"nb_levels": 0,
"value": "n/a",
"is_row": "n/a",
"description": "n/a",
"controlled_term": "n/a",
"units": "n/a",
"term_url": "n/a",
}
return {
"dataset": dataset_name,
"nb_rows": nb_rows,
"column": "n/a",
"type": "n/a",
"nb_levels": 0,
"description": "n/a",
"controlled_term": "n/a",
"units": "n/a",
"term_url": "n/a",
}
def init_output(include_levels: bool = False) -> dict[str, list]:
"""Return a dict with keys corresponding to the columns of the output tsv."""
if include_levels:
return {
"dataset": [],
"nb_rows": [],
"column": [],
"value": [],
"type": [],
"nb_levels": [],
"is_row": [],
"description": [],
"controlled_term": [],
"units": [],
"term_url": [],
}
else:
return {
"dataset": [],
"nb_rows": [],
"column": [],
"type": [],
"nb_levels": [],
"description": [],
"controlled_term": [],
"units": [],
"term_url": [],
}
def exclude_datasets(dataset: pd.DataFrame):
"""Detect if the dataset should be excluded from further analysis."""
return not dataset["has_mri"] or not dataset["has_participant_tsv"]
def get_participants_dict(dataset: pd.DataFrame, src_pth: Path):
"""Load participants.json if it exists."""
participants_dict = {}
if dataset["has_participant_json"]:
participant_json = src_pth / dataset["name"] / "participants.json"
with open(participant_json) as f:
participants_dict = json.load(f)
return participants_dict
def get_column_description(participants_dict, column):
"""Get the column description from participants.json \
if the file and description exist."""
if participants_dict and participants_dict.get(column):
return participants_dict[column].get("Description", "n/a")
return "n/a"
def get_column_unit(participants_dict, column):
"""Get the column unit from participants.json \
if the file and unit description exist."""
if participants_dict and participants_dict.get(column):
return participants_dict[column].get("Unit", "n/a")
return "n/a"
def get_column_term_url(participants_dict, column):
"""Get the column unit from participants.json \
if the file and TermURL description exist."""
if participants_dict and participants_dict.get(column):
return participants_dict[column].get("TermURL", "n/a")
return "n/a"
def update_row_with_column_info(
this_row: dict,
column: str,
participants: pd.DataFrame,
participants_dict: dict,
):
this_row["column"] = column.strip()
this_row["is_row"] = True
if column == "participant_id":
this_row["controlled_term"] = "nb:ParticipantID"
this_row["description"] = get_column_description(participants_dict, column)
this_row["unit"] = get_column_unit(participants_dict, column)
this_row["term_url"] = get_column_term_url(participants_dict, column)
this_row["type"] = get_column_type(participants[column])
this_row["nb_levels"] = len(participants[column].unique())
return this_row