-
Notifications
You must be signed in to change notification settings - Fork 0
/
website_management.py
435 lines (382 loc) · 12.8 KB
/
website_management.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
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
"""Helper functions to manage the Streamlit application."""
import streamlit as st
import pandas as pd
from pandas.api.types import (
is_categorical_dtype,
is_numeric_dtype,
is_object_dtype,
)
from datetime import datetime
import itables
from itables import JavascriptFunction
@st.cache_data
def load_data() -> dict:
"""Retrieve our data and loads it into the pd.DataFrame object.
Returns
-------
dict
returns a dict containing the pd.DataFrame objects of our datasets.
"""
# DATA_URL needs to be the URL of the last version of the data.
# I cannot be the identifier provided by the master DOI.
DATA_URL = "https://zenodo.org/record/7856806"
dfs = {}
datasets = pd.read_parquet(
f"{DATA_URL}/files/datasets.parquet"
)
gro = pd.read_parquet(
f"{DATA_URL}/files/gromacs_gro_files.parquet"
)
gro_data = pd.merge(
gro,
datasets,
how="left",
on=["dataset_id", "dataset_origin"],
validate="many_to_one",
)
mdp = pd.read_parquet(
f"{DATA_URL}/files/gromacs_mdp_files.parquet"
)
mdp_data = pd.merge(
mdp,
datasets,
how="left",
on=["dataset_id", "dataset_origin"],
validate="many_to_one",
)
dfs["datasets"] = datasets
dfs["gro"] = gro_data
dfs["mdp"] = mdp_data
return dfs
def is_isoformat(dates: object) -> bool:
"""Check that all dates are in iso 8601 format.
Parameters
----------
dates: object
contains all dates from a pandas dataframe.
Returns
-------
bool
returns false if at least one element does not respect the format
otherwise returns true.
"""
for date_str in dates:
# Try to convert a string into an iso datatime format
try:
datetime.fromisoformat(date_str)
except Exception:
return False
return True
def filter_dataframe(df: pd.DataFrame, add_filter) -> pd.DataFrame:
"""Add a UI on top of a dataframe to let user filter columns.
This function is based on the code from the following repository:
https://github.com/tylerjrichards/st-filter-dataframe
Parameters
----------
df : pd.DataFrame
original dataframe.
add_filter : bool
tells if the user wants to apply filter.
Returns
-------
pd.DataFrame
Filtered dataframe
"""
if not add_filter:
return df
df = df.copy()
tmp_col = {}
# Try to convert datetimes into a standard format (datetime, no timezone)
for col in df.columns:
if is_object_dtype(df[col]):
try:
tmp_col[col] = pd.to_datetime(df[col].copy())
df[col] = pd.to_datetime(df[col]).dt.strftime("%Y-%m-%d")
except Exception:
pass
modification_container = st.expander(label="Filter dataframe on:", expanded=True)
with modification_container:
to_filter_columns = st.multiselect(
label="Filter dataframe on",
options=df.columns.drop(["URL", "ID"], errors="ignore"),
label_visibility="collapsed",
)
for column in to_filter_columns:
left, right, _ = st.columns((1, 20, 5))
left.write("↳")
# Treat columns with < 10 unique values as categorical
if is_categorical_dtype(df[column]) or df[column].nunique() < 10:
user_cat_input = right.multiselect(
f"Values for {column}",
df[column].unique(),
default=list(df[column].unique()),
)
df = df[df[column].isin(user_cat_input)]
elif is_numeric_dtype(df[column]):
_min = float(df[column].min())
_max = float(df[column].max())
step = (_max - _min) / 100
user_num_input = right.slider(
f"Values for {column}",
_min,
_max,
(_min, _max),
step=step,
)
df = df[df[column].between(*user_num_input)]
elif is_isoformat(df[column]):
user_date_input = right.date_input(
f"Values for {column}",
value=(
tmp_col[column].min(),
tmp_col[column].max(),
),
)
if len(user_date_input) == 2:
user_date_input = tuple(map(pd.to_datetime, user_date_input))
start_date, end_date = user_date_input
df = df.loc[tmp_col[column].between(start_date, end_date)]
else:
user_text_input = right.text_input(
f"Substring or regex in {column}",
)
if user_text_input:
df = df[
df[column].str.contains(user_text_input, case=False, na=False)
]
return df
def link_content_func() -> str:
"""Return a JavaScript template as a string to display a tooltip and href.
The template create a hyperlink to a specifi column and display a tooltip
for each cells of the table. The template will be configured in the
display_table function.
Returns
-------
str
return the JS code as a string.
"""
return """
function (td, cellData, rowData, row, col) {
if (col == 3) {
td.innerHTML = "<a href="+rowData[1]+" target='_blank'>"+cellData+"</a>";
}
td.setAttribute('title', cellData);
}
"""
@st.cache_data
def display_table(data_filtered: pd.DataFrame) -> str:
"""Display a table of the query data.
To get more information about the itables library, please visit:
https://mwouts.github.io/itables/advanced_parameters.html
Parameters
----------
data_filtered: pd.DataFrame
filtered dataframe.
Returns
-------
str
a HTML string containing the datatable.
"""
st.write(f"{len(data_filtered)} elements found")
table = itables.to_html_datatable(
data_filtered,
# Style display of the table
classes="display nowrap cell-border",
# Element to display
dom="ltpr",
# Number of elements to display
lengthMenu=[20, 50, 100, 250],
style="width:100%",
# Apply Javascript function to all cells
columnDefs=[
{
"targets": "_all",
"createdCell": JavascriptFunction(link_content_func()),
}
],
# Enable scrolling
scrollX=True,
# Set a vertical scroll
scrollY=650,
# Desactivate downsampling
maxBytes=0,
)
return table
def display_search_bar(select_data: str = "datasets") -> tuple:
"""Configure the display of the search bar.
Parameters
----------
select_data: str
Type of data to search for.
Values: ["datasets", "gro","mdp"]
Default: "datasets"
Returns
-------
tuple
contains search word, a bool for checkbox and a layout of
the site.
"""
st.title("MDverse data explorer")
placeholder = (
"Enter search term. For instance: Covid, POPC, Gromacs, CHARMM36, 1402417"
)
label_search = ""
if select_data == "datasets":
label_search = "Datasets quick search"
elif select_data == "gro":
label_search = ".gro files quick search"
elif select_data == "mdp":
label_search = ".mdp files quick search"
col_keyup, col_filter, col_download, _ = st.columns([4, 1.2, 1, 1])
with col_keyup:
search = st.text_input(label_search, placeholder=placeholder)
return search, col_filter, col_download
def display_export_button(data_filtered: pd.DataFrame) -> None:
"""Add a download button to export the data from the table.
Parameters
----------
data_filtered: pd.DataFrame
filtered dataframe.
"""
date_now = f"{datetime.now():%Y-%m-%d_%H-%M-%S}"
data_filtered = data_filtered.drop("index", axis=1)
# Change URL column to the last column
temp_cols = list(data_filtered.columns)
new_cols = temp_cols[1:] + temp_cols[0:1]
data_filtered = data_filtered[new_cols]
st.download_button(
label="🛒 Export to tsv",
data=data_filtered.to_csv(sep="\t", index=False).encode("utf-8"),
file_name=f"mdverse_{date_now}.tsv",
mime="text/tsv",
)
def update_contents(data_filtered: pd.DataFrame, select_data: str) -> None:
"""Change the content display according to the cursor position.
Parameters
----------
data_filtered: pd.DataFrame
filtered dataframe.
select_data: str
Type of data to search for.
Values: ["datasets", "gro","mdp"]
"""
selected_row = st.session_state["cursor" + select_data]
data = data_filtered.iloc[selected_row]
contents = f"""
**Dataset:**
[{data["Dataset"]} {data["ID"]}]({data["URL"]})<br />
**Creation date:** {data["Creation date"]}<br />
**Author(s):** {data["Authors"]}<br />
**Title:** *{data["Title"]}*<br />
**Description:**<br /> {data["Description"]}
"""
st.session_state["content"] = contents
def display_slider(select_data: str, size_selected: int) -> None:
"""Display a sidebar for the information to be displayed.
Parameters
----------
select_data: str
Type of data to search for.
Values: ["datasets", "gro","mdp"]
size_selected: int
number of rows selected.
"""
cursor = st.sidebar.slider("Selected row:", 1, size_selected, 1)
st.session_state["cursor" + select_data] = cursor - 1
def display_details(data_filtered: pd.DataFrame, select_data: str) -> None:
"""Show the details of the selected rows in the sidebar.
Parameters
----------
data_filtered: pd.DataFrame
filtered dataframe.
select_data: str
Type of data to search for.
Values: ["datasets", "gro","mdp"]
"""
if (
"cursor" + select_data not in st.session_state
or "content" not in st.session_state
):
st.session_state["cursor" + select_data] = 0
st.session_state["content"] = ""
size_selected = len(data_filtered)
if size_selected:
if size_selected > 1:
display_slider(select_data, size_selected)
update_contents(data_filtered, select_data)
st.sidebar.markdown(st.session_state["content"], unsafe_allow_html=True)
else:
st.session_state["cursor" + select_data] = 0
def load_css() -> None:
"""Load a css style."""
st.markdown(
"""
<style>
/* Centre the add filter checkbox and the download button */
.stCheckbox {
position: absolute;
top: 40px;
}
.stDownloadButton {
position: absolute;
top: 33px;
}
/* Responsive display */
@media (max-width:640px) {
.stCheckbox {
position: static;
}
.stDownloadButton {
position: static;
}
}
/* Maximize thedusplay of the data explorer search */
.block-container:first-of-type {
padding-top: 20px;
padding-left: 20px;
padding-right: 20px;
}
</style>
""",
unsafe_allow_html=True,
)
itables.options.css = """
/* Change the display of the table */
.itables {
font-family: 'sans-serif';
font-size: 0.8rem;
background: white;
padding: 10px;
}
/* Specific column titles */
.itables table th {
word-wrap: break-word;
font-size: 11px;
}
/* Cells specific */
.itables table td {
word-wrap: break-word;
min-width: 50px;
max-width: 50px;
overflow: hidden;
text-overflow: ellipsis;
font-size: 12px;
}
/* Set the width of the id column */
.itables table td:nth-child(4) {
min-width: 80px;
max-width: 80px;
}
/* Set the width of the title and description columns */
.itables table td:nth-child(5), .itables table td:nth-child(8) {
max-width: 300px;
}
/* Hide the URL column */
.itables table th:nth-child(2), .itables table td:nth-child(2){
display:none;
}
/* Apply colour to links */
a:link, a:visited {
color: rgb(51, 125, 255);
}
"""