-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhumidity-explorer.js
More file actions
465 lines (386 loc) · 14.2 KB
/
humidity-explorer.js
File metadata and controls
465 lines (386 loc) · 14.2 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
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
/*
* Humidity Explorer
*
* Set of script to:
* - Calculate Specific and Relative Humidity based on Air Temperature,
* Dew Point Temperaure and Surface Pressure
* - Visualise it based on selected date and hour (UTC)
*
* Contact: Benny Istanto. Climate Geographer - GOST/DECAT/DECDG, The World Bank
* If you found a mistake, send me an email to bistanto@worldbank.org
*
* Changelog:
* 2023-10-15 first draft
* 2023-10-16 add clip function to area of interest
* 2023-10-17 add country selector as area of interest
* 2024-08-29 add error handling when the input data is not available
* ------------------------------------------------------------------------------
*/
/*
* SELECT YOUR OWN STUDY AREA
*/
// Select a full country by changing the countryname variable
// Fetch the List of Countries
var aoi;
var FIPS_countrycode = '';
var countries = ee.FeatureCollection('USDOS/LSIB_SIMPLE/2017');
var countryList = countries.aggregate_array('country_na').getInfo();
countryList.sort(); // This will sort the country list
// Update the AOI based on Selected Country
function updateAOI(countryName) {
var countryFeature = countries.filter(ee.Filter.eq('country_na', countryName)).first();
var FIPS = countryFeature.get('country_co');
aoi = ee.FeatureCollection([countryFeature]);
FIPS_countrycode = FIPS.getInfo(); // Get the FIPS to a global variable
Map.layers().reset();
Map.addLayer(aoi, {}, 'AoI', true);
Map.centerObject(aoi); // Center of the map
}
// Initialize the AOI with the default value
updateAOI('Indonesia');
/*
* VISUALIZATION AND STYLING
*/
// Create the application title bar.
Map.add(ui.Label('Humidity Explorer', {fontWeight: 'bold', fontSize: '24px'}));
// SYMBOLOGY
// Visualization parameters
// Temperature
var tempVisC = {
min: -30,
max: 40,
palette: [
'000080', '0000d9', '4000ff', '8000ff', '0080ff', '00ffff',
'00ff80', '80ff00', 'daff00', 'ffff00', 'fff500', 'ffda00',
'ffb000', 'ffa400', 'ff4f00', 'ff2500', 'ff0a00', 'ff00ff',
]
};
// Pressure
var pressureVisHpa = {
min: 500,
max: 1050,
palette: ['blue', 'lightblue', 'white', 'yellow', 'red']
};
// Specific Humidity
var qVis = {
min: 0,
max: 0.04,
palette: [
'a50026', 'd73027', 'f46d43', 'fdae61', 'fee090', 'e0f3f8',
'abd9e9', '74add1', '4575b4', '313695'
]
};
// Relative Humidity
var RHVis = {
min: 0,
max: 100,
palette: [
'a50026', 'd73027', 'f46d43', 'fdae61', 'fee090', 'e0f3f8',
'abd9e9', '74add1', '4575b4', '313695'
]
};
// Boundaries
var BNDvis = {fillColor: "#00000000", color: '646464', width: 0.5,};
// COLOR BAR
// Number of color bar
var nStepsR = 15;
// A color bar widget. Makes a horizontal color bar to display the given color palette.
function ColorBar(palette) {
return ui.Thumbnail({
image: ee.Image.pixelLonLat().select(0).int(),
params: {
bbox: [0, 0, nStepsR, 0.1],
dimensions: '100x5',
format: 'png',
min: 0,
max: nStepsR,
palette: palette,
},
style: {stretch: 'horizontal', margin: '0px 8px'},
});
}
// LEGEND STYLE
// Returns a labeled legend, with a color bar and three labels representing
// the minimum, middle, and maximum values.
function makeLegend(title, vis) {
var colorBar = ColorBar(vis.palette);
var minLabel = vis.min.toString();
var maxLabel = vis.max.toString();
var midLabel = ((vis.min + vis.max) / 2).toFixed(2).toString(); // Compute the middle value and format it
var labels = ui.Panel(
[
ui.Label(minLabel, {margin: '4px 8px'}),
ui.Label(midLabel, {margin: '4px 8px', textAlign: 'center', stretch: 'horizontal'}),
ui.Label(maxLabel, {margin: '4px 8px'})
],
ui.Panel.Layout.flow('horizontal')
);
return ui.Panel(
[
ui.Label(title, {fontWeight: 'bold'}),
colorBar,
labels
]
);
}
// Styling for the legend title.
var LEGEND_TITLE_STYLE = {
fontSize: '20px',
fontWeight: 'bold',
stretch: 'horizontal',
textAlign: 'center',
margin: '4px',
};
// Styling for the legend footnotes.
var LEGEND_FOOTNOTE_STYLE = {
fontSize: '12px',
stretch: 'horizontal',
textAlign: 'center',
margin: '4px',
};
// Assemble the legend panel.
var legendPanel = ui.Panel(
[
ui.Label('Legend', LEGEND_TITLE_STYLE),
makeLegend('Dew Point/Air Temperature (°C)', tempVisC),
makeLegend('Pressure (hPa)', pressureVisHpa),
makeLegend('Specific Humidity', qVis),
makeLegend('Relative Humidity', RHVis),
// Add more legends as needed
ui.Label('Source: ERA5-Land Hourly, in 0.1deg per pixel', LEGEND_FOOTNOTE_STYLE),
],
ui.Panel.Layout.flow('vertical'),
{width: '300px', position: 'bottom-left'}
);
// Add the Panel to the map.
Map.add(legendPanel);
/*
* DATE AND HOUR CONFIGURATION
*/
// Strip time off current date/time
// As ERA5-Land data is not real time available at GEE, sometimes has a lag up to 10 days
// So for first data to be loaded into map will be 10 days before
var firstload = ee.Date(new Date().toISOString().split('T')[0]).advance(-10, 'day');
print(firstload);
// First date available to access via slider
var start_period = ee.Date('1950-01-01');
// Start and End
var startDate = start_period.getInfo();
var endDate = firstload.getInfo();
// Define your initial date and hour.
var initialDate = firstload;
var initialHour = '00';
// Create a dropdown for hour selection.
var hours = [];
for (var i = 0; i < 24; i++) {
hours.push(i < 10 ? '0' + i : i.toString());
}
var hourSelector = ui.Select({
items: hours,
value: initialHour,
style: {width: '60px', padding: '5px'},
onChange: updateVisualization
});
// Create a label for the dropdown.
var hourLabel = ui.Label('Hour (UTC):', {fontWeight: 'bold'});
// Create a panel to hold the label and the dropdown.
var hourPanel = ui.Panel({
widgets: [hourLabel, hourSelector],
style: {position: 'bottom-right'}
});
// Slider function
var dateSlider = ui.DateSlider({
start: startDate.value,
end: endDate.value,
value: initialDate,
period: 1, // 1-day granularity.
style: {width: '300px', padding: '10px', position: 'bottom-right'},
onChange: updateVisualization // Function to call when date changes.
});
// Add the Country Dropdown
var countrySelector = ui.Select({
items: countryList,
value: 'Indonesia',
onChange: function(countryName) {
updateAOI(countryName);
updateVisualization();
}
});
// Create a panel to hold the country selecteor, date slider and the hour dropdown.
var countryLabel = ui.Label('Country:', {fontWeight: 'bold'});
var countryPanel = ui.Panel({
widgets: [countryLabel, countrySelector],
style: {position: 'bottom-right'}
});
var accessPanel = ui.Panel({
widgets: [countryPanel, dateSlider, hourPanel],
layout: ui.Panel.Layout.flow('horizontal'), // Align widgets horizontally
style: {position: 'bottom-right'}
});
Map.add(accessPanel);
/*
* MAIN FUNCTION
*/
// Function to update the visualization based on selected date and hour.
//
// Reference
// Alduchov, O. A., & Eskridge, R. E. (1996). Improved Magnus form approximation of saturation vapor pressure.
// Journal of Applied Meteorology, 35(4), 601-609.
//
// 611.21: This is the saturation vapor pressure of water at the triple point (in Pascals).
// The triple point is a specific combination of temperature and pressure at which water can
// coexist in three phases (solid, liquid, and gas) simultaneously.
//
// 17.502 and 32.19: These are constants specific to the Magnus formula over water.
// They are used to adjust the curve of the formula to fit the actual observed data.
// The values would be different for saturation over ice.
//
// 0.622: This constant is the ratio of the molecular weight of water to the molecular weight of dry air.
// It's used in the formula to calculate specific humidity.
function updateVisualization() {
// Remove previous layers
Map.layers().reset();
// Initial Date and Hour
var selectedDate = dateSlider.getValue();
var selectedHour = hourSelector.getValue();
var selectedDateString = selectedDate.toString();
var startDateString = selectedDateString.split(',')[0];
var selectedDateStart = ee.Date(Number(startDateString));
// Convert the selected date to an ee.Date
var date = selectedDateStart;
// Use the selected hour directly to advance the date
var startDateTime = date.advance(ee.Number.parse(selectedHour), 'hour');
// Add an hour to the start time to get the end time
var endDateTime = startDateTime.advance(1, 'hour');
// These are USDOS LSIB boundaries simplified for boundary visualization.
var bnd = ee.FeatureCollection("USDOS/LSIB_SIMPLE/2017");
// Filter your collection by this time range and update the map.
// Load the specific image from the ECMWF/ERA5_LAND/HOURLY collection
var collection = ee.ImageCollection("ECMWF/ERA5_LAND/HOURLY");
var filteredCollection = collection.filterDate(startDateTime, endDateTime);
print('Filtered Collection:', filteredCollection);
// Check if the filtered collection has any images
var collectionSize = filteredCollection.size().getInfo();
if (collectionSize === 0) {
print('Error: No data available for the selected date and time.');
return; // Exit the function if no data is available
}
var specificImage = filteredCollection.first();
print('Specific Image:', specificImage);
// Verify that the image contains the expected bands
var availableBands = specificImage.bandNames();
print('Available Bands:', availableBands);
// Check if the required bands are present
if (availableBands.contains('temperature_2m') &&
availableBands.contains('dewpoint_temperature_2m') &&
availableBands.contains('surface_pressure')) {
// Extract temperature, dew point temperature, and surface pressure bands
var temperatureK = specificImage.select('temperature_2m');
var dewPointK = specificImage.select('dewpoint_temperature_2m');
var pressurePa = specificImage.select('surface_pressure');
// Constants
var T0 = 273.16; // Reference temperature in K
// Compute saturation vapor pressure for air temperature
var es = temperatureK.expression('611.21 * exp(17.502 * (T - T0) / (T - 32.19))', {
'T': temperatureK,
'T0': T0
});
// Compute vapor pressure for dew point temperature
var e = dewPointK.expression('611.21 * exp(17.502 * (Td - T0) / (Td - 32.19))', {
'Td': dewPointK,
'T0': T0
});
// Calculate specific humidity
var q = e.expression('0.622 * e / p', {
'e': e,
'p': pressurePa
});
// Calculate relative humidity
var RH = e.expression('100 * e / es', {
'e': e,
'es': es
});
// Convert temperature from Kelvin to Celsius
var temperatureC = temperatureK.subtract(273.15);
var dewPointC = dewPointK.subtract(273.15);
// Convert pressure from Pa to hPa (or millibars)
var pressureHpa = pressurePa.divide(100);
// Attach as properties to specificImage
specificImage = specificImage.set('temperatureC', temperatureC);
specificImage = specificImage.set('dewPointC', dewPointC);
specificImage = specificImage.set('pressureHpa', pressureHpa);
specificImage = specificImage.set('q', q);
specificImage = specificImage.set('RH', RH);
print('Bands after adding calculated variables:', specificImage.bandNames()); // Print the band names to verify
currentImage = specificImage;
currentImage = currentImage.addBands(temperatureC.rename('temperatureC'));
currentImage = currentImage.addBands(dewPointC.rename('dewPointC'));
currentImage = currentImage.addBands(pressureHpa.rename('pressureHpa'));
currentImage = currentImage.addBands(q.rename('q'));
currentImage = currentImage.addBands(RH.rename('RH'));
// Display temperature, dew point temperature, pressure, specific humidity, and relative humidity
Map.addLayer(temperatureC.clip(aoi), tempVisC, 'Temperature (°C)', false);
Map.addLayer(dewPointC.clip(aoi), tempVisC, 'Dew Point Temperature (°C)', false);
Map.addLayer(pressureHpa.clip(aoi), pressureVisHpa, 'Pressure (hPa)', false);
Map.addLayer(q.clip(aoi), qVis, 'Specific Humidity');
Map.addLayer(RH.clip(aoi), RHVis, 'Relative Humidity');
// Optional: Add the boundaries for better visualization.
Map.addLayer(bnd.style({fillColor: "#00000000", color: '646464', width: 0.5}));
} else {
// Print an error message if the required bands are not available
print('Error: One or more required bands are missing in the selected image.');
}
}
// Update variables
var currentImage;
// Initial visualization.
updateVisualization();
/*
* DATA DOWNLOAD
*/
// Function to export a specific image band to Google Drive
function exportBandToDrive(image, bandName, descriptionPrefix, folderName, scale, maxPixels, region) {
Export.image.toDrive({
image: image.select(bandName),
description: descriptionPrefix + '_' + bandName,
folder: folderName,
scale: scale,
maxPixels: maxPixels,
region: region
});
}
// Add download button to panel
var download = ui.Button({
label: 'Download the data',
style: {position: 'top-center', color: 'black'},
onClick: function() {
// Warning message for the user
alert("Download request started! Please go to Tasks, wait until the download list appear. Click RUN for each data you want to download.");
// Export parameters
var dt = ee.Date(dateSlider.getValue()[0]);
var hour = hourSelector.getValue();
var scaleValue = 11132;
var maxPixelsValue = 1e12;
var folderName = 'GEE';
var area = aoi;
var descriptionPrefix = FIPS_countrycode + '_era5land_' + hour + 'h_' + dt.format('yyyy-MM-dd').getInfo();
// List of bands to export
var bands = [
{name: 'temperatureC', description: 't2m'},
{name: 'dewPointC', description: 'dewPoint'},
{name: 'pressureHpa', description: 'pressure'},
{name: 'q', description: 'sh'},
{name: 'RH', description: 'rh'}
];
// Loop through each band and export
bands.forEach(function(band) {
exportBandToDrive(currentImage, band.name, descriptionPrefix + '_' + band.description, folderName, scaleValue, maxPixelsValue, area);
});
print('Data download initiated for:', dt.format('yyyy-MM-dd').getInfo());
}
});
// Add the button to the map and the panel to root.
Map.add(download);
/*
* END OF SCRIPT
*/