-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.js
More file actions
435 lines (383 loc) · 12.8 KB
/
Copy pathdata.js
File metadata and controls
435 lines (383 loc) · 12.8 KB
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
/* ============================================
DATA MODULE - EM-DAT Dataset Processing
============================================ */
// Global data exports
let RAW_DATA = [];
let TYPOLOGY_DATA = [];
let GLOBAL_AVG_BY_TYPE_YEAR = []; // avg disasters per country per year (÷ 220)
let MAP_DATA = {};
let COUNTRY_DOMINANT = {};
let COUNTRY_EVENTS = {};
let COUNTRY_STATS = {};
let SUMMARY_STATS = {};
let TOP_EVENTS = [];
let REGIONAL_DATA = [];
let DATA_SOURCE = 'empty';
let DATA_LOAD_ERROR = null;
const WORLD_COUNTRY_COUNT = 220;
// Metadata for normalized values from the CSV `type` column.
const DISASTER_TYPE_META = {
all: { label: 'All', color: '#1E3A8A', order: 0 },
drought: { label: 'Drought', color: '#FFC857', order: 10 },
earthquake: { label: 'Earthquake', color: '#C96B32', order: 20 },
extreme_temperature: { label: 'Extreme Temperature', color: '#FF5DB8', order: 30 },
flood: { label: 'Flood', color: '#5EA8FF', order: 40 },
landslide: { label: 'Landslide', color: '#7FE36A', order: 50 },
storm: { label: 'Storm', color: '#8C86FF', order: 60 },
epidemic: { label: 'Epidemic', color: '#6EE7C8', order: 70 },
infestation: { label: 'Infestation', color: '#D6E75B', order: 80 },
animal_incident: { label: 'Animal Incident', color: '#6DD6E8', order: 90 },
volcano: { label: 'Volcano', color: '#FF695B', order: 100 },
wildfire: { label: 'Wildfire', color: '#FFA142', order: 110 },
impact: { label: 'Impact', color: '#C7A8FF', order: 120 }
};
const DISASTER_COLORS = Object.fromEntries(
Object.entries(DISASTER_TYPE_META).map(([type, meta]) => [type, meta.color])
);
// Historical ISO codes → current canonical ISO codes (matches globe logic)
const ISO_ALIASES = {
CSK: 'CZE',
DDR: 'DEU',
DFR: 'DEU',
SCG: 'SRB',
SUN: 'RUS',
YMD: 'YEM',
YMN: 'YEM',
YUG: 'SRB'
};
function canonicalIso(iso) {
return ISO_ALIASES[iso] || iso;
}
const COUNTRY_NAME_ALIASES = {
'bolivia plurinational state of': 'Bolivia',
'brunei darussalam': 'Brunei',
'central african rep': 'Central African Republic',
'czech republic': 'Czechia',
'dem rep congo': 'DR Congo',
'dominican rep': 'Dominican Republic',
'eq guinea': 'Equatorial Guinea',
'iran islamic republic of': 'Iran',
'lao peoples democratic republic': 'Laos',
'macedonia': 'North Macedonia',
'micronesia federated states of': 'Micronesia',
'netherlands kingdom of the': 'Netherlands',
'republic of congo': 'Congo',
'republic of korea': 'South Korea',
'russian federation': 'Russia',
's korea': 'South Korea',
's sudan': 'South Sudan',
'solomon is': 'Solomon Islands',
'state of palestine': 'Palestine',
'swaziland': 'Eswatini',
'syrian arab republic': 'Syria',
'tanzanian united republic': 'Tanzania',
'united republic of tanzania': 'Tanzania',
'turkiye': 'Turkey',
'united kingdom of great britain and northern ireland': 'United Kingdom',
'venezuela bolivarian republic of': 'Venezuela',
'viet nam': 'Vietnam',
'democratic peoples republic of korea': 'North Korea',
'korea democratic peoples republic of': 'North Korea',
'korea republic of': 'South Korea',
'moldova republic of': 'Moldova',
'taiwan province of china': 'Taiwan',
'hong kong special administrative region of china': 'Hong Kong',
'macao special administrative region of china': 'Macao',
'virgin islands british': 'British Virgin Islands',
'virgin islands us': 'US Virgin Islands',
'saint helena ascension and tristan da cunha': 'Saint Helena',
'saint kitts and nevis': 'St Kitts and Nevis',
'saint lucia': 'St Lucia',
'saint vincent and the grenadines': 'St Vincent',
'sao tome and principe': 'São Tomé and Príncipe',
'turks and caicos islands': 'Turks and Caicos',
'wallis and futuna islands': 'Wallis and Futuna',
'western sahara': 'Western Sahara',
'british indian ocean territory': 'BIOT'
};
function normalizeCountryName(raw) {
if (!raw) return raw;
const key = raw.toLowerCase().replace(/[^a-z\s]/g, ' ').replace(/\s+/g, ' ').trim();
if (COUNTRY_NAME_ALIASES[key]) return COUNTRY_NAME_ALIASES[key];
// Title-case the original if no alias found
return raw.replace(/\w\S*/g, w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase());
}
// Initialize data from the cleaned EM-DAT CSV.
async function initData(csvPath = 'data/emdat_clean.csv') {
const csvCandidates = Array.from(new Set([
csvPath,
'docs/data/emdat_clean.csv',
'/docs/data/emdat_clean.csv'
]));
let lastError = null;
for (const candidate of csvCandidates) {
try {
console.log(`Loading EM-DAT dataset from ${candidate}...`);
const raw = await d3.csv(candidate);
if (raw.length > 0) {
loadRawRows(raw);
DATA_SOURCE = 'csv';
DATA_LOAD_ERROR = null;
console.log(`Loaded ${raw.length} EM-DAT records from ${candidate}`);
processData();
console.log('Data processing complete');
return;
}
} catch (error) {
lastError = error;
}
}
DATA_SOURCE = 'error';
DATA_LOAD_ERROR = lastError;
RAW_DATA = [];
TYPOLOGY_DATA = [];
MAP_DATA = {};
COUNTRY_DOMINANT = {};
COUNTRY_EVENTS = {};
COUNTRY_STATS = {};
SUMMARY_STATS = {};
TOP_EVENTS = [];
REGIONAL_DATA = [];
console.error('Failed to load real EM-DAT CSV. Start a local server from docs/ or the repo root.', lastError);
}
function loadRawRows(raw) {
RAW_DATA = raw.map(d => ({
year: +d.year,
iso: d.iso,
country: d.country,
region: d.region || 'Unknown',
subregion: d.subregion || 'Unknown',
type: d.type,
rawType: d.raw_type || d.type,
typeDetail: d.type_detail,
name: d.name || 'Unnamed Event',
deaths: +d.deaths || 0,
affected: +d.affected || 0,
damage: +d.damage_usd_thousands || 0,
lat: +d.lat || null,
lon: +d.lon || null
}));
}
// Process loaded data into required formats
function processData() {
// 1. TYPOLOGY_DATA: Annual counts by type
const disasterTypes = getAvailableDisasterTypes().map(({ type }) => type);
const yearlyTypes = d3.rollup(RAW_DATA, v => d3.rollup(v, vv => vv.length, d => d.type), d => d.year);
TYPOLOGY_DATA = Array.from(yearlyTypes, ([year, counts]) => {
const row = { year };
disasterTypes.forEach(type => {
row[type] = counts.get(type) || 0;
});
return row;
}).sort((a, b) => a.year - b.year);
// 1b. GLOBAL_AVG_BY_TYPE_YEAR: average per country (fixed denominator = 220)
GLOBAL_AVG_BY_TYPE_YEAR = TYPOLOGY_DATA.map(row => {
const avg = { year: row.year };
disasterTypes.forEach(type => {
avg[type] = +(row[type] / WORLD_COUNTRY_COUNT).toFixed(4);
});
return avg;
});
// 2. COUNTRY_DOMINANT: Dominant disaster type per country
const countryTypes = d3.rollup(
RAW_DATA,
v => d3.rollup(v, vv => vv.length, d => d.type),
d => d.iso
);
COUNTRY_DOMINANT = {};
countryTypes.forEach((types, iso) => {
const sortedTypes = Array.from(types, ([type, count]) => ({ type, count }))
.sort((a, b) => b.count - a.count);
if (sortedTypes.length > 0) {
const dominant = sortedTypes[0].type;
COUNTRY_DOMINANT[iso] = {
type: dominant,
color: DISASTER_COLORS[dominant] || '#666'
};
}
});
// 3. COUNTRY_EVENTS: All events per country
const eventsByCountry = d3.group(RAW_DATA, d => d.iso);
COUNTRY_EVENTS = {};
eventsByCountry.forEach((events, iso) => {
COUNTRY_EVENTS[iso] = events
.sort((a, b) => a.year - b.year)
.map(e => ({
year: e.year,
type: e.type,
name: e.name,
deaths: e.deaths,
affected: e.affected,
damage: e.damage
}));
});
// 4. COUNTRY_STATS: Summary statistics per country
const countryData = d3.rollup(
RAW_DATA,
v => {
const typeCount = d3.rollup(v, vv => vv.length, d => d.type);
const mostFrequent = Array.from(typeCount, ([type, count]) => ({ type, count }))
.sort((a, b) => b.count - a.count)[0];
const deathsByYear = d3.rollup(v, vv => d3.sum(vv, d => d.deaths), d => d.year);
const deadliestYear = Array.from(deathsByYear, ([year, deaths]) => ({ year, deaths }))
.sort((a, b) => b.deaths - a.deaths)[0];
return {
totalEvents: v.length,
totalDeaths: d3.sum(v, d => d.deaths),
totalAffected: d3.sum(v, d => d.affected),
totalDamage: d3.sum(v, d => d.damage),
mostFrequentType: mostFrequent ? mostFrequent.type : 'unknown',
worstYear: deadliestYear ? deadliestYear.year : null,
country: v[0].country,
region: v[0].region,
typeBreakdown: Object.fromEntries(typeCount)
};
},
d => d.iso
);
COUNTRY_STATS = Object.fromEntries(countryData);
// 5. MAP_DATA: Country data by time period
MAP_DATA = {
'2000_2025': {}
};
Object.entries(COUNTRY_STATS).forEach(([iso, stats]) => {
MAP_DATA['2000_2025'][iso] = {
count: stats.totalEvents,
deaths: stats.totalDeaths,
damage: stats.totalDamage
};
});
// 6. SUMMARY_STATS: Global summary
SUMMARY_STATS = {
totalEvents: RAW_DATA.length,
totalDeaths: d3.sum(RAW_DATA, d => d.deaths),
totalCountries: new Set(RAW_DATA.map(d => d.iso)).size,
totalDamage: d3.sum(RAW_DATA, d => d.damage)
};
// 7. TOP_EVENTS: Top 10 deadliest events
TOP_EVENTS = RAW_DATA
.filter(d => d.deaths > 0)
.sort((a, b) => b.deaths - a.deaths)
.slice(0, 10)
.map(d => ({
year: d.year,
country: d.country,
iso: d.iso,
type: d.type,
name: d.name,
deaths: d.deaths
}));
// 8. REGIONAL_DATA: Data grouped by region
const regionalGroups = d3.rollup(
RAW_DATA,
v => ({
events: v.length,
deaths: d3.sum(v, d => d.deaths),
affected: d3.sum(v, d => d.affected),
damage: d3.sum(v, d => d.damage)
}),
d => d.region
);
REGIONAL_DATA = Array.from(regionalGroups, ([region, stats]) => ({
region,
...stats
})).sort((a, b) => b.events - a.events);
}
// Helper function to get country data by year and type filters
function getFilteredEvents(filters = {}) {
if (!RAW_DATA || RAW_DATA.length === 0) {
return [];
}
let filtered = RAW_DATA;
const { yearStart = null, yearEnd = null, types = 'all' } = filters;
if (yearStart !== null) {
filtered = filtered.filter(d => d.year >= yearStart);
}
if (yearEnd !== null) {
filtered = filtered.filter(d => d.year <= yearEnd);
}
if (Array.isArray(types)) {
if (types.length === 0) return [];
const selected = new Set(types);
filtered = filtered.filter(d => selected.has(d.type));
} else if (types && types !== 'all') {
filtered = filtered.filter(d => d.type === types);
}
return filtered;
}
// Helper function to get country data by year and type filters
function getFilteredCountryData(year = null, type = 'all') {
if (!RAW_DATA || RAW_DATA.length === 0) {
return MAP_DATA['2000_2025'] || {};
}
const filters = typeof year === 'object' && year !== null
? year
: {
yearStart: year || null,
yearEnd: year || null,
types: type
};
const filtered = getFilteredEvents(filters);
const countryData = d3.rollup(
filtered,
v => {
const typeCounts = d3.rollup(v, vv => vv.length, d => d.type);
const dominantType = Array.from(typeCounts, ([eventType, count]) => ({ eventType, count }))
.sort((a, b) => b.count - a.count)[0]?.eventType || 'unknown';
return {
count: v.length,
deaths: d3.sum(v, d => d.deaths),
damage: d3.sum(v, d => d.damage),
dominantType
};
},
d => d.iso
);
return Object.fromEntries(countryData);
}
function getFilteredEventCount(filters = {}) {
if (!RAW_DATA || RAW_DATA.length === 0) {
return SUMMARY_STATS.totalEvents || 0;
}
return getFilteredEvents(filters).length;
}
function getAvailableDisasterTypes() {
const types = RAW_DATA.length
? Array.from(new Set(RAW_DATA.map(d => d.type).filter(Boolean)))
: [];
// Add the "All" option at the beginning
const allOption = {
type: 'all',
label: 'All',
color: '#1E3A8A',
order: 0
};
const typeOptions = types
.map(type => ({
type,
label: getDisasterTypeLabel(type),
color: getDisasterColor(type),
order: DISASTER_TYPE_META[type]?.order ?? 999
}))
.sort((a, b) => a.order - b.order || a.label.localeCompare(b.label));
return [allOption, ...typeOptions];
}
// Helper to format large numbers
function formatNumber(num) {
if (num >= 1000000) {
return (num / 1000000).toFixed(1) + 'M';
} else if (num >= 1000) {
return (num / 1000).toFixed(0) + 'K';
}
return num.toString();
}
// Helper to get disaster color
function getDisasterColor(type) {
return DISASTER_COLORS[type] || '#97AEC4';
}
function getDisasterTypeLabel(type) {
return DISASTER_TYPE_META[type]?.label || type.replace(/_/g, ' ');
}
function isRealDataLoaded() {
return DATA_SOURCE === 'csv' && RAW_DATA.length > 0;
}