-
Notifications
You must be signed in to change notification settings - Fork 1
/
forecast_mhw.js
567 lines (499 loc) · 18.5 KB
/
forecast_mhw.js
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
// global constant for object ID
const momCobaltMapFcastMHW = $('#momCobaltIFrameFcastMHW');
const dashDropDownID = 'analysisMOMCobaltFcastMHW'
const dashNavPillID = 'dashNavForecastMHW'
const dashContentID = 'dashContentForecastMHW'
// global info
var mapDataFcastMHW = {}; // parsed html output
var locationDataFcastMHW; // lcoation info from the mom_folium
// Initial initYear options (using forecast.js function)
window.createMomCobaltInitYearOpt('iniYearMOMCobaltFcastMHW');
// Initial initMonth options (using forecast.js function)
window.createMomCobaltInitMonthOpt('iniMonthMOMCobaltFcastMHW');
// global variable for initial time
let iniYearMHW = $("#iniYearMOMCobaltFcastMHW").val();
let iniMonthMHW = $("#iniMonthMOMCobaltFcastMHW").find("option:selected").text();
// global time slider related variables
const timeSliderFcastMHW = $("#timeRangeFcastMHW");
// forecast time title
const tValueFcastMHW = $(".timeValueFcastMHW");
// initial time title
const initTValueFcastMHW = $(".initTimeValueFcastMHW");
// default initial time
initTValueFcastMHW.text(iniMonthMHW +' '+ iniYearMHW)
// default tick lead time
const containerTickFcast = $(".ticksFcast");
// find default time tick info (using forecast.js function)
var leadMonthListMHW, leadIndexMHW;
[leadIndexMHW, leadMonthListMHW] = window.generateFcastLeadMonth(
iYear = parseInt($("#iniYearMOMCobaltFcastMHW").val()),
iMonth = parseInt($("#iniMonthMOMCobaltFcastMHW").val())
);
// set default time slider info
timeSliderFcastMHW.attr("min", 0);
timeSliderFcastMHW.attr("max", leadIndexMHW.length - 1);
timeSliderFcastMHW.val(0);
// set default forecast time title
var leadFoliumFcastMHW = leadMonthListMHW[timeSliderFcastMHW.val()]; // global
tValueFcastMHW.text(leadFoliumFcastMHW);
// screen size specific adjustment (using forecast.js function)
window.tickSpaceChangeFcast(leadMonthListMHW)
// Initial stat options (using historical.js function)
window.createMomCobaltOpt_singleID('statMOMCobaltFcastMHW',momCobaltStatsFcastMHW)
// setup colorbar option (using historical.js function)
window.createMomCobaltCbarOpt('cbarOptsFcastMHW','inferno');
// initialize the plotly
$(document).ready(function() {
window.asyncInitializePlotlyResize('mhwForecast')
});
///////////////// event listener ////////////////
// screen size adjustment trigger by window resizing
$(window).resize(function() {
window.tickSpaceChangeFcast(leadMonthListMHW);
});
// add event listener on figure all clear button
$("#tMHWButtonMinusOne").on("click", function () {
changeLeadTimeStep(-1);
});
$("#tMHWButtonPlusOne").on("click", function () {
changeLeadTimeStep(1);
});
// add event listener on figure all clear button
$("#clearFigOptBtnFcastMHW").on("click", function () {
$("input.figOpt").val('');
});
// add event listener on create map button
$("#momCobaltBtnFcastMHW").on("click", function () {
// update map
replaceFoliumForecastMHW()
// update initial time
iniYearMHW = $("#iniYearMOMCobaltFcastMHW").val();
iniMonthMHW = $("#iniMonthMOMCobaltFcastMHW").find("option:selected").text();
initTValueFcastMHW.text(iniMonthMHW +' '+ iniYearMHW)
// update tick lead time reassign global variables
var newleadIndex, newleadMonthList;
[newleadIndex, newleadMonthList] = window.generateFcastLeadMonth(
iYear = parseInt($("#iniYearMOMCobaltFcastMHW").val()),
iMonth = parseInt($("#iniMonthMOMCobaltFcastMHW").val())
);
leadIndexMHW = newleadIndex
leadMonthListMHW = newleadMonthList
// update forecast time title
leadFoliumFcastMHW = leadMonthListMHW[timeSliderFcastMHW.val()]; // global
tValueFcastMHW.text(leadFoliumFcastMHW);
// remove marker on the leaflet map when ever there is figure update (resetting)
var removeMarker = {
type: 'removeMarker'
};
momCobaltMapFcastMHW[0].contentWindow.postMessage(removeMarker, "*")
});
// event listener for updating the figure (when mouse up the slider handle)
timeSliderFcastMHW.on("mouseup", function() {
// set forecast time (title is set when mouse move)
leadFoliumFcastMHW = leadMonthListMHW[$(this).val()];
// update map
replaceFoliumForecastMHW()
// remove marker on the leaflet map when ever there is figure update (resetting)
var removeMarker = {
type: 'removeMarker'
};
momCobaltMapFcastMHW[0].contentWindow.postMessage(removeMarker, "*")
});
// event listener for updating the slider value when sliding
timeSliderFcastMHW.on("input", function() {
// update forecast time title
leadFoliumFcastMHW = leadMonthListMHW[$(this).val()];
tValueFcastMHW.text(leadFoliumFcastMHW);
});
// event listen for analyses dashboard dropdown change
$("#"+dashDropDownID).on("change", function(){
// Related ID name
// dropdown option ID = xxxVal
// content ID = xxx
// navpil ID = xxxPill
// get the dropdown option ID name
var selectedValue = $('#'+dashDropDownID+' :selected').val();
// change the active navpil
$("#"+dashNavPillID+" > ul.nav-pills > li.nav-item").removeClass("active");
$("#"+selectedValue.slice(0, -3)+'Pill').addClass("active");
// change the active navtab
$("#"+dashNavPillID+" > ul.nav-tabs > li.nav-item").removeClass("active");
$("#"+selectedValue.slice(0, -3)+'Tab').addClass("active");
// change the active navpil content
$("#"+dashContentID+" div.tab-pane").removeClass("active");
$("#"+selectedValue.slice(0, -3)).addClass("active");
// Manually trigger a resize event for triggering plotly resizing
window.dispatchEvent(new Event('resize'));
})
// event listener for navpil being clicked
$("#"+dashNavPillID+" > ul.nav-pills > li.nav-item > .nav-link").on('click',function(){
let hrefID = $(this).attr('href')
let hrefIDText = hrefID.slice(1)
// reuse changeDashSelect (historical.js)
window.changeDashSelect(dashDropDownID,hrefIDText+'Val')
// Manually trigger a resize event for triggering plotly resizing
window.dispatchEvent(new Event('resize'));
});
// event listener for navtab being clicked
$("#"+dashNavPillID+" > ul.nav-tabs > li.nav-item > .nav-link").on('click',function(){
let hrefID = $(this).attr('href')
let hrefIDText = hrefID.slice(1)
// reuse changeDashSelect (historical.js)
window.changeDashSelect(dashDropDownID,hrefIDText+'Val')
// Manually trigger a resize event for triggering plotly resizing
window.dispatchEvent(new Event('resize'));
});
// event listener for the "message" event when map location click
$(window).on("message", receiveMessageFcastMHW);
/////////////////////// function section /////////////////////
// function for advancing/recede to the next option in the list
// used directly in html page button with attribute onclick
function changeLeadTimeStep(timeStep) {
var nextTime = parseInt(timeSliderFcastMHW.val())+timeStep;
timeSliderFcastMHW.val(nextTime);
leadFoliumFcastMHW = leadMonthListMHW[timeSliderFcastMHW.val()];
tValueFcastMHW.text(leadFoliumFcastMHW);
replaceFoliumForecastMHW();
};
// function for replace folium overlap info (image and colorbar)
let statMapFcastMHW;
let statMapFcastNameMHW;
function replaceFoliumForecastMHW() {
showLoadingSpinner("loading-spinner-map-Fcastmhw");
statMapFcastMHW = $("#statMOMCobaltFcastMHW").val();
statMapFcastNameMHW = $('#statMOMCobaltFcastMHW').find('option:selected').text()
let cbar = $("#cbarOptsFcastMHW")
let maxval = $("#maxvalFcastMHW");
let minval = $("#minvalFcastMHW");
let nlevel = $("#nlevelFcastMHW");
var ajaxGet = "/cgi-bin/cefi_portal/mom_folium_fcast_mhw.py"
+"?region="+$("#regMOMCobaltFcastMHW").val()
+"&iniyear="+$("#iniYearMOMCobaltFcastMHW").val()
+"&inimonth="+$("#iniMonthMOMCobaltFcastMHW").val()
+"&lead="+timeSliderFcastMHW.val()
+"&stat="+statMapFcastMHW
+"&cbar="+cbar.val()
+"&maxval="+maxval.val()
+"&minval="+minval.val()
+"&nlevel="+nlevel.val()
console.log('https://webtest.psd.esrl.noaa.gov/'+ajaxGet)
fetch(ajaxGet)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok for forecast map fetch');
}
return response.json();
})
.then(jsonData => {
// Process the response data here
mapDataFcastMHW = {
type: 'mapData', // used in hindcast_mom.js for type check
image: jsonData.image,
domain1: jsonData.domain1,
domain2: jsonData.domain2,
range: jsonData.range,
tick: jsonData.tick,
label: jsonData.label
};
// console.log(mapDataFcastMHW)
momCobaltMapFcastMHW[0].contentWindow.postMessage(mapDataFcastMHW, "*")
hideLoadingSpinner("loading-spinner-map-Fcastmhw");
})
.catch(error => {
// Handle errors here
console.error('Processing mhw forecast folium map error:', error);
});
// momCobaltMap.attr("src", ajaxGet)
};
// function for retrieving lon lat from iframe leaflet
// getting the lon lat from iframe and send to
// server to get
// 1. value of the marker on the shading
// 2. plotly figure create/refresh
var varDataFcastMHW = null
function receiveMessageFcastMHW(event) {
// Access the data sent from the iframe
if (event.originalEvent.origin === window.location.origin) {
// console.log(event.originalEvent)
if (event.originalEvent.data.type === 'locationData') {
locationDataFcastMHW = event.originalEvent.data;
// displaying the variable value on iframe marker
const promisevarValFcast = new Promise((resolve, reject) => {
getvarValFcastMHW(locationDataFcastMHW) // function return promise obj from fetch
.then(varDataFcastMHW => {
// send the value back to iframe
var dataJson = {
type: 'varValFcastData',
var: varDataFcastMHW
};
momCobaltMapFcastMHW[0].contentWindow.postMessage(dataJson, "*")
resolve();
})
.catch(error => {
console.error('Error in promisevarValFcast:', error);
reject(error);
});
});
// display forecast spread plotly
plotFcast(locationDataFcastMHW)
}
// console.log("Received data from iframe:", locationDataFcastMHW);
// console.log(event.originalEvent.origin);
};
};
// function to get variable value based on locationData and dataFolium
function getvarValFcastMHW(infoLonLat) {
var ajaxGet = "/cgi-bin/cefi_portal/mom_extract_variableValue_fcast_mhw.py"
+"?region="+$("#regMOMCobaltFcastMHW").val()
+"&stat="+statMapFcastMHW
+"&lon="+infoLonLat.longitude
+"&lat="+infoLonLat.latitude
+"&iniyear="+$("#iniYearMOMCobaltFcastMHW").val()
+"&inimonth="+$("#iniMonthMOMCobaltFcastMHW").val()
+"&lead="+timeSliderFcastMHW.val()
console.log('https://webtest.psd.esrl.noaa.gov/'+ajaxGet)
const ajaxGetPromise = fetch(ajaxGet)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
// Process the response data here
var lines = data.split('\n');
return lines[0]
})
.catch(error => {
// Handle errors here
console.error('Fetch MHW value error:', error);
});
return ajaxGetPromise
};
// function for setting up promises in Forecast prob TS spread
// 1. input lon lat location
// 2. fetch forecast TSs (return promise)
// 3. create plotly object on webpage (execute when promise resolved)
function plotFcast(infoLonLat) {
showLoadingSpinner("loading-spinner-fcastmhw-prob");
showLoadingSpinner("loading-spinner-fcastmhw-spread");
// get promise obj from fetch
fetchFcastsTS(infoLonLat)
.then((jsonData)=>{
plotlyFcastsProb(jsonData);
plotlyForecastSpread(jsonData);
})
.then(()=>{
hideLoadingSpinner("loading-spinner-fcastmhw-prob");
hideLoadingSpinner("loading-spinner-fcastmhw-spread");
})
.catch((error)=>{
console.error('Plotting MHW time series error:',error);
})
};
// function to fetch all forecast ts based on locationData
// response in the json format
function fetchFcastsTS(infoLonLat) {
var ajaxGet = "/cgi-bin/cefi_portal/mom_extract_timeseries_fcast_mhw.py"
+"?region="+$("#regMOMCobaltFcastMHW").val()
+"&lon="+infoLonLat.longitude
+"&lat="+infoLonLat.latitude
+"&iniyear="+$("#iniYearMOMCobaltFcastMHW").val()
+"&inimonth="+$("#iniMonthMOMCobaltFcastMHW").val()
console.log('https://webtest.psd.esrl.noaa.gov/'+ajaxGet)
var ajaxGetPromise = fetch(ajaxGet)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.catch(error => {
// Handle errors here
console.error('Fetch MHW time series error:', error);
});
return ajaxGetPromise
};
// function for creating the plotly forecast prob time series
function plotlyFcastsProb(jsonData) {
// getting the y axis format using forecast.js function
var yformat = window.decimal_format(jsonData.mhw_prob90.ts);
var trace1Color = "rgba(113, 29, 176, 0.7)";
var trace = {
x: leadMonthListMHW,
y: jsonData.mhw_prob90.ts,
type: 'scatter',
mode: 'lines+markers',
marker: { size: 5 },
line: {
shape: 'linear',
color: trace1Color,
width: 3
},
// legend
name: jsonData.mhw_prob90.varname
};
var data = [trace];
var layout = {
hovermode: 'closest',
showlegend: false,
title:
'MHW Probability <br>' +
' @ (lat:'+parseFloat(jsonData.location.lat).toFixed(2)+'N,'+
'lon:'+parseFloat(jsonData.location.lon).toFixed(2)+'E)',
autosize: true,
annotations: [{
x: 0,
y: 0,
xref: 'paper',
yref: 'paper',
text: 'Source: NOAA CEFI data portal',
showarrow: false
}],
// width: 550,
// height: 400,
margin: {
l: 80,
r: 80,
b: 80,
t: 100,
// pad: 4
},
xaxis: {
title: 'Lead time'
},
yaxis: {
title: {
text: 'MHW Probability (%)',
standoff: 10,
font: { color: trace1Color }
},
tickfont: { color: trace1Color },
tickformat: yformat,
tickmode: 'auto'
},
modebar: {
remove: ["autoScale2d", "autoscale", "zoom", "zoom2d", ]
},
dragmode: "select"
// responsive: true
};
Plotly.newPlot('plotly-fcastmhw-prob', data, layout);
};
// function for creating the plotly forecast spread time series
function plotlyForecastSpread(jsonData) {
// getting the y axis format using forecast.js function
var yformat = decimal_format(jsonData.ssta_avg.ts);
// ensemble mean
var trace1Color = "rgba(113, 29, 176, 0.7)";
var trace = {
x: leadMonthListMHW,
y: jsonData.ssta_avg.ts,
type: 'scatter',
mode: 'lines+markers',
marker: { size: 5 },
line: {
shape: 'linear',
color: trace1Color,
width: 3
},
name: 'ssta ens mean'
};
var data = [trace];
// ensemble members
var trace2Color = "rgba(113, 29, 176, 0.1)";
for (var i=1; i<=10; i++) {
var key = 'ssta_ens'+i
var trace_ens = {
x: leadMonthListMHW,
y: jsonData[key].ts,
type: 'scatter',
mode: 'lines+markers',
marker: { size: 2 },
line: {
shape: 'linear',
color: trace2Color },
name: key
};
data.push(trace_ens);
}
// threshold
var trace3Color = "rgba(203, 128, 171, 0.9)";
var trace_thres = {
x: leadMonthListMHW,
y: jsonData.tos_threshold90.ts,
type: 'scatter',
mode: 'lines+markers',
marker: { size: 2 },
line: {
shape: 'linear',
color: trace3Color,
dash: 'dash'
},
name: '90% threshold'
};
data.push(trace_thres);
// plotly figure layout
var layout = {
hovermode: 'closest',
showlegend: true,
legend: {
x: 1, // Positioning on the right
y: 0,
xanchor: 'left' // Anchor the legend to avoid it getting cut off
},
title:
'MHW Magnitude <br>' +
' @ (lat:'+parseFloat(jsonData.location.lat).toFixed(2)+'N,'+
'lon:'+parseFloat(jsonData.location.lon).toFixed(2)+'E)',
autosize: true,
annotations: [{
x: 0,
y: 0,
xref: 'paper',
yref: 'paper',
text: 'Source: NOAA CEFI data portal',
showarrow: false
}],
// width: 550,
// height: 400,
margin: {
l: 80,
r: 150,
b: 80,
t: 100,
// pad: 4
},
xaxis: {
title: 'Lead time'
},
yaxis: {
title: {
text: 'Sea Surface Temperature Anomaly (degC)',
standoff: 10,
font: { color: trace1Color }
},
tickfont: { color: trace1Color },
tickformat: yformat,
tickmode: 'auto'
},
modebar: {
remove: ["autoScale2d", "autoscale", "zoom", "zoom2d", ]
},
dragmode: "select"
// responsive: true
};
Plotly.newPlot('plotly-fcastmhw-mag', data, layout);
};
///////// information function start /////////
function momCobaltStatsFcastMHW() {
stats_list = [
'MHW probability (90th)',
'MHW magnitude'
]
stats_value = [
'mhw_prob90',
'ssta_avg'
]
return [stats_list, stats_value];
};