-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathseatingChartTool.py
More file actions
231 lines (196 loc) · 6.99 KB
/
Copy pathseatingChartTool.py
File metadata and controls
231 lines (196 loc) · 6.99 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
import base64
import copy
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table_experiments as dt
import flask
import io
import json
import pandas as pd
import numpy as np
import plotly
import plotly.graph_objs as go
import seatingChart.seatingchart as sc
app = dash.Dash()
app.scripts.config.serve_locally = True
# app.css.config.serve_locally = True
# TODO: Guest list data should only be in the displayed table (No global state!)
NUM_TABLES = 11
GUESTS_PER_TABLE = 10
import itertools
seatTableNumbersNested = [[i + 1] * GUESTS_PER_TABLE for i in range(NUM_TABLES)]
seatTableNumbers = list(itertools.chain.from_iterable(seatTableNumbersNested))
GUEST_LIST_INPUT = pd.read_csv('example/guestlist.csv')
GUEST_LIST_INPUT['friends'] = ''
NUM_GUESTS = len(GUEST_LIST_INPUT)
for i, seatTableNumber in enumerate(seatTableNumbers):
try:
row = GUEST_LIST_INPUT.loc[i]
GUEST_LIST_INPUT.loc[i, 'Table'] = seatTableNumber
except KeyError:
GUEST_LIST_INPUT.loc[i, 'Table'] = seatTableNumber
GUEST_LIST_INPUT.loc[i, 'Guest Name'] = 'Empty'
GUEST_LIST_INPUT.loc[i, 'friends'] = ''
app.layout = html.Div([
html.H4('Guest List'),
dt.DataTable(
rows=GUEST_LIST_INPUT.to_dict('records'),
# optional - sets the order of columns
# columns=sorted(DF_GAPMINDER.columns),
row_selectable=True,
filterable=True,
sortable=True,
selected_row_indices=[],
id='guest-list'
),
html.Button(id='button-friend', n_clicks=0, children='Make friends'),
html.Button(id='sorter', n_clicks=0, children='Sort!'),
html.A('Download CSV', id='my-link'),
html.Div(id='table-action'),
html.H1(id='friend-count', children='Number of friendships:'),
dcc.Graph(
id='graph-guest-sorter'
),
], className='container')
@app.callback(
Output('friend-count', 'children'),
[Input('guest-list', 'rows')]
)
def countFriends(rows):
df = pd.DataFrame(rows)
return 'Number of friendships: {}'.format(sc.countFriendships(df))
@app.callback(
Output('guest-list', 'selected_row_indices'),
[Input('graph-guest-sorter', 'clickData')],
[State('guest-list', 'selected_row_indices')])
def update_selected_row_indices(clickData, selected_row_indices):
if clickData:
for point in clickData['points']:
if point['pointNumber'] in selected_row_indices:
selected_row_indices.remove(point['pointNumber'])
else:
selected_row_indices.append(point['pointNumber'])
return selected_row_indices
@app.callback(
Output('graph-guest-sorter', 'figure'),
[Input('guest-list', 'rows'),
Input('guest-list', 'selected_row_indices')])
def update_figure(rows, selected_row_indices):
df = pd.DataFrame(rows)
for tableNum, tableGroup in df.groupby('Table'):
lg = len(tableGroup)
tableNum = int(tableNum)
df.loc[tableGroup.index, 'x'] = tableNum // 2
df.loc[tableGroup.index, 'y'] = tableNum % 2 + .9 * np.arange(lg)/float(lg)
return {
'data': [go.Scatter(
x=df['x'],
y=df['y'],
text=[n[0:10] for n in df['Guest Name']],
customdata=df.index,
mode='markers+text',
textposition='middle right',
marker={
'size': 15,
'opacity': 0.5,
'line': {'width': 0.5, 'color': 'white'},
},
selectedpoints=selected_row_indices,
selected={
'marker': {
'color': 'rgba(255, 0, 0, 1.)',
}
},
)],
'layout': go.Layout(
xaxis={
'showgrid': False,
'zeroline': False,
'showticklabels': False,
},
yaxis={
'showgrid': False,
'zeroline': False,
'showticklabels': False,
},
margin={'l': 40, 'b': 30, 't': 10, 'r': 0},
height=450,
hovermode='closest'
)
}
@app.callback(Output('my-link', 'href'), [Input('guest-list', 'rows')])
def update_link(rows):
df = pd.DataFrame(rows)
buffer = io.StringIO() #creating an empty buffer
df.to_csv(buffer, index=False) #filling that buffer
buffer.seek(0) #set to the start of the stream
dfEncoded = base64.b64encode(buffer.getvalue().encode('utf-8'))
buffer.close()
return '/dash/urlToDownload3?value=' + dfEncoded.decode("utf-8")
@app.server.route('/dash/urlToDownload3')
def download_csv():
value = flask.request.args.get('value')
mem = io.BytesIO()
mem.write(base64.b64decode(value))
mem.seek(0)
file = flask.send_file(mem,
mimetype='text/csv',
attachment_filename='downloadFile.csv',
as_attachment=True)
return file
@app.callback(
Output('table-action', 'children'),
[Input('button-friend', 'n_clicks'),
Input('sorter', 'n_clicks')],
[State('table-action', 'children')]
)
def decideTableAction(nclicksF, nclicksS, tableActionData):
if tableActionData is None:
return json.dumps((None, nclicksF, nclicksS))
tableAction, oldNclicksF, oldNclicksS = json.loads(tableActionData)
newClickF, newClickS = nclicksF - oldNclicksF, nclicksS - oldNclicksS
if newClickF:
return json.dumps(('friend', nclicksF, nclicksS))
elif newClickS:
return json.dumps(('sort', nclicksF, nclicksS))
else:
raise Exception
@app.callback(
Output('guest-list', 'rows'),
[Input('table-action', 'children')],
[State('guest-list', 'rows'),
State('guest-list', 'selected_row_indices')]
)
def sortTables(tableActionData, rows, selectedRowIndices):
if tableActionData is None:
return pd.DataFrame(rows).to_dict('records')
tableAction, _, _ = json.loads(tableActionData)
df = pd.DataFrame(rows)
if tableAction == 'sort':
print("now do Metropolis algorithim to increase friendships")
nsteps = 1000
for i in range(nsteps):
temp = 0.1
df = sc.metropolisStep(df, temp)
return df.to_dict('records')
elif tableAction == 'friend':
names = df.loc[selectedRowIndices, 'Guest Name'].values.tolist()
for i in selectedRowIndices:
namesTemp = copy.copy(names)
namesTemp.remove(df.loc[i, 'Guest Name'])
if df.loc[i, 'friends']:
oldFriends = df.loc[i, 'friends'].split(',')
oldFriends = [f.strip() for f in oldFriends]
friends = set(oldFriends + namesTemp)
else:
friends = set(namesTemp)
df.loc[i, 'friends'] = ', '.join(friends)
return df.to_dict('records')
return df.to_dict('records')
app.css.append_css({
'external_url': 'https://codepen.io/chriddyp/pen/bWLwgP.css'
})
if __name__ == '__main__':
app.run_server(debug=True)