-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadeck-reader.js
More file actions
1901 lines (1626 loc) · 76.3 KB
/
adeck-reader.js
File metadata and controls
1901 lines (1626 loc) · 76.3 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
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
/**
* Cyclone Viewer
* Copyright (c) 2025 Keith Roberts
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* ADECK File Reader
* Parses ADECK/BDECK format (Automated Tropical Cyclone Forecast) files and converts to a format usable by the cyclone viewer
*/
window.AdeckReader = {
// Initialize hiddenTracks as an object at the top level
hiddenTracks: {},
addFixViewButton: function() {
const dialog = document.getElementById('adeck-storm-selection');
if (dialog) {
// Create the Fix View button
const fixViewButton = document.createElement('button');
fixViewButton.textContent = 'Fix View';
fixViewButton.className = 'fix-view-button';
// Add click event listener to toggle the fix view state
fixViewButton.addEventListener('click', function () {
window.isViewFixed = !window.isViewFixed;
if (window.isViewFixed) {
// Store the current map bounds
window.fixedBounds = map.getBounds();
console.log('Fixing view to bounds:', window.fixedBounds);
} else {
// Clear the fixed bounds
window.fixedBounds = null;
console.log('Unfixing view.');
}
// Update button text based on the state
fixViewButton.textContent = window.isViewFixed ? 'Unfix View' : 'Fix View';
// Show notification
showNotification(
window.isViewFixed ? 'Map view is now fixed' : 'Map view is now unfixed',
'info',
1500
);
});
// Append the button to the dialog
dialog.appendChild(fixViewButton);
}
},
/**
* Parse ADECK file content and extract storm tracks
* @param {string} content - Raw text content of the ADECK file
* @returns {Object} Object containing storm tracks and metadata
*/
parseAdeckFile: function(content) {
console.log("Parsing ADECK file...");
// Split content into lines and filter out empty lines and comments
const lines = content.split(/\r?\n/).filter(line => {
const trimmed = line.trim();
return trimmed.length > 0 && !trimmed.startsWith('#');
});
if (lines.length === 0) {
console.error("ADECK file is empty or contains only comments");
return { storms: [], count: 0 };
}
// Check if the first line is a header
const firstLine = lines[0].trim().toUpperCase();
const isHeader = firstLine.includes("BASIN") &&
(firstLine.includes("CYCLONE") || firstLine.includes("CYCLONE_NUM")) &&
firstLine.includes("LAT") &&
firstLine.includes("LON");
// Extract column indices from header or use defaults
let columnMap = this.getDefaultColumnMap();
if (isHeader) {
console.log("Found header row:", firstLine);
columnMap = this.parseHeaderRow(firstLine);
// Remove header from lines to process
lines.shift();
}
console.log("Using column mapping:", columnMap);
// For storing all storms by their unique ID
const stormsByModelAndInit = {};
// Process each line
let processedLines = 0;
lines.forEach((line, lineIndex) => {
try {
const parts = line.split(',').map(part => part.trim());
// Skip lines that don't have enough parts
if (parts.length < Math.max(columnMap.lat, columnMap.lon, columnMap.model) + 1) {
console.warn(`Line ${lineIndex + 1} has insufficient data (${parts.length} columns)`);
return;
}
// Extract values using column map
const record = this.extractValuesFromLine(parts, columnMap);
// Skip if critical data is missing
if (!record ||
!record.basin ||
!record.number ||
!record.initYYYYMMDDHH ||
!record.model ||
record.latitude === undefined ||
record.longitude === undefined) {
console.warn(`Skipping line ${lineIndex + 1} due to missing critical data`);
return;
}
// Create a storm ID based on basin, cyclone number, and year
const year = record.initYYYYMMDDHH.substring(0, 4);
const stormId = `${record.basin}${record.number}${year}`;
// Format official cyclone identifier (e.g., "aal162004")
const cycloneId = this.formatCycloneId(record.basin, record.number, year);
// Create a unique model/init time key
const modelInitKey = `${stormId}_${record.model}_${record.initYYYYMMDDHH}`;
// Get or create storm object
if (!stormsByModelAndInit[modelInitKey]) {
// Format initialization time nicely for display
const initDate = this.formatDateTime(record.initYYYYMMDDHH);
// Create a human-readable cyclone name
const cycloneName = this.formatCycloneName(record.basin, record.number, year);
stormsByModelAndInit[modelInitKey] = {
id: modelInitKey,
stormId: stormId,
name: `${record.model} [${initDate}]`,
basin: record.basin,
year: parseInt(year),
number: record.number,
model: record.model,
initTime: record.initYYYYMMDDHH,
cycloneId: cycloneId, // Add formatted cyclone ID (e.g., "aal162004")
cycloneName: cycloneName, // Add human-readable name (e.g., "AL16 (2004)")
points: []
};
}
// Convert ADECK point to cyclone viewer format
const point = this.convertPointFormat(record);
// Add point to storm only if it has valid coordinates
if (point && !isNaN(point.latitude) && !isNaN(point.longitude)) {
stormsByModelAndInit[modelInitKey].points.push(point);
processedLines++;
} else {
console.warn(`Skipping point with invalid coordinates: lat=${point?.latitude}, lon=${point?.longitude}`);
}
} catch (error) {
console.error(`Error parsing line ${lineIndex + 1}:`, error, line);
}
});
// Convert to array and sort storm points by forecast hour (TAU)
const storms = Object.values(stormsByModelAndInit).map(storm => {
storm.points.sort((a, b) => a.tau - b.tau);
return storm;
});
//console.log("Storm init times:", storms.map(s => s.initTime));
console.log(`Parsed ${storms.length} forecast tracks with ${processedLines} valid points from ADECK file`);
return {
storms: storms,
count: storms.length
};
},
/**
* Get default column mapping for ADECK format
*/
getDefaultColumnMap: function() {
return {
basin: 0, // BASIN
cycloneNum: 1, // CYCLONE_NUM
initTime: 2, // YYYYMMDDHH
tau: 3, // TAU (HH since init time)
model: 4, // MODEL (name of the forecast model)
forecast_lead: 5, // Forecast lead time (not always present)
lat: 6, // LAT
lon: 7, // LON
vmax: 8, // VMAX
mslp: 9, // MSLP
stormType: 10, // TY (tropical depression, tropical storm, etc.)
rmw: 20 // RMW (Radius of Maximum Wind) - typically in column 20
};
},
/**
* Parse header row to determine column positions
*/
parseHeaderRow: function(headerLine) {
const parts = headerLine.split(',').map(part => part.trim().toUpperCase());
const columnMap = {};
parts.forEach((header, index) => {
if (header === 'BASIN') columnMap.basin = index;
else if ((header === 'CYCLONE_NUM' || header === 'CYCLONE' || header.includes('CY')) && header.includes('NUM')) columnMap.cycloneNum = index;
else if (header === 'YYYYMMDDHH' || header.includes('DATE') || header.includes('TIME')) columnMap.initTime = index;
else if (header === 'MODEL' || header.includes('TECH')) columnMap.model = index;
else if (header === 'TAU' || header.includes('HOUR') || header.includes('FHOUR')) columnMap.tau = index;
else if (header === 'FORECAST_LEAD' || header === 'LEAD' || header === 'LEAD_TIME') columnMap.forecast_lead = index;
else if (header === 'LAT') columnMap.lat = index;
else if (header === 'LON') columnMap.lon = index;
else if (header === 'VMAX' || header.includes('WIND')) columnMap.vmax = index;
else if (header === 'MSLP' || header.includes('PRES')) columnMap.mslp = index;
else if (header === 'TY' || header.includes('TYPE')) columnMap.stormType = index;
});
// Fallback to defaults for any missing columns
const defaults = this.getDefaultColumnMap();
for (const key in defaults) {
if (columnMap[key] === undefined) {
columnMap[key] = defaults[key];
console.log(`Header missing ${key}, using default position ${defaults[key]}`);
}
}
return columnMap;
},
/**
* Extract values from a line using column mapping
*/
extractValuesFromLine: function(parts, columnMap) {
if (!parts || parts.length <= Math.max(columnMap.lat, columnMap.lon)) {
console.warn("Line has insufficient columns for lat/lon");
return null;
}
const record = {
basin: parts[columnMap.basin] || 'XX',
number: parts[columnMap.cycloneNum] || '00',
initYYYYMMDDHH: parts[columnMap.initTime] || '0000000000',
model: parts[columnMap.model] || 'UNKN',
};
// Determine forecast lead time, prioritizing forecast_lead over tau if available
if (columnMap.forecast_lead !== undefined && parts[columnMap.forecast_lead] && parts[columnMap.forecast_lead].trim() !== '') {
record.forecast_lead = parseInt(parts[columnMap.forecast_lead]) || 0;
// Also set tau for backward compatibility
record.tau = record.forecast_lead;
} else {
record.tau = parseInt(parts[columnMap.tau]) || 0;
record.forecast_lead = record.tau; // Set forecast_lead to tau for consistency
}
const initDateTime = record.initYYYYMMDDHH;
if (initDateTime && initDateTime.length >= 10) {
record.year = parseInt(initDateTime.substring(0, 4));
record.month = parseInt(initDateTime.substring(4, 6));
record.day = parseInt(initDateTime.substring(6, 8));
record.hour = parseInt(initDateTime.substring(8, 10));
record.minute = 0;
} else {
const now = new Date();
record.year = now.getUTCFullYear();
record.month = now.getUTCMonth() + 1;
record.day = now.getUTCDate();
record.hour = now.getUTCHours();
record.minute = 0;
}
try {
const latPart = parts[columnMap.lat];
if (latPart) {
if (latPart.includes('N') || latPart.includes('S')) {
const numericPart = latPart.replace(/[NS]/g, '');
const latValue = parseFloat(numericPart);
const adjustedLatValue = numericPart.includes('.') ? latValue : latValue / 10.0;
record.latitude = latPart.includes('S') ? -adjustedLatValue : adjustedLatValue;
record.latitudeFormatted = `${adjustedLatValue.toFixed(1)}°${latPart.includes('S') ? 'S' : 'N'}`;
} else {
let latValue = parseFloat(latPart);
if (Math.abs(latValue) > 90) {
latValue = latValue / 10.0;
}
record.latitude = latValue;
record.latitudeFormatted = `${latValue.toFixed(1)}°${latValue >= 0 ? 'N' : 'S'}`;
}
}
} catch (e) {
console.error("Error parsing latitude:", parts[columnMap.lat], e);
}
try {
const lonPart = parts[columnMap.lon];
if (lonPart) {
if (lonPart.includes('E') || lonPart.includes('W')) {
const numericPart = lonPart.replace(/[EW]/g, '');
const lonValue = parseFloat(numericPart);
const adjustedLonValue = numericPart.includes('.') ? lonValue : lonValue / 10.0;
record.longitude = lonPart.includes('W') ? -adjustedLonValue : adjustedLonValue;
record.longitudeFormatted = `${adjustedLonValue.toFixed(1)}°${lonPart.includes('W') ? 'W' : 'E'}`;
} else {
let lonValue = parseFloat(lonPart);
if (Math.abs(lonValue) > 180) {
lonValue = lonValue / 10.0;
}
if ((record.basin === 'AL' || record.basin === 'EP' || record.basin === 'CP') && lonValue > 0) {
record.longitude = -lonValue;
} else {
record.longitude = lonValue;
}
record.longitudeFormatted = `${Math.abs(lonValue).toFixed(1)}°${lonValue >= 0 ? 'E' : 'W'}`;
}
}
} catch (e) {
console.error("Error parsing longitude:", parts[columnMap.lon], e);
}
// Skip records with (0,0) coordinates
if (record.latitude === 0. && record.longitude === 0.) {
console.warn("Skipping point with (0,0) coordinates");
return null;
}
if (parts[columnMap.vmax] && parts[columnMap.vmax] !== '') {
const vmax = parseFloat(parts[columnMap.vmax]);
if (!isNaN(vmax)) {
record.max_wind_kt = vmax;
if (vmax === 0.0) {
record.max_wind_kt = null;
}
record.wind_speed = vmax * 0.514444;
}
}
if (parts[columnMap.mslp] && parts[columnMap.mslp] !== '') {
const mslp = parseFloat(parts[columnMap.mslp]);
if (!isNaN(mslp)) {
record.mslp = mslp;
}
}
// Extract RMW (Radius of Maximum Wind) - field #20
if (columnMap.rmw !== undefined && parts.length > columnMap.rmw && parts[columnMap.rmw] && parts[columnMap.rmw].trim() !== '') {
const rmwValue = parseInt(parts[columnMap.rmw].trim());
if (!isNaN(rmwValue) && rmwValue > 0) {
record.rmw = rmwValue * 1852; // Convert from nautical miles to meters
}
}
if (columnMap.stormType !== undefined && parts[columnMap.stormType]) {
record.type = parts[columnMap.stormType];
}
if (columnMap.model !== undefined && parts[columnMap.model]) {
record.modelRaw = parts[columnMap.model].trim();
}
return record;
},
/**
* Format a human-readable model name, especially for ensemble members
* @param {string} modelId - The raw model identifier
* @returns {string} Human-readable model name
*/
formatModelName: function(modelId) {
// Check for ensemble pattern (PHXX where XX are digits)
const ensembleMatch = modelId.match(/^PH(\d{2})$/);
if (ensembleMatch) {
const ensembleNumber = parseInt(ensembleMatch[1], 10);
return `Ensemble No. ${ensembleNumber}`;
}
// Return original model ID if no special formatting needed
return modelId;
},
/**
* Convert ADECK record to cyclone viewer point format
*/
convertPointFormat: function(record) {
if (record.latitude === undefined || record.longitude === undefined ||
isNaN(record.latitude) || isNaN(record.longitude)) {
return null;
}
try {
const baseDate = new Date(Date.UTC(
record.year,
record.month - 1,
record.day,
record.hour || 0,
record.minute || 0
));
const forecastLead = record.forecast_lead !== undefined ? record.forecast_lead : record.tau || 0;
const forecastDate = new Date(baseDate.getTime() + (forecastLead * 60 * 60 * 1000));
const point = {
latitude: record.latitude,
longitude: record.longitude,
forecast_lead: forecastLead,
tau: forecastLead,
year_utc: forecastDate.getUTCFullYear(),
month_utc: forecastDate.getUTCMonth() + 1,
day_utc: forecastDate.getUTCDate(),
hour_utc: forecastDate.getUTCHours(),
minute_utc: forecastDate.getUTCMinutes(),
init_time: record.initYYYYMMDDHH,
wind_speed: record.wind_speed || null,
mslp: record.mslp || null,
rmw: record.rmw || null, // Add RMW to point object
model: record.model || "UNKNOWN",
displayModel: this.formatModelName(record.model || "UNKNOWN"), // Add display name
type: record.type || null,
latitudeFormatted: record.latitudeFormatted,
longitudeFormatted: record.longitudeFormatted,
modelRaw: record.modelRaw || record.model
};
return point;
} catch (error) {
console.error("Error creating point from record:", error, record);
return null;
}
},
/**
* Format date-time string for display
*/
formatDateTime: function(yyyymmddhh) {
if (!yyyymmddhh || yyyymmddhh.length < 10) return 'Unknown';
const year = yyyymmddhh.substring(0, 4);
const month = yyyymmddhh.substring(4, 6);
const day = yyyymmddhh.substring(6, 8);
const hour = yyyymmddhh.substring(8, 10);
return `${year}-${month}-${day} ${hour}Z`;
},
/**
* Format the official cyclone identifier in lowercase format
*/
formatCycloneId: function(basin, number, year) {
return `a${basin.toLowerCase()}${number}${year}`;
},
/**
* Format a human-readable cyclone name
*/
formatCycloneName: function(basin, number, year) {
let basinName = basin;
const basinNames = {
'AL': 'Atlantic',
'EP': 'Eastern Pacific',
'CP': 'Central Pacific',
'WP': 'Western Pacific',
'IO': 'Indian Ocean',
'SH': 'Southern Hemisphere',
'BB': 'Bay of Bengal',
'AS': 'Arabian Sea',
'SL': 'South Atlantic'
};
if (basinNames[basin]) {
basinName = basinNames[basin];
}
return `${basinName} - Cyclone ${number} (${year})`;
},
/**
* Check if a model is recognized in our system
*/
isKnownModel: function(model) {
return !!this.getModelColor(model);
},
/**
* create isDefaultModel with ALL the models
*/
isDefaultModel: function(model) {
// Check for ensemble pattern (PHXX)
if (model.match(/^PH\d{2}$/)) {
return true; // Include all ensemble members as default models
}
// Models to show by default all the models
const defaultModels = [
'OFCL', 'OFCI', 'CARQ',
'AVNO', 'AVNI', 'GFS',
'GFDI', 'GFDL', 'GFDT', 'GFDN',
'UKMI', 'UKM', 'UKX', 'UKXI', 'UKX2', 'UKM2',
'CMC', 'HWRF', 'HMON',
'EMXI', 'EMX', 'EMX2', 'ECMWF',
'NGPS', 'NGPI', 'NGP2',
'DSHP', 'SHIP', 'LGEM', 'SHFR', 'SHNS', 'DRCL',
'TVCN', 'TVCE', 'TVCX',
'CONU', 'GUNA', 'GUNS', 'HCCA',
'BAMD', 'BAMM', 'BAMS', 'LBAR', 'XTRP',
'CLIP', 'CLP5', 'DRCL', 'MRCL',
// Add all other models here
];
return defaultModels.includes(model);
},
/**
* Process tracks for display by adding special styling for first points
*/
processTracksForDisplay: function(storms, defaultModelsOnly = true) {
// Filter storms if defaultModelsOnly is true
let filteredStorms = storms;
if (defaultModelsOnly) {
filteredStorms = storms.filter(storm => this.isDefaultModel(storm.model));
// If no default models, fall back to all known models
if (filteredStorms.length === 0) {
filteredStorms = storms.filter(storm => this.isKnownModel(storm.model));
}
}
// Process each storm to mark first point and enhance display
return filteredStorms.map(storm => {
// Mark first point for special styling
if (storm.points && storm.points.length > 0) {
storm.points[0].isFirstPoint = true;
// Calculate perpendicular line coordinates for the first point
if (storm.points.length > 1) {
// Get first two points to determine direction
const p1 = storm.points[0];
const p2 = storm.points[1];
// Calculate direction vector
const dx = p2.longitude - p1.longitude;
const dy = p2.latitude - p1.latitude;
// Normalize and get perpendicular vector (rotate 90 degrees)
const length = Math.sqrt(dx * dx + dy * dy);
const perpDx = -dy / length;
const perpDy = dx / length;
//console.log(`Perpendicular vector for ${storm.name}: (${perpDx}, ${perpDy})`);
// Create perpendicular line of appropriate length (adjust the multiplier for desired length)
const perpLineLength = 1.0; // Adjust this for longer/shorter perpendicular lines
p1.perpLine = {
start: {
lat: p1.latitude - perpDy * perpLineLength,
lng: p1.longitude - perpDx * perpLineLength
},
end: {
lat: p1.latitude + perpDy * perpLineLength,
lng: p1.longitude + perpDx * perpLineLength
},
color: this.getModelColor(storm.model) // Use the same color as the track
};
}
// Ensure forecast lead time is properly formatted for all points
storm.points.forEach(point => {
// Make sure forecast_lead and tau are synchronized
if (point.forecast_lead !== undefined && point.tau === undefined) {
point.tau = point.forecast_lead;
} else if (point.tau !== undefined && point.forecast_lead === undefined) {
point.forecast_lead = point.tau;
}
// Make sure init_time is available for display
if (!point.init_time && storm.initTime) {
point.init_time = storm.initTime;
}
});
}
return storm;
});
},
/**
* Draw perpendicular line for ADECK track start points
* @param {Object} point - The first point of a track with perpLine property
* @param {Object} map - The Leaflet map object
* @returns {Object} The created polyline object
*/
drawPerpendicularLine: function(point, map) {
if (!point || !point.perpLine || !map) return null;
// Create polyline for the perpendicular line
const perpLine = L.polyline([
[point.perpLine.start.lat, point.perpLine.start.lng],
[point.perpLine.end.lat, point.perpLine.end.lng]
], {
color: point.perpLine.color || '#FFFFFF',
weight: 3,
opacity: 0.2,
dashArray: '5,5' // Make it dashed for better visibility
}).addTo(map);
return perpLine;
},
/**
* Highlight rows in the UI that match the selected model
*/
highlightModelRows: function(modelName) {
document.querySelectorAll('.model-row').forEach(row => {
if (row.dataset.model === modelName) {
row.classList.add('highlighted');
} else {
row.classList.remove('highlighted');
}
});
},
/**
* Highlight the selected model in UI elements
* @param {string} modelName - Name of the model to highlight
*/
highlightSelectedModel: function(modelName) {
// Update row highlighting
document.querySelectorAll('.model-row').forEach(row => {
if (row.dataset.model === modelName) {
row.classList.add('selected');
} else {
row.classList.remove('selected');
}
});
// Update model buttons if they exist
document.querySelectorAll('.adeck-model-button').forEach(btn => {
if (btn.dataset.model === modelName) {
btn.classList.add('selected');
} else {
btn.classList.remove('selected');
}
});
},
/**
* Group storms by date and model for organization in the UI
* @param {Array} storms - Array of storm track objects
* @returns {Object} Grouped storms by date and model
*/
groupStormsByDateAndModel: function(storms) {
const grouped = {};
// First, ensure we have storms to process
if (!storms || !Array.isArray(storms) || storms.length === 0) {
return {};
}
// Group by initialization date and then by model
storms.forEach(storm => {
// Use the init time as the primary key, fallback to a default if not available
const dateKey = storm.initTime || 'BEST_TRACK';
// Create date group if it doesn't exist
if (!grouped[dateKey]) {
grouped[dateKey] = {};
}
// Create model group under this date if it doesn't exist
const modelName = storm.model || 'BEST_TRACK';
if (!grouped[dateKey][modelName]) {
grouped[dateKey][modelName] = [];
}
// Add this storm to the appropriate group
grouped[dateKey][modelName].push(storm);
});
return grouped;
},
/**
* Create initialization time selector dropdown
* @param {Array} storms - Array of storm track objects
* @param {Function} onChangeCallback - Function to call when init time changes
* @returns {HTMLElement} The init time selector UI element
*/
createInitTimeSelector: function(storms, onChangeCallback) {
const container = document.createElement('div');
container.className = 'init-time-selector';
const label = document.createElement('label');
label.textContent = 'Initialization Time:';
label.className = 'init-time-label';
const dropdown = document.createElement('select');
dropdown.className = 'init-time-dropdown';
// Get unique init times
const initTimes = [...new Set(storms.map(storm => storm.initTime))];
// Sort by most recent first
initTimes.sort((a, b) => b.localeCompare(a));
// Add options to dropdown
initTimes.forEach((initTime) => {
const option = document.createElement('option');
option.value = initTime;
option.textContent = this.formatDateTime(initTime);
dropdown.appendChild(option);
});
// Add change handler for dropdown
dropdown.addEventListener('change', function() {
const selectedInitTime = this.value;
// Preserve both the model filter preference and the category
const modelFilterPreference = window.lastModelFilterPreference !== undefined ?
window.lastModelFilterPreference : true;
// Store the currently selected category to restore it after changing init time
const categoryDropdown = document.querySelector('.model-category-dropdown');
if (categoryDropdown) {
window.lastModelCategory = categoryDropdown.value;
}
if (onChangeCallback) {
onChangeCallback(selectedInitTime);
} else {
// Call the default handler
window.AdeckReader.displayTracksByInitTime(storms, selectedInitTime, modelFilterPreference);
}
});
container.appendChild(label);
container.appendChild(dropdown);
return container;
},
/**
* Display tracks for a specific initialization time
* @param {Array} storms - All storm track objects
* @param {string} initTime - Selected initialization time (null for all)
* @param {boolean} defaultModelsOnly - Whether to show only default models
*/
displayTracksByInitTime: function(storms, initTime = null, defaultModelsOnly = true) {
if (!storms || storms.length === 0) {
console.log("No storms available to display");
return;
}
// If no init time specified, use the latest one
if (!initTime) {
const initTimes = [...new Set(storms.map(storm => storm.initTime))];
initTimes.sort((a, b) => b.localeCompare(a)); // Most recent first
initTime = initTimes[0];
// Update the dropdown to match if it exists
const dropdown = document.querySelector('.init-time-dropdown');
if (dropdown) {
dropdown.value = initTime;
}
}
// Filter storms by the selected init time
let filteredStorms;
if (initTime === 'all') {
filteredStorms = storms;
} else {
filteredStorms = storms.filter(storm => storm.initTime === initTime);
}
console.log(`Filtered to ${filteredStorms.length} tracks for init time ${initTime}`);
// Preserve the current model filter preference
const currentModelPreference = window.currentModelFilterPreference !== undefined ?
window.currentModelFilterPreference : defaultModelsOnly;
// Store the currently selected model category before updating the UI
const categoryDropdown = document.querySelector('.model-category-dropdown');
const previousCategory = categoryDropdown ? categoryDropdown.value : 'all';
window.lastModelCategory = previousCategory;
console.log(`Preserving model category: ${previousCategory}`);
// Update the storm list UI
this.updateStormList(filteredStorms);
// Display the tracks with the preserved model preference
if (typeof window.displayAdeckTracks === 'function') {
console.log(`Using model filter preference: ${currentModelPreference}`);
console.log(`Last selected model category: ${window.lastModelCategory || 'all'}`);
// First ensure the category dropdown has the correct value
if (window.lastModelCategory && categoryDropdown && categoryDropdown.value !== window.lastModelCategory) {
categoryDropdown.value = window.lastModelCategory;
}
// Then trigger the filtering by category before displaying tracks
if (window.lastModelCategory && window.lastModelCategory !== 'all') {
this.filterModelsByCategory(window.lastModelCategory, this.getModelCategories());
}
// Finally, display the tracks with the selected category already applied
window.displayAdeckTracks(filteredStorms, window.selectedStormID, currentModelPreference, window.lastModelCategory);
} else {
this.updateStormList(filteredStorms);
}
},
/**
* Filter models by category
* @param {string} categoryId - ID of the category to filter by
* @param {Array} modelCategories - Array of model category definitions
*/
filterModelsByCategory: function(categoryId, modelCategories) {
// Find the selected category and its models
const category = modelCategories.find(cat => cat.id === categoryId);
if (!category) return;
// Get the models in this category
const modelsInCategory = category.models || [];
// Update the UI to show only models in this category
const modelRows = document.querySelectorAll('.model-row');
modelRows.forEach(row => {
const modelName = row.dataset.model;
if (categoryId === 'all' || modelsInCategory.includes(modelName)) {
row.style.display = ''; // Show the row
// Also show the parent category section if it's not currently visible
const categorySection = row.closest('.model-category-section');
if (categorySection) {
categorySection.style.display = '';
}
} else {
row.style.display = 'none'; // Hide the row
// Check if all rows in this category are now hidden
const categorySection = row.closest('.model-category-section');
if (categorySection) {
const visibleRows = categorySection.querySelectorAll('.model-row[style="display: ;"], .model-row:not([style*="display: none"])');
if (visibleRows.length === 0) {
categorySection.style.display = 'none'; // Hide the entire category
}
}
}
});
return modelsInCategory;
},
/**
* Update storm list display in the dialog
* @param {Array} filteredStorms - Storms to display
*/
updateStormList: function(filteredStorms) {
// Find the storm list element
const stormList = document.querySelector('.storm-list');
if (!stormList) return;
stormList.innerHTML = '';
if (filteredStorms.length === 0) {
stormList.innerHTML = '<div class="empty-state">No tracks available for this initialization time.</div>';
return;
}
// Group by model type
const modelCategories = this.getModelCategories();
// Only show models that are actually plotted
const availableModels = [...new Set(filteredStorms.map(storm => storm.model))];
// Create category sections - but only for models that are being displayed
modelCategories.slice(1).forEach(category => {
// Filter storms by this category, but only including models that are in the available set
const categoryModels = category.models.filter(model => {
// Check direct match
if (availableModels.includes(model)) return true;
// Check pattern match (for ensembles)
if (category.id === 'ensembles' && availableModels.some(m => m.match(/^PH\d{2}$/))) {
return true;
}
return false;
});
// Include ensemble models if we're in the ensemble category
let categoryStorms = [];
if (category.id === 'ensembles') {
categoryStorms = filteredStorms.filter(storm =>
categoryModels.includes(storm.model) ||
storm.model.match(/^PH\d{2}$/)
);
} else {
categoryStorms = filteredStorms.filter(storm => categoryModels.includes(storm.model));
}
if (categoryStorms.length === 0) return;
const categorySection = document.createElement('div');
categorySection.className = 'model-category-section';
const categoryHeader = document.createElement('h4');
categoryHeader.className = 'category-header';
categoryHeader.textContent = category.name;
categorySection.appendChild(categoryHeader);
// Create table for models
const modelTable = document.createElement('table');
modelTable.className = 'model-table';
// Add header row
const thead = document.createElement('thead');
const headerRow = document.createElement('tr');
// Removed the "Points" column, keeping only Model and Init Time
['Model', 'Init Time'].forEach(title => {
const th = document.createElement('th');
th.textContent = title;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
modelTable.appendChild(thead);
// Add rows for each model
const tbody = document.createElement('tbody');
categoryStorms.forEach(storm => {
const row = document.createElement('tr');
row.className = 'model-row';
row.dataset.model = storm.model;
row.dataset.stormId = storm.id;
// Model column
const modelCell = document.createElement('td');
modelCell.style.fontWeight = 'bold';
// Create visibility toggle button
const visibilityBtn = document.createElement('button');
visibilityBtn.className = 'visibility-toggle';
visibilityBtn.dataset.visible = 'true';
visibilityBtn.textContent = '👁️'; // Unicode eye symbol instead of Font Awesome
visibilityBtn.title = 'Toggle visibility';
visibilityBtn.style.marginRight = '5px';
visibilityBtn.style.border = 'none';
visibilityBtn.style.background = 'transparent';
visibilityBtn.style.cursor = 'pointer';
visibilityBtn.dataset.stormId = storm.id; // Add this to easily find the button later
// Add click handler for visibility toggle
visibilityBtn.addEventListener('click', (e) => {
e.stopPropagation(); // Prevent row selection
this.toggleTrackVisibility(storm.id);
});
// Create a wrapper div to contain button and model name
const modelWrapper = document.createElement('div');
modelWrapper.style.display = 'flex';
modelWrapper.style.alignItems = 'center';
modelWrapper.appendChild(visibilityBtn);
// Use formatted model name if available
const displayModelName = this.formatModelName(storm.model);
modelWrapper.appendChild(document.createTextNode(displayModelName));
// Apply color indicator
const modelColor = this.getModelColor(storm.model);
modelCell.style.borderLeft = `4px solid ${modelColor}`;
// Add the wrapper to the cell
modelCell.appendChild(modelWrapper);
row.appendChild(modelCell);
// Init time column
const initTimeCell = document.createElement('td');
initTimeCell.textContent = this.formatDateTime(storm.initTime);
row.appendChild(initTimeCell);
tbody.appendChild(row);
});
modelTable.appendChild(tbody);
categorySection.appendChild(modelTable);
stormList.appendChild(categorySection);