-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdashtest.py
420 lines (372 loc) · 17.1 KB
/
dashtest.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
# -*- coding: utf-8 -*-
from dash import Dash, dcc, html, dash_table, Input, Output
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
import scipy.stats
import random
import math
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = Dash(__name__, external_stylesheets=external_stylesheets)
# Stores information
dfs = {'indvs':None, 'stats':None}
cols = {'indvs':None, 'stats':None, 'uniq_stats':None}
class generationViewer():
def __init__(self, indvs=None, stats=None, rslts=None, debug=False):
if indvs is None and stats is None and rslts is None:
raise ValueError('Need to pass idnvs, stats, or rslts')
def load(input):
if isinstance(input, str):
df = pd.read_csv(input)
elif isinstance(input, dict):
df = pd.DataFrame(input)
elif isinstance(input, pd.DataFrame):
df = input
df = df.select_dtypes(include=\
('int16','int32','int64','boolean',\
'float16','float32','float64'))
return df
# Interpret results
if rslts is not None:
indvs, stats = rslts.to_df()
dfs['indvs'] = indvs
cols['indvs'] = sorted(list(indvs.columns))
dfs['stats'] = stats
cols['stats'] = sorted([col for col in stats.columns \
if '.95CI' not in col])
cols['uniq_stats'] = sorted(list({col if '.' not in col \
else ''.join(col.split('.')[:-1]) \
for col in cols['stats']}))
else:
if indvs is not None:
indvs = load(indvs)
dfs['indvs'] = indvs
cols['indvs'] = sorted(list(indvs.columns))
if stats is not None:
stats = load(stats)
dfs['stats'] = stats
cols['stats'] = sorted([col for col in stats.columns \
if '.95CI' not in col])
cols['uniq_stats'] = sorted(list({col if '.' not in col \
else ''.join(col.split('.')[:-1]) \
for col in cols['stats']}))
# Raise an error if min/max don't match
if indvs is not None and stats is not None:
gen_min, gen_max = stats['_gen'].min(), stats['_gen'].max()
run_min, run_max = stats['_run'].min(), stats['_run'].max()
if gen_min != indvs['_gen'].min():
raise ValueError
if gen_max != indvs['_gen'].max():
raise ValueError
if run_min != indvs['_run'].min():
raise ValueError
if run_max != indvs['_run'].max():
raise ValueError
app.layout = html.Div([
html.Div(children=[
html.Label('Run'),
dcc.RangeSlider(run_min, run_max, 1, value=[run_max, run_max],\
id='run-slider', tooltip={"placement": "bottom",\
"always_visible": True}),
html.Label('Generation'),
dcc.RangeSlider(gen_min, gen_max, value=[gen_max, gen_max],\
id='gen-slider', tooltip={"placement": "bottom",\
"always_visible": True})
], style={'padding': 10, 'flex-direction': 'column'}),
dcc.Tabs([
dcc.Tab(label='Individual Info', children=[
dcc.Graph(id='indvs-graph'),
html.Div(children=[
html.Label('X-Axis'),
dcc.Dropdown(cols['indvs'] + [''],\
None,\
id='indvs-x-axis-selector'),
html.Br(),
html.Label('Y-Axis'),
dcc.Dropdown(cols['indvs'] + [''],
None,
multi=True,\
id='indvs-y-axis-selector'),
html.Br(),
html.Label('Color', id='indvs-color-selector-lbl'),
dcc.Dropdown(cols['indvs'],
None,\
id='indvs-color-selector'),
html.Br(),
html.Label('Size', id='indvs-size-selector-lbl'),
dcc.Dropdown(cols['indvs'],
None,\
id='indvs-size-selector'),
], style={'padding': 10, 'flex-direction': 'row'}),
html.Div(children=\
[html.Label('variables')]+\
[html.Label(col) for col in cols['indvs']],\
style={'padding': 10, 'flex-direction': 'row'}),
]),
dcc.Tab(label='Population Statistics', children=[
dcc.Graph(id='stats-graph'),
html.Div(children=[
html.Label('X-Axis'),
dcc.Dropdown(cols['stats'],\
None,\
id='stats-x-axis-selector'),
html.Br(),
html.Label('Y-Axis'),
dcc.Dropdown(cols['stats'],
None,
multi=True,\
id='stats-y-axis-selector'),
html.Br(),
html.Label('Color', id='stats-color-selector-lbl'),
dcc.Dropdown(cols['stats'],
None,\
id='stats-color-selector'),
html.Br(),
html.Label('Size', id='stats-size-selector-lbl'),
dcc.Dropdown(cols['stats'],
None,\
id='stats-size-selector'),
html.Br(),
html.Label('Graph Type'),
dcc.Dropdown(['Bar', 'Line', 'Scatter', ''], 'Line',\
id='stats-graph-type-selector'),
html.Div(children=\
[html.Label('variables')]+\
[html.Label(col) for col in cols['uniq_stats']],\
style={'padding': 10, 'flex-direction': 'row'}),
], style={'padding': 10, 'flex-direction': 'row'})
]),
]),
])
app.run_server(debug=debug)
# Hides colors / size if not scatterplot / bar
@app.callback(
Output('stats-size-selector', 'style'),
Output('stats-size-selector-lbl', 'style'),
Output('stats-color-selector', 'style'),
Output('stats-color-selector-lbl', 'style'),
Input('stats-graph-type-selector', 'value'),
Input('stats-y-axis-selector', 'value')
)
def hide_or_show_clr_size_stats(graph_type, y_vals):
if y_vals is not None and isinstance(y_vals, (list,tuple)) and len(y_vals) > 1:
return {'display': 'none'}, {'display': 'none'}, \
{'display': 'none'}, {'display': 'none'}
elif graph_type == 'Scatter':
return {'display': 'block'}, {'display': 'block'}, \
{'display': 'block'}, {'display': 'block'}
elif graph_type == 'Bar':
return {'display': 'none'}, {'display': 'none'}, \
{'display': 'block'}, {'display': 'block'}
elif graph_type == 'Line':
return {'display': 'none'}, {'display': 'none'}, \
{'display': 'block'}, {'display': 'block'}
# Hides colors / size if not scatterplot / bar
@app.callback(
Output('indvs-size-selector', 'style'),
Output('indvs-size-selector-lbl', 'style'),
Output('indvs-color-selector', 'style'),
Output('indvs-color-selector-lbl', 'style'),
Input('indvs-y-axis-selector', 'value'),
)
def hide_or_show_clr_size_indvs(y_vals):
print('Called hide_or_show_clr_size_indvs')
if y_vals is not None and isinstance(y_vals, (list,tuple)) and len(y_vals) > 1:
return {'display': 'none'}, {'display': 'none'}, \
{'display': 'none'}, {'display': 'none'}
else:
return {'display': 'block'}, {'display': 'block'}, \
{'display': 'block'}, {'display': 'block'}
def get_mean_and_CI(df, x, y):
stats = df.groupby(x)[y].agg(['mean', 'count', 'std'])
ci = [row['mean'] + 1.96*(row['std']/row['count']) \
for index, row in stats.iterrows()]
return stats.index.tolist(), stats['mean'].tolist(), ci
def _filter_by_runs_and_gens(df, run, gen):
print('Called _filter_by_runs_and_gens')
filtered_df = df[df._run >= run[0]]
filtered_df = filtered_df[filtered_df._run <= run[1]]
filtered_df = filtered_df[filtered_df._gen >= gen[0]]
filtered_df = filtered_df[filtered_df._gen <= gen[1]]
return filtered_df
def _create_line_graph(df, x, y, clr):
print('Called _create_line_graph')
fig = go.Figure()
if len(y) == 1 and clr is not None:
groups = df.groupby(clr)
for name in groups.groups.keys():
c1, c2, c3 = random.randint(0,255),\
random.randint(0,255),\
random.randint(0,255)
x_vals, means, ci = get_mean_and_CI(groups.get_group(name), x, y[0])
fig.add_trace(go.Scatter(x=x_vals, \
y=means,\
mode='lines', \
name=name,\
line_color=f'rgba({c1},{c2},{c3},1)',\
showlegend=True,\
error_y=dict(
type='data',
array=ci,
visible=True)))
return fig
else:
# Group by x-axis
for y_indx, y_header in enumerate(y):
c1, c2, c3 = random.randint(0,255),\
random.randint(0,255),\
random.randint(0,255)
x_vals, means, ci = get_mean_and_CI(df, x, y_header)
fig.add_trace(go.Scatter(x=x_vals, \
y=means,\
mode='lines', \
name=y_header,\
line_color=f'rgba({c1},{c2},{c3},1)',\
showlegend=True,\
error_y=dict(
type='data',
array=ci,
visible=True)))
return fig
def _create_scatter_plot(df, x, y, clr, size):
print('Called _create_scatter_plot')
if len(y) == 1:
if clr is None and size is None:
return px.scatter(df, x=x, y=y[0])
elif clr is not None and size is not None:
return px.scatter(df, x=x, y=y[0], color=clr, size=size)
elif size is not None:
return px.scatter(df, x=x, y=y[0], size=size)
elif clr is not None:
return px.scatter(df, x=x, y=y[0], color=clr)
else:
fig = go.Figure()
for y_val in y:
c1,c2,c3 = random.randint(0,255), \
random.randint(0,255), \
random.randint(0,255)
fig.add_trace(go.Scatter(x=df[x], \
y=df[y_val],\
mode='markers', \
name=y_val,\
line_color=f'rgba({c1},{c2},{c3},1)',\
showlegend=True))
return fig
def _create_bar_chart(df, x, y, clr):
print('Called _create_bar_chart')
fig = go.Figure()
if len(y) == 1 and clr is not None:
groups = df.groupby(clr)
for name in groups.groups.keys():
x_vals, means, ci = get_mean_and_CI(groups.get_group(name), x, y[0])
fig.add_trace(go.Bar(x=x_vals, \
y=means,\
name=name,\
showlegend=True,\
error_y=dict(
type='data',
array=ci,
visible=True)))
return fig
else:
# Group by x-axis
for y_indx, y_header in enumerate(y):
x_vals, means, ci = get_mean_and_CI(df, x, y_header)
fig.add_trace(go.Bar(x=x_vals, \
y=means,\
name=y_header,\
showlegend=True,\
error_y=dict(
type='data',
array=ci,
visible=True)))
return fig
@app.callback(
Output('stats-graph', 'figure'),
Input('run-slider', 'value'),
Input('gen-slider', 'value'),
Input('stats-x-axis-selector', 'value'),
Input('stats-y-axis-selector', 'value'),
Input('stats-color-selector', 'value'),
Input('stats-size-selector', 'value'),
Input('stats-graph-type-selector','value'))
def update_stats_fig(run, gen, x, y, clr, size, graph_type):
print('Called update_stats_fig')
# If missing any of essential values, just return
if y == None or None in y or len(y) == 0 or x is None or graph_type is None:
fig = go.Figure()
fig.update_layout(legend_title_text = "Legend")
fig.update_xaxes(title_text='')
fig.update_layout(transition_duration=500)
y_axis_name = y[0] if (y is not None and len(y) == 1) else 'y-axis'
fig.update_layout(title = "Empty Plot",\
xaxis_title = x if x is not None else 'x-axis',\
yaxis_title = y_axis_name,\
legend_title = 'Legend')
return fig
# Get only values in run/gen range
df = _filter_by_runs_and_gens(dfs['stats'], run, gen)
# Sort by X-Axis
df.sort_values(by=x)
# Create the apropriate graph
if graph_type == 'Line':
fig = _create_line_graph(df, x, y, clr)
elif graph_type == 'Scatter':
fig = _create_scatter_plot(df, x, y, clr, size)
elif graph_type == 'Bar':
fig = _create_bar_chart(df, x, y, clr)
y_axis_name = y[0] if len(y) == 1 else 'y-axis'
fig.update_layout(legend_title_text = "Legend")
fig.update_xaxes(title_text='')
fig.update_layout(transition_duration=500)
fig.update_layout(title = f"{y} over {x}",\
xaxis_title = x if x is not None else 'x-axis',\
yaxis_title = y_axis_name,\
legend_title = 'Legend')
return fig
@app.callback(
Output('indvs-graph', 'figure'),
Input('run-slider', 'value'),
Input('gen-slider', 'value'),
Input('indvs-x-axis-selector', 'value'),
Input('indvs-y-axis-selector', 'value'),
Input('indvs-color-selector', 'value'),
Input('indvs-size-selector', 'value'))
def update_indvs_fig(run, gen, x, y, clr, size):
print('Called update_indvs_fig')
graph_type = 'Scatter'
# If missing any of essential values, just return
if y == None or None in y or len(y) == 0 or x is None or graph_type is None:
fig = go.Figure()
fig.update_layout(legend_title_text = "Legend")
fig.update_xaxes(title_text='')
fig.update_layout(transition_duration=500)
y_axis_name = y[0] if (y is not None and len(y) == 1) else 'y-axis'
fig.update_layout(title = "Empty Plot",\
xaxis_title = x if x is not None else 'x-axis',\
yaxis_title = y_axis_name,\
legend_title = 'Legend')
return fig
# Get only values in run/gen range
df = _filter_by_runs_and_gens(dfs['indvs'], run, gen)
# Sort by X-Axis
df.sort_values(by=x)
# Create the apropriate graph
if graph_type == 'Line':
fig = _create_line_graph(df, x, y, clr)
elif graph_type == 'Scatter':
fig = _create_scatter_plot(df, x, y, clr, size)
elif graph_type == 'Bar':
fig = _create_bar_chart(df, x, y, clr)
y_axis_name = y[0] if len(y) == 1 else 'y-axis'
fig.update_layout(legend_title_text = "Legend")
fig.update_xaxes(title_text='')
fig.update_layout(transition_duration=500)
fig.update_layout(title = f"{y} over {x}",\
xaxis_title = x if x is not None else 'x-axis',\
yaxis_title = y_axis_name,\
legend_title = 'Legend')
return fig
#if __name__ == '__main__':
# app.run_server(debug=True)