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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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Input data for the temporal and spatial RF models\n",
    "\n",
    "Builds `RF_temporal_data.csv` (weekly) and `RF_spatial_data.csv` (1-km grid), following Sections 2.3.1-2.3.4 of the\n",
    "manuscript and Section S1 of the Supplementary Material. Input files are not included; file and column names are\n",
    "placeholders.\n",
    "\n",
    "Disease groups (ICD-10): LRI = J10-J18 and J21-J22; CRD = J44-J45; Other = J00-J99 excluding LRI and CRD.\n",
    "Age groups: G1 = 0-4 years; G2 = 5-59 years; G3 = 60 years and over."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Libraries\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import geopandas as gpd\n",
    "import rasterio\n",
    "from rasterio.mask import mask\n",
    "from shapely.geometry import box, mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Input and output files\n",
    "air_quality_path = '.../path/to/input/air_quality.csv' # datetime, station, so2, no2, nox, co, o3, pm10\n",
    "weather_path = '.../path/to/input/weather.csv' # date, t_mean, t_min, t_max, rh, ws, insolation, evaporation, rainfall\n",
    "admissions_path = '.../path/to/input/admissions.csv' # SIH records\n",
    "population_path = '.../path/to/input/population.csv' # year, population\n",
    "postal_codes_path = '.../path/to/input/pcodes.csv' # cep, x, y\n",
    "\n",
    "boundary_path = '.../path/to/input/municipalities.shp' # Curitiba and Araucária\n",
    "tracts_path = '.../path/to/input/census.shp' # pop, pci, literate, white, black, yellow, brown, indigenous\n",
    "roads_path = '.../path/to/input/roads.shp'\n",
    "gdp_path = '.../path/to/input/gdp.tif'\n",
    "lcz_path = '.../path/to/input/lcz.tif'\n",
    "\n",
    "output_dir = '.../path/to/output/'\n",
    "\n",
    "TARGET_CRS = 'EPSG:31982' # SIRGAS 2000 / UTM zone 22S"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Hospital admissions (DataSUS SIH)\n",
    "# MUNIC_RES: municipality, DT_INTER: admission date, DIAG_PRINC: ICD-10 code,\n",
    "# COD_IDADE: age unit (4 = years), IDADE: age, CEP: postal code\n",
    "adm = pd.read_csv(admissions_path, dtype={'CEP': str, 'DIAG_PRINC': str})\n",
    "\n",
    "# Residents of Curitiba (410690) and Araucária (410180), 2003-2017\n",
    "adm = adm[adm['MUNIC_RES'].isin([410690, 410180])]\n",
    "\n",
    "adm['date'] = pd.to_datetime(adm['DT_INTER'].astype(str), format='%Y%m%d')\n",
    "adm = adm[(adm['date'] >= '2003-01-01') & (adm['date'] <= '2017-12-31')]\n",
    "\n",
    "# Disease group (ICD-10)\n",
    "adm['code'] = adm['DIAG_PRINC'].str[:3]\n",
    "\n",
    "lri_codes = ['J10', 'J11', 'J12', 'J13', 'J14', 'J15', 'J16', 'J17', 'J18', 'J21', 'J22']\n",
    "crd_codes = ['J44', 'J45']\n",
    "\n",
    "adm = adm[adm['code'].str.startswith('J')]\n",
    "\n",
    "adm['disease'] = 'Other'\n",
    "adm.loc[adm['code'].isin(lri_codes), 'disease'] = 'LRI'\n",
    "adm.loc[adm['code'].isin(crd_codes), 'disease'] = 'CRD'\n",
    "\n",
    "# Age in years and age group\n",
    "adm['age'] = np.where(adm['COD_IDADE'] == 4, adm['IDADE'], 0)\n",
    "\n",
    "adm['group'] = 'G2'\n",
    "adm.loc[adm['age'] <= 4, 'group'] = 'G1'\n",
    "adm.loc[adm['age'] >= 60, 'group'] = 'G3'\n",
    "\n",
    "print(adm['disease'].value_counts())\n",
    "print(adm['group'].value_counts())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Temporal input matrix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Air quality: daily mean per station, then mean of the eight stations\n",
    "pollutants = ['so2', 'no2', 'nox', 'co', 'o3', 'pm10']\n",
    "\n",
    "aq = pd.read_csv(air_quality_path, parse_dates=['datetime'])\n",
    "aq['date'] = aq['datetime'].dt.floor('D')\n",
    "\n",
    "aq_station = aq.groupby(['station', 'date'])[pollutants].mean().reset_index()\n",
    "aq_daily = aq_station.groupby('date')[pollutants].mean()\n",
    "\n",
    "print(aq_daily.describe().round(1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Weather and daily temperature amplitude\n",
    "wx = pd.read_csv(weather_path, parse_dates=['date']).set_index('date')\n",
    "wx['t_amp'] = wx['t_max'] - wx['t_min']\n",
    "\n",
    "print(wx.describe().round(1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Climate indices: consecutive days meeting a condition (reset to zero when not met)\n",
    "# Dry: rainfall < 1 mm; wet: rainfall >= 1 mm; hot: TX > 75th percentile; cold: TN < 25th percentile\n",
    "def consecutive_days(condition):\n",
    "    counter = np.zeros(len(condition))\n",
    "    for i in range(len(condition)):\n",
    "        if condition[i]:\n",
    "            if i == 0:\n",
    "                counter[i] = 1\n",
    "            else:\n",
    "                counter[i] = counter[i - 1] + 1\n",
    "        else:\n",
    "            counter[i] = 0\n",
    "    return counter\n",
    "\n",
    "\n",
    "tx_75 = wx['t_max'].quantile(0.75)\n",
    "tn_25 = wx['t_min'].quantile(0.25)\n",
    "\n",
    "wx['cdd'] = consecutive_days((wx['rainfall'] < 1.0).values)\n",
    "wx['cwd'] = consecutive_days((wx['rainfall'] >= 1.0).values)\n",
    "wx['chd'] = consecutive_days((wx['t_max'] > tx_75).values)\n",
    "wx['ccd'] = consecutive_days((wx['t_min'] < tn_25).values)\n",
    "\n",
    "print('TX 75th percentile:', tx_75, '| TN 25th percentile:', tn_25)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Weekly means (rainfall: weekly total)\n",
    "daily = wx.join(aq_daily, how='outer')\n",
    "\n",
    "weather = ['t_min', 't_max', 't_mean', 't_amp', 'rh', 'ws', 'insolation', 'evaporation']\n",
    "climate = ['cdd', 'cwd', 'chd', 'ccd']\n",
    "\n",
    "weekly = daily[weather + climate + pollutants].resample('7D').mean()\n",
    "weekly['rainfall'] = daily['rainfall'].resample('7D').sum(min_count=1)\n",
    "\n",
    "weekly.index.name = 'date'\n",
    "weekly = weekly.reset_index()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Trend and season\n",
    "# Unix time (elapsed seconds since 1970-01-01) and Julian day (1-366)\n",
    "weekly['unix_time'] = (weekly['date'] - pd.Timestamp('1970-01-01')).dt.total_seconds()\n",
    "weekly['julian_day'] = weekly['date'].dt.dayofyear\n",
    "\n",
    "# Season (one-hot, summer as reference)\n",
    "season = {12: 'summer', 1: 'summer', 2: 'summer',\n",
    "          3: 'fall', 4: 'fall', 5: 'fall',\n",
    "          6: 'winter', 7: 'winter', 8: 'winter',\n",
    "          9: 'spring', 10: 'spring', 11: 'spring'}\n",
    "\n",
    "weekly['season'] = weekly['date'].dt.month.map(season)\n",
    "\n",
    "weekly['season_fall'] = (weekly['season'] == 'fall').astype(int)\n",
    "weekly['season_spring'] = (weekly['season'] == 'spring').astype(int)\n",
    "weekly['season_winter'] = (weekly['season'] == 'winter').astype(int)\n",
    "\n",
    "weekly = weekly.drop(columns='season')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Weekly admissions per 1 million inhabitants\n",
    "population = pd.read_csv(population_path).set_index('year')['population']\n",
    "\n",
    "# week of each admission\n",
    "start = weekly['date'].iloc[0]\n",
    "adm['week'] = start + pd.to_timedelta((adm['date'] - start).dt.days // 7 * 7, unit='D')\n",
    "\n",
    "weekly_pop = weekly['date'].dt.year.map(population).values\n",
    "\n",
    "for d in ['LRI', 'CRD', 'Other']:\n",
    "    for g in ['General', 'G1', 'G2', 'G3']:\n",
    "        if g == 'General':\n",
    "            sel = adm[adm['disease'] == d]\n",
    "            col_name = d\n",
    "        else:\n",
    "            sel = adm[(adm['disease'] == d) & (adm['group'] == g)]\n",
    "            col_name = d + '_' + g\n",
    "\n",
    "        counts = sel.groupby('week').size()\n",
    "        weekly[col_name] = counts.reindex(weekly['date']).fillna(0).values / weekly_pop * 1_000_000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Save\n",
    "weekly.to_csv(output_dir + 'RF_temporal_data.csv', index=False)\n",
    "\n",
    "print(weekly.shape)\n",
    "weekly.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Spatial input matrix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1-km grid\n",
    "boundary = gpd.read_file(boundary_path).to_crs(TARGET_CRS)\n",
    "xmin, ymin, xmax, ymax = boundary.total_bounds\n",
    "\n",
    "cells = []\n",
    "for x in np.arange(xmin, xmax, 1000):\n",
    "    for y in np.arange(ymin, ymax, 1000):\n",
    "        cells.append(box(x, y, x + 1000, y + 1000))\n",
    "\n",
    "grid = gpd.GeoDataFrame(geometry=cells, crs=TARGET_CRS)\n",
    "grid = grid[grid.intersects(boundary.union_all())].reset_index(drop=True)\n",
    "\n",
    "grid['grid_id'] = range(len(grid))\n",
    "grid['left'] = grid.bounds['minx']\n",
    "grid['bottom'] = grid.bounds['miny']\n",
    "grid['right'] = grid.bounds['maxx']\n",
    "grid['top'] = grid.bounds['maxy']\n",
    "grid['area_km2'] = grid.geometry.area / 1e6\n",
    "\n",
    "print('cells:', len(grid))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Census data, weighted by the area of each tract inside the cell\n",
    "tracts = gpd.read_file(tracts_path).to_crs(TARGET_CRS)\n",
    "tracts['tract_area'] = tracts.geometry.area\n",
    "\n",
    "pieces = gpd.overlay(tracts, grid[['grid_id', 'geometry']], how='intersection')\n",
    "pieces['piece_area'] = pieces.geometry.area\n",
    "pieces['fraction'] = pieces['piece_area'] / pieces['tract_area']\n",
    "pieces['pop_piece'] = pieces['pop'] * pieces['fraction']\n",
    "\n",
    "census = pieces.groupby('grid_id')['pop_piece'].sum().rename('pop').to_frame()\n",
    "\n",
    "for v in ['pci', 'literate', 'white', 'black', 'yellow', 'brown', 'indigenous']:\n",
    "    weighted = (pieces[v] * pieces['piece_area']).groupby(pieces['grid_id']).sum()\n",
    "    census[v] = weighted / pieces.groupby('grid_id')['piece_area'].sum()\n",
    "\n",
    "grid = grid.merge(census, left_on='grid_id', right_index=True, how='left')\n",
    "\n",
    "# Population density (inhab. per km2)\n",
    "grid['popd'] = grid['pop'] / grid['area_km2']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Per capita GDP\n",
    "with rasterio.open(gdp_path) as src:\n",
    "    centroids = grid.geometry.centroid.to_crs(src.crs)\n",
    "    coords = [(p.x, p.y) for p in centroids]\n",
    "    values = np.array([v[0] for v in src.sample(coords)], dtype=float)\n",
    "\n",
    "    if src.nodata is not None:\n",
    "        values[values == src.nodata] = np.nan\n",
    "\n",
    "grid['gdp'] = values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Road density (km-1)\n",
    "roads = gpd.read_file(roads_path).to_crs(TARGET_CRS)\n",
    "\n",
    "segments = gpd.overlay(roads, grid[['grid_id', 'geometry']], how='intersection', keep_geom_type=True)\n",
    "segments['length_km'] = segments.geometry.length / 1000\n",
    "\n",
    "road_length = segments.groupby('grid_id')['length_km'].sum()\n",
    "\n",
    "grid['road_length'] = grid['grid_id'].map(road_length).fillna(0)\n",
    "grid['road_dens'] = grid['road_length'] / grid['area_km2']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Local climate zones: fraction of each class in the cell (classes 11-17 = LCZ A-G)\n",
    "lcz_names = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'A', 'B', 'C', 'D', 'E', 'F', 'G']\n",
    "\n",
    "for n in lcz_names:\n",
    "    grid['LCZ_' + n] = 0.0\n",
    "\n",
    "with rasterio.open(lcz_path) as src:\n",
    "    cells_lcz = grid.to_crs(src.crs)\n",
    "\n",
    "    for idx, row in cells_lcz.iterrows():\n",
    "        out_image, out_transform = mask(src, [mapping(row.geometry)], crop=True)\n",
    "        pixels = out_image[0]\n",
    "\n",
    "        if src.nodata is not None:\n",
    "            pixels = pixels[pixels != src.nodata]\n",
    "\n",
    "        if pixels.size == 0:\n",
    "            continue\n",
    "\n",
    "        values, counts = np.unique(pixels, return_counts=True)\n",
    "\n",
    "        for val, count in zip(values, counts):\n",
    "            if 1 <= val <= 17:\n",
    "                grid.loc[idx, 'LCZ_' + lcz_names[int(val) - 1]] = count / counts.sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Admissions per cell (from postal codes) per 1 million inhabitants\n",
    "postal = pd.read_csv(postal_codes_path, dtype={'cep': str})\n",
    "\n",
    "points = adm.merge(postal, left_on='CEP', right_on='cep', how='inner')\n",
    "points = gpd.GeoDataFrame(points, geometry=gpd.points_from_xy(points['x'], points['y']), crs=TARGET_CRS)\n",
    "\n",
    "points = gpd.sjoin(points, grid[['grid_id', 'geometry']], how='inner', predicate='within')\n",
    "\n",
    "cell_pop = grid['pop'].replace(0, np.nan) # cells without population\n",
    "\n",
    "for d in ['LRI', 'CRD', 'Other']:\n",
    "    for g in ['General', 'G1', 'G2', 'G3']:\n",
    "        if g == 'General':\n",
    "            sel = points[points['disease'] == d]\n",
    "            col_name = d\n",
    "        else:\n",
    "            sel = points[(points['disease'] == d) & (points['group'] == g)]\n",
    "            col_name = d + '_' + g\n",
    "\n",
    "        counts = sel.groupby('grid_id').size()\n",
    "        grid[col_name] = grid['grid_id'].map(counts).fillna(0) / cell_pop * 1_000_000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Rename and save\n",
    "names = {'white': 'WHT', 'black': 'BLK', 'yellow': 'YEL', 'brown': 'BRN', 'indigenous': 'IND',\n",
    "         'literate': 'LT', 'popd': 'PD', 'pci': 'PCI', 'road_dens': 'RD', 'gdp': 'GDP'}\n",
    "\n",
    "grid = grid.rename(columns=names)\n",
    "\n",
    "lcz_cols = ['LCZ_' + n for n in lcz_names]\n",
    "targets = ['LRI', 'LRI_G1', 'LRI_G2', 'LRI_G3',\n",
    "           'CRD', 'CRD_G1', 'CRD_G2', 'CRD_G3',\n",
    "           'Other', 'Other_G1', 'Other_G2', 'Other_G3']\n",
    "\n",
    "spatial = grid[['grid_id', 'left', 'top', 'right', 'bottom'] + list(names.values()) + lcz_cols + targets]\n",
    "spatial.to_csv(output_dir + 'RF_spatial_data.csv', index=False)\n",
    "\n",
    "print(spatial.shape)\n",
    "spatial.head()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}