dhammo2 commited on
Commit
5ed3053
·
verified ·
1 Parent(s): bc5605e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1098 -1098
app.py CHANGED
@@ -1,1098 +1,1098 @@
1
- ## MOPAC Spatial Propensity Matching
2
-
3
- ## Daniel Hammocks - 2024-08-14
4
- ## GH: dhammo2
5
-
6
- ## This code takes the JSON extracted from the Metropolitan Police R HTML Ouput
7
- ## and creates a geoJSON/Shapefile of control and intervention groups including
8
- ## all data displayed on the graph.
9
-
10
- ###############################################################################
11
- ################################# APPLICATION #################################
12
- ###############################################################################
13
-
14
-
15
- #%% Versioning
16
-
17
- # v1.0.0 - Original Dashboard
18
- # v2.0.0 - Introduced Download Option
19
- # v3.0.0 - Added Multi-Page Functionality
20
- # v4.0.0 - Introduced Quality Assurance
21
- # - Altered Calculation for PSM to search control only.
22
- # v5.0.0 - Ensure that Area Matching Does Not Return Self
23
- # v6.0.0 - Added Quality Assurance
24
- # v7.0.0 - Complete Quality Assurance Information
25
-
26
-
27
- #%% NOTES
28
-
29
- #DISABLE LOGGING WHEN DONE
30
-
31
- #Put Error Notices for QA at top.
32
-
33
- #%% Required Libraries
34
-
35
- import dash
36
- import dash_bootstrap_components as dbc
37
- from dash import dcc, html, Input, Output, State
38
- import pandas as pd
39
- import numpy as np
40
- from sklearn.linear_model import LogisticRegression
41
- from sklearn.neighbors import NearestNeighbors
42
- from sklearn.preprocessing import StandardScaler
43
- import io
44
- import base64
45
- from datetime import datetime
46
- from scipy import stats
47
- import plotly.graph_objects as go
48
- from scipy.stats import gaussian_kde
49
-
50
-
51
- import logging
52
- import os
53
-
54
-
55
-
56
-
57
- #%% App Initialisation
58
-
59
- # Initialize the Dash app
60
- app = dash.Dash(__name__, suppress_callback_exceptions=True, external_stylesheets=[dbc.themes.BOOTSTRAP])
61
-
62
- app.title = "MOPAC | DS"
63
-
64
- logging.basicConfig(level=logging.DEBUG)
65
-
66
- #%% Navigation Layout
67
-
68
-
69
- navbar = dbc.NavbarSimple(
70
- children=[
71
- dbc.NavItem(dbc.NavLink("Overview", href="/")),
72
- dbc.NavItem(dbc.NavLink("Area Similarity & Matching", href="/match")),
73
- dbc.NavItem(dbc.NavLink("Quality Assurance", href="/quality")),
74
-
75
- ],
76
- brand="MOPAC | DS - Area Similarity and Matching Application",
77
- brand_href="#",
78
- color="primary",
79
- dark=True,
80
- fluid=True
81
- )
82
-
83
-
84
- #%% Page Layout
85
-
86
- overview_layout = html.Div(
87
- children=[html.Br(),
88
- html.H1(children="Overview"),
89
- html.P("This application enables users to identify similar "
90
- "geographic areas based on a set of covariates "
91
- "(characteristics) related to each area. Two methods have "
92
- "been implemented enabling the user to both identify "
93
- "similar areas based on a set of characteristics but to "
94
- "also identify similar areas once a treatment has already "
95
- "been assigned. The two methods are detailed below."),
96
-
97
- html.Br(),
98
- html.Hr(),
99
-
100
- html.H3('Data Formatting Requirements'),
101
- html.Div([
102
- html.Div([
103
- html.H4('Example Data Structure'),
104
-
105
- html.Br(),
106
-
107
- html.Table([
108
- html.Thead(
109
- html.Tr([
110
- html.Th('Area_ID', style={'border': '1px solid black'}),
111
- html.Th('Population', style={'border': '1px solid black'}),
112
- html.Th('Income', style={'border': '1px solid black'}),
113
- html.Th('Education', style={'border': '1px solid black'}),
114
- html.Th('Treatment (optional)', style={'border': '1px solid black'})
115
- ], style={'background-color': '#f2f2f2', 'font-weight': 'bold', 'text-align': 'center'})
116
- ),
117
- html.Tbody([
118
- html.Tr([
119
- html.Td('Area_001', style={'border': '1px solid black'}),
120
- html.Td('10000', style={'border': '1px solid black'}),
121
- html.Td('50000', style={'border': '1px solid black'}),
122
- html.Td('12', style={'border': '1px solid black'}),
123
- html.Td('1', style={'border': '1px solid black'})
124
- ]),
125
- html.Tr([
126
- html.Td('Area_002', style={'border': '1px solid black'}),
127
- html.Td('15000', style={'border': '1px solid black'}),
128
- html.Td('60000', style={'border': '1px solid black'}),
129
- html.Td('14', style={'border': '1px solid black'}),
130
- html.Td('0', style={'border': '1px solid black'})
131
- ]),
132
- html.Tr([
133
- html.Td('Area_003', style={'border': '1px solid black'}),
134
- html.Td('12000', style={'border': '1px solid black'}),
135
- html.Td('55000', style={'border': '1px solid black'}),
136
- html.Td('13', style={'border': '1px solid black'}),
137
- html.Td('1', style={'border': '1px solid black'})
138
- ]),
139
- html.Tr([
140
- html.Td('...', style={'border': '1px solid black'}),
141
- html.Td('...', style={'border': '1px solid black'}),
142
- html.Td('...', style={'border': '1px solid black'}),
143
- html.Td('...', style={'border': '1px solid black'}),
144
- html.Td('...', style={'border': '1px solid black'})
145
- ])
146
- ], style={'text-align': 'center'}),
147
- ], style={
148
- 'width': '80%',
149
- 'border-collapse': 'collapse',
150
- 'margin-top': '10px',
151
- 'border': '1px solid black'
152
- }),
153
-
154
- html.Br(),
155
- html.A(
156
- html.Img(src='assets/DataOverview.png',
157
- style={'width': '85%', 'height': 'auto'})
158
- , href="assets/DataOverview.png", target="_blank", style={'font-size': '20px', 'text-decoration': 'none', 'color': 'blue'}),
159
- html.P("Click to Expand.", style={'width': '85%', 'textAlign': 'center'})
160
-
161
-
162
-
163
- ], style={'width': '33%', 'display': 'inline-block', 'vertical-align': 'top'}),
164
-
165
-
166
- html.Div([
167
- html.H4('Required Data Format'),
168
- html.P('To use the Area Similarity and Matching application, please provide your data in a CSV format with the following structure:'),
169
-
170
- html.H5('1. Area ID/Name'),
171
- html.P('A unique identifier or name for each area (e.g., "Area_ID" or "Area_Name"). This will be used to identify and match areas.'),
172
-
173
- html.H5('2. Covariate Columns'),
174
- html.P('One or more columns containing the demographic or other relevant variables (covariates) that will be used to compare areas. Examples include population, income, education level, etc.'),
175
-
176
- html.H5('3. [Optional] Treatment Column'),
177
- html.P('The treatment column is optional but can be included if you want to perform Propensity Score Matching (PSM). This should be a binary column indicating whether an area has received a treatment (e.g., "Treatment", where 1 = treated, 0 = not treated). If this column is provided, the application will use it to perform PSM. If not provided, the application will simply match areas based on similarity using covariates.'),
178
-
179
- html.H4('Key Points'),
180
- html.Ul([
181
- html.Li('The Area ID/Name must be unique for each area.'),
182
- html.Li('Covariates should be numeric and relevant to the analysis.'),
183
- html.Li('The Treatment column is optional; if included, it allows for Propensity Score Matching, otherwise, the app can identify similar areas without considering treatment.')
184
- ])
185
- ], style={'width': '66%', 'display': 'inline-block', 'vertical-align': 'top'}),
186
- ]),
187
-
188
-
189
- html.Hr(),
190
- dbc.Row([
191
-
192
- dbc.Col([
193
- html.H3("Propensity Score Matching (PSM)"),
194
- html.B("This method assumes the treatment areas are known.", style={'color':'red'}),
195
-
196
- html.H5('What is the Goal?'),
197
- html.P('The goal of PSM is to find areas that are most similar to each other based on certain covariates (characteristics like population, income, etc.) in order to balance the covariates between the treatment and control groups. By ensuring that the treatment and control groups are balanced in terms of covariates, PSM helps reduce confounding bias, leading to more accurate estimates of the treatment effect.'),
198
-
199
- html.H5('Step 1: Collect Information'),
200
- html.Ul([
201
- html.Li('Start with a list of areas that received a "treatment" (e.g., a new program or policy) and potential control areas.'),
202
- html.Li('Gather information (like demographics) about both treated and nearby areas.')
203
- ]),
204
-
205
- html.H5('Step 2: Calculate a Score (Using Logistic Regression)'),
206
- html.Ul([
207
- html.Li('Use a statistical method called logistic regression to calculate a "score" for each area.'),
208
- html.Li('This propensity score tells us how likely each area is to have received the treatment based on its characteristics.')
209
- ]),
210
-
211
- html.H5('Step 3: Match Areas (Using Nearest Neighbor)'),
212
- html.Ul([
213
- html.Li('For each treated area, find a similar untreated area with the closest score.'),
214
- html.Li('This is like finding the "nearest neighbor" in terms of similarity.')
215
- ]),
216
-
217
- html.H5('Step 4: Identify Similar Areas'),
218
- html.Ul([
219
- html.Li('After matching, you have pairs of areas where each treated area is matched with a nearby area that is most similar based on the characteristics considered.')
220
- ]),
221
-
222
- html.H5('Result'),
223
- html.P('We now know which areas are most similar to each other, helping us understand the impact of the treatment by comparing them.')
224
-
225
- ], width = 6),
226
-
227
- dbc.Col([
228
- html.H3("Nearest Neighbour Matching (NNM)"),
229
-
230
- html.H5('What is the Goal?'),
231
- html.P('We want to find areas that are most similar to each other based on certain characteristics (like population, income, etc.), without focusing on any specific treatment.'),
232
-
233
- html.H5('Step 1: Collect Information'),
234
- html.Ul([
235
- html.Li('Start by gathering information about the areas you are interested in, such as demographics, socio-economic data, or any other relevant characteristics.')
236
- ]),
237
-
238
- html.H5('Step 2: Calculate Similarity'),
239
- html.Ul([
240
- html.Li('Use the characteristics (also called covariates) of each area to calculate a measure of similarity between areas.'),
241
- html.Li('The most common approach is to calculate the "distance" between areas in the space defined by these covariates.')
242
- ]),
243
-
244
- html.H5('Step 3: Find Nearest Neighbors'),
245
- html.Ul([
246
- html.Li('For each area, find the other area that has the smallest "distance" to it.'),
247
- html.Li('This is known as finding the "nearest neighbor."'),
248
- html.Li('The nearest neighbor is considered the most similar area based on the covariates.')
249
- ]),
250
-
251
- html.H5('Step 4: Identify Similar Areas'),
252
- html.Ul([
253
- html.Li('After finding the nearest neighbors, you have a list of pairs of areas where each pair consists of the most similar areas based on the characteristics considered.')
254
- ]),
255
-
256
- html.H5('Result'),
257
- html.P('You now know which areas are most similar to each other, based purely on their characteristics, allowing for various analyses or comparisons.')
258
-
259
-
260
- ], width = 6)
261
-
262
- ])
263
-
264
-
265
- ]
266
- )
267
-
268
-
269
- match_layout = html.Div(
270
- children=[
271
- html.Br(),
272
- html.H1("Area Similarity and Matching", className="mb-2"),
273
-
274
- dbc.Row([
275
- dbc.Col(html.P("Upload a CSV file with your geographic areas and demographic variables. "
276
- "Select the analysis mode below and follow the steps to identify similar areas."),
277
- className="mb-4")
278
- ]),
279
-
280
- dbc.Row([
281
-
282
- dbc.Col([
283
- html.H4("Settings"),
284
-
285
- dbc.Col(html.H5("Treatment Status"), className="mb-2"),
286
- dbc.Col(html.P("Have the treatment areas already been selected?" ),
287
- className="mb-4"),
288
- dbc.RadioItems(
289
- options=[
290
- {"label": "Yes", "value": 1},
291
- {"label": "No", "value": 0}
292
- ],
293
- value=0, # Default value
294
- id="treatment-toggle",
295
- inline=True, # Display radio buttons inline
296
- className="mb-4"
297
- ),
298
-
299
- dbc.Col(html.H5("File Upload"), className="mb-2"),
300
- dcc.Upload(
301
- id='upload-data',
302
- children=html.Div([
303
- 'Drag and Drop or ',
304
- html.A('Select Files')
305
- ]),
306
- style={
307
- 'width': '100%', 'height': '60px', 'lineHeight': '60px',
308
- 'borderWidth': '1px', 'borderStyle': 'dashed',
309
- 'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px',
310
- 'margin-left' : '0px'
311
- },
312
- multiple=False
313
- ),
314
- dbc.Progress(id="upload-progress",
315
- value=0,
316
- striped=True,
317
- animated=True,
318
- style={'transition': 'width 0.5s',
319
- 'backgroundColor': 'lightgray'},
320
- className="mb-4"),
321
- html.Div(id='output-data-upload'),
322
-
323
-
324
- dbc.Col(html.H5("Column Selection"), className="mb-2"),
325
-
326
- html.H6("Select Area ID/Name Column"),
327
- dcc.Dropdown(id='area-id-column', placeholder="Select Area ID/Name Column"),
328
-
329
- html.H6("Select Treatment Column (if applicable)"),
330
- dcc.Dropdown(id='treatment-column', placeholder="Select Treatment Column"),
331
-
332
- html.H6("Select Covariate Columns"),
333
- dcc.Dropdown(id='covariate-columns', multi=True, placeholder="Select Covariate Columns"),
334
-
335
- html.Br(),
336
- html.Button("Run Analysis", id="run-analysis", n_clicks=0, className="btn btn-primary"),
337
- html.Button("Clear Data", id="clear-button", className="btn btn-primary",
338
- style={
339
- 'backgroundColor': 'red', # Red background color
340
- 'color': 'white', # White text color
341
- 'border': 'none', # Remove border
342
- 'cursor': 'pointer',
343
- 'margin-left': '20px'
344
- }),
345
-
346
- html.Br(),
347
- html.Br(),
348
- html.H4("Download Results"),
349
- dcc.Store(id='raw-results'),
350
- html.Div(html.Button("Download Results",
351
- id = "download-button",
352
- n_clicks = 0,
353
- className="btn btn-secondary"),
354
- style={'margin-top': '10px'}),
355
-
356
- dcc.Download(id="download-data")
357
-
358
- ], width=3),
359
-
360
- dbc.Col([
361
- html.H4("Output"),
362
- html.Div(id="analysis-output")
363
-
364
- ], width=9)
365
-
366
- ])
367
-
368
- ]
369
- )
370
-
371
- quality_layout = html.Div([
372
- html.H1("Propensity Score Matching Evaluation Metrics"),
373
- html.Br(),
374
-
375
- dbc.Row([
376
- dbc.Col([
377
- html.Button("Run Quality Assurance Script", id="run-quality", n_clicks=0, className="btn btn-primary", style = {'margin-bottom': '20px',}),
378
- ], width = 3),
379
- dbc.Col([
380
- html.Div(id='output-quality-error', style={'color':'red'})
381
- ], width = 9)
382
- ]),
383
-
384
- html.Br(),
385
-
386
- dbc.Row([
387
- html.H3("Distribution of Propensity Scores"),
388
-
389
- dbc.Col([
390
- html.H4("Plot"),
391
-
392
- html.Div(id='propensity-distribution')
393
-
394
-
395
- ], width=8),
396
-
397
- dbc.Col([
398
- html.H4("Explanation"),
399
-
400
- html.P(
401
- "In this application, the Propensity Score Distribution visualises the likelihood that an area "
402
- "or individual would receive the treatment based on observed covariates. The propensity score "
403
- "is a value between 0 and 1 that indicates the probability of receiving treatment, given a set "
404
- "of characteristics. "
405
- "The plot displays the distribution of propensity scores "
406
- "for both the treated and control groups. "
407
- ),
408
-
409
- html.P("Key Considerations:"),
410
- html.Ul([
411
- html.Li(
412
- "Overlap of Distributions: Ideally, the propensity score distributions for treated and control "
413
- "groups should overlap significantly. This overlap indicates that the groups are comparable in terms "
414
- "of covariates, which is crucial for reducing bias in the analysis."
415
- ),
416
- html.Li(
417
- "Quality of Matching: After matching, a significant overlap with similar shapes in the distributions "
418
- "suggests successful balancing of covariates between the groups. Poor overlap or disparate shapes may "
419
- "indicate inadequate matching."
420
- ),
421
- html.Li(
422
- "Potential Issues: Sparse regions in the distribution suggest a lack of overlap, meaning some treated "
423
- "units lack suitable control matches. Additionally, outliers or extreme scores may signal issues with "
424
- "the model or covariates."
425
- ),
426
- ]),
427
- html.P(
428
- "By examining these distributions, you can assess the effectiveness of the matching process and identify "
429
- "any potential issues that could affect the reliability of the analysis."
430
- )
431
-
432
- ],
433
- width=4,
434
- style={
435
- 'backgroundColor': 'rgba(173, 216, 230, 0.8)', # Pale blue color
436
- 'padding': '20px',
437
- 'border': '1px solid #ccc'
438
- })
439
- ],
440
- style={
441
- 'backgroundColor': 'rgba(173, 216, 230, 0.5)', # Pale blue color
442
- 'padding': '20px',
443
- 'border': '1px solid #ccc'
444
- }),
445
-
446
- dbc.Row([
447
- html.H3("Balance of Covariates"),
448
-
449
- dbc.Col([
450
- html.H4("Explanation"),
451
-
452
- dcc.Markdown('''
453
- **Balance of Covariates Distribution Plots** are visual tools used to compare the distributions of covariates (variables) between treated and control groups after matching. The goal is to assess if the matching process has made the treated and control groups similar in terms of the covariates. If the matching is successful, the distributions for the treated and control groups should appear more similar, suggesting that the groups are well balanced.
454
-
455
- **Standard Mean Difference (SMD)** is a numerical metric used to quantify the balance of covariates between treated and control groups. It measures the difference in means of a covariate between the two groups, standardised by the pooled standard deviation. An SMD close to 0 indicates that the covariate is well-balanced between the groups, while a larger SMD suggests imbalance.
456
-
457
- **Interpreting the Plots and SMD:**
458
- - **Well-Matched Covariates:** After matching, the covariate distributions between treated and control groups should overlap significantly, and the SMD should be close to 0.
459
- - **Poor Matching:** If the distributions differ significantly or the SMD is still large after matching, it indicates that the matching did not adequately balance the groups.
460
- - **SMD Threshold:** As a general rule, an SMD below 0.1 is considered acceptable, indicating a good balance between the groups.
461
-
462
- These tools help assess the effectiveness of the matching process and ensure that the treatment effect is estimated from comparable groups.
463
- '''),
464
-
465
- ], width=3,
466
- style={
467
- 'backgroundColor': 'rgba(172, 230, 174, 0.8)',
468
- 'padding': '20px',
469
- 'border': '1px solid #ccc'
470
- }),
471
-
472
- dbc.Col([
473
- html.H4("Plot & Standard Mean Difference (SMD)"),
474
- html.Div([
475
- html.Div(id='output-covariate-balance',
476
- style={
477
- 'display': 'grid',
478
- 'gridTemplateColumns': 'repeat(auto-fill, minmax(400px, 1fr))',
479
- 'gap': '20px'})
480
- ], style={'padding': '20px'})
481
-
482
-
483
- ], width=9)
484
-
485
-
486
- ],
487
- style={
488
- 'backgroundColor': 'rgba(172, 230, 174, 0.5)', # Pale blue color
489
- 'padding': '20px',
490
- 'border': '1px solid #ccc'
491
- }),
492
-
493
- dbc.Row([
494
- html.H3("t-Test"),
495
-
496
- dbc.Col([
497
- html.H4("Results"),
498
-
499
- html.Br(),
500
-
501
- html.Div(id="ttest-output")
502
-
503
- ], width=3),
504
-
505
- dbc.Col([
506
- html.H4("Explanation"),
507
-
508
- dcc.Markdown('''
509
- In Propensity Score Matching (PSM), the **t-test** is used to assess the balance of covariates between the treated group (those who received the treatment) and the control group (those who did not receive the treatment).
510
-
511
- The t-test evaluates the null hypothesis that the means of a specific covariate are equal between the treated and control groups. Essentially, it checks whether the difference in means is statistically significant. A well-balanced covariate between the groups is indicated by a high p-value, suggesting that the matching process has been effective.
512
-
513
- ###### How to Interpret the t-Test in PSM?
514
-
515
- - **P-value**:
516
- - **High P-value (e.g., p > 0.05)**: Indicates no statistically significant difference in means between the treated and control groups, suggesting that the covariate is well balanced after matching.
517
- - **Low P-value (e.g., p < 0.05)**: Indicates a significant difference in means, suggesting that the covariate is not well balanced, even after matching.
518
-
519
- ###### Why is the t-Test Important in PSM?
520
-
521
- The t-test is crucial for assessing the success of the matching process. By checking for balance in covariates, it helps ensure that the treated and control groups are comparable. This balance is essential for reducing confounding bias and obtaining accurate estimates of the treatment effect. Significant differences detected by the t-test may indicate that the matching process needs improvement to achieve better balance.
522
-
523
- In summary, the t-test helps validate the effectiveness of the matching process by evaluating whether covariates are balanced between the treated and control groups, ensuring a more accurate assessment of treatment effects.
524
-
525
- ''')
526
-
527
- ], width=9,
528
- style={
529
- 'backgroundColor': 'rgba(157, 39, 245, 0.3)',
530
- 'padding': '20px',
531
- 'border': '1px solid #ccc'
532
- })
533
- ],
534
- style={
535
- 'backgroundColor': 'rgba(157, 39, 245, 0.2)',
536
- 'padding': '20px',
537
- 'border': '1px solid #ccc'
538
- })
539
-
540
-
541
- ])
542
-
543
-
544
- #%% App Layout
545
-
546
- app.layout = html.Div(
547
- [
548
- dcc.Location(id="url", refresh=False),
549
- navbar,
550
- dbc.Container(id="page-content", className="mb-4", fluid=True),
551
- dcc.Store(id='stored-data', storage_type='session')
552
- ]
553
- )
554
-
555
- @app.callback(Output("page-content", "children"), Input("url", "pathname"))
556
- def display_page(pathname):
557
- if pathname == "/":
558
- return overview_layout
559
- elif pathname == "/match":
560
- return match_layout
561
- elif pathname == "/quality":
562
- return quality_layout
563
- else:
564
- return dbc.Jumbotron(
565
- [
566
- html.H1("404: Not found", className="text-danger"),
567
- html.Hr(),
568
- html.P(f"The pathname {pathname} was not recognized..."),
569
- ]
570
- )
571
-
572
-
573
-
574
- #%% Retain Data Across Pages
575
-
576
- #Callback to store input values automatically when they change
577
-
578
- @app.callback(
579
- Output('stored-data', 'data'),
580
- Input('treatment-toggle', 'value'),
581
- Input('upload-data', 'contents'),
582
- Input('upload-data', 'filename'),
583
- Input('area-id-column', 'value'),
584
- Input('treatment-column', 'value'),
585
- Input('covariate-columns', 'value')
586
- )
587
-
588
- def store_inputs(treatment_toggle, contents, filename, area_id_col, treatment_col, covariates_cols):
589
-
590
- return {'treatment_toggle': treatment_toggle,
591
- 'contents': contents,
592
- 'filename': filename,
593
- 'area_id_col': area_id_col,
594
- 'treatment_col': treatment_col,
595
- 'covariate-columns': covariates_cols}
596
-
597
-
598
- #Load Data When Revisit Matching
599
- @app.callback(
600
- Output('treatment-toggle', 'value'),
601
- Output('upload-data', 'contents'),
602
- Output('upload-data', 'filename'),
603
- Output('area-id-column', 'value'),
604
- Output('treatment-column', 'value'),
605
- Output('covariate-columns', 'value'),
606
- Output('run-analysis', 'n_clicks'),
607
- Input('url', 'pathname'),
608
- State('stored-data', 'data')
609
- )
610
- def restore_toggle_state(pathname, stored_data):
611
-
612
- if pathname == '/match' and stored_data is not None:
613
- return stored_data.get('treatment_toggle'), stored_data.get('contents'), stored_data.get('filename'), stored_data.get('area_id_col'), stored_data.get('treatment_col'), stored_data.get('covariate-columns'), 1
614
-
615
- return dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update
616
-
617
-
618
- #Add Clear Button
619
-
620
- @app.callback(
621
- Output('stored-data', 'data', allow_duplicate=True),
622
- Output('treatment-toggle', 'value', allow_duplicate=True),
623
- Output('upload-data', 'contents', allow_duplicate=True),
624
- Output('upload-data', 'filename', allow_duplicate=True),
625
- Output('area-id-column', 'value', allow_duplicate=True),
626
- Output('treatment-column', 'value', allow_duplicate=True),
627
- Output('covariate-columns', 'value', allow_duplicate=True),
628
- Output('run-analysis', 'n_clicks', allow_duplicate=True),
629
- Input('clear-button', 'n_clicks'),
630
- prevent_initial_call=True
631
- )
632
- def clear_stored_data(n_clicks):
633
- if n_clicks:
634
-
635
- return None, None, None, None, None, None, None, 0
636
-
637
- return dash.no_update
638
-
639
- #%% App Functions
640
-
641
-
642
-
643
- # Utility function to parse the uploaded CSV file
644
- def parse_contents(contents, filename):
645
- content_type, content_string = contents.split(',')
646
- decoded = base64.b64decode(content_string)
647
- try:
648
- if 'csv' in filename:
649
- df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))
650
- else:
651
- return None
652
- except Exception as e:
653
- print(e)
654
- return None
655
- return df
656
-
657
- # Update the progress bar and dropdown options based on uploaded file
658
- @app.callback(
659
- Output('upload-progress', 'value'),
660
- Output('upload-progress', 'children'),
661
- Output('upload-progress', 'style'),
662
- Output('area-id-column', 'options'),
663
- Output('treatment-column', 'options'),
664
- Output('covariate-columns', 'options'),
665
- Input('upload-data', 'contents'),
666
- State('upload-data', 'filename')
667
- )
668
-
669
- def update_progress_bar(contents, filename):
670
- if contents is None:
671
- return 0, "", {'backgroundColor': 'lightgray'}, [], [], []
672
-
673
- # Start the progress bar at 50% when the file is detected
674
- progress_value = 50
675
- progress_text = "Uploading..."
676
-
677
- # Parse the file
678
- df = parse_contents(contents, filename)
679
- if df is not None:
680
- columns = [{'label': col, 'value': col} for col in df.columns]
681
-
682
- # Finish the progress bar when the file is fully loaded
683
- return 100, "Upload Complete", {'backgroundColor': 'green'}, columns, columns, columns
684
- else:
685
- return 0, "Failed to upload", {'backgroundColor': 'red'}, [], [], []
686
-
687
-
688
- # Conditional analysis based on treatment selection
689
- @app.callback(
690
- [Output('analysis-output', 'children'),
691
- Output('raw-results', 'data')],
692
- Input('run-analysis', 'n_clicks'),
693
- State('treatment-toggle', 'value'),
694
- State('upload-data', 'contents'),
695
- State('upload-data', 'filename'),
696
- State('area-id-column', 'value'),
697
- State('treatment-column', 'value'),
698
- State('covariate-columns', 'value'),
699
- prevent_initial_call=True
700
- )
701
- def run_analysis(n_clicks, treatment_toggle, contents, filename, area_id_col, treatment_col, covariates_cols):
702
- if n_clicks == 0 or contents is None:
703
- return "", ""
704
-
705
- df = parse_contents(contents, filename)
706
- if df is not None and area_id_col is not None and covariates_cols:
707
- # Set the area ID as the index for easier referencing
708
- df.set_index(area_id_col, inplace=True)
709
-
710
- #Standardize Covariates
711
- scaler = StandardScaler()
712
- covariates_scaled = scaler.fit_transform(df[covariates_cols])
713
-
714
- if treatment_toggle:
715
- # Treatment areas selected: Perform propensity score matching
716
- if treatment_col is None:
717
- return "Please select a treatment column.", ""
718
-
719
- if area_id_col == treatment_col:
720
- return "The treatment column must be different from the label column.", ""
721
-
722
- if not set(df[treatment_col].unique()).issubset({0, 1}):
723
- return "Treatment column must contain a binary response. 1 = Treatment // 0 = Control.", ""
724
-
725
- #Estimate Propensity Scores
726
- logistic = LogisticRegression()
727
- logistic.fit(covariates_scaled, df[treatment_col])
728
- df['propensity_score'] = logistic.predict_proba(covariates_scaled)[:, 1]
729
-
730
- #Extract Treatment & Control
731
- treated = df[df[treatment_col] == 1]
732
- control = df[df[treatment_col] == 0]
733
-
734
- #Perform Matching
735
- nn = NearestNeighbors(n_neighbors=1)
736
- nn.fit(control[['propensity_score']])
737
-
738
- treated_indices = df[df[treatment_col] == 1].index
739
- control_indices = df[df[treatment_col] == 0].index
740
-
741
- if len(treated_indices) > 0:
742
- distances, indices = nn.kneighbors(treated[['propensity_score']])
743
- matched_data = pd.DataFrame({
744
- 'Treated_Area': treated_indices,
745
- 'Matched_Control_Area': control.iloc[indices.flatten()].index,
746
- 'Distance': distances.flatten()
747
- })
748
-
749
- # Create raw results dataframe
750
- raw_results = matched_data.copy()
751
-
752
- return dbc.Table.from_dataframe(matched_data, striped=True, bordered=True, hover=True), raw_results.to_dict('records')
753
-
754
- return "No treated areas to match.", ""
755
-
756
- else:
757
- # No treatment: Find similar areas using nearest neighbors
758
- nn = NearestNeighbors(n_neighbors=2) # 2 to get the nearest neighbor excluding the point itself
759
- nn.fit(covariates_scaled)
760
-
761
- distances, indices = nn.kneighbors(covariates_scaled)
762
-
763
- #Filter Self Returns
764
- indicesResults = []
765
-
766
- for i in range(len(indices)):
767
-
768
- #If NN 1 == index select NN 2 else NN 1
769
- if int(indices[i][0]) == i:
770
- indicesResults.append((indices[i][1], distances[i][1]))
771
- else:
772
- indicesResults.append((indices[i][0], distances[i][0]))
773
-
774
- indicesResults = np.array(indicesResults)
775
-
776
-
777
- similar_areas = pd.DataFrame({
778
- 'Area': df.index,
779
- 'Most_Similar_Area': df.index[indicesResults[:, 0].astype(int)],
780
- 'Similarity_Score': indicesResults[:, 1]
781
- })
782
-
783
- # Create raw results dataframe
784
- raw_results = similar_areas.copy()
785
-
786
- return dbc.Table.from_dataframe(similar_areas, striped=True, bordered=True, hover=True), raw_results.to_dict('records')
787
-
788
- return "Please upload a valid CSV file and select the appropriate columns.", ""
789
-
790
-
791
-
792
-
793
- # Example callback for downloading data
794
- @app.callback(
795
- Output("download-data", "data"),
796
- Input("download-button", "n_clicks"),
797
- State("raw-results", "data"),
798
- prevent_initial_call=True
799
- )
800
- def download_results(n_clicks, raw_results):
801
- if n_clicks > 0 and raw_results is not None:
802
- # Convert raw results to DataFrame and then to CSV
803
- df_raw = pd.DataFrame(raw_results)
804
-
805
- # Get the current time
806
- now = datetime.now()
807
- current_dt = now.strftime("%Y-%m-%d_%H%M%S")
808
-
809
- return dcc.send_data_frame(df_raw.to_csv, "MOPAC_SpatialMatching_"+str(current_dt)+".csv")
810
-
811
-
812
- #%% Quality Assurance Functions
813
-
814
-
815
- def calculate_smd(df, treatment_col, covariates_cols, state):
816
- smd = []
817
- treated = df[df[treatment_col] == 1]
818
- control = df[df[treatment_col] == 0]
819
-
820
- for cov in covariates_cols:
821
- treated_mean = treated[cov].mean()
822
- control_mean = control[cov].mean()
823
- treated_std = treated[cov].std()
824
- control_std = control[cov].std()
825
-
826
- pooled_std = np.sqrt((treated_std**2 + control_std**2) / 2)
827
- #smd[cov] = np.abs(treated_mean - control_mean) / pooled_std
828
-
829
- smd.append(f'SMD {state}: {np.abs(treated_mean - control_mean) / pooled_std}')
830
-
831
- return smd
832
-
833
-
834
- def plot_covariate_distributions(df, treatment_col, covariates_cols):
835
- plots = []
836
- for cov in covariates_cols:
837
- fig = go.Figure()
838
-
839
- # Define colors for treatments
840
- treatments = df[treatment_col].unique()
841
- colors = ['blue', 'green'] # Customize as needed
842
- treatment_colors = {treatment: colors[i % len(colors)] for i, treatment in enumerate(treatments)}
843
- label_mapping = {1: 'Treatment', 0: 'Control'} # Adjust as needed
844
-
845
- # Add a histogram trace for each treatment
846
- for treatment in treatments:
847
- subset = df[df[treatment_col] == treatment]
848
- color = treatment_colors[treatment]
849
-
850
- # Add histogram trace
851
- fig.add_trace(go.Histogram(
852
- x=subset[cov],
853
- name=label_mapping.get(treatment, str(treatment)),
854
- opacity=0.6,
855
- histnorm='probability density',
856
- nbinsx=30,
857
- bingroup=1, # Ensure histograms are layered
858
- marker_color=color # Set color of histogram bars
859
- ))
860
-
861
- # Calculate KDE for each subset
862
- kde = gaussian_kde(subset[cov].dropna())
863
- x = np.linspace(subset[cov].min(), subset[cov].max(), 1000)
864
- kde_y = kde(x)
865
-
866
- # Add KDE trace with the same color
867
- fig.add_trace(go.Scatter(
868
- x=x,
869
- y=kde_y,
870
- mode='lines',
871
- name=f'KDE {label_mapping.get(treatment, str(treatment))}',
872
- line=dict(color=color, width=2), # Set color of KDE line
873
- showlegend=False # Hide KDE lines from the legend
874
- ))
875
-
876
- # Update layout
877
- fig.update_layout(
878
- title=f'Distribution of {cov}',
879
- xaxis_title=cov,
880
- yaxis_title='Density',
881
- barmode='overlay', # Layer the histograms
882
- legend_title='Treatment',
883
- bargap=0.1
884
- )
885
-
886
- plots.append(fig)
887
-
888
- return plots
889
-
890
-
891
- def plot_propensity_scores(df, treatment_col):
892
- fig = go.Figure()
893
-
894
- # Define labels for treatment and control
895
- label_mapping = {1: 'Treatment', 0: 'Control'}
896
-
897
- # Get unique treatments
898
- treatments = df[treatment_col].unique()
899
-
900
- # Define a color map (you can customize these colors)
901
- colors = ['blue', 'green']
902
-
903
- # Ensure the number of colors matches the number of treatments
904
- treatment_colors = {treatment: colors[i % len(colors)] for i, treatment in enumerate(treatments)}
905
-
906
- # Add a histogram trace for each treatment
907
- for treatment in treatments:
908
- subset = df[df[treatment_col] == treatment]
909
- color = treatment_colors[treatment]
910
-
911
- # Add histogram trace
912
- fig.add_trace(go.Histogram(
913
- x=subset['propensity_score'],
914
- name=label_mapping.get(treatment, str(treatment)), # Set custom label
915
- opacity=0.6,
916
- histnorm='probability density', # Use density
917
- nbinsx=30,
918
- bingroup=1, # Ensures histograms are layered
919
- marker_color=color # Set the color of the histogram bars
920
- ))
921
-
922
- # Calculate KDE for each subset
923
- kde = gaussian_kde(subset['propensity_score'].dropna())
924
- x = np.linspace(subset['propensity_score'].min(), subset['propensity_score'].max(), 1000)
925
- kde_y = kde(x)
926
-
927
- # Add KDE trace with the same color
928
- fig.add_trace(go.Scatter(
929
- x=x,
930
- y=kde_y,
931
- mode='lines',
932
- name=f'KDE {label_mapping.get(treatment, str(treatment))}', # Set custom label for KDE
933
- line=dict(color=color, width=2), # Set the color of the KDE line
934
- showlegend=False # Hide KDE lines from the legend
935
- ))
936
-
937
- # Update layout
938
- fig.update_layout(
939
- title='Distribution of Propensity Scores',
940
- xaxis_title='Propensity Score',
941
- yaxis_title='Density', # Use 'Density' on the Y-axis
942
- barmode='overlay', # Layer the histograms
943
- legend_title='Group',
944
- bargap=0.1
945
- )
946
-
947
- return fig
948
-
949
-
950
- def t_test_covariates(df, treatment_col, covariates_cols):
951
- t_test_results = {}
952
- treated = df[df[treatment_col] == 1]
953
- control = df[df[treatment_col] == 0]
954
-
955
- for cov in covariates_cols:
956
- t_stat, p_value = stats.ttest_ind(treated[cov], control[cov], equal_var=False)
957
- t_test_results[cov] = {'t_stat': t_stat, 'p_value': p_value}
958
-
959
- return t_test_results
960
-
961
-
962
- @app.callback(
963
- Output('output-quality-error', 'children'),
964
- Output('output-covariate-balance', 'children'),
965
- Output('ttest-output', 'children'),
966
- Output('propensity-distribution', 'children'),
967
- Input('run-quality', 'n_clicks'),
968
- Input('url', 'pathname'),
969
- Input('stored-data', 'data')
970
-
971
- )
972
- def quality_assurance(n_clicks, pathname, stored_data):
973
-
974
- if pathname == '/quality' and n_clicks:
975
-
976
- if stored_data is None:
977
- return "Error: Please Run the Analysis First.", "", "", ""
978
-
979
- #Get the data
980
- treatment_toggle = stored_data.get('treatment_toggle')
981
- file_contents = stored_data.get('contents')
982
- file_name = stored_data.get('filename')
983
- area_id_col = stored_data.get('area_id_col')
984
- treatment_col = stored_data.get('treatment_col')
985
- covariate_cols = stored_data.get('covariate-columns')
986
-
987
- if any(value is None for value in stored_data.values()):
988
- return "Error: Please Run the Treatment-Control Matching First.", "", "", ""
989
-
990
- if not treatment_toggle:
991
- return "Error: Quality Assurance Requires a Treatment and Control Group", "", "", ""
992
-
993
- if treatment_col is None:
994
- return "Error: Please select a treatment column.", "", "", ""
995
-
996
- if area_id_col == treatment_col:
997
- return "Error: The treatment column must be different from the label column.", "", "", ""
998
-
999
-
1000
- #Parse data
1001
- df = parse_contents(file_contents, file_name)
1002
-
1003
- if not set(df[treatment_col].unique()).issubset({0, 1}):
1004
- return "Error: Treatment column must contain a binary response. 1 = Treatment // 0 = Control.", "", "", ""
1005
-
1006
- #Check Treated Areas True
1007
- if len(df[df[treatment_col] == 1].index) == 0:
1008
- return "Error: No treated areas to match.", "", "", ""
1009
-
1010
- def generate_match_data(df, treatment_col, covariate_cols):
1011
-
1012
- #Get subset of data
1013
- treatment = df[treatment_col]
1014
- covariates = df[covariate_cols]
1015
-
1016
-
1017
- #Data Transform
1018
- scaler = StandardScaler()
1019
- covariates_scaled = scaler.fit_transform(covariates)
1020
-
1021
- #Propensity Scores
1022
- logistic = LogisticRegression()
1023
- logistic.fit(covariates_scaled, treatment)
1024
-
1025
- # Get the propensity scores
1026
- df['propensity_score'] = logistic.predict_proba(covariates_scaled)[:, 1]
1027
-
1028
-
1029
- #Subset data
1030
- treated = df[df[treatment_col] == 1]
1031
- control = df[df[treatment_col] == 0]
1032
-
1033
- #NN Matching
1034
- nn = NearestNeighbors(n_neighbors=1)
1035
- nn.fit(control[['propensity_score']])
1036
-
1037
- distances, indices = nn.kneighbors(treated[['propensity_score']])
1038
-
1039
- matched_control = control.iloc[indices.flatten()]
1040
-
1041
-
1042
- df_matched = pd.concat([treated, matched_control])
1043
-
1044
- return(df_matched)
1045
-
1046
-
1047
- df_matched = generate_match_data(df, treatment_col, covariate_cols)
1048
-
1049
-
1050
- ## BALANCE OF COVARIATES
1051
- plots_boc = plot_covariate_distributions(df_matched, treatment_col, covariate_cols)
1052
-
1053
- stats_boc_b = calculate_smd(df, treatment_col, covariate_cols, 'Before')
1054
- stats_boc_a = calculate_smd(df_matched, treatment_col, covariate_cols, 'After')
1055
-
1056
-
1057
- out_covariate_balance = []
1058
-
1059
- for plot, stat_b, stat_a in zip(plots_boc, stats_boc_b, stats_boc_a):
1060
-
1061
- out_covariate_balance.append(html.Div([dcc.Graph(figure=plot),
1062
- html.Br(),
1063
- html.P(stat_b),
1064
- html.P(stat_a)], className='grid-item'))
1065
-
1066
- ## Propensity Distribution
1067
- prop_plot = plot_propensity_scores(df, treatment_col)
1068
-
1069
-
1070
- ## t-TEST RESULTS
1071
- t_test_results = t_test_covariates(df, treatment_col, covariate_cols)
1072
-
1073
- out_t_test = []
1074
-
1075
- for main_key, sub_dict in t_test_results.items():
1076
-
1077
- p_value = sub_dict.get('p_value')
1078
- t_stat = sub_dict.get('t_stat')
1079
-
1080
- out_t_test.append(html.Div([html.H6(main_key),
1081
- html.Ul([
1082
- html.Li(f'p-Value: {p_value}'),
1083
- html.Li(f't-Stat: {t_stat}')
1084
- ])
1085
- ]))
1086
-
1087
- return "", out_covariate_balance, out_t_test, html.Div([dcc.Graph(figure=prop_plot)])
1088
-
1089
- else:
1090
-
1091
- return "", "", "", ""
1092
-
1093
-
1094
- #%% Main
1095
-
1096
- # Run the app
1097
- if __name__ == '__main__':
1098
- app.run_server(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))
 
1
+ ## MOPAC Spatial Propensity Matching
2
+
3
+ ## Daniel Hammocks - 2024-08-14
4
+ ## GH: dhammo2
5
+
6
+ ## This code takes the JSON extracted from the Metropolitan Police R HTML Ouput
7
+ ## and creates a geoJSON/Shapefile of control and intervention groups including
8
+ ## all data displayed on the graph.
9
+
10
+ ###############################################################################
11
+ ################################# APPLICATION #################################
12
+ ###############################################################################
13
+
14
+
15
+ #%% Versioning
16
+
17
+ # v1.0.0 - Original Dashboard
18
+ # v2.0.0 - Introduced Download Option
19
+ # v3.0.0 - Added Multi-Page Functionality
20
+ # v4.0.0 - Introduced Quality Assurance
21
+ # - Altered Calculation for PSM to search control only.
22
+ # v5.0.0 - Ensure that Area Matching Does Not Return Self
23
+ # v6.0.0 - Added Quality Assurance
24
+ # v7.0.0 - Complete Quality Assurance Information
25
+
26
+
27
+ #%% NOTES
28
+
29
+ #DISABLE LOGGING WHEN DONE
30
+
31
+ #Put Error Notices for QA at top.
32
+
33
+ #%% Required Libraries
34
+
35
+ import dash
36
+ import dash_bootstrap_components as dbc
37
+ from dash import dcc, html, Input, Output, State
38
+ import pandas as pd
39
+ import numpy as np
40
+ from sklearn.linear_model import LogisticRegression
41
+ from sklearn.neighbors import NearestNeighbors
42
+ from sklearn.preprocessing import StandardScaler
43
+ import io
44
+ import base64
45
+ from datetime import datetime
46
+ from scipy import stats
47
+ import plotly.graph_objects as go
48
+ from scipy.stats import gaussian_kde
49
+
50
+
51
+ import logging
52
+ import os
53
+
54
+
55
+
56
+
57
+ #%% App Initialisation
58
+
59
+ # Initialize the Dash app
60
+ app = dash.Dash(__name__, suppress_callback_exceptions=True, external_stylesheets=[dbc.themes.BOOTSTRAP])
61
+
62
+ app.title = "MOPAC | DS"
63
+
64
+ logging.basicConfig(level=logging.DEBUG)
65
+
66
+ #%% Navigation Layout
67
+
68
+
69
+ navbar = dbc.NavbarSimple(
70
+ children=[
71
+ dbc.NavItem(dbc.NavLink("Overview", href="/")),
72
+ dbc.NavItem(dbc.NavLink("Area Similarity & Matching", href="/match")),
73
+ dbc.NavItem(dbc.NavLink("Quality Assurance", href="/quality")),
74
+
75
+ ],
76
+ brand="MOPAC | DS - Area Similarity and Matching Application",
77
+ brand_href="#",
78
+ color="primary",
79
+ dark=True,
80
+ fluid=True
81
+ )
82
+
83
+
84
+ #%% Page Layout
85
+
86
+ overview_layout = html.Div(
87
+ children=[html.Br(),
88
+ html.H1(children="Overview"),
89
+ html.P("This application enables users to identify similar "
90
+ "geographic areas based on a set of covariates "
91
+ "(characteristics) related to each area. Two methods have "
92
+ "been implemented enabling the user to both identify "
93
+ "similar areas based on a set of characteristics but to "
94
+ "also identify similar areas once a treatment has already "
95
+ "been assigned. The two methods are detailed below."),
96
+
97
+ html.Br(),
98
+ html.Hr(),
99
+
100
+ html.H3('Data Formatting Requirements'),
101
+ html.Div([
102
+ html.Div([
103
+ html.H4('Example Data Structure'),
104
+
105
+ html.Br(),
106
+
107
+ html.Table([
108
+ html.Thead(
109
+ html.Tr([
110
+ html.Th('Area_ID', style={'border': '1px solid black'}),
111
+ html.Th('Population', style={'border': '1px solid black'}),
112
+ html.Th('Income', style={'border': '1px solid black'}),
113
+ html.Th('Education', style={'border': '1px solid black'}),
114
+ html.Th('Treatment (optional)', style={'border': '1px solid black'})
115
+ ], style={'background-color': '#f2f2f2', 'font-weight': 'bold', 'text-align': 'center'})
116
+ ),
117
+ html.Tbody([
118
+ html.Tr([
119
+ html.Td('Area_001', style={'border': '1px solid black'}),
120
+ html.Td('10000', style={'border': '1px solid black'}),
121
+ html.Td('50000', style={'border': '1px solid black'}),
122
+ html.Td('12', style={'border': '1px solid black'}),
123
+ html.Td('1', style={'border': '1px solid black'})
124
+ ]),
125
+ html.Tr([
126
+ html.Td('Area_002', style={'border': '1px solid black'}),
127
+ html.Td('15000', style={'border': '1px solid black'}),
128
+ html.Td('60000', style={'border': '1px solid black'}),
129
+ html.Td('14', style={'border': '1px solid black'}),
130
+ html.Td('0', style={'border': '1px solid black'})
131
+ ]),
132
+ html.Tr([
133
+ html.Td('Area_003', style={'border': '1px solid black'}),
134
+ html.Td('12000', style={'border': '1px solid black'}),
135
+ html.Td('55000', style={'border': '1px solid black'}),
136
+ html.Td('13', style={'border': '1px solid black'}),
137
+ html.Td('1', style={'border': '1px solid black'})
138
+ ]),
139
+ html.Tr([
140
+ html.Td('...', style={'border': '1px solid black'}),
141
+ html.Td('...', style={'border': '1px solid black'}),
142
+ html.Td('...', style={'border': '1px solid black'}),
143
+ html.Td('...', style={'border': '1px solid black'}),
144
+ html.Td('...', style={'border': '1px solid black'})
145
+ ])
146
+ ], style={'text-align': 'center'}),
147
+ ], style={
148
+ 'width': '80%',
149
+ 'border-collapse': 'collapse',
150
+ 'margin-top': '10px',
151
+ 'border': '1px solid black'
152
+ }),
153
+
154
+ html.Br(),
155
+ html.A(
156
+ html.Img(src='assets/DataOverview.png',
157
+ style={'width': '85%', 'height': 'auto'})
158
+ , href="assets/DataOverview.png", target="_blank", style={'font-size': '20px', 'text-decoration': 'none', 'color': 'blue'}),
159
+ html.P("Click to Expand.", style={'width': '85%', 'textAlign': 'center'})
160
+
161
+
162
+
163
+ ], style={'width': '33%', 'display': 'inline-block', 'vertical-align': 'top'}),
164
+
165
+
166
+ html.Div([
167
+ html.H4('Required Data Format'),
168
+ html.P('To use the Area Similarity and Matching application, please provide your data in a CSV format with the following structure:'),
169
+
170
+ html.H5('1. Area ID/Name'),
171
+ html.P('A unique identifier or name for each area (e.g., "Area_ID" or "Area_Name"). This will be used to identify and match areas.'),
172
+
173
+ html.H5('2. Covariate Columns'),
174
+ html.P('One or more columns containing the demographic or other relevant variables (covariates) that will be used to compare areas. Examples include population, income, education level, etc.'),
175
+
176
+ html.H5('3. [Optional] Treatment Column'),
177
+ html.P('The treatment column is optional but can be included if you want to perform Propensity Score Matching (PSM). This should be a binary column indicating whether an area has received a treatment (e.g., "Treatment", where 1 = treated, 0 = not treated). If this column is provided, the application will use it to perform PSM. If not provided, the application will simply match areas based on similarity using covariates.'),
178
+
179
+ html.H4('Key Points'),
180
+ html.Ul([
181
+ html.Li('The Area ID/Name must be unique for each area.'),
182
+ html.Li('Covariates should be numeric and relevant to the analysis.'),
183
+ html.Li('The Treatment column is optional; if included, it allows for Propensity Score Matching, otherwise, the app can identify similar areas without considering treatment.')
184
+ ])
185
+ ], style={'width': '66%', 'display': 'inline-block', 'vertical-align': 'top'}),
186
+ ]),
187
+
188
+
189
+ html.Hr(),
190
+ dbc.Row([
191
+
192
+ dbc.Col([
193
+ html.H3("Propensity Score Matching (PSM)"),
194
+ html.B("This method assumes the treatment areas are known.", style={'color':'red'}),
195
+
196
+ html.H5('What is the Goal?'),
197
+ html.P('The goal of PSM is to find areas that are most similar to each other based on certain covariates (characteristics like population, income, etc.) in order to balance the covariates between the treatment and control groups. By ensuring that the treatment and control groups are balanced in terms of covariates, PSM helps reduce confounding bias, leading to more accurate estimates of the treatment effect.'),
198
+
199
+ html.H5('Step 1: Collect Information'),
200
+ html.Ul([
201
+ html.Li('Start with a list of areas that received a "treatment" (e.g., a new program or policy) and potential control areas.'),
202
+ html.Li('Gather information (like demographics) about both treated and nearby areas.')
203
+ ]),
204
+
205
+ html.H5('Step 2: Calculate a Score (Using Logistic Regression)'),
206
+ html.Ul([
207
+ html.Li('Use a statistical method called logistic regression to calculate a "score" for each area.'),
208
+ html.Li('This propensity score tells us how likely each area is to have received the treatment based on its characteristics.')
209
+ ]),
210
+
211
+ html.H5('Step 3: Match Areas (Using Nearest Neighbor)'),
212
+ html.Ul([
213
+ html.Li('For each treated area, find a similar untreated area with the closest score.'),
214
+ html.Li('This is like finding the "nearest neighbor" in terms of similarity.')
215
+ ]),
216
+
217
+ html.H5('Step 4: Identify Similar Areas'),
218
+ html.Ul([
219
+ html.Li('After matching, you have pairs of areas where each treated area is matched with a nearby area that is most similar based on the characteristics considered.')
220
+ ]),
221
+
222
+ html.H5('Result'),
223
+ html.P('We now know which areas are most similar to each other, helping us understand the impact of the treatment by comparing them.')
224
+
225
+ ], width = 6),
226
+
227
+ dbc.Col([
228
+ html.H3("Nearest Neighbour Matching (NNM)"),
229
+
230
+ html.H5('What is the Goal?'),
231
+ html.P('We want to find areas that are most similar to each other based on certain characteristics (like population, income, etc.), without focusing on any specific treatment.'),
232
+
233
+ html.H5('Step 1: Collect Information'),
234
+ html.Ul([
235
+ html.Li('Start by gathering information about the areas you are interested in, such as demographics, socio-economic data, or any other relevant characteristics.')
236
+ ]),
237
+
238
+ html.H5('Step 2: Calculate Similarity'),
239
+ html.Ul([
240
+ html.Li('Use the characteristics (also called covariates) of each area to calculate a measure of similarity between areas.'),
241
+ html.Li('The most common approach is to calculate the "distance" between areas in the space defined by these covariates.')
242
+ ]),
243
+
244
+ html.H5('Step 3: Find Nearest Neighbors'),
245
+ html.Ul([
246
+ html.Li('For each area, find the other area that has the smallest "distance" to it.'),
247
+ html.Li('This is known as finding the "nearest neighbor."'),
248
+ html.Li('The nearest neighbor is considered the most similar area based on the covariates.')
249
+ ]),
250
+
251
+ html.H5('Step 4: Identify Similar Areas'),
252
+ html.Ul([
253
+ html.Li('After finding the nearest neighbors, you have a list of pairs of areas where each pair consists of the most similar areas based on the characteristics considered.')
254
+ ]),
255
+
256
+ html.H5('Result'),
257
+ html.P('You now know which areas are most similar to each other, based purely on their characteristics, allowing for various analyses or comparisons.')
258
+
259
+
260
+ ], width = 6)
261
+
262
+ ])
263
+
264
+
265
+ ]
266
+ )
267
+
268
+
269
+ match_layout = html.Div(
270
+ children=[
271
+ html.Br(),
272
+ html.H1("Area Similarity and Matching", className="mb-2"),
273
+
274
+ dbc.Row([
275
+ dbc.Col(html.P("Upload a CSV file with your geographic areas and demographic variables. "
276
+ "Select the analysis mode below and follow the steps to identify similar areas."),
277
+ className="mb-4")
278
+ ]),
279
+
280
+ dbc.Row([
281
+
282
+ dbc.Col([
283
+ html.H4("Settings"),
284
+
285
+ dbc.Col(html.H5("Treatment Status"), className="mb-2"),
286
+ dbc.Col(html.P("Have the treatment areas already been selected?" ),
287
+ className="mb-4"),
288
+ dbc.RadioItems(
289
+ options=[
290
+ {"label": "Yes", "value": 1},
291
+ {"label": "No", "value": 0}
292
+ ],
293
+ value=0, # Default value
294
+ id="treatment-toggle",
295
+ inline=True, # Display radio buttons inline
296
+ className="mb-4"
297
+ ),
298
+
299
+ dbc.Col(html.H5("File Upload"), className="mb-2"),
300
+ dcc.Upload(
301
+ id='upload-data',
302
+ children=html.Div([
303
+ 'Drag and Drop or ',
304
+ html.A('Select Files')
305
+ ]),
306
+ style={
307
+ 'width': '100%', 'height': '60px', 'lineHeight': '60px',
308
+ 'borderWidth': '1px', 'borderStyle': 'dashed',
309
+ 'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px',
310
+ 'margin-left' : '0px'
311
+ },
312
+ multiple=False
313
+ ),
314
+ dbc.Progress(id="upload-progress",
315
+ value=0,
316
+ striped=True,
317
+ animated=True,
318
+ style={'transition': 'width 0.5s',
319
+ 'backgroundColor': 'lightgray'},
320
+ className="mb-4"),
321
+ html.Div(id='output-data-upload'),
322
+
323
+
324
+ dbc.Col(html.H5("Column Selection"), className="mb-2"),
325
+
326
+ html.H6("Select Area ID/Name Column"),
327
+ dcc.Dropdown(id='area-id-column', placeholder="Select Area ID/Name Column"),
328
+
329
+ html.H6("Select Treatment Column (if applicable)"),
330
+ dcc.Dropdown(id='treatment-column', placeholder="Select Treatment Column"),
331
+
332
+ html.H6("Select Covariate Columns"),
333
+ dcc.Dropdown(id='covariate-columns', multi=True, placeholder="Select Covariate Columns"),
334
+
335
+ html.Br(),
336
+ html.Button("Run Analysis", id="run-analysis", n_clicks=0, className="btn btn-primary"),
337
+ html.Button("Clear Data", id="clear-button", className="btn btn-primary",
338
+ style={
339
+ 'backgroundColor': 'red', # Red background color
340
+ 'color': 'white', # White text color
341
+ 'border': 'none', # Remove border
342
+ 'cursor': 'pointer',
343
+ 'margin-left': '20px'
344
+ }),
345
+
346
+ html.Br(),
347
+ html.Br(),
348
+ html.H4("Download Results"),
349
+ dcc.Store(id='raw-results'),
350
+ html.Div(html.Button("Download Results",
351
+ id = "download-button",
352
+ n_clicks = 0,
353
+ className="btn btn-secondary"),
354
+ style={'margin-top': '10px'}),
355
+
356
+ dcc.Download(id="download-data")
357
+
358
+ ], width=3),
359
+
360
+ dbc.Col([
361
+ html.H4("Output"),
362
+ html.Div(id="analysis-output")
363
+
364
+ ], width=9)
365
+
366
+ ])
367
+
368
+ ]
369
+ )
370
+
371
+ quality_layout = html.Div([
372
+ html.H1("Propensity Score Matching Evaluation Metrics"),
373
+ html.Br(),
374
+
375
+ dbc.Row([
376
+ dbc.Col([
377
+ html.Button("Run Quality Assurance Script", id="run-quality", n_clicks=0, className="btn btn-primary", style = {'margin-bottom': '20px',}),
378
+ ], width = 3),
379
+ dbc.Col([
380
+ html.Div(id='output-quality-error', style={'color':'red'})
381
+ ], width = 9)
382
+ ]),
383
+
384
+ html.Br(),
385
+
386
+ dbc.Row([
387
+ html.H3("Distribution of Propensity Scores"),
388
+
389
+ dbc.Col([
390
+ html.H4("Plot"),
391
+
392
+ html.Div(id='propensity-distribution')
393
+
394
+
395
+ ], width=8),
396
+
397
+ dbc.Col([
398
+ html.H4("Explanation"),
399
+
400
+ html.P(
401
+ "In this application, the Propensity Score Distribution visualises the likelihood that an area "
402
+ "or individual would receive the treatment based on observed covariates. The propensity score "
403
+ "is a value between 0 and 1 that indicates the probability of receiving treatment, given a set "
404
+ "of characteristics. "
405
+ "The plot displays the distribution of propensity scores "
406
+ "for both the treated and control groups. "
407
+ ),
408
+
409
+ html.P("Key Considerations:"),
410
+ html.Ul([
411
+ html.Li(
412
+ "Overlap of Distributions: Ideally, the propensity score distributions for treated and control "
413
+ "groups should overlap significantly. This overlap indicates that the groups are comparable in terms "
414
+ "of covariates, which is crucial for reducing bias in the analysis."
415
+ ),
416
+ html.Li(
417
+ "Quality of Matching: After matching, a significant overlap with similar shapes in the distributions "
418
+ "suggests successful balancing of covariates between the groups. Poor overlap or disparate shapes may "
419
+ "indicate inadequate matching."
420
+ ),
421
+ html.Li(
422
+ "Potential Issues: Sparse regions in the distribution suggest a lack of overlap, meaning some treated "
423
+ "units lack suitable control matches. Additionally, outliers or extreme scores may signal issues with "
424
+ "the model or covariates."
425
+ ),
426
+ ]),
427
+ html.P(
428
+ "By examining these distributions, you can assess the effectiveness of the matching process and identify "
429
+ "any potential issues that could affect the reliability of the analysis."
430
+ )
431
+
432
+ ],
433
+ width=4,
434
+ style={
435
+ 'backgroundColor': 'rgba(173, 216, 230, 0.8)', # Pale blue color
436
+ 'padding': '20px',
437
+ 'border': '1px solid #ccc'
438
+ })
439
+ ],
440
+ style={
441
+ 'backgroundColor': 'rgba(173, 216, 230, 0.5)', # Pale blue color
442
+ 'padding': '20px',
443
+ 'border': '1px solid #ccc'
444
+ }),
445
+
446
+ dbc.Row([
447
+ html.H3("Balance of Covariates"),
448
+
449
+ dbc.Col([
450
+ html.H4("Explanation"),
451
+
452
+ dcc.Markdown('''
453
+ **Balance of Covariates Distribution Plots** are visual tools used to compare the distributions of covariates (variables) between treated and control groups after matching. The goal is to assess if the matching process has made the treated and control groups similar in terms of the covariates. If the matching is successful, the distributions for the treated and control groups should appear more similar, suggesting that the groups are well balanced.
454
+
455
+ **Standard Mean Difference (SMD)** is a numerical metric used to quantify the balance of covariates between treated and control groups. It measures the difference in means of a covariate between the two groups, standardised by the pooled standard deviation. An SMD close to 0 indicates that the covariate is well-balanced between the groups, while a larger SMD suggests imbalance.
456
+
457
+ **Interpreting the Plots and SMD:**
458
+ - **Well-Matched Covariates:** After matching, the covariate distributions between treated and control groups should overlap significantly, and the SMD should be close to 0.
459
+ - **Poor Matching:** If the distributions differ significantly or the SMD is still large after matching, it indicates that the matching did not adequately balance the groups.
460
+ - **SMD Threshold:** As a general rule, an SMD below 0.1 is considered acceptable, indicating a good balance between the groups.
461
+
462
+ These tools help assess the effectiveness of the matching process and ensure that the treatment effect is estimated from comparable groups.
463
+ '''),
464
+
465
+ ], width=3,
466
+ style={
467
+ 'backgroundColor': 'rgba(172, 230, 174, 0.8)',
468
+ 'padding': '20px',
469
+ 'border': '1px solid #ccc'
470
+ }),
471
+
472
+ dbc.Col([
473
+ html.H4("Plot & Standard Mean Difference (SMD)"),
474
+ html.Div([
475
+ html.Div(id='output-covariate-balance',
476
+ style={
477
+ 'display': 'grid',
478
+ 'gridTemplateColumns': 'repeat(auto-fill, minmax(400px, 1fr))',
479
+ 'gap': '20px'})
480
+ ], style={'padding': '20px'})
481
+
482
+
483
+ ], width=9)
484
+
485
+
486
+ ],
487
+ style={
488
+ 'backgroundColor': 'rgba(172, 230, 174, 0.5)', # Pale blue color
489
+ 'padding': '20px',
490
+ 'border': '1px solid #ccc'
491
+ }),
492
+
493
+ dbc.Row([
494
+ html.H3("t-Test"),
495
+
496
+ dbc.Col([
497
+ html.H4("Results"),
498
+
499
+ html.Br(),
500
+
501
+ html.Div(id="ttest-output")
502
+
503
+ ], width=3),
504
+
505
+ dbc.Col([
506
+ html.H4("Explanation"),
507
+
508
+ dcc.Markdown('''
509
+ In Propensity Score Matching (PSM), the **t-test** is used to assess the balance of covariates between the treated group (those who received the treatment) and the control group (those who did not receive the treatment).
510
+
511
+ The t-test evaluates the null hypothesis that the means of a specific covariate are equal between the treated and control groups. Essentially, it checks whether the difference in means is statistically significant. A well-balanced covariate between the groups is indicated by a high p-value, suggesting that the matching process has been effective.
512
+
513
+ ###### How to Interpret the t-Test in PSM?
514
+
515
+ - **P-value**:
516
+ - **High P-value (e.g., p > 0.05)**: Indicates no statistically significant difference in means between the treated and control groups, suggesting that the covariate is well balanced after matching.
517
+ - **Low P-value (e.g., p < 0.05)**: Indicates a significant difference in means, suggesting that the covariate is not well balanced, even after matching.
518
+
519
+ ###### Why is the t-Test Important in PSM?
520
+
521
+ The t-test is crucial for assessing the success of the matching process. By checking for balance in covariates, it helps ensure that the treated and control groups are comparable. This balance is essential for reducing confounding bias and obtaining accurate estimates of the treatment effect. Significant differences detected by the t-test may indicate that the matching process needs improvement to achieve better balance.
522
+
523
+ In summary, the t-test helps validate the effectiveness of the matching process by evaluating whether covariates are balanced between the treated and control groups, ensuring a more accurate assessment of treatment effects.
524
+
525
+ ''')
526
+
527
+ ], width=9,
528
+ style={
529
+ 'backgroundColor': 'rgba(157, 39, 245, 0.3)',
530
+ 'padding': '20px',
531
+ 'border': '1px solid #ccc'
532
+ })
533
+ ],
534
+ style={
535
+ 'backgroundColor': 'rgba(157, 39, 245, 0.2)',
536
+ 'padding': '20px',
537
+ 'border': '1px solid #ccc'
538
+ })
539
+
540
+
541
+ ])
542
+
543
+
544
+ #%% App Layout
545
+
546
+ app.layout = html.Div(
547
+ [
548
+ dcc.Location(id="url", refresh=False),
549
+ navbar,
550
+ dbc.Container(id="page-content", className="mb-4", fluid=True),
551
+ dcc.Store(id='stored-data', storage_type='session')
552
+ ]
553
+ )
554
+
555
+ @app.callback(Output("page-content", "children"), Input("url", "pathname"))
556
+ def display_page(pathname):
557
+ if pathname == "/":
558
+ return overview_layout
559
+ elif pathname == "/match":
560
+ return match_layout
561
+ elif pathname == "/quality":
562
+ return quality_layout
563
+ else:
564
+ return dbc.Jumbotron(
565
+ [
566
+ html.H1("404: Not found", className="text-danger"),
567
+ html.Hr(),
568
+ html.P(f"The pathname {pathname} was not recognized..."),
569
+ ]
570
+ )
571
+
572
+
573
+
574
+ #%% Retain Data Across Pages
575
+
576
+ #Callback to store input values automatically when they change
577
+
578
+ @app.callback(
579
+ Output('stored-data', 'data'),
580
+ Input('treatment-toggle', 'value'),
581
+ Input('upload-data', 'contents'),
582
+ Input('upload-data', 'filename'),
583
+ Input('area-id-column', 'value'),
584
+ Input('treatment-column', 'value'),
585
+ Input('covariate-columns', 'value')
586
+ )
587
+
588
+ def store_inputs(treatment_toggle, contents, filename, area_id_col, treatment_col, covariates_cols):
589
+
590
+ return {'treatment_toggle': treatment_toggle,
591
+ 'contents': contents,
592
+ 'filename': filename,
593
+ 'area_id_col': area_id_col,
594
+ 'treatment_col': treatment_col,
595
+ 'covariate-columns': covariates_cols}
596
+
597
+
598
+ #Load Data When Revisit Matching
599
+ @app.callback(
600
+ Output('treatment-toggle', 'value'),
601
+ Output('upload-data', 'contents'),
602
+ Output('upload-data', 'filename'),
603
+ Output('area-id-column', 'value'),
604
+ Output('treatment-column', 'value'),
605
+ Output('covariate-columns', 'value'),
606
+ Output('run-analysis', 'n_clicks'),
607
+ Input('url', 'pathname'),
608
+ State('stored-data', 'data')
609
+ )
610
+ def restore_toggle_state(pathname, stored_data):
611
+
612
+ if pathname == '/match' and stored_data is not None:
613
+ return stored_data.get('treatment_toggle'), stored_data.get('contents'), stored_data.get('filename'), stored_data.get('area_id_col'), stored_data.get('treatment_col'), stored_data.get('covariate-columns'), 1
614
+
615
+ return dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update
616
+
617
+
618
+ #Add Clear Button
619
+
620
+ @app.callback(
621
+ Output('stored-data', 'data', allow_duplicate=True),
622
+ Output('treatment-toggle', 'value', allow_duplicate=True),
623
+ Output('upload-data', 'contents', allow_duplicate=True),
624
+ Output('upload-data', 'filename', allow_duplicate=True),
625
+ Output('area-id-column', 'value', allow_duplicate=True),
626
+ Output('treatment-column', 'value', allow_duplicate=True),
627
+ Output('covariate-columns', 'value', allow_duplicate=True),
628
+ Output('run-analysis', 'n_clicks', allow_duplicate=True),
629
+ Input('clear-button', 'n_clicks'),
630
+ prevent_initial_call=True
631
+ )
632
+ def clear_stored_data(n_clicks):
633
+ if n_clicks:
634
+
635
+ return None, None, None, None, None, None, None, 0
636
+
637
+ return dash.no_update
638
+
639
+ #%% App Functions
640
+
641
+
642
+
643
+ # Utility function to parse the uploaded CSV file
644
+ def parse_contents(contents, filename):
645
+ content_type, content_string = contents.split(',')
646
+ decoded = base64.b64decode(content_string)
647
+ try:
648
+ if 'csv' in filename:
649
+ df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))
650
+ else:
651
+ return None
652
+ except Exception as e:
653
+ print(e)
654
+ return None
655
+ return df
656
+
657
+ # Update the progress bar and dropdown options based on uploaded file
658
+ @app.callback(
659
+ Output('upload-progress', 'value'),
660
+ Output('upload-progress', 'children'),
661
+ Output('upload-progress', 'style'),
662
+ Output('area-id-column', 'options'),
663
+ Output('treatment-column', 'options'),
664
+ Output('covariate-columns', 'options'),
665
+ Input('upload-data', 'contents'),
666
+ State('upload-data', 'filename')
667
+ )
668
+
669
+ def update_progress_bar(contents, filename):
670
+ if contents is None:
671
+ return 0, "", {'backgroundColor': 'lightgray'}, [], [], []
672
+
673
+ # Start the progress bar at 50% when the file is detected
674
+ progress_value = 50
675
+ progress_text = "Uploading..."
676
+
677
+ # Parse the file
678
+ df = parse_contents(contents, filename)
679
+ if df is not None:
680
+ columns = [{'label': col, 'value': col} for col in df.columns]
681
+
682
+ # Finish the progress bar when the file is fully loaded
683
+ return 100, "Upload Complete", {'backgroundColor': 'green'}, columns, columns, columns
684
+ else:
685
+ return 0, "Failed to upload", {'backgroundColor': 'red'}, [], [], []
686
+
687
+
688
+ # Conditional analysis based on treatment selection
689
+ @app.callback(
690
+ [Output('analysis-output', 'children'),
691
+ Output('raw-results', 'data')],
692
+ Input('run-analysis', 'n_clicks'),
693
+ State('treatment-toggle', 'value'),
694
+ State('upload-data', 'contents'),
695
+ State('upload-data', 'filename'),
696
+ State('area-id-column', 'value'),
697
+ State('treatment-column', 'value'),
698
+ State('covariate-columns', 'value'),
699
+ prevent_initial_call=True
700
+ )
701
+ def run_analysis(n_clicks, treatment_toggle, contents, filename, area_id_col, treatment_col, covariates_cols):
702
+ if n_clicks == 0 or contents is None:
703
+ return "", ""
704
+
705
+ df = parse_contents(contents, filename)
706
+ if df is not None and area_id_col is not None and covariates_cols:
707
+ # Set the area ID as the index for easier referencing
708
+ df.set_index(area_id_col, inplace=True)
709
+
710
+ #Standardize Covariates
711
+ scaler = StandardScaler()
712
+ covariates_scaled = scaler.fit_transform(df[covariates_cols])
713
+
714
+ if treatment_toggle:
715
+ # Treatment areas selected: Perform propensity score matching
716
+ if treatment_col is None:
717
+ return "Please select a treatment column.", ""
718
+
719
+ if area_id_col == treatment_col:
720
+ return "The treatment column must be different from the label column.", ""
721
+
722
+ if not set(df[treatment_col].unique()).issubset({0, 1}):
723
+ return "Treatment column must contain a binary response. 1 = Treatment // 0 = Control.", ""
724
+
725
+ #Estimate Propensity Scores
726
+ logistic = LogisticRegression()
727
+ logistic.fit(covariates_scaled, df[treatment_col])
728
+ df['propensity_score'] = logistic.predict_proba(covariates_scaled)[:, 1]
729
+
730
+ #Extract Treatment & Control
731
+ treated = df[df[treatment_col] == 1]
732
+ control = df[df[treatment_col] == 0]
733
+
734
+ #Perform Matching
735
+ nn = NearestNeighbors(n_neighbors=1)
736
+ nn.fit(control[['propensity_score']])
737
+
738
+ treated_indices = df[df[treatment_col] == 1].index
739
+ control_indices = df[df[treatment_col] == 0].index
740
+
741
+ if len(treated_indices) > 0:
742
+ distances, indices = nn.kneighbors(treated[['propensity_score']])
743
+ matched_data = pd.DataFrame({
744
+ 'Treated_Area': treated_indices,
745
+ 'Matched_Control_Area': control.iloc[indices.flatten()].index,
746
+ 'Distance': distances.flatten()
747
+ })
748
+
749
+ # Create raw results dataframe
750
+ raw_results = matched_data.copy()
751
+
752
+ return dbc.Table.from_dataframe(matched_data, striped=True, bordered=True, hover=True), raw_results.to_dict('records')
753
+
754
+ return "No treated areas to match.", ""
755
+
756
+ else:
757
+ # No treatment: Find similar areas using nearest neighbors
758
+ nn = NearestNeighbors(n_neighbors=2) # 2 to get the nearest neighbor excluding the point itself
759
+ nn.fit(covariates_scaled)
760
+
761
+ distances, indices = nn.kneighbors(covariates_scaled)
762
+
763
+ #Filter Self Returns
764
+ indicesResults = []
765
+
766
+ for i in range(len(indices)):
767
+
768
+ #If NN 1 == index select NN 2 else NN 1
769
+ if int(indices[i][0]) == i:
770
+ indicesResults.append((indices[i][1], distances[i][1]))
771
+ else:
772
+ indicesResults.append((indices[i][0], distances[i][0]))
773
+
774
+ indicesResults = np.array(indicesResults)
775
+
776
+
777
+ similar_areas = pd.DataFrame({
778
+ 'Area': df.index,
779
+ 'Most_Similar_Area': df.index[indicesResults[:, 0].astype(int)],
780
+ 'Similarity_Score': indicesResults[:, 1]
781
+ })
782
+
783
+ # Create raw results dataframe
784
+ raw_results = similar_areas.copy()
785
+
786
+ return dbc.Table.from_dataframe(similar_areas, striped=True, bordered=True, hover=True), raw_results.to_dict('records')
787
+
788
+ return "Please upload a valid CSV file and select the appropriate columns.", ""
789
+
790
+
791
+
792
+
793
+ # Example callback for downloading data
794
+ @app.callback(
795
+ Output("download-data", "data"),
796
+ Input("download-button", "n_clicks"),
797
+ State("raw-results", "data"),
798
+ prevent_initial_call=True
799
+ )
800
+ def download_results(n_clicks, raw_results):
801
+ if n_clicks > 0 and raw_results is not None:
802
+ # Convert raw results to DataFrame and then to CSV
803
+ df_raw = pd.DataFrame(raw_results)
804
+
805
+ # Get the current time
806
+ now = datetime.now()
807
+ current_dt = now.strftime("%Y-%m-%d_%H%M%S")
808
+
809
+ return dcc.send_data_frame(df_raw.to_csv, "MOPAC_SpatialMatching_"+str(current_dt)+".csv")
810
+
811
+
812
+ #%% Quality Assurance Functions
813
+
814
+
815
+ def calculate_smd(df, treatment_col, covariates_cols, state):
816
+ smd = []
817
+ treated = df[df[treatment_col] == 1]
818
+ control = df[df[treatment_col] == 0]
819
+
820
+ for cov in covariates_cols:
821
+ treated_mean = treated[cov].mean()
822
+ control_mean = control[cov].mean()
823
+ treated_std = treated[cov].std()
824
+ control_std = control[cov].std()
825
+
826
+ pooled_std = np.sqrt((treated_std**2 + control_std**2) / 2)
827
+ #smd[cov] = np.abs(treated_mean - control_mean) / pooled_std
828
+
829
+ smd.append(f'SMD {state}: {np.abs(treated_mean - control_mean) / pooled_std}')
830
+
831
+ return smd
832
+
833
+
834
+ def plot_covariate_distributions(df, treatment_col, covariates_cols):
835
+ plots = []
836
+ for cov in covariates_cols:
837
+ fig = go.Figure()
838
+
839
+ # Define colors for treatments
840
+ treatments = df[treatment_col].unique()
841
+ colors = ['blue', 'green'] # Customize as needed
842
+ treatment_colors = {treatment: colors[i % len(colors)] for i, treatment in enumerate(treatments)}
843
+ label_mapping = {1: 'Treatment', 0: 'Control'} # Adjust as needed
844
+
845
+ # Add a histogram trace for each treatment
846
+ for treatment in treatments:
847
+ subset = df[df[treatment_col] == treatment]
848
+ color = treatment_colors[treatment]
849
+
850
+ # Add histogram trace
851
+ fig.add_trace(go.Histogram(
852
+ x=subset[cov],
853
+ name=label_mapping.get(treatment, str(treatment)),
854
+ opacity=0.6,
855
+ histnorm='probability density',
856
+ nbinsx=30,
857
+ bingroup=1, # Ensure histograms are layered
858
+ marker_color=color # Set color of histogram bars
859
+ ))
860
+
861
+ # Calculate KDE for each subset
862
+ kde = gaussian_kde(subset[cov].dropna())
863
+ x = np.linspace(subset[cov].min(), subset[cov].max(), 1000)
864
+ kde_y = kde(x)
865
+
866
+ # Add KDE trace with the same color
867
+ fig.add_trace(go.Scatter(
868
+ x=x,
869
+ y=kde_y,
870
+ mode='lines',
871
+ name=f'KDE {label_mapping.get(treatment, str(treatment))}',
872
+ line=dict(color=color, width=2), # Set color of KDE line
873
+ showlegend=False # Hide KDE lines from the legend
874
+ ))
875
+
876
+ # Update layout
877
+ fig.update_layout(
878
+ title=f'Distribution of {cov}',
879
+ xaxis_title=cov,
880
+ yaxis_title='Density',
881
+ barmode='overlay', # Layer the histograms
882
+ legend_title='Treatment',
883
+ bargap=0.1
884
+ )
885
+
886
+ plots.append(fig)
887
+
888
+ return plots
889
+
890
+
891
+ def plot_propensity_scores(df, treatment_col):
892
+ fig = go.Figure()
893
+
894
+ # Define labels for treatment and control
895
+ label_mapping = {1: 'Treatment', 0: 'Control'}
896
+
897
+ # Get unique treatments
898
+ treatments = df[treatment_col].unique()
899
+
900
+ # Define a color map (you can customize these colors)
901
+ colors = ['blue', 'green']
902
+
903
+ # Ensure the number of colors matches the number of treatments
904
+ treatment_colors = {treatment: colors[i % len(colors)] for i, treatment in enumerate(treatments)}
905
+
906
+ # Add a histogram trace for each treatment
907
+ for treatment in treatments:
908
+ subset = df[df[treatment_col] == treatment]
909
+ color = treatment_colors[treatment]
910
+
911
+ # Add histogram trace
912
+ fig.add_trace(go.Histogram(
913
+ x=subset['propensity_score'],
914
+ name=label_mapping.get(treatment, str(treatment)), # Set custom label
915
+ opacity=0.6,
916
+ histnorm='probability density', # Use density
917
+ nbinsx=30,
918
+ bingroup=1, # Ensures histograms are layered
919
+ marker_color=color # Set the color of the histogram bars
920
+ ))
921
+
922
+ # Calculate KDE for each subset
923
+ kde = gaussian_kde(subset['propensity_score'].dropna())
924
+ x = np.linspace(subset['propensity_score'].min(), subset['propensity_score'].max(), 1000)
925
+ kde_y = kde(x)
926
+
927
+ # Add KDE trace with the same color
928
+ fig.add_trace(go.Scatter(
929
+ x=x,
930
+ y=kde_y,
931
+ mode='lines',
932
+ name=f'KDE {label_mapping.get(treatment, str(treatment))}', # Set custom label for KDE
933
+ line=dict(color=color, width=2), # Set the color of the KDE line
934
+ showlegend=False # Hide KDE lines from the legend
935
+ ))
936
+
937
+ # Update layout
938
+ fig.update_layout(
939
+ title='Distribution of Propensity Scores',
940
+ xaxis_title='Propensity Score',
941
+ yaxis_title='Density', # Use 'Density' on the Y-axis
942
+ barmode='overlay', # Layer the histograms
943
+ legend_title='Group',
944
+ bargap=0.1
945
+ )
946
+
947
+ return fig
948
+
949
+
950
+ def t_test_covariates(df, treatment_col, covariates_cols):
951
+ t_test_results = {}
952
+ treated = df[df[treatment_col] == 1]
953
+ control = df[df[treatment_col] == 0]
954
+
955
+ for cov in covariates_cols:
956
+ t_stat, p_value = stats.ttest_ind(treated[cov], control[cov], equal_var=False)
957
+ t_test_results[cov] = {'t_stat': t_stat, 'p_value': p_value}
958
+
959
+ return t_test_results
960
+
961
+
962
+ @app.callback(
963
+ Output('output-quality-error', 'children'),
964
+ Output('output-covariate-balance', 'children'),
965
+ Output('ttest-output', 'children'),
966
+ Output('propensity-distribution', 'children'),
967
+ Input('run-quality', 'n_clicks'),
968
+ Input('url', 'pathname'),
969
+ Input('stored-data', 'data')
970
+
971
+ )
972
+ def quality_assurance(n_clicks, pathname, stored_data):
973
+
974
+ if pathname == '/quality' and n_clicks:
975
+
976
+ if stored_data is None:
977
+ return "Error: Please Run the Analysis First.", "", "", ""
978
+
979
+ #Get the data
980
+ treatment_toggle = stored_data.get('treatment_toggle')
981
+ file_contents = stored_data.get('contents')
982
+ file_name = stored_data.get('filename')
983
+ area_id_col = stored_data.get('area_id_col')
984
+ treatment_col = stored_data.get('treatment_col')
985
+ covariate_cols = stored_data.get('covariate-columns')
986
+
987
+ if any(value is None for value in stored_data.values()):
988
+ return "Error: Please Run the Treatment-Control Matching First.", "", "", ""
989
+
990
+ if not treatment_toggle:
991
+ return "Error: Quality Assurance Requires a Treatment and Control Group", "", "", ""
992
+
993
+ if treatment_col is None:
994
+ return "Error: Please select a treatment column.", "", "", ""
995
+
996
+ if area_id_col == treatment_col:
997
+ return "Error: The treatment column must be different from the label column.", "", "", ""
998
+
999
+
1000
+ #Parse data
1001
+ df = parse_contents(file_contents, file_name)
1002
+
1003
+ if not set(df[treatment_col].unique()).issubset({0, 1}):
1004
+ return "Error: Treatment column must contain a binary response. 1 = Treatment // 0 = Control.", "", "", ""
1005
+
1006
+ #Check Treated Areas True
1007
+ if len(df[df[treatment_col] == 1].index) == 0:
1008
+ return "Error: No treated areas to match.", "", "", ""
1009
+
1010
+ def generate_match_data(df, treatment_col, covariate_cols):
1011
+
1012
+ #Get subset of data
1013
+ treatment = df[treatment_col]
1014
+ covariates = df[covariate_cols]
1015
+
1016
+
1017
+ #Data Transform
1018
+ scaler = StandardScaler()
1019
+ covariates_scaled = scaler.fit_transform(covariates)
1020
+
1021
+ #Propensity Scores
1022
+ logistic = LogisticRegression()
1023
+ logistic.fit(covariates_scaled, treatment)
1024
+
1025
+ # Get the propensity scores
1026
+ df['propensity_score'] = logistic.predict_proba(covariates_scaled)[:, 1]
1027
+
1028
+
1029
+ #Subset data
1030
+ treated = df[df[treatment_col] == 1]
1031
+ control = df[df[treatment_col] == 0]
1032
+
1033
+ #NN Matching
1034
+ nn = NearestNeighbors(n_neighbors=1)
1035
+ nn.fit(control[['propensity_score']])
1036
+
1037
+ distances, indices = nn.kneighbors(treated[['propensity_score']])
1038
+
1039
+ matched_control = control.iloc[indices.flatten()]
1040
+
1041
+
1042
+ df_matched = pd.concat([treated, matched_control])
1043
+
1044
+ return(df_matched)
1045
+
1046
+
1047
+ df_matched = generate_match_data(df, treatment_col, covariate_cols)
1048
+
1049
+
1050
+ ## BALANCE OF COVARIATES
1051
+ plots_boc = plot_covariate_distributions(df_matched, treatment_col, covariate_cols)
1052
+
1053
+ stats_boc_b = calculate_smd(df, treatment_col, covariate_cols, 'Before')
1054
+ stats_boc_a = calculate_smd(df_matched, treatment_col, covariate_cols, 'After')
1055
+
1056
+
1057
+ out_covariate_balance = []
1058
+
1059
+ for plot, stat_b, stat_a in zip(plots_boc, stats_boc_b, stats_boc_a):
1060
+
1061
+ out_covariate_balance.append(html.Div([dcc.Graph(figure=plot),
1062
+ html.Br(),
1063
+ html.P(stat_b),
1064
+ html.P(stat_a)], className='grid-item'))
1065
+
1066
+ ## Propensity Distribution
1067
+ prop_plot = plot_propensity_scores(df, treatment_col)
1068
+
1069
+
1070
+ ## t-TEST RESULTS
1071
+ t_test_results = t_test_covariates(df, treatment_col, covariate_cols)
1072
+
1073
+ out_t_test = []
1074
+
1075
+ for main_key, sub_dict in t_test_results.items():
1076
+
1077
+ p_value = sub_dict.get('p_value')
1078
+ t_stat = sub_dict.get('t_stat')
1079
+
1080
+ out_t_test.append(html.Div([html.H6(main_key),
1081
+ html.Ul([
1082
+ html.Li(f'p-Value: {p_value}'),
1083
+ html.Li(f't-Stat: {t_stat}')
1084
+ ])
1085
+ ]))
1086
+
1087
+ return "", out_covariate_balance, out_t_test, html.Div([dcc.Graph(figure=prop_plot)])
1088
+
1089
+ else:
1090
+
1091
+ return "", "", "", ""
1092
+
1093
+
1094
+ #%% Main
1095
+
1096
+ # Run the app
1097
+ if __name__ == '__main__':
1098
+ app.run_server(debug=False, host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))