-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhindcast.js
2625 lines (2307 loc) · 82.5 KB
/
hindcast.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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// global constant for object ID
const momCobaltMap = $('#momCobaltIFrame');
const momCobaltBtn = $("#momCobaltBtn");
// const clearFigOptBtn = $("#clearFigOptBtn")
const timeSlider = $("#timeRange");
const tValue = $(".timeValue");
const containerTick = $(".ticks");
// global info for leaflet maps
var mapData = {} // parsed html output
var locationData;
var polygonData;
var dateFolium;
// global info for time slider
var yearValues = [];
var rangeValues = [];
// global info for options value
var regValue;
var freqValue;
var varValue;
var statValue;
var depthValue;
var blockValue;
var var2Value;
var depth2Value;
var block2Value;
// Initial region options (for all region options)
initialize()
/////////////// event listener ///////////
// // add the initial time options
// createMomCobaltIniOpt(dataCobaltID);
$(window).resize(function() {
tickSpaceChange();
});
// event listen for region change => variable list and frequency options in json
$("#regMOMCobalt").on("change", function(){
regValue = $('#regMOMCobalt').val();
createFreqVarIndexOption(regValue);
});
// event listen for freq change => slider, depth & bottom options
$("#freqMOMCobalt").on("change", function(){
freqValue = $('#freqMOMCobalt').val();
// time slider change
if (freqValue === 'daily'){
[yearValues, rangeValues] = generateDailyDateList();
timeSlider.attr("min", 0);
timeSlider.attr("max", rangeValues.length - 1);
const foundIndex = rangeValues.indexOf(dateFolium+"-01");
timeSlider.val(foundIndex);
dateFolium = rangeValues[timeSlider.val()];
} else if (freqValue === 'monthly'){
[yearValues, rangeValues] = generateDateList();
timeSlider.attr("min", 0);
timeSlider.attr("max", rangeValues.length - 1);
const foundIndex = rangeValues.indexOf(dateFolium.slice(0, -3));
timeSlider.val(foundIndex);
dateFolium = rangeValues[timeSlider.val()];
};
tValue.text(dateFolium);
// change depth and block options for the new freq
// need to fetch the backend data for the depth options
updateDepthAndBlockOptions(regValue, freqValue, varValue)
// change depth2 and block2 options for the new freq
// need to fetch the backend data for the depth options
updateDepthAndBlockOptions(regValue, freqValue, var2Value, 'depthMOMCobaltTS2', 'blockMOMCobaltTS2')
});
// event listen for variable change => depth & bottom options
$("#varMOMCobalt").on("change", function(){
// varValue update
varValue = $('#varMOMCobalt').val();
// change depth and block options for the new freq
// need to fetch the backend data for the depth options
updateDepthAndBlockOptions(regValue, freqValue, varValue)
});
// event listen for variable2 change => depth2 & bottom2 options
$("#varMOMCobaltTS2").on("change", function(){
// varValue update
var2Value = $('#varMOMCobaltTS2').val();
// change depth2 and block2 options for the new freq
// need to fetch the backend data for the depth options
updateDepthAndBlockOptions(regValue, freqValue, var2Value, 'depthMOMCobaltTS2', 'blockMOMCobaltTS2')
// plot ts2
plotTSs(locationData);
});
// event listen for analyses dashboard dropdown change with nav pil
$("#analysisMOMCobalt").on("change", function(){
// Related ID name
// dropdown option ID = xxxVal
// content ID = xxx
// navpil ID = xxxPill
// get the dropdown option ID name
var selectedValue = $('#analysisMOMCobalt :selected').val();
// change the active navpil
$("#dashNavHistrun > ul.nav-pills > li.nav-item").removeClass("active");
$("#"+selectedValue.slice(0, -3)+'Pill').addClass("active");
// change the active navtab
$("#dashNavHistrun > ul.nav-tabs > li.nav-item").removeClass("active");
$("#"+selectedValue.slice(0, -3)+'Tab').addClass("active");
// change the active navpil content
$("#dashContentHistrun 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
$("#dashNavHistrun > ul.nav-pills > li.nav-item > .nav-link").on('click',function(){
let hrefID = $(this).attr('href');
let hrefIDText = hrefID.slice(1);
changeDashSelect('analysisMOMCobalt',hrefIDText+'Val');
window.dispatchEvent(new Event('resize'));
});
// event listener for navtab being clicked
$("#dashNavHistrun > ul.nav-tabs > li.nav-item > .nav-link").on('click',function(){
let hrefID = $(this).attr('href');
let hrefIDText = hrefID.slice(1);
changeDashSelect('analysisMOMCobalt',hrefIDText+'Val');
window.dispatchEvent(new Event('resize'));
});
// event listener for slider change => figure & date
timeSlider.on("mouseup", function() {
$("div.workingTop").removeClass("hidden");
$("div.errorTop").addClass("hidden");
$("div.whiteTop").addClass("hidden");
dateFolium = rangeValues[$(this).val()];
replaceFolium()
});
// event listener for slider change => Update the current slider value
timeSlider.on("input", function() {
dateFolium = rangeValues[$(this).val()];
tValue.text(dateFolium);
});
// event listener for clicking create map button
momCobaltBtn.on("click", function () {
$("div.workingTop").removeClass("hidden");
$("div.errorTop").addClass("hidden");
$("div.whiteTop").addClass("hidden");
replaceFolium()
$("#tsView > div.workingTop").removeClass("hidden");
$("#tsView > div.errorTop").addClass("hidden");
$("#tsView > div.whiteTop").addClass("hidden");
hideLoadingSpinner("loading-spinner-ts");
// $('#varMOMCobaltTS2').val('');
// $("#depthMOMCobaltTS2").val('');
});
// // event listener for clicking clear figure options
// clearFigOptBtn.on("click", function () {
// $("input.figOpt").val('');
// });
// // add event listener on reset time series select in plotly
// $("#clearTSselectBtn").on("click", function () {
// if (locationData !== undefined && locationData !== null) {
// if (varFoliumMap !== undefined && varFoliumMap !== null) {
// if ($('#varMOMCobaltTS2').val() !== undefined && $('#varMOMCobaltTS2').val() !== null) {
// plotTSs(locationData)
// } else {
// plotTS1(locationData);
// }
// }
// }
// });
// // add event listener on reset time series select in plotly
// $("#clearTS2Btn").on("click", function () {
// $('#varMOMCobaltTS2').val('');
// $('#depthMOMCobaltTS2').val('');
// if (locationData !== undefined && locationData !== null) {
// if (varFoliumMap !== undefined && varFoliumMap !== null) {
// plotTS1(locationData);
// }
// }
// });
// event listener for the "message" event (location click) => send to leaflet js
$(window).on("message", receiveMessage);
// // add event listener on adding 2nd time series in plotly
// $('#varMOMCobaltTS2').on("change", function () {
// // depth option change
// $("#depthMOMCobaltTS2").empty();
// createMomCobaltDepthOpt($("#varMOMCobaltTS2").val(),"depthMOMCobaltTS2");
// // var2Value
// varind2 = varnamelist2[1].indexOf($("#varMOMCobaltTS2").val())
// var2Value = varnamelist2[0][varind2]
// if (locationData !== undefined && locationData !== null) {
// if (varFoliumMap !== undefined && varFoliumMap !== null) {
// if ($('#varMOMCobaltTS2').val() !== undefined && $('#varMOMCobaltTS2').val() !== null) {
// plotTSs(locationData)
// } else {
// plotTS1(locationData);
// }
// }
// }
// });
// // add event listener on selecting depth for 3d 2nd variable
// $('#depthMOMCobaltTS2').on("change", function () {
// if (locationData !== undefined && locationData !== null) {
// if (varFoliumMap !== undefined && varFoliumMap !== null) {
// if ($('#varMOMCobaltTS2').val() !== undefined && $('#varMOMCobaltTS2').val() !== null) {
// plotTSs(locationData)
// } else {
// plotTS1(locationData);
// }
// }
// }
// });
// add event listener on selecting depth for 3d 2nd variable
$('#indexMOMCobaltTS').on("change", function () {
plotIndexes()
});
///////// functional function start /////////
// function for advancing/recede to the next option in the list
// used directly in html page button with attribute onclick
function changeTimeStep(timeStep) {
var nextTime = parseInt(timeSlider.val())+timeStep;
timeSlider.val(nextTime);
$("div.workingTop").removeClass("hidden");
$("div.errorTop").addClass("hidden");
$("div.whiteTop").addClass("hidden");
dateFolium = rangeValues[timeSlider.val()];
tValue.text(dateFolium);
replaceFolium();
}
// functions for timeline tick
function generateTick(tickList) {
$("div.ticks span").remove();
// console.log(tickList.length)
for (let i = 0; i < tickList.length; i++) {
// Create a new <span> element
const span = $("<span></span>");
// Set some content or attributes for the <span>
span.text(`${tickList[i]}`);
span.addClass("tickYear");
// Append the <span> to the containerTick <div>
containerTick.append(span);
};
};
/**
* Truncate a string to a specified length and add ellipsis if it exceeds that length.
* @param {string} str - The string to truncate.
* @param {number} maxLength - The maximum length of the truncated string.
* @returns {string} - The truncated string with ellipsis if it exceeds the maximum length.
*/
function truncateString(str, maxLength) {
if (str.length > maxLength) {
return str.substring(0, maxLength - 3) + '...';
} else {
return str;
}
}
function updateDepthAndBlockOptions(regValue, freqValue, varValue, depthID='depthMOMCobalt', blockID='blockMOMCobalt') {
// Change depth and block options for the new freq
// Need to fetch the backend data for the depth options
fetchVariableDepthBotOptions(
regValue, 'full_domain', 'hindcast', freqValue, 'regrid', varValue
).then((jsonData) => {
if (jsonData.depth === 0) {
// Create the single layer options
createDropdownOptions(depthID, ['single layer'], ['single_layer']);
} else {
// Create the depth options
let depthlist = jsonData.depth;
createDropdownOptions(depthID, depthlist, depthlist);
}
if (jsonData.bottom === 0) {
console.log(jsonData.bottom);
// Create the single layer options
createDropdownOptions(blockID, ['not applicable'], ['not_applicable']);
} else {
// Create the depth options
let bottomlist = jsonData.bottom;
createDropdownOptions(blockID, bottomlist, bottomlist);
}
depthValue = $('#'+depthID).val(); // initial depth value
blockValue = $('#'+blockID).val(); // initial block value
}).catch(error => {
console.error('Error in fetching depth options:', error);
});
}
// initialize the region freq variable optios
async function initialize() {
// Wait for createGeneralOption to complete region options
// async needed for freq, var, depth, block options backend fetch
await createGeneralOption('regMOMCobalt',momCobaltRegs);
regValue = $('#regMOMCobalt').val(); // initial region value
// Wait for createFreqVarIndexOption to complete
// fetch the backend data for the var, freq options
// async needed for depth, block options backend fetch
await createFreqVarIndexOption(regValue);
// $('#freqMOMCobalt').val('monthly');
freqValue = $('#freqMOMCobalt').val(); // initial frequency value
varValue = $('#varMOMCobalt').val(); // initial variable value
// Default time slider related variables
[yearValues, rangeValues] = generateDateList(); // initial monthly time slider
timeSlider.attr("min", 0);
timeSlider.attr("max", rangeValues.length - 1);
timeSlider.val(rangeValues.length - 1);
dateFolium = rangeValues[timeSlider.val()];
tValue.text(dateFolium);
// change slider size based on window size at initial loading
tickSpaceChange();
// Initial stat options
createGeneralOption('statMOMCobalt',momCobaltStats)
statValue = $('#statMOMCobalt').val(); // initial stats value
// Initial depth options based on variable
// fetch the backend data for the depth, block options
updateDepthAndBlockOptions(regValue, freqValue, varValue)
// create colorbar options
createMomCobaltCbarOpt('cbarOpts','RdBu_r')
// // var2Value update
// var2Value = $('#varMOMCobaltTS2').val();
// // change depth2 and block2 options for the new freq
// // need to fetch the backend data for the depth options
// updateDepthAndBlockOptions(regValue, freqValue, var2Value, 'depthMOMCobaltTS2', 'blockMOMCobaltTS2')
// create initial plotly object place holder
asyncInitializePlotlyResize('all')
// create index plotly
initializePlotly('indexes');
plotIndexes()
}
// function to get the option list in the json files
export async function createGeneralOption(selectID, optionListFunc) {
// fetch list
let [optionList,valueList] = optionListFunc();
// create dropdown options
createDropdownOptions(selectID,optionList,valueList);
}
// function for create option
export function optionList(listname,listval) {
let df = document.createDocumentFragment(); // create a document fragment to hold the options created later
for (let i = 0; i < listname.length; i++) { // loop
let option = document.createElement('option'); // create the option element
option.value = listval[i]; // set the value property
// truncate the string if it is too long
let truncName = truncateString(listname[i], 50)
option.appendChild(document.createTextNode(truncName)); // set the textContent in a safe way.
df.appendChild(option); // append the option to the document fragment
}
return df;
};
// function for create option
export function createDropdownOptions(selectID,showList,valueList) {
let elm = document.getElementById(selectID);
// Remove all existing options
while (elm.firstChild) {
elm.removeChild(elm.firstChild);
}
let df = optionList(showList,valueList);
elm.appendChild(df);
};
// asyn function to get the option list in the json files
export async function createFreqVarIndexOption(regname) {
// fetch hindcast json specific to region
var region;
var subdomain;
var expType = 'hindcast';
if (regname === 'northwest_atlantic'){
region = 'northwest_atlantic';
subdomain = 'full_domain';
} else if (regname === 'northeast_pacific'){
region = 'northeast_pacific';
subdomain = 'full_domain';
};
// get frequeuncy json
let dataAccessJson = await fetchDataOptionVis(region,subdomain,expType);
// get variable json
let variableJson = await fetchVarOptionVis(region,subdomain,expType);
// get index json
let indexJson = await fetchIndexOptionHindVis(region,subdomain,expType);
// create frequency options
let freqList = dataAccessJson.output_frequency;
createDropdownOptions('freqMOMCobalt',freqList,freqList);
// create variable options
let varOptionList = variableJson.var_options;
let varValueList = variableJson.var_values;
createDropdownOptions('varMOMCobalt',varOptionList,varValueList);
// only when the json file of a index exist
if (indexJson) {
// create index options (under index dashboard)
let indexOptionList = indexJson.varname;
let indexNameOptionList = indexJson.longname;
let indexFileLocationList = indexJson.file;
createDropdownOptions('indexMOMCobaltTS',indexNameOptionList,indexFileLocationList);
plotIndexes();
}
// // create 2nd variable options
// let var2OptionList = variableJson.var_options;
// let var2ValueList = variableJson.var_values;
// createDropdownOptions('varMOMCobaltTS2',var2OptionList,var2ValueList);
}
// async fetching the data_access_json cefi_data_option
export async function fetchDataOptionVis(reg,subDom,expType) {
try {
const response = await fetch(
'data_option_json/cefi_data_options.Projects.CEFI.regional_mom6.cefi_portal.'+
reg+
'.'+
subDom+
'.'+
expType+
'.json'
);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json(); // JSON data
// console.log('JSON data:', data);
return data;
} catch (error) {
console.error('There was a problem when async fetchDataOption:', error);
}
}
// async fetching the data_access_json cefi_var_option
export async function fetchVarOptionVis(reg,subDom,expType) {
try {
const response = await fetch(
'data_option_json/cefi_var_options.Projects.CEFI.regional_mom6.cefi_portal.'+
reg+
'.'+
subDom+
'.'+
expType+
'.json'
);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json(); // JSON data
// console.log('JSON data:', data);
return data;
} catch (error) {
console.error('There was a problem when async fetchVarOption:', error);
}
}
// async fetching the data_access_json cefi_data_option
async function fetchIndexOptionHindVis(reg,subDom,expType) {
try {
const response = await fetch(
'data_option_json/cefi_index_options.Projects.CEFI.regional_mom6.cefi_derivative.'+
reg+
'.'+
subDom+
'.'+
expType+
'.json'
);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json(); // JSON data
// console.log('JSON data:', data);
return data;
} catch (error) {
$('#indexMOMCobaltTS').empty();
initializePlotly('indexes');
console.error('There was a problem when async fetchIndexOption:', error);
}
}
// async functions for fetching variable and experiment specific option from backend
export async function fetchVariableDepthBotOptions(reg,subDom,expType,outFreq,gridType,variable) {
var ajaxGet = "/cgi-bin/cefi_portal/vistab_create_variable_depth_bot_options.py"
+"?region="+reg
+"&subdomain="+subDom
+"&experiment_type="+expType
+"&output_frequency="+outFreq
+"&grid_type="+gridType
+"&variable="+variable;
console.log('https://webtest.psd.esrl.noaa.gov/'+ajaxGet)
return 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 json failed when creating variable depth bottom options:', error);
});
}
// functions for generating year and date list for timeslider (monthly)
function generateDateList(startYear = 1993, endYear = 2019) {
var dateList = [];
var yearList = [];
for (var year = startYear; year <= endYear; year++) {
yearList.push(year)
for (var month = 1; month <= 12; month++) {
var monthStr = month < 10 ? "0" + month : month;
dateList.push(year + "-" + monthStr);
}
}
return [yearList, dateList];
}
// functions for generating year and date list for timeslider (daily)
function generateDailyDateList(startYear = 1993, endYear = 2019) {
var dateList = [];
var yearList = [];
for (var year = startYear; year <= endYear; year++) {
yearList.push(year);
for (var month = 1; month <= 12; month++) {
var daysInMonth = new Date(year, month, 0).getDate(); // Get the number of days in the month
for (var day = 1; day <= daysInMonth; day++) {
dateList.push(`${year}-${month < 10 ? "0" + month : month}-${day < 10 ? "0" + day : day}`);
}
}
}
return [yearList, dateList];
}
// function for create option for colorbar
export function createMomCobaltCbarOpt(cbarOptID='cbarOpts',defaultCbar='RdBu_r') {
let elm = document.getElementById(cbarOptID);
let list_cbar = colorbarOpt()
let df = optionList(list_cbar,list_cbar);
return new Promise((resolve) => {
elm.appendChild(df); // append the document fragment to the DOM. this is the better way rather than setting innerHTML a bunch of times (or even once with a long string)
elm.selectedIndex = list_cbar.indexOf(defaultCbar);
// console.log("Async work completed!");
resolve(); // Resolve the promise when done
});
};
// function for option change due to nav pill change at the bottom
function changeDashSelect(dashDropDownID,optionVal) {
// change pick option
$('#' + dashDropDownID).val(optionVal).change();
}
// function for changing the tick mark of time slider
function tickSpaceChange() {
if ($(window).width() < 600) {
var result = [];
for (var i = 3; i < yearValues.length; i += 5) {
result.push(yearValues[i]);
}
generateTick(result);
} else if ($(window).width() < 1200) {
var result = [];
for (var i = 2; i < yearValues.length; i += 2) {
result.push(yearValues[i]);
}
generateTick(result);
} else {
generateTick(yearValues);
};
};
// intialize the plotly plot
// Initial dashboard plot
export function asyncInitializePlotlyResize(flag) {
// make sure the plotly object is created then resize
return initializePlotly(flag)
.then(() => {
window.dispatchEvent(new Event('resize'));
})
.catch(error => {
console.error('Error in async plotly initialization:', error);
});
}
export function initializePlotly(flag) {
var trace = {
x: "",
y: "",
type: 'scatter',
mode: 'lines+markers',
marker: { size: 8 },
line: { shape: 'linear' },
name: ""
};
var layoutTS = {
title:
'Click on map for time series',
autosize: true,
width: 500,
height: 400,
xaxis: { title: 'Date' },
yaxis: { title: 'Variable' },
hovermode: 'closest',
showlegend: false,
// responsive: true
};
var layoutBox = {
title:
'Box plot',
autosize: true,
// width: 1000,
// height: 400,
hovermode: 'closest',
showlegend: false,
// responsive: true
};
var layoutHist = {
title:
'Histogram',
autosize: true,
// width: 1000,
// height: 400,
hovermode: 'closest',
showlegend: false,
// responsive: true
};
var layoutProf = {
title:
'Profile',
autosize: true,
// width: 1000,
// height: 400,
hovermode: 'closest',
showlegend: false,
// responsive: true
};
var layoutIndex = {
title:
'Index not available',
autosize: true,
width: 1000,
height: 400,
hovermode: 'closest',
showlegend: false,
// responsive: true
};
var layout2 = {
title:
'Draw polyline on map',
autosize: true,
// width: 1000,
// height: 400,
xaxis: { title: 'Date' },
yaxis: { title: 'Variable' },
hovermode: 'closest',
showlegend: false,
// responsive: true
};
var layoutFcst = {
title:
'Create Forecast Map first<br>& pick point on the shaded area',
autosize: true,
width: 500,
height: 400,
xaxis: { title: 'Date' },
yaxis: { title: 'Variable' },
hovermode: 'closest',
showlegend: false,
responsive: true
};
var config = {responsive: true}
if (flag ==='all'){
Plotly.newPlot('plotly-time-series', [trace], layoutTS,config);
// Plotly.newPlot('plotly-box-plot', [trace], layoutBox,config);
// Plotly.newPlot('plotly-histogram', [trace], layoutHist,config);
Plotly.newPlot('plotly-vertical-prof', [trace], layoutProf,config);
// Plotly.newPlot('plotly-vertical-s', [trace], layoutProf,config);
// Plotly.newPlot('plotly-transect', [trace], layout2,config);
Plotly.newPlot('plotly-index', [trace], layoutIndex,config);
} else if (flag ==='vertical') {
Plotly.newPlot('plotly-vertical-prof', [trace], layoutProf,config);
// Plotly.newPlot('plotly-vertical-s', [trace], layoutProf,config);
} else if (flag ==='indexes') {
Plotly.newPlot('plotly-index', [trace], layoutIndex,config);
} else if (flag ==='tseries') {
Plotly.newPlot('plotly-time-series', [trace], layoutTS,config);
} else if (flag ==='transect') {
// Plotly.newPlot('plotly-transect', [trace], layout2,config);
} else if (flag ==='forecast') {
Plotly.newPlot('plotly-fcast-spread', [trace], layoutFcst, config);
Plotly.newPlot('plotly-fcast-box', [trace], layoutFcst, config);
} else if (flag ==='mhwForecast') {
Plotly.newPlot('plotly-fcastmhw-prob', [trace], layoutTS,config);
Plotly.newPlot('plotly-fcastmhw-mag', [trace], layoutTS,config);
} else if (flag ==='forecastLive') {
Plotly.newPlot('plotly-fcast-live-spread', [trace], layoutFcst, config);
Plotly.newPlot('plotly-fcast-live-box', [trace], layoutFcst, config);
};
return new Promise(resolve => {
// console.log('Initial Plotly created');
resolve();
});
};
// // function for create option with subgroup
// function optionSubgroupList(listname,listval,listsubgroup) {
// let df = document.createDocumentFragment(); // create a document fragment to hold the options created later
// // object subgroup
// const monthlyGroup = document.createElement('optgroup');
// monthlyGroup.label = 'Monthly variables';
// const dailyGroup = document.createElement('optgroup');
// dailyGroup.label = 'Daily variables';
// const monthlyIndexGroup = document.createElement('optgroup');
// monthlyIndexGroup.label = 'Monthly indexes';
// const annualIndexGroup = document.createElement('optgroup');
// annualIndexGroup.label = 'Annual indexes';
// var mvflag = false
// var dvflag = false
// var miflag = false
// var aiflag = false
// for (let i = 0; i < listname.length; i++) {
// let option = document.createElement('option'); // create the option element
// option.value = listval[i]; // set the value property
// option.appendChild(document.createTextNode(listname[i])); // set the textContent in a safe way.
// if (listsubgroup[i].indexOf("monthly")!==-1){
// monthlyGroup.appendChild(option);
// mvflag = true
// } else if (listsubgroup[i].indexOf("daily")!==-1){
// dailyGroup.appendChild(option);
// dvflag = true
// } else if (listsubgroup[i].indexOf("mon_index")!==-1){
// monthlyIndexGroup.appendChild(option);
// miflag = true
// } else if (listsubgroup[i].indexOf("ann_index")!==-1){
// annualIndexGroup.appendChild(option);
// aiflag = true
// }
// }
// // append the subgroup in the desired order
// if (aiflag) {
// df.appendChild(annualIndexGroup);
// }
// if (mvflag) {
// df.appendChild(monthlyGroup);
// }
// // df.appendChild(monthlyGroup); // append the option to the document fragment
// if (miflag) {
// df.appendChild(monthlyIndexGroup);
// }
// // df.appendChild(dailyGroup);
// if (dvflag) {
// df.appendChild(dailyGroup);
// }
// return df;
// };
// // function for create option for general options (single ID)
// function createMomCobaltOpt_singleID(selectID,optionListFunc) {
// let elm = document.getElementById(selectID);
// let optlist = optionListFunc();
// df = optionList(optlist[0],optlist[1]);
// elm.appendChild(df);
// };
// // function for create option for general options
// function createMomCobaltOpt(selectClass,optionListFunc) {
// let elms = document.getElementsByClassName(selectClass);
// let optlist = optionListFunc();
// df = optionList(optlist[0],optlist[1]);
// // loop through all region dropdown with the selectClassName
// for(let i = 0; i < elms.length; i++) {
// let clonedf = df.cloneNode(true); // Clone the child element
// elms[i].appendChild(clonedf); // Append the cloned child to the current element
// }
// };
// // function for create option for variables (optimized for different purposes)
// function createMomCobaltVarOpt(dataCobaltID,selectID) {
// let elm = document.getElementById(selectID);
// let varlist = momCobaltVars();
// if (dataCobaltID == "MOMCobalt") {
// // for hindcast run var
// varlist = momCobaltVars();
// } else if (dataCobaltID == "MOMCobalt+Index") {
// // for second time series comp
// varlist = momCobaltVars();
// indexlist = indexes();
// varlist[0] = varlist[0].concat(indexlist[0]);
// varlist[1] = varlist[1].concat(indexlist[1]);
// varlist[2] = varlist[2].concat(indexlist[2]);
// } else if (dataCobaltID == "onlyIndexes") {
// // for index
// indexlist = indexes("onlyIndex");
// varlist[0] = indexlist[0];
// varlist[1] = indexlist[1];
// varlist[2] = indexlist[2];
// };
// // df = optionList(varlist[0],varlist[1]);
// df = optionSubgroupList(varlist[0],varlist[1],varlist[2]);
// elm.appendChild(df); // append the document fragment to the DOM. this is the better way rather than setting innerHTML a bunch of times (or even once with a long string)
// };
// Display loading spinner
export function showLoadingSpinner(divID) {
// console.log('spin')
$("#"+divID).css("display", "block");
}
// Hide loading spinner
export function hideLoadingSpinner(divID) {
// console.log('stop spin')
$("#"+divID).css("display", "none");
}
// function for replace folium overlap info (image and colorbar)
// reason of seperate from the other global variable
// this make sure the variable that is plotted on the map sync
// with the "Plotly time series"
let varFoliumMap;
let regFoliumMap;
let freqFoliumMap;
let statFoliumMap;
let depthFoliumMap;
function replaceFolium() {
showLoadingSpinner("loading-spinner-map");
varFoliumMap = $("#varMOMCobalt").val();
regFoliumMap = $("#regMOMCobalt").val();
freqFoliumMap = $("#freqMOMCobalt").val();
statFoliumMap = $("#statMOMCobalt").val();
depthFoliumMap = $("#depthMOMCobalt").val();
// variables only used on the Folium map
// initiated every time when the create map is triggered
let block = $("#blockMOMCobalt").val();
let cbar = $("#cbarOpts").val();
let maxval = $("#maxval").val();
let minval = $("#minval").val();
let nlevel = $("#nlevel").val();
var ajaxGet = "/cgi-bin/cefi_portal/vistab_mom_folium.py"
+"?variable="+varFoliumMap
+"®ion="+regFoliumMap
+"&output_frequency="+freqFoliumMap
+"&subdomain=full_domain"
+"&experiment_type=hindcast"
+"&grid_type=regrid"
+"&date="+dateFolium
+"&stat="+statFoliumMap
+"&depth="+depthFoliumMap
+"&block="+block
+"&cbar="+cbar
+"&maxval="+maxval
+"&minval="+minval
+"&nlevel="+nlevel
console.log('https://webtest.psd.esrl.noaa.gov/'+ajaxGet)
fetch(ajaxGet) // Replace with the URL you want to request
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(jsonData => {
// Process the response data here
// console.log(jsonData);
mapData = {
type: 'mapData',
image: jsonData.image,
image_bound: jsonData.image_bound,
map_center: jsonData.map_center,
map_crs: jsonData.map_crs,
domain1: jsonData.domain1,
domain2: jsonData.domain2,
range: jsonData.range,
tick: jsonData.tick,
label: jsonData.label
};
// console.log(mapData)
momCobaltMap[0].contentWindow.postMessage(mapData, "*")
// get same point time series when points and variable are defined/clicked
if (locationData !== undefined && locationData !== null) {
console.log(locationData)
if (varFoliumMap !== undefined && varFoliumMap !== null) {
plotTS1(locationData);
plotVertProfs(locationData);
// if ($('#varMOMCobaltTS2').val() !== undefined && $('#varMOMCobaltTS2').val() !== null) {
// plotTSs(locationData);
// } else {
// plotTS1(locationData);
// }
}
// //// current function only allowed in monthly data
// if (dateFolium.length === 7){
// plotVertProfs(locationData);
// } else {
// // initialize plotly
// initializePlotly('vertical');
// }
}
// get same polyline transect when polyline and variable are defined
if (polygonData !== undefined && polygonData !== null) {
if (varFoliumMap !== undefined && varFoliumMap !== null) {
plotTransect(polygonData);
//// current function only allowed in monthly data
// if (dateFolium.length === 7){
// plotTransect(polygonData);
// } else {
// // initialize plotly