KrihsM commited on
Commit
dc622ef
·
verified ·
1 Parent(s): 032675d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -93
app.py CHANGED
@@ -1,8 +1,3 @@
1
- import io
2
- import os
3
- import glob
4
- import tempfile
5
-
6
  import pandas as pd
7
  import numpy as np
8
  import gradio as gr
@@ -11,12 +6,14 @@ import h3.api.basic_str as h3
11
  import folium
12
  from shapely.geometry import Polygon
13
  import geopandas as gpd
 
 
 
 
14
 
15
  # Define feature lists & descriptions
16
- PRIMARY_FEATURES = ['OEM Critical Facilities', 'Flooding', 'METRO',
17
- 'HPW Critical Facilities', 'Other Critical Facilities']
18
- SECONDARY_FEATURES = ['PCI', 'ADT', 'RPL_THEME_1', 'RPL_THEME_2',
19
- 'RPL_THEME_3', 'RPL_THEME_4', 'RPL_THEME_ALL']
20
  ALL_FEATURES = PRIMARY_FEATURES + SECONDARY_FEATURES
21
  EXTRA_COLUMNS = ['PCI Score', 'SURFACETYP', 'METRO_ROUTES', 'STREETNAME']
22
 
@@ -35,27 +32,40 @@ FEATURE_DESCRIPTIONS = {
35
  'RPL_THEME_ALL': 'Overall social vulnerability (combined).'
36
  }
37
 
 
 
38
  def load_data(path="./MainInstances.xlsx"):
39
  df = pd.read_excel(path, dtype={'SURFACETYP': str})
40
  df.columns = df.columns.str.strip()
 
 
 
 
41
  for col in ['GRID_ID'] + ALL_FEATURES + ['PCI Score', 'METRO_ROUTES', 'STREETNAME']:
42
  if col not in df.columns:
43
- df[col] = 0 if col not in ['GRID_ID','SURFACETYP','STREETNAME'] else ''
44
- df = df[['GRID_ID'] + ALL_FEATURES + ['PCI Score', 'SURFACETYP', 'METRO_ROUTES', 'STREETNAME']]
 
 
 
45
  num_cols = ALL_FEATURES + ['PCI Score', 'METRO_ROUTES']
46
  df[num_cols] = df[num_cols].apply(pd.to_numeric, errors='coerce').fillna(0)
 
47
  df['SURFACETYP'] = df['SURFACETYP'].fillna('').astype(str).str.strip()
48
  return df
49
 
 
50
  def h3_poly_coords(h3_id):
51
  return [(lat, lon) for lat, lon in h3.cell_to_boundary(h3_id)]
52
 
 
53
  def calculate_index(df, features, weights):
54
  w = np.array(weights) / np.sum(weights)
55
  df_idx = df.copy()
56
  df_idx['Index'] = df_idx[features].values.dot(w)
57
  return df_idx
58
 
 
59
  def stats_text(df_idx):
60
  s = df_idx['Index'].describe()
61
  return (
@@ -67,6 +77,7 @@ def stats_text(df_idx):
67
  f"- Max: {s['max']:.4f}"
68
  )
69
 
 
70
  def make_histogram(df_idx):
71
  fig, ax = plt.subplots()
72
  ax.hist(df_idx['Index'], bins=30)
@@ -77,6 +88,7 @@ def make_histogram(df_idx):
77
  plt.close(fig)
78
  return fig
79
 
 
80
  def create_index_map(df_idx, features):
81
  sel = df_idx[df_idx['Index'] >= df_idx['Index'].quantile(0.5)]
82
  center = (29.76, -95.37)
@@ -85,6 +97,7 @@ def create_index_map(df_idx, features):
85
  m = folium.Map(location=center, zoom_start=10)
86
  for _, row in sel.iterrows():
87
  idx = row['Index']
 
88
  norm = (idx - sel['Index'].min()) / (sel['Index'].max() - sel['Index'].min()) if sel['Index'].max() > sel['Index'].min() else 0.5
89
  color = f"rgb({int(255*norm)},0,{int(255*(1-norm))})"
90
  popup = "<br>".join(
@@ -94,21 +107,17 @@ def create_index_map(df_idx, features):
94
  )
95
  folium.Polygon(
96
  locations=h3_poly_coords(row['GRID_ID']),
97
- color='black', fill=True,
98
- fill_color=color, fill_opacity=0.6 if 3 <= idx <= 4 else 0,
99
  popup=popup
100
  ).add_to(m)
101
- legend = '''
102
- <div style="position: fixed; top:10px; right:10px; background:white;
103
- padding:8px; border:1px solid #ccc; z-index:9999;">
104
- <b>Index</b><br>
105
- <i style="background: rgb(0,0,255);opacity:0.6;padding:2px;">&nbsp;</i> 3–4<br>
106
- <i style="background:transparent;border:1px solid #ccc;padding:2px;">&nbsp;</i> outside
107
- </div>
108
- '''
109
  m.get_root().html.add_child(folium.Element(legend))
110
  return m._repr_html_()
111
 
 
112
  def find_clusters(hex_ids, min_size):
113
  clusters, visited = [], set()
114
  for h in hex_ids:
@@ -126,67 +135,37 @@ def find_clusters(hex_ids, min_size):
126
  clusters.append(cluster)
127
  return clusters
128
 
 
 
129
  def create_cluster_outputs(df_idx, threshold, min_size):
130
  filt = df_idx[df_idx['Index'] >= threshold]
131
  if filt.empty:
132
- return "No hexes above threshold.", None, None
133
  clusters = find_clusters(filt['GRID_ID'].tolist(), min_size)
134
  if not clusters:
135
- return "No clusters found.", None, None
136
  ids = set().union(*clusters)
137
  table = df_idx[df_idx['GRID_ID'].isin(ids)][['GRID_ID','Index'] + EXTRA_COLUMNS]
138
  m = folium.Map(location=h3.cell_to_latlng(next(iter(ids))), zoom_start=10)
139
  for _, row in table.iterrows():
140
- folium.Polygon(locations=h3_poly_coords(row['GRID_ID']),
141
- color='blue', fill=True, fill_opacity=0.6).add_to(m)
142
- return "Clusters ready!", m._repr_html_(), table
143
-
144
- # --- New: prepare data & in-memory ZIP functions ---
145
- def prepare_data(wt, threshold, min_size):
146
- # Reconstruct weights DataFrame
147
- df_wt = pd.DataFrame(wt, columns=["Feature","Description","Weight"])
148
- df_wt['Weight'] = pd.to_numeric(df_wt['Weight'], errors='coerce').fillna(0)
149
- sel = df_wt[df_wt['Weight'] > 0]
150
- df = load_data()
151
- df_idx = calculate_index(df, sel['Feature'].tolist(), sel['Weight'].tolist())
152
- filt = df_idx[df_idx['Index'] >= threshold]
153
- clusters = find_clusters(filt['GRID_ID'].tolist(), int(min_size))
154
- ids = set().union(*clusters) if clusters else set()
155
- table = df_idx[df_idx['GRID_ID'].isin(ids)][['GRID_ID','Index'] + EXTRA_COLUMNS]
156
- polys = [Polygon(h3.cell_to_boundary(h)) for h in ids]
157
- return table, polys
158
-
159
- def make_shapefile_zip(wt, threshold, min_size):
160
- table, polys = prepare_data(wt, threshold, min_size)
161
- gdf = gpd.GeoDataFrame(table, geometry=polys, crs='EPSG:4326')
162
- # Write shapefile parts to temp dir, then zip in-memory
163
- mem = io.BytesIO()
164
- with tempfile.TemporaryDirectory() as tmpdir:
165
- base = os.path.join(tmpdir, 'focus_area')
166
- gdf.to_file(base + '.shp') # creates .shp, .shx, .dbf, .prj
167
- with zipfile.ZipFile(mem, mode='w') as zf:
168
- for fname in glob.glob(base + '.*'):
169
- zf.write(fname, arcname=os.path.basename(fname))
170
- mem.seek(0)
171
- return mem
172
-
173
- # --- Build Gradio app ---
174
  def create_app():
175
  df = load_data()
176
-
177
  with gr.Blocks() as app:
178
- gr.Markdown("# Focus Area Identification by Creating a Risk Index")
179
  gr.Markdown("Build a custom risk index for Houston thoroughfare hexes by assigning feature weights.")
180
 
181
- # --- Step 1: Weights & Index ---
182
  gr.Markdown("### Step 1: Assign weights to features")
183
  init = pd.DataFrame({
184
  "Feature": ALL_FEATURES,
185
  "Description": [FEATURE_DESCRIPTIONS[f] for f in ALL_FEATURES],
186
  "Weight": [0]*len(ALL_FEATURES)
187
  })
188
- wf = gr.Dataframe(value=init, headers=["Feature","Description","Weight"],
189
- datatype=["str","str","number"], interactive=True)
190
  btn1 = gr.Button("Calculate Index")
191
  stat_msg = gr.Markdown()
192
  out_stats = gr.Markdown()
@@ -194,49 +173,73 @@ def create_app():
194
  out_map = gr.HTML()
195
 
196
  def calc(wt):
197
- df_wt = pd.DataFrame(wt, columns=["Feature","Description","Weight"])
198
- df_wt['Weight'] = pd.to_numeric(df_wt['Weight'], errors='coerce').fillna(0)
199
- sel = df_wt[df_wt['Weight'] > 0]
200
- if not np.isclose(sel['Weight'].sum(), 100):
201
- raise ValueError(f"Weights sum to {sel['Weight'].sum():.2f}, must be 100.")
202
- df_idx = calculate_index(df, sel['Feature'].tolist(), sel['Weight'].tolist())
203
- return ("Risk Index created!",
204
- stats_text(df_idx),
205
- make_histogram(df_idx),
206
- create_index_map(df_idx, sel['Feature'].tolist()))
207
 
208
  btn1.click(calc, inputs=[wf], outputs=[stat_msg, out_stats, out_hist, out_map])
209
 
210
- # --- Step 2: Clustering & Download ---
211
  gr.Markdown("### Step 2: Prioritized Focus Area Creation")
212
  thr = gr.Number(label="Index Threshold", value=3)
213
  ms = gr.Number(label="Minimum Cluster Size", value=3)
214
  btn2 = gr.Button("Create Clusters")
215
  cl_msg = gr.Markdown()
216
  cl_map = gr.HTML()
217
- cl_tbl = gr.Dataframe(label="Focus Area Hexes Data", interactive=False)
218
-
219
- btn2.click(lambda wt, t, m: create_cluster_outputs(
220
- calculate_index(df,
221
- pd.DataFrame(wt, columns=["Feature","Description","Weight"])
222
- .assign(Weight=lambda x: pd.to_numeric(x.Weight, errors='coerce').fillna(0))
223
- .query("Weight>0")[["Feature","Weight"]]
224
- .pipe(lambda df2: (df2.Feature.tolist(), df2.Weight.tolist()))),
225
- thr, ms),
226
- inputs=[wf, thr, ms],
227
- outputs=[cl_msg, cl_map, cl_tbl])
228
-
229
- # DownloadButton for in-memory ZIP
230
- download_btn = gr.DownloadButton(
231
- label="Download Focus Area Shapefile Zip",
232
- fn=make_shapefile_zip,
233
- inputs=[wf, thr, ms],
234
- file_name="focus_area.zip"
235
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
  return app
238
 
239
  if __name__ == '__main__':
240
  app = create_app()
241
  app.queue()
242
- app.launch(debug=True, show_error=True)
 
 
 
 
 
 
1
  import pandas as pd
2
  import numpy as np
3
  import gradio as gr
 
6
  import folium
7
  from shapely.geometry import Polygon
8
  import geopandas as gpd
9
+ import tempfile
10
+ import zipfile
11
+ import os
12
+ import glob
13
 
14
  # Define feature lists & descriptions
15
+ PRIMARY_FEATURES = ['OEM Critical Facilities', 'Flooding', 'METRO', 'HPW Critical Facilities', 'Other Critical Facilities']
16
+ SECONDARY_FEATURES = ['PCI', 'ADT', 'RPL_THEME_1', 'RPL_THEME_2', 'RPL_THEME_3', 'RPL_THEME_4', 'RPL_THEME_ALL']
 
 
17
  ALL_FEATURES = PRIMARY_FEATURES + SECONDARY_FEATURES
18
  EXTRA_COLUMNS = ['PCI Score', 'SURFACETYP', 'METRO_ROUTES', 'STREETNAME']
19
 
 
32
  'RPL_THEME_ALL': 'Overall social vulnerability (combined).'
33
  }
34
 
35
+ # Load data including SurfaceTyp only once
36
+
37
  def load_data(path="./MainInstances.xlsx"):
38
  df = pd.read_excel(path, dtype={'SURFACETYP': str})
39
  df.columns = df.columns.str.strip()
40
+ # Ensure SurfaceTyp column exists
41
+ if 'SURFACETYP' not in df.columns:
42
+ df['SURFACETYP'] = ''
43
+ # Ensure other columns exist
44
  for col in ['GRID_ID'] + ALL_FEATURES + ['PCI Score', 'METRO_ROUTES', 'STREETNAME']:
45
  if col not in df.columns:
46
+ df[col] = 0
47
+ # Trim to needed columns
48
+ cols = ['GRID_ID'] + ALL_FEATURES + ['PCI Score', 'SURFACETYP', 'METRO_ROUTES', 'STREETNAME']
49
+ df = df[cols]
50
+ # Convert numeric fields
51
  num_cols = ALL_FEATURES + ['PCI Score', 'METRO_ROUTES']
52
  df[num_cols] = df[num_cols].apply(pd.to_numeric, errors='coerce').fillna(0)
53
+ # Clean SurfaceTyp
54
  df['SURFACETYP'] = df['SURFACETYP'].fillna('').astype(str).str.strip()
55
  return df
56
 
57
+ # H3 boundary to coords
58
  def h3_poly_coords(h3_id):
59
  return [(lat, lon) for lat, lon in h3.cell_to_boundary(h3_id)]
60
 
61
+ # Compute weighted index
62
  def calculate_index(df, features, weights):
63
  w = np.array(weights) / np.sum(weights)
64
  df_idx = df.copy()
65
  df_idx['Index'] = df_idx[features].values.dot(w)
66
  return df_idx
67
 
68
+ # Stats markdown
69
  def stats_text(df_idx):
70
  s = df_idx['Index'].describe()
71
  return (
 
77
  f"- Max: {s['max']:.4f}"
78
  )
79
 
80
+ # Histogram
81
  def make_histogram(df_idx):
82
  fig, ax = plt.subplots()
83
  ax.hist(df_idx['Index'], bins=30)
 
88
  plt.close(fig)
89
  return fig
90
 
91
+ # Create index map
92
  def create_index_map(df_idx, features):
93
  sel = df_idx[df_idx['Index'] >= df_idx['Index'].quantile(0.5)]
94
  center = (29.76, -95.37)
 
97
  m = folium.Map(location=center, zoom_start=10)
98
  for _, row in sel.iterrows():
99
  idx = row['Index']
100
+ fill_opacity = 0.6 if 3 <= idx <= 4 else 0
101
  norm = (idx - sel['Index'].min()) / (sel['Index'].max() - sel['Index'].min()) if sel['Index'].max() > sel['Index'].min() else 0.5
102
  color = f"rgb({int(255*norm)},0,{int(255*(1-norm))})"
103
  popup = "<br>".join(
 
107
  )
108
  folium.Polygon(
109
  locations=h3_poly_coords(row['GRID_ID']),
110
+ color='black', fill=True, fill_color=color, fill_opacity=fill_opacity,
 
111
  popup=popup
112
  ).add_to(m)
113
+ legend = '''<div style="position: fixed; top:10px; right:10px; background:white; padding:8px; border:1px solid #ccc; z-index:9999;">
114
+ <b>Index</b><br><i style="background: rgb(0,0,255);opacity:0.6;padding:2px;">&nbsp;</i> 3–4<br>
115
+ <i style="background:transparent;border:1px solid #ccc;padding:2px;">&nbsp;</i> outside
116
+ </div>'''
 
 
 
 
117
  m.get_root().html.add_child(folium.Element(legend))
118
  return m._repr_html_()
119
 
120
+ # Clustering logic
121
  def find_clusters(hex_ids, min_size):
122
  clusters, visited = [], set()
123
  for h in hex_ids:
 
135
  clusters.append(cluster)
136
  return clusters
137
 
138
+ # Generate clusters map/table
139
+
140
  def create_cluster_outputs(df_idx, threshold, min_size):
141
  filt = df_idx[df_idx['Index'] >= threshold]
142
  if filt.empty:
143
+ return "No hexes above threshold.", None, None, None
144
  clusters = find_clusters(filt['GRID_ID'].tolist(), min_size)
145
  if not clusters:
146
+ return "No clusters found.", None, None, None
147
  ids = set().union(*clusters)
148
  table = df_idx[df_idx['GRID_ID'].isin(ids)][['GRID_ID','Index'] + EXTRA_COLUMNS]
149
  m = folium.Map(location=h3.cell_to_latlng(next(iter(ids))), zoom_start=10)
150
  for _, row in table.iterrows():
151
+ folium.Polygon(locations=h3_poly_coords(row['GRID_ID']), color='blue', fill=True, fill_opacity=0.6).add_to(m)
152
+ return "Clusters ready!", m._repr_html_(), table, None
153
+
154
+ # Build Gradio app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  def create_app():
156
  df = load_data()
 
157
  with gr.Blocks() as app:
158
+ gr.Markdown("# Focus Area Identification by creating a Risk Index")
159
  gr.Markdown("Build a custom risk index for Houston thoroughfare hexes by assigning feature weights.")
160
 
161
+ # Feature Weights
162
  gr.Markdown("### Step 1: Assign weights to features")
163
  init = pd.DataFrame({
164
  "Feature": ALL_FEATURES,
165
  "Description": [FEATURE_DESCRIPTIONS[f] for f in ALL_FEATURES],
166
  "Weight": [0]*len(ALL_FEATURES)
167
  })
168
+ wf = gr.Dataframe(value=init, headers=["Feature","Description","Weight"], datatype=["str","str","number"], interactive=True)
 
169
  btn1 = gr.Button("Calculate Index")
170
  stat_msg = gr.Markdown()
171
  out_stats = gr.Markdown()
 
173
  out_map = gr.HTML()
174
 
175
  def calc(wt):
176
+ try:
177
+ df_wt = pd.DataFrame(wt, columns=["Feature","Description","Weight"]) if isinstance(wt, list) else wt
178
+ df_wt['Weight'] = pd.to_numeric(df_wt['Weight'], errors='coerce').fillna(0)
179
+ sel = df_wt[df_wt['Weight']>0]
180
+ if not np.isclose(sel['Weight'].sum(), 100):
181
+ raise ValueError(f"Weights sum to {sel['Weight'].sum():.2f}, must be 100.")
182
+ df_idx = calculate_index(df, sel['Feature'].tolist(), sel['Weight'].tolist())
183
+ return "Risk Index created!", stats_text(df_idx), make_histogram(df_idx), create_index_map(df_idx, sel['Feature'].tolist())
184
+ except Exception as e:
185
+ return f"⚠️ Error calculating index: {e}", None, None, None
186
 
187
  btn1.click(calc, inputs=[wf], outputs=[stat_msg, out_stats, out_hist, out_map])
188
 
189
+ # Clustering
190
  gr.Markdown("### Step 2: Prioritized Focus Area Creation")
191
  thr = gr.Number(label="Index Threshold", value=3)
192
  ms = gr.Number(label="Minimum Cluster Size", value=3)
193
  btn2 = gr.Button("Create Clusters")
194
  cl_msg = gr.Markdown()
195
  cl_map = gr.HTML()
196
+ cl_tbl = gr.Dataframe(label="Focus Area Hexes Data")
197
+ cl_zip = gr.File(label="Download Focus Area Shapefile Zip")
198
+
199
+ def cluster(wt, t, msize):
200
+ try:
201
+ df_wt = pd.DataFrame(wt, columns=["Feature","Description","Weight"]) if isinstance(wt, list) else wt
202
+ df_wt['Weight'] = pd.to_numeric(df_wt['Weight'], errors='coerce').fillna(0)
203
+ sel = df_wt[df_wt['Weight']>0]
204
+ if not np.isclose(sel['Weight'].sum(), 100):
205
+ raise ValueError(f"Weights sum to {sel['Weight'].sum():.2f}, must be 100.")
206
+ df_idx = calculate_index(df, sel['Feature'].tolist(), sel['Weight'].tolist())
207
+ return create_cluster_outputs(df_idx, t, int(msize))
208
+ except Exception as e:
209
+ return f"⚠️ Error clustering: {e}", None, None, None
210
+
211
+ btn2.click(cluster, inputs=[wf, thr, ms], outputs=[cl_msg, cl_map, cl_tbl, cl_zip])
212
+
213
+ # On-demand download
214
+ def download_shp(wt, t, msize):
215
+ try:
216
+ df_wt = pd.DataFrame(wt, columns=["Feature","Description","Weight"]) if isinstance(wt, list) else wt
217
+ df_wt['Weight'] = pd.to_numeric(df_wt['Weight'], errors='coerce').fillna(0)
218
+ sel = df_wt[df_wt['Weight']>0]
219
+ df_idx = calculate_index(df, sel['Feature'].tolist(), sel['Weight'].tolist())
220
+ filt = df_idx[df_idx['Index'] >= t]
221
+ clusters = find_clusters(filt['GRID_ID'].tolist(), int(msize))
222
+ ids = set().union(*clusters) if clusters else []
223
+ table = df_idx[df_idx['GRID_ID'].isin(ids)][['GRID_ID','Index'] + EXTRA_COLUMNS]
224
+ tmp = tempfile.mkdtemp()
225
+ base = os.path.join(tmp, 'focus_area')
226
+ polys = [Polygon(h3.cell_to_boundary(h)) for h in ids]
227
+ gdf = gpd.GeoDataFrame(table, geometry=polys, crs='EPSG:4326')
228
+ gdf.to_file(base + '.shp')
229
+ zip_path = base + '.zip'
230
+ with zipfile.ZipFile(zip_path, 'w') as zf:
231
+ for f in glob.glob(base + '.*'):
232
+ zf.write(f, arcname=os.path.basename(f))
233
+ return zip_path
234
+ except Exception as e:
235
+ return None
236
+
237
+ download_btn = gr.Button("Download Focus Area Shapefile Zip")
238
+ download_btn.click(download_shp, inputs=[wf, thr, ms], outputs=[cl_zip])
239
 
240
  return app
241
 
242
  if __name__ == '__main__':
243
  app = create_app()
244
  app.queue()
245
+ app.launch(debug=True, show_error=True)