DavyMorgan commited on
Commit
b82829d
Β·
verified Β·
1 Parent(s): 8ad6835

support upload npy file, improve UI

Browse files
Files changed (1) hide show
  1. app.py +250 -256
app.py CHANGED
@@ -1,256 +1,250 @@
1
- import gradio as gr
2
- import numpy as np
3
- import plotly.graph_objects as go
4
- import plotly.express as px
5
- from sklearn.metrics import pairwise_distances
6
- import torch
7
-
8
- def plot_from_npy(npy_data):
9
- fig = go.Figure()
10
-
11
- fig.add_trace(go.Scatter(x=[1, 2, 3, 4], y=[10, 11, 12, 13], mode='lines', name='New York'))
12
- fig.update_layout(title_text="Facility Distribution in Cities")
13
- fig.update_xaxes(title_text="Time")
14
- fig.update_yaxes(title_text="Facility Count")
15
-
16
-
17
- actual_fig = fig # Replace this line with your actual_fig
18
- solution_fig = fig # Replace this line with your solution_fig
19
-
20
- return actual_fig, solution_fig
21
-
22
- def solver_plot(data_npy, boost=False):
23
- actual_fig = go.Figure()
24
- solution_fig = go.Figure()
25
- actual_ac = 0 # Replace this line with your actual_ac
26
- solution_ac = 0 # Replace this line with your solution_ac
27
- return actual_fig, solution_fig, actual_ac, solution_ac
28
-
29
- def demo_plot(city, facility):
30
- all_facility = ["🏫 School", "πŸ₯ Hospital", "🌳 Park"]
31
- for i in range(len(all_facility)):
32
- if all_facility[i] in facility:
33
- all_facility[i] = True
34
- else:
35
- all_facility[i] = False
36
-
37
- city_name = city.replace(' ', '_')
38
- data = np.loadtxt(f'demo/{city_name}.npy')
39
- positions = data[:, :2]
40
- demands = data[:, 2:5]
41
- actual_facility = data[:, 5:8]
42
- solution_facility = data[:, 8:11]
43
-
44
- actual_fig = go.Figure()
45
- solution_fig = go.Figure()
46
- for i in range(len(all_facility)):
47
- if not all_facility[i]:
48
- continue
49
-
50
- actual_fig.add_trace(go.Scattermapbox(
51
- lat=positions[actual_facility[:, i] == 1][:, 0],
52
- lon=positions[actual_facility[:, i] == 1][:, 1],
53
- mode='markers',
54
- marker=go.scattermapbox.Marker(
55
- size=10,
56
- color=px.colors.qualitative.Plotly[i]
57
- ),
58
- name=f'Facility {i+1}'
59
- ))
60
- solution_fig.add_trace(go.Scattermapbox(
61
- lat=positions[solution_facility[:, i] == 1][:, 0],
62
- lon=positions[solution_facility[:, i] == 1][:, 1],
63
- mode='markers',
64
- marker=go.scattermapbox.Marker(
65
- size=10,
66
- color=px.colors.qualitative.Plotly[i]
67
- ),
68
- name=f'Facility {i+1}'
69
- ))
70
-
71
- actual_fig.update_layout(
72
- mapbox=dict(
73
- style='carto-positron',
74
- center=dict(lat=np.mean(positions[actual_facility[:, i] == 1][:, 0]), \
75
- lon=np.mean(positions[actual_facility[:, i] == 1][:, 1])),
76
- zoom=11.0
77
- ),
78
- margin=dict(l=0, r=0, b=0, t=0),)
79
-
80
- solution_fig.update_layout(
81
- mapbox=dict(
82
- style='carto-positron',
83
- center=dict(lat=np.mean(positions[solution_facility[:, i] == 1][:, 0]), \
84
- lon=np.mean(positions[solution_facility[:, i] == 1][:, 1])),
85
- zoom=11.0
86
- ),
87
- margin=dict(l=0, r=0, b=0, t=0),)
88
- # show legend
89
- actual_fig.update_layout(showlegend=True)
90
- solution_fig.update_layout(showlegend=True)
91
-
92
- positions = np.deg2rad(positions)
93
- dist = pairwise_distances(positions, metric='haversine') * 6371
94
- actual_ac = 0
95
- solution_ac = 0
96
- for i in range(len(all_facility)):
97
- if not all_facility[i]:
98
- continue
99
- ac_matrix = dist * demands[:, i][:, None]
100
- actual_ac += ac_matrix[:, actual_facility[:, i] == 1].min(axis=-1).sum()
101
- solution_ac += ac_matrix[:, solution_facility[:, i] == 1].min(axis=-1).sum()
102
-
103
- return actual_fig, solution_fig, actual_ac, solution_ac
104
-
105
-
106
- def solver_plot(data_npy, boost=False):
107
- data = data_npy.split('\n')
108
- n = len(data)
109
- p = int((len(data[0].split(' '))-2) / 2)
110
-
111
- positions = []
112
- demands = []
113
- actual_facilities = []
114
- for row in data:
115
- row = row.split(' ')
116
- row = [x for x in row if len(x)]
117
- print(row)
118
-
119
- positions.append([float(row[0]), float(row[1])])
120
-
121
- demand = []
122
- for i in range(2, 2+p):
123
- demand.append(float(row[i]))
124
- demands.append(demand)
125
-
126
- actual_facility = []
127
- for i in range(2+p, 2+2*p):
128
- actual_facility.append(bool(int(row[i])))
129
- actual_facilities.append(actual_facility)
130
- positions = np.array(positions)
131
- demands = np.array(demands)
132
- actual_facilities = np.array(actual_facilities)
133
- solution_facilities = ~actual_facilities
134
- print(actual_facilities)
135
-
136
- actual_fig = go.Figure()
137
- solution_fig = go.Figure()
138
- for i in range(p):
139
- actual_fig.add_trace(go.Scattermapbox(
140
- lat=positions[actual_facilities[:, i]][:, 0],
141
- lon=positions[actual_facilities[:, i]][:, 1],
142
- mode='markers',
143
- marker=go.scattermapbox.Marker(
144
- size=10,
145
- color=px.colors.qualitative.Plotly[i]
146
- ),
147
- name=f'Facility {i+1}'
148
- ))
149
- solution_fig.add_trace(go.Scattermapbox(
150
- lat=positions[solution_facilities[:, i]][:, 0],
151
- lon=positions[solution_facilities[:, i]][:, 1],
152
- mode='markers',
153
- marker=go.scattermapbox.Marker(
154
- size=10,
155
- color=px.colors.qualitative.Plotly[i]
156
- ),
157
- name=f'Facility {i+1}'
158
- ))
159
-
160
- actual_fig.update_layout(
161
- mapbox=dict(
162
- style='carto-positron',
163
- center=dict(lat=np.mean(positions[actual_facilities[:, i]][:, 0]), \
164
- lon=np.mean(positions[actual_facilities[:, i]][:, 1])),
165
- zoom=11.0
166
- ),
167
- margin=dict(l=0, r=0, b=0, t=0),)
168
-
169
- solution_fig.update_layout(
170
- mapbox=dict(
171
- style='carto-positron',
172
- center=dict(lat=np.mean(positions[solution_facilities[:, i]][:, 0]), \
173
- lon=np.mean(positions[solution_facilities[:, i]][:, 1])),
174
- zoom=11.0
175
- ),
176
- margin=dict(l=0, r=0, b=0, t=0),)
177
- # show legend
178
- actual_fig.update_layout(showlegend=True)
179
- solution_fig.update_layout(showlegend=True)
180
-
181
- positions = np.deg2rad(positions)
182
- dist = pairwise_distances(positions, metric='haversine') * 6371
183
- actual_ac = 0
184
- solution_ac = 0
185
- for i in range(p):
186
- ac_matrix = dist * demands[:, i][:, None]
187
- actual_ac += ac_matrix[:, actual_facilities[:, i]].min(axis=-1).sum()
188
- solution_ac += ac_matrix[:, solution_facilities[:, i]].min(axis=-1).sum()
189
-
190
- return actual_fig, solution_fig, actual_ac, solution_ac
191
-
192
-
193
-
194
-
195
- def get_example():
196
- return [
197
- ("40.71 -73.93 213 0\n\
198
- 40.72 -73.99 15 1\n\
199
- 40.65 -73.88 365 1\n\
200
- 40.57 -73.96 629 0\n\
201
- 40.70 -73.97 106 0\n\
202
- 40.61 -73.95 189 1"),
203
- ("40.71 -73.93 213 124 0 1\n\
204
- 40.72 -73.99 15 43 1 0\n\
205
- 40.65 -73.88 365 214 1 0\n\
206
- 40.57 -73.96 629 431 0 1\n\
207
- 40.70 -73.97 106 241 0 1\n\
208
- 40.61 -73.95 189 264 1 0")
209
- ]
210
-
211
-
212
-
213
- with gr.Blocks() as demo:
214
- gr.Markdown("## Demo")
215
- with gr.Column():
216
- city = gr.Radio(choices=["New York", "Boston", "Los Angeles", "Chicago"], value="New York", label="Select City:")
217
- facility = gr.CheckboxGroup(choices=["🏫 School", "πŸ₯ Hospital", "🌳 Park"], value=["πŸ₯ Hospital"], label="Select Facility:")
218
- btn = gr.Button(value="πŸš€ Generate")
219
- with gr.Row():
220
- actual_map = gr.Plot(label='Actual Facility Distribution')
221
- solution_map = gr.Plot(label='Relocation Facility Distribution')
222
- with gr.Row():
223
- actual_ac = gr.Textbox(label='Real-world Access Cost')
224
- solution_ac = gr.Textbox(label='Relocation Access Cost')
225
- demo.load(fn=demo_plot, inputs=[city, facility], outputs=[actual_map, solution_map, actual_ac, solution_ac])
226
- btn.click(fn=demo_plot, inputs=[city, facility], outputs=[actual_map, solution_map, actual_ac, solution_ac])
227
-
228
- gr.Markdown("## FLP&IUMFLP Solver")
229
- with gr.Column():
230
- with gr.Row():
231
- data_npy = gr.Textbox(label="Input")
232
- data_file = gr.UploadButton(
233
- label="πŸ“ Upload a npy file",
234
- file_count="multiple",
235
- file_types=[".npy"])
236
- with gr.Row():
237
- boost = gr.Checkbox(label="Turbo Boost", value=False)
238
- btn2 = gr.Button(value="πŸš€ Generate")
239
- with gr.Row():
240
- actual_map = gr.Plot(label='Real-world Facility Distribution')
241
- solution_map = gr.Plot(label='Relocation Facility Distribution')
242
- with gr.Row():
243
- actual_ac = gr.Textbox(label='Real-world Access Cost')
244
- solution_ac = gr.Textbox(label='Relocation Access Cost')
245
- data_file.upload(fn=solver_plot, inputs=[data_file, boost], outputs=[actual_map, solution_map, actual_ac, solution_ac])
246
- btn2.click(fn=solver_plot, inputs=[data_npy, boost], outputs=[actual_map, solution_map, actual_ac, solution_ac])
247
-
248
- gr.Examples(
249
- examples=get_example(),
250
- inputs=[data_npy],
251
- fn=plot_from_npy,
252
- outputs=[actual_map, solution_map],
253
- )
254
-
255
- if __name__ == "__main__":
256
- demo.launch()
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import plotly.graph_objects as go
4
+ import plotly.express as px
5
+ from sklearn.metrics import pairwise_distances
6
+ import torch
7
+
8
+ def plot_from_npy(npy_data):
9
+ fig = go.Figure()
10
+
11
+ fig.add_trace(go.Scatter(x=[1, 2, 3, 4], y=[10, 11, 12, 13], mode='lines', name='New York'))
12
+ fig.update_layout(title_text="Facility Distribution in Cities")
13
+ fig.update_xaxes(title_text="Time")
14
+ fig.update_yaxes(title_text="Facility Count")
15
+
16
+
17
+ actual_fig = fig # Replace this line with your actual_fig
18
+ solution_fig = fig # Replace this line with your solution_fig
19
+
20
+ return actual_fig, solution_fig
21
+
22
+ def solver_plot(data_npy, boost=False):
23
+ actual_fig = go.Figure()
24
+ solution_fig = go.Figure()
25
+ actual_ac = 0 # Replace this line with your actual_ac
26
+ solution_ac = 0 # Replace this line with your solution_ac
27
+ return actual_fig, solution_fig, actual_ac, solution_ac
28
+
29
+ def demo_plot(city, facility):
30
+ facility_name = ["🏫 School", "πŸ₯ Hospital", "🌳 Park"]
31
+ all_facility = ["🏫 School", "πŸ₯ Hospital", "🌳 Park"]
32
+ for i in range(len(all_facility)):
33
+ if all_facility[i] in facility:
34
+ all_facility[i] = True
35
+ else:
36
+ all_facility[i] = False
37
+
38
+ city_name = city.replace(' ', '_')
39
+ data = np.loadtxt(f'demo/{city_name}.npy')
40
+ positions = data[:, :2]
41
+ demands = data[:, 2:5]
42
+ actual_facility = data[:, 5:8]
43
+ solution_facility = data[:, 8:11]
44
+
45
+ actual_fig = go.Figure()
46
+ solution_fig = go.Figure()
47
+ for i in range(len(all_facility)):
48
+ if not all_facility[i]:
49
+ continue
50
+
51
+ actual_fig.add_trace(go.Scattermapbox(
52
+ lat=positions[actual_facility[:, i] == 1][:, 0],
53
+ lon=positions[actual_facility[:, i] == 1][:, 1],
54
+ mode='markers',
55
+ marker=go.scattermapbox.Marker(
56
+ size=10,
57
+ color=px.colors.qualitative.Plotly[i]
58
+ ),
59
+ name=facility_name[i],
60
+ ))
61
+ solution_fig.add_trace(go.Scattermapbox(
62
+ lat=positions[solution_facility[:, i] == 1][:, 0],
63
+ lon=positions[solution_facility[:, i] == 1][:, 1],
64
+ mode='markers',
65
+ marker=go.scattermapbox.Marker(
66
+ size=10,
67
+ color=px.colors.qualitative.Plotly[i]
68
+ ),
69
+ name=facility_name[i],
70
+ ))
71
+
72
+ actual_fig.update_layout(
73
+ mapbox=dict(
74
+ style='carto-positron',
75
+ center=dict(lat=np.mean(positions[actual_facility[:, i] == 1][:, 0]), \
76
+ lon=np.mean(positions[actual_facility[:, i] == 1][:, 1])),
77
+ zoom=11.0
78
+ ),
79
+ margin=dict(l=0, r=0, b=0, t=0),)
80
+
81
+ solution_fig.update_layout(
82
+ mapbox=dict(
83
+ style='carto-positron',
84
+ center=dict(lat=np.mean(positions[solution_facility[:, i] == 1][:, 0]), \
85
+ lon=np.mean(positions[solution_facility[:, i] == 1][:, 1])),
86
+ zoom=11.0
87
+ ),
88
+ margin=dict(l=0, r=0, b=0, t=0),)
89
+ # show legend
90
+ actual_fig.update_layout(showlegend=True)
91
+ solution_fig.update_layout(showlegend=True)
92
+
93
+ positions = np.deg2rad(positions)
94
+ dist = pairwise_distances(positions, metric='haversine') * 6371
95
+ actual_ac = 0
96
+ solution_ac = 0
97
+ for i in range(len(all_facility)):
98
+ if not all_facility[i]:
99
+ continue
100
+ ac_matrix = dist * demands[:, i][:, None]
101
+ actual_ac += ac_matrix[:, actual_facility[:, i] == 1].min(axis=-1).sum()
102
+ solution_ac += ac_matrix[:, solution_facility[:, i] == 1].min(axis=-1).sum()
103
+
104
+ return actual_fig, solution_fig, actual_ac, solution_ac
105
+
106
+
107
+ def solver_plot(data_npy, boost=False):
108
+ data = data_npy.split('\n')
109
+ n = len(data)
110
+ p = int((len(data[0].split(' '))-2) / 2)
111
+
112
+ positions = []
113
+ demands = []
114
+ actual_facilities = []
115
+ for row in data:
116
+ row = row.split(' ')
117
+ row = [x for x in row if len(x)]
118
+ print(row)
119
+
120
+ positions.append([float(row[0]), float(row[1])])
121
+
122
+ demand = []
123
+ for i in range(2, 2+p):
124
+ demand.append(float(row[i]))
125
+ demands.append(demand)
126
+
127
+ actual_facility = []
128
+ for i in range(2+p, 2+2*p):
129
+ actual_facility.append(bool(int(float(row[i]))))
130
+ actual_facilities.append(actual_facility)
131
+ positions = np.array(positions)
132
+ demands = np.array(demands)
133
+ actual_facilities = np.array(actual_facilities)
134
+ solution_facilities = ~actual_facilities
135
+ print(actual_facilities)
136
+
137
+ actual_fig = go.Figure()
138
+ solution_fig = go.Figure()
139
+ for i in range(p):
140
+ actual_fig.add_trace(go.Scattermapbox(
141
+ lat=positions[actual_facilities[:, i]][:, 0],
142
+ lon=positions[actual_facilities[:, i]][:, 1],
143
+ mode='markers',
144
+ marker=go.scattermapbox.Marker(
145
+ size=10,
146
+ color=px.colors.qualitative.Plotly[i]
147
+ ),
148
+ name=f'Facility {i+1}'
149
+ ))
150
+ solution_fig.add_trace(go.Scattermapbox(
151
+ lat=positions[solution_facilities[:, i]][:, 0],
152
+ lon=positions[solution_facilities[:, i]][:, 1],
153
+ mode='markers',
154
+ marker=go.scattermapbox.Marker(
155
+ size=10,
156
+ color=px.colors.qualitative.Plotly[i]
157
+ ),
158
+ name=f'Facility {i+1}'
159
+ ))
160
+
161
+ actual_fig.update_layout(
162
+ mapbox=dict(
163
+ style='carto-positron',
164
+ center=dict(lat=np.mean(positions[actual_facilities[:, i]][:, 0]), \
165
+ lon=np.mean(positions[actual_facilities[:, i]][:, 1])),
166
+ zoom=11.0
167
+ ),
168
+ margin=dict(l=0, r=0, b=0, t=0),)
169
+
170
+ solution_fig.update_layout(
171
+ mapbox=dict(
172
+ style='carto-positron',
173
+ center=dict(lat=np.mean(positions[solution_facilities[:, i]][:, 0]), \
174
+ lon=np.mean(positions[solution_facilities[:, i]][:, 1])),
175
+ zoom=11.0
176
+ ),
177
+ margin=dict(l=0, r=0, b=0, t=0),)
178
+ # show legend
179
+ actual_fig.update_layout(showlegend=True)
180
+ solution_fig.update_layout(showlegend=True)
181
+
182
+ positions = np.deg2rad(positions)
183
+ dist = pairwise_distances(positions, metric='haversine') * 6371
184
+ actual_ac = 0
185
+ solution_ac = 0
186
+ for i in range(p):
187
+ ac_matrix = dist * demands[:, i][:, None]
188
+ actual_ac += ac_matrix[:, actual_facilities[:, i]].min(axis=-1).sum()
189
+ solution_ac += ac_matrix[:, solution_facilities[:, i]].min(axis=-1).sum()
190
+
191
+ return actual_fig, solution_fig, actual_ac, solution_ac
192
+
193
+
194
+ def get_example():
195
+ return [
196
+ ('40.71 -73.93 213 0\n40.72 -73.99 15 1\n40.65 -73.88 365 1\n40.57 -73.96 629 0\n40.70 -73.97 106 0\n40.61 -73.95 189 1'),
197
+ ("40.71 -73.93 213 124 0 1\n40.72 -73.99 15 43 1 0\n40.65 -73.88 365 214 1 0\n40.57 -73.96 629 431 0 1\n40.70 -73.97 106 241 0 1\n40.61 -73.95 189 264 1 0")
198
+ ]
199
+
200
+
201
+ def load_npy_file(file_obj):
202
+ data = np.load(file_obj.name)
203
+ string_array = '\n'.join([' '.join(map(str, row)) for row in data])
204
+ return string_array
205
+
206
+
207
+ with gr.Blocks() as demo:
208
+ gr.Markdown("## Demo")
209
+ with gr.Column():
210
+ city = gr.Radio(choices=["New York", "Boston", "Los Angeles", "Chicago"], value="New York", label="Select City:")
211
+ facility = gr.CheckboxGroup(choices=["🏫 School", "πŸ₯ Hospital", "🌳 Park"], value=["πŸ₯ Hospital"], label="Select Facility:")
212
+ btn = gr.Button(value="πŸš€ Generate")
213
+ with gr.Row():
214
+ actual_map = gr.Plot(label='Actual Facility Distribution')
215
+ solution_map = gr.Plot(label='Relocated Facility Distribution')
216
+ with gr.Row():
217
+ actual_ac = gr.Textbox(label='Real-world Access Cost')
218
+ solution_ac = gr.Textbox(label='Relocated Access Cost')
219
+ demo.load(fn=demo_plot, inputs=[city, facility], outputs=[actual_map, solution_map, actual_ac, solution_ac])
220
+ btn.click(fn=demo_plot, inputs=[city, facility], outputs=[actual_map, solution_map, actual_ac, solution_ac])
221
+
222
+ gr.Markdown("## FLP & IUMFLP Solver")
223
+ with gr.Column():
224
+ with gr.Row():
225
+ data_npy = gr.Textbox(label="Input")
226
+ data_file = gr.UploadButton(
227
+ label="πŸ“ Upload a npy file",
228
+ file_count="single",
229
+ file_types=[".npy"])
230
+ with gr.Row():
231
+ gr.Examples(
232
+ examples=get_example(),
233
+ inputs=[data_npy],
234
+ fn=plot_from_npy,
235
+ outputs=[actual_map, solution_map],
236
+ )
237
+ with gr.Row():
238
+ boost = gr.Checkbox(label="Turbo Boost (accelerate solution generation with fewer SWAP steps)", value=False)
239
+ btn2 = gr.Button(value="πŸš€ Generate")
240
+ with gr.Row():
241
+ actual_map = gr.Plot(label='Initial Solution')
242
+ solution_map = gr.Plot(label='Final Solution')
243
+ with gr.Row():
244
+ actual_ac = gr.Textbox(label='Initial Access Cost')
245
+ solution_ac = gr.Textbox(label='Final Access Cost')
246
+ data_file.upload(fn=load_npy_file, inputs=[data_file], outputs=[data_npy])
247
+ btn2.click(fn=solver_plot, inputs=[data_npy, boost], outputs=[actual_map, solution_map, actual_ac, solution_ac])
248
+
249
+ if __name__ == "__main__":
250
+ demo.launch()