@@ -45,65 +45,6 @@ city_center$lon = st_coordinates(city_center)[,1]
4545city_center$lat = st_coordinates(city_center)[,2]
4646```
4747
48- ::: callout-note
49- ## Note
50-
51- If you don't have census data at a reasonable level (census blocks), you can recreate random points in your city.
52- See the code bellow 🔎
53- :::
54-
55- ``` {r}
56- #| code-fold: true
57- #| code-summary: "Generate synthetic census-like points for a City"
58- # 0. Load libraries
59- library(sf)
60- library(dplyr)
61-
62- # 1. Read city polygon (replace with your file path)
63- city_limit <- st_read("data/city_limit.gpkg") |> st_transform(4326)
64-
65- # 2. Set parameters
66- set.seed(42) # for reproducibility
67- total_pop <- 545000 # your city population
68- avg_residents <- 300 # a census block average
69- n_points <- round(total_pop / avg_residents)
70-
71- # 3. Generate random points within the city boundary
72- census_syn <- st_sample(city_limit, size = n_points, type = "random") |>
73- st_as_sf() |>
74- mutate(id = 1:n_points)
75-
76- # # 4. Compute distance from city center (for density weighting) - OPTIONAL
77- # center <- st_centroid(city_limit)
78- # dist_center <- as.numeric(st_distance(census_syn, center)) # in meters
79- #
80- # # 5. Create weights so closer points get higher population - OPTIONAL
81- # # Inverse distance weighting (add +1 to avoid division by zero)
82- # weights <- 1 / (dist_center + 1)
83-
84- # assign random populations that sum to total_pop
85- weights <- runif(n_points)
86-
87- # Normalize weights to sum to 1 and assign residents
88- residents <- round(weights / sum(weights) * total_pop)
89-
90- # 6. Adjust rounding so the total sums exactly to total_pop
91- diff <- total_pop - sum(residents)
92- if (diff != 0) {
93- residents[1:abs(diff)] <- residents[1:abs(diff)] + sign(diff)
94- }
95-
96- # 7. Add residents to points
97- census_syn$residents <- residents
98- sum(census_syn$residents) # should be total_pop
99-
100- # 8. Quick visualization
101- mapview::mapview(census_syn, zcol = "residents")
102-
103- # 9. Save to GeoPackage
104- st_write(census_syn, "data/synthetic_census_points.gpkg", delete_dsn = TRUE)
105- ```
106-
10748## Travel Time Matrix {#ttm}
10849
10950``` {r}
0 commit comments