-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinputs-form.qmd
474 lines (379 loc) · 16.5 KB
/
inputs-form.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
---
title: "Gagarin City Scan Test"
format:
html:
theme: [custom.scss, none]
editor: source
execute:
echo: false
output: false
---
::: setup
{{< include scrollytelling.qmd >}}
```{ojs}
// Object of forms for interactively adding takeaway bullets
takeaway_inputs = ({})
```
```{r}
#| include: false
# Read functions & packages
# Only the github version of leaflet supports terra, in place of raster, which is now required as sp (on which raster depends) is being deprecated
# devtools::install_github('rstudio/leaflet')
source("fns.R")
# City parameters
city_params <- read_yaml("city_inputs.yml")
# cities <- list.files("cities")
city <- city_params$city_name
city_string <- tolower(city) %>% stringr::str_replace_all(" ", "-")
city_dir <- paste0("cities/", city_string, "/")
output_dir <- paste0(city_dir, "styled-maps/")
# raster_dir <- paste0(city_dir, "/output")
country <- city_params$country
# Visualization parameters
basemap_opacity <- 0.3
legend_opacity <- 0.8
vwidth <- 900
vheight <- vwidth
# this is to enable fractional zoom in mapshot
useragent <- 'Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0'
# Layers
layer_params <- read_yaml('layers.yml')
```
```{r}
#| include: false
# Define the AOI
aoi <- st_read(paste0(city_dir, "AOI"))
aoi_bounds <- st_bbox(aoi)
# Inititate the map here, will build on it in each "slide"
all_maps <- plot_basemap("vector")
# Keep track of added layers
added_layers <- c()
```
:::
::: topbar
# {{< meta title >}}
::: navigation
```{r}
#| output: asis
# Dynamically add sections to table of contents ... there's probably a better way?
sections <- readLines("/Users/bennotkin/Documents/world-bank/crp/city-scans/city-scan-automation/frontend/city-scan-html-sample/index.qmd") %>%
subset(str_detect(., "^##")) %>% str_replace("# ", "- ") %>% str_replace_all("#", " ")
anchors <- sections %>% str_extract("^\\s*- (.*$)", group = T) %>% tolower() %>% str_replace_all(c("[^a-z\\s]" = "", "\\s+" = "-")) %>%
str_replace("(.*)", "(#\\1)")
paste0(str_replace(sections, "(^\\s*- )(.+$)", "\\1[\\2]"), anchors) %>% { cat("- <span id='dynamic-header'>City Scan</span> ∨", ., sep = "\n") }
```
[Prewritten](https://bennotkin.quarto.pub/city-scan-html-sample/)
:::
:::
::: text-column
# {{< meta title >}}
## Setting the Context
### Basic City Information
```{r}
# Add a map layer? But it's just the AOI
```
```{ojs}
//| output: true
viewof basic_info = Inputs.textarea({placeholder: "Write a description of the city's geography, history, economy and culture. Add styling with markdown.", width: "100%"})
// I could set submit: true to require a submit button, but I think it's easier if they don't have to
// Only helpful if we're doing something other than letting them record everything at the end
```
```{ojs}
// This compiles the form results together
takeaway_inputs.basic_info = basic_info
```
::: footnote
The black boundary marks the area of interest for the City Scan.
:::
### The State of Urban Infrastructure and Service Delivery
_Insert the infrastructure text here._
## Population and Demographic Trends
### Growth

```{ojs}
//| output: true
viewof population_growth = Inputs.textarea({placeholder: "What are the key takeaways from this data?", width: "100%"})
// I could set submit: true to require a submit button, but I think it's easier if they don't have to
// Only helpful if we're doing something other than letting them record everything at the end
```
```{ojs}
// This compiles the form results together
takeaway_inputs.population_growth = population_growth
```
Population figures are typically used as a denominator for many indicators, and are a measure of demand for services. The line chart above summarizes the city's population change according to census and other public data. High growth of urban populations, caused by rates of natural increase (more births than deaths) in urban areas, migration from rural to urban areas, and the transformation of rural settlements into urban places, puts pressure on cities to meet the new demand.
### Density

```{ojs}
//| output: true
viewof population_density_chart = Inputs.textarea({placeholder: "What are the key takeaways from this data?", width: "100%"})
// I could set submit: true to require a submit button, but I think it's easier if they don't have to
// Only helpful if we're doing something other than letting them record everything at the end
```
```{ojs}
// This compiles the form results together
takeaway_inputs.population_density_chart = population_density_chart
```
Density is calculated using the most recent census population recorded and the official land area occupied by the city, and is an important measure of how cities function. Higher population density enables governments to more easily deliver essential infrastructure and services in urban areas at relatively low cost per capita. However, such benefits do not materialize automatically or inevitably. Whether a city's population dynamics pose challenges or offer opportunities typically depends on the policies in play.
::: footnote
Populations and areas are from CityPopulation.de. Note that the extents used by CityPopulation.de may differ from the AOIs used by the City Scans. The area for Gagarin (Combined) uses the combined areas of each of the six included villages; it does not include the space in between.
:::
### Population Distribution by Age & Sex

```{ojs}
//| output: true
viewof population_age_sex = Inputs.textarea({placeholder: "What are the key takeaways from this data?", width: "100%"})
// I could set submit: true to require a submit button, but I think it's easier if they don't have to
// Only helpful if we're doing something other than letting them record everything at the end
```
```{ojs}
// This compiles the form results together
takeaway_inputs.population_age_sex = population_age_sex
```
This column chart classifies the city's population according to age group, forming the basis of population projections. Populations vary significantly in their proportions of young and old people, with growing populations generally appearing younger, and declining or slowly growing populations generally appearing older.
::: footnote
Data from WorldPop. Bondarenko, et al, Estimates of total number of people per grid square broken down by gender and age groupings for 51 countries across sub-Saharan Africa in 2020 using Ecopia.AI and Maxar Technologies building footprints, 2020.
Reproductive age is defined as 15--49. Working age is defined as 15--64.
:::
### Population Density
```{r}
#| include: false
# Read population data
pop <- fuzzy_read(city_dir, "population")
add_pop_layer <- create_layer_function(data = pop, yaml_key = "population")
all_maps <- add_pop_layer(all_maps)
# This could be put into the add_*_layer() functions themselves
# hideGroup("population-density")
added_layers <- c(added_layers, "population-density")
```
```{ojs}
//| output: true
viewof population_density = Inputs.textarea({placeholder: "What are the key takeaways from this data?", width: "100%"})
// I could set submit: true to require a submit button, but I think it's easier if they don't have to
// Only helpful if we're doing something other than letting them record everything at the end
```
```{ojs}
// This compiles the form results together
takeaway_inputs.population_density = population_density
```
This map estimates population numbers per 10,000 m^2^ grid cell. It provides a more consistent representation of population distributions across different landscapes than administrative unit counts. Knowing where people are is critical for impact assessments and intervention plans, especially those focused on service delivery, food security, climate change, network systems and natural disasters.
### Relative Wealth Index
```{r}
#| include: false
# Read RWI
rwi <-
st_read(paste0(city_dir, "output/relative_wealth_index"), quiet = T) %>%
select(values = rwi, long = longitude, lat = latitude)
# # Using terra intead of sf for consistency
# # Except this doesn't work well because there are multiple value columns so it gets complicated to use programmatically
# rwi <- vect(paste0(city_dir, "output/relative_wealth_index"))
# rwi_range <- max(c(abs(min(rwi$values)), max(rwi$values))) %>% {c(-., 0, .)}
# rwi_color_scale <- colorNumeric(
# palette = colorRamp(
# c('#ED431B', '#FF9169', '#FFFFBA', '#70C5AD', '#009E7A'),
# interpolate = 'linear'),
# domain = NULL,
# na.color = 'transparent')
#
# add_rwi_layer <- function(map) {
# map %>% addPolygons(
# data = rwi,
# fillColor = ~ rwi_color_scale(values),
# fillOpacity = 1,
# stroke = F,
# group = "rwi",
# label = ~ values) %>%
# addLegend(
# 'bottomright',
# pal = rwi_color_scale,
# values = c(min(rwi$values, na.rm = T), max(rwi$values, na.rm = T)),
# opacity = legend_opacity,
# # bins = 3, # legend color ramp does not render if there are too many bins
# title = layer_params$rwi$title,
# labFormat = labelFormat(),
# group = "rwi",
# # Adding classname because hideGroup() doesn't hide legend; see workaround
# # here: https://github.com/rstudio/leaflet/issues/477#issuecomment-678542769
# className = "info legend rwi"
# )
# }
#
# plot_basemap() %>% add_rwi_layer() %>%
# htmlwidgets::onRender("
# function(el, x) {
# var updateLegend = function () {
# var selectedGroup = document.querySelectorAll('input:checked')[0].nextSibling.innerText.substr(1);
#
# document.querySelectorAll('.legend').forEach(a => a.hidden=true);
# document.querySelectorAll('.legend').forEach(l => {
# if (l.classList.contains(selectedGroup)) l.hidden=false;
# });
# };
# updateLegend();
# this.on('overlayremove', el => updateLegend());
# }") %>%
# hideGroup("rwi")
add_rwi_layer <- create_layer_function(
data = rwi, yaml_key = "rwi",
labFormat = labelFormat(digits = 1))
all_maps <- add_rwi_layer(all_maps)
# This could be put into the add_*_layer() functions themselves
# hideGroup("relative-wealth-index")
added_layers <- c(added_layers, layer_params[["rwi"]]$group)
```
```{ojs}
//| output: true
viewof rwi = Inputs.textarea({placeholder: "What are the key takeaways from this data?", width: "100%"})
// I could set submit: true to require a submit button, but I think it's easier if they don't have to
// Only helpful if we're doing something other than letting them record everything at the end
```
```{ojs}
// This compiles the form results together
takeaway_inputs.rwi = rwi
```
This map shows micro-estimates of wealth and poverty relative to the whole country that cover the populated surface at a 2.4 km^2^ resolution. Many critical policy decisions, from strategic investments to the allocation of humanitarian aid, rely on data about the geographic distribution of wealth and poverty.
::: footnote
Map data from Meta Data for Good.
:::
## Economic Activity
### Economic Hotspots
```{r}
economic_activity <- fuzzy_read(city_dir, "avg_rad_sum")
add_economic_activity_layer <- create_layer_function(
data = economic_activity, yaml_key = "economic-activity",
labFormat = labelFormat(digits = 2))
all_maps <- add_economic_activity_layer(all_maps)
added_layers <- c(added_layers, layer_params[["economic-activity"]]$group)
```
```{ojs}
//| output: true
viewof economic_hotspots = Inputs.textarea({placeholder: "What are the key takeaways from this data?", width: "100%"})
// I could set submit: true to require a submit button, but I think it's easier if they don't have to
// Only helpful if we're doing something other than letting them record everything at the end
```
```{ojs}
// This compiles the form results together
takeaway_inputs.economic_hotspots = economic_hotspots
```
This map measures the total emissions of nighttime lights from the monthly average of radiance for 2014 through 2022. Nighttime light radiance is a common proxy for economic activity: where there is more artificial light, there is generally more commercial activity.
::: footnote
Map data from NOAA, “VIIRS Daily Mosaic”.
:::
### Change in Economic Hotspots
```{r}
economic_change <- fuzzy_read(city_dir, "linfit")
add_economic_change_layer <- create_layer_function(data = economic_change, yaml_key = "economic-change")
all_maps <- add_economic_change_layer(all_maps)
added_layers <- c(added_layers, layer_params[["economic-change"]]$group)
```
```{ojs}
//| output: true
viewof economic_change = Inputs.textarea({placeholder: "What are the key takeaways from this data?", width: "100%"})
// I could set submit: true to require a submit button, but I think it's easier if they don't have to
// Only helpful if we're doing something other than letting them record everything at the end
```
```{ojs}
// This compiles the form results together
takeaway_inputs.economic_change = economic_change
```
The map illustrates monthly temporal changes from 2014 to 2022 in the emission of nighttime lights, indicating changes in economic activity. Positive values represent an increase in the intensity of nighttime light emission and, by proxy, economic activity, while negative values represent a decrease in the intensity of nighttime light emission, and economic activity.
::: footnote
Map data from NOAA, “VIIRS Daily Mosaic”.
:::
## Built Form
### Urban Extent and Change
```{r}
wsf <- fuzzy_read(city_dir, "WSF.*4326")
values(wsf)[values(wsf) == 0] <- NA
add_wsf_layer <- create_layer_function(data = wsf, yaml_key = "wsf")
all_maps <- add_wsf_layer(all_maps)
added_layers <- c(added_layers, layer_params[["wsf"]]$group)
```
```{ojs}
//| output: true
viewof wsf = Inputs.textarea({placeholder: "What are the key takeaways from this data?", width: "100%"})
// I could set submit: true to require a submit button, but I think it's easier if they don't have to
// Only helpful if we're doing something other than letting them record everything at the end
```
```{ojs}
// This compiles the form results together
takeaway_inputs.wsf = wsf
```
::: footnote
Map data from DLR, 2015, “World Settlement Footprint Evolution - Landsat 5/7 - Global”.
:::
### Now with layers control
Add text
::: footnote
See https://rstudio.github.io/leaflet/showhide.html.
:::
### Land Cover
```{r}
# lc <- fuzzy_read(city_dir, "landcover")
# lc_values <- c(
# # 'No data' = 0,
# 'Tree cover' = 10,
# 'Shrubland' = 20,
# 'Grassland' = 30,
# 'Cropland' = 40,
# 'Built-up' = 50,
# 'Bare/sparse vegetation' = 60,
# 'Snow and ice' = 70,
# 'Permanent water bodies' = 80,
# 'Herbaceous wetland' = 90,
# 'Mangroves' = 95)
# lc_colors <- colorFactor(
# palette = c(
# '0' = 'transparent', # 'No data'
# '10' = '#277242', # 'Tree cover'
# '20' = '#DEBA59', # 'Shrubland'
# '30' = '#79A54F', # 'Grassland'
# '40' = '#E88B39', # 'Cropland'
# '50' = '#C62421', # 'Built-up'
# '60' = '#9C9085', # 'Bare/sparse vegetation'
# '70' = '#DDDDDD', # 'Snow and ice'
# '80' = '#2491D7', # 'Permanent water bodies'
# '90' = '#707CBA', # 'Herbaceous wetland'
# '95' = '#00C86E', # 'Mangroves'
# '100' = '#f6e8a1' # 'Moss and Lichen'),
# levels = c(10*0:9, 95),
# na.color = '#00000000')
# add_lc_layer <- create_layer_function(data = lc, yaml_key = "lc", color_scale = lc_colors)
# add_lc_layer(all_maps)
```
## Another section
### And a "slide" within it
Text
## Download your bullets
*This should probably be moved to floating button.*
```{ojs}
//| output: true
// Taken from https://observablehq.com/@palewire/saving-json
function serialize (data) {
let s = JSON.stringify(data);
return new Blob([s], {type: "application/json"})
}
// This is the wrong way to do this. I am refreshing the takeaway_inputs every tenth of a second
// Instead it should only update when someone hits submit or the text changes
{
DOM.download(serialize(takeaway_inputs), "city-scan-text.json", "Download JSON")
while (true) {
await Promises.delay(1000);
yield DOM.download(serialize(takeaway_inputs), "city-scan-text.json", "Download JSON")
}
}
// console.log(takeaway_inputs)
// DOM.download(serialize(takeaway_inputs), "city-scan-text.json", "Download JSON")
```
:::
::: maps
```{r}
#| output: true
all_maps %>%
add_aoi() %>%
addLayersControl(
overlayGroups = added_layers,
options = layersControlOptions(collapsed = FALSE))
# If I want to use javascript directly I could use htmlwidgets::onRender(),
# or maybe just an observable cell
```
:::