-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSedimentDataExplorer.js
More file actions
2846 lines (2605 loc) · 125 KB
/
SedimentDataExplorer.js
File metadata and controls
2846 lines (2605 loc) · 125 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
let testOne = {};
let radarPlot = "None";
let resuspensionSize = 0;
let kmlLayers = {};
let chosenStandard = 'Proposed Cefas Action Levels';
// let chosenStandard = "Candian Quality Guidelines";
// import {parse, stringify, toJSON, fromJSON} from 'flatted';
const autocolors = window['chartjs-plugin-autocolors'];
Chart.register(autocolors);
const annotationPlugin = window['chartjs-plugin-annotation'];
Chart.register(annotationPlugin);
// Importing the necessary library for coordinate conversion
window.dredgeVolumeData = null;
// const osGridConverter = require('os-transform.js');
const osGridConverter = window['os-transform.js'];
// Define the colors for the circle markers. This array will be used by both the map and the file list.
const markerColors = [
'#FF5733', '#33CFFF', '#33FF57', '#FF33A1', '#A133FF',
'#FFC300', '#33FFA1', '#C70039', '#900C3F'
];
/* markerPath = 'markers/';
markerPngs = ['marker-icon-red.png', 'marker-icon-orange.png', 'marker-icon-yellow.png',
'marker-icon-green.png', 'marker-icon-blue.png', 'marker-icon-violet.png',
'marker-icon-grey.png', 'marker-icon-gold.png','marker-icon-black.png'];*/
// Define the projection for British National Grid (OSGB 1936)
proj4.defs("EPSG:27700", "+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +towgs84=446.448,-125.157,542.060,0.1502,0.2470,0.8421,-20.4894 +units=m +no_defs");
let lastInstanceNo = 0;
let lastScatterInstanceNo = 0;
let noInstances = 16;
let exportLink = null;
let chartInstance = [];
let popupInstance = [];
let instanceType = [];
let instanceSheet = [];
let highlighted = [];
let legends = [];
let ylinlog = [];
let stacked = [];
let largeSize = [];
let xAxisSort = 'normal';
let lookSetting = 'colour';
let highlightMarkers = {};
for (i = 1; i < noInstances; i++) {
chartInstance[i] = null;
instanceType[i] = null;
instanceSheet[i] = null;
}
determinands = {};
determinands.pah = {};
determinands.pah.all = ['Acenapthene', 'Acenapthylene', 'Anthracene', 'Benz[a]anthracene', 'Benzo[a]pyrene', 'Benzo[b]fluoranthene',
'Benzo[g,h,i]perylene', 'Benzo[e]pyrene', 'Benzo[k]fluoranthene', 'C1-Napthalenes', 'C1-Phenanthrenes',
'C2-Napthalenes', 'C3-Napthalenes', 'Chrysene', 'Dibenz[a,h]anthracene', 'Fluoranthene',
'Fluorene', 'Indeno[123-c,d]pyrene', 'Napthalene', 'Perylene', 'Phenanthrene', 'Pyrene'];
determinands.pah.lmw = ['Acenapthene', 'Acenapthylene', 'Anthracene', 'C1-Napthalenes', 'Fluorene','Napthalene', 'Phenanthrene'];
determinands.pah.hmw = ['Benz[a]anthracene', 'Benzo[a]pyrene', 'Chrysene', 'Dibenz[a,h]anthracene', 'Fluoranthene', 'Pyrene'];
determinands.pah.epa = ['Acenapthene', 'Acenapthylene', 'Anthracene', 'Benz[a]anthracene', 'Benzo[a]pyrene', 'Benzo[b]fluoranthene',
'Benzo[g,h,i]perylene', 'Benzo[k]fluoranthene', 'Chrysene', 'Dibenz[a,h]anthracene', 'Fluoranthene',
'Fluorene', 'Indeno[123-c,d]pyrene', 'Napthalene', 'Phenanthrene', 'Pyrene'];
determinands.pah.smallpts = ['Acenapthene', 'Acenapthylene', 'Anthracene', 'Benz[a]anthracene', 'Benzo[a]pyrene', 'Benzo[b]fluoranthene',
'Benzo[g,h,i]perylene', 'Benzo[e]pyrene', 'Benzo[k]fluoranthene', 'Chrysene', 'Dibenz[a,h]anthracene',
'Fluoranthene', 'Fluorene', 'Indeno[123-c,d]pyrene', 'Pyrene'];
determinands.pah.organicc = ['C1-Napthalenes', 'C1-Phenanthrenes', 'C2-Napthalenes', 'C3-Napthalenes', 'Napthalene', 'Phenanthrene'];
determinands['PAH data'] = determinands.pah.all;
determinands['PCB data'] = ["2,2',4,5,5'-Pentachlorobiphenyl", "2,3,3',4,4'-Pentachlorobiphenyl", "2,3,3',4',6-Pentachlorobiphenyl",
"2,3',4,4',5-Pentachlorobiphenyl", "2,2',3,3',4,4'-Hexachlorobiphenyl", "2,2',3,4,4',5'-Hexachlorobiphenyl",
"2,2',3,4,5,5'-Hexachlorobiphenyl", "2,2',3,4',5',6-Hexachlorobiphenyl", "2,2',3,5,5',6-Hexachlorobiphenyl",
"2,2',4,4',5,5'-Hexachlorobiphenyl", "2,3,3',4,4',5-Hexachlorobiphenyl", "2,3,3',4,4',6-Hexachlorobiphenyl",
"2,2',3,3',4,4',5-Heptachlorobiphenyl", "2,2',5-Trichlorobiphenyl", "2,2',3,4,4',5,5'-Heptachlorobiphenyl",
"2,2',3,4,4',5',6-Heptachlorobiphenyl", "2,2',3,4',5,5',6-Heptachlorobiphenyl", "2,2',3,3',4,4',5,5'-Octachlorobiphenyl",
"2,4,4'-Trichlorobiphenyl", "2,4',5-Trichlorobiphenyl", "2,2',3,5'-Tetrachlorobiphenyl", "2,2',4,4'-Tetrachlorobiphenyl",
"2,2',4,5'-Tetrachlorobiphenyl", "2,2',5,5'-Tetrachlorobiphenyl", "2,3',4,4'-Tetrachlorobiphenyl"];
determinands['Organochlorine data'] = ['alpha-hexachlorocyclohexane (AHCH)', 'beta-hexachlorocyclohexane (BHCH)',
'gamma-hexachlorocyclohexane (GHCH)', 'Dieldrin', 'Hexachlorobenzene (HCB)',
'1,1-Dichloro-2,2-bis(p-chlorophenyl) ethylene (PPDDE)', 'Dichlorodiphenyltrichloroethane (PPDDT)',
'1,1-dichloro-2,2-bis(p-chlorophenyl)ethane (PPTDE)'];
determinands['Trace metal data'] = ['Arsenic (As)', 'Cadmium (Cd)', 'Chromium (Cr)', 'Copper (Cu)', 'Mercury (Hg)',
'Nickel (Ni)', 'Lead (Pb)', 'Zinc (Zn)'];
determinands['Organotins data'] = ['Dibutyltine (DBT)', 'Tributyltin (TBT)'];
determinands['BDE data'] = ['2,2′,4,4′,6-penta-bromodiphenyl ether (BDE100)', 'Hexabromodiphenyl ether (BDE138)',
'2,2′,4,4′,5,5′-hexa-bromodiphenyl ether (BDE153)', '2,2′,4,4′,5,6′-hexa-bromodiphenyl ether (BDE154)',
'2,2´,4-tri-bromodiphenylether (BDE17)', '2,2′,3,4,4′,5′,6-heptabromodiphenyl ether (BDE183)',
"2,2',3,3',4,4',5,5',6,6'-decabrominated diphenyl ether (BDE 209)", "2,4,4'-tribromodiphenyl ether (BDE28)",
'2,2′,4,4′-Tetrabromodiphenyl ether (BDE47)', "2,3',4,4'-Tetrabromodiphenyl ether (BDE66)",
"2,2',3,4,4'-Pentabromodiphenyl ether (BDE85)", "2,2',4,4',5-pentabromodiphenyl ether (BDE99)"];
dataSheetNames = ['Physical Data','Trace metal data','PAH data','PCB data','BDE data','Organotins data','Organochlorine data'];
dataSheetAbr = {'Physical Data': 'Phys','Trace metal data': 'TM','PAH data': 'PAH','PCB data': 'PCB','BDE data': 'BDE','Organotins data': 'OT',
'Organochlorine data': 'OC'};
dataSheetNamesCheckboxes = [];
calcSheetNames = ['Physical Stats','PSA Charts','Metals calcs','PAH calcs','PCB calcs','BDE calcs','Organotin calcs','Organochlorine calcs'];
let sortButtonGroups = {};
for (let i = 0; i < dataSheetNames.length; i++) {
dataSheetNamesCheckboxes[i] = dataSheetNames[i].replace(/\s/g, '').toLowerCase();
sortButtonGroups[dataSheetNames[i]] = [];
}
// disableRadioButtons(dataSheetNamesCheckboxes,true);
sheetsToDisplay = {};
completeSheet = {};
for (i = 0; i < dataSheetNames.length; i++) {
sheetName = dataSheetNames[i];
sheetsToDisplay[sheetName] = false;
completeSheet[sheetName] = false;
}
/* dataSheetNames.forEach(sheetName => {
disableRadioButtons(sortButtonGroups[sheetName], false);
completeSheet[sheetName] = true;
})*/
subChartNames = ['samplegroup','chemicalgroup','correlationplots','pcaanalysis','gorhamtest','totalhc','pahratios',
'ringfractions','eparatios','simpleratios','congenertest', 'pcanormalise','pcalmw','pcahmw',
'pcaepa','pcasmallpts','pcaorganiccarbon','relationareadensity','relationhc',
'relationtotalsolids','relationorganiccarbon','splitbyweight','splitbyarea',
'totalsolidsandtotalcarbon','cumulative','mapgrid'];
// relationNames = ['relationareadensity','relationhc','relationtotalsolids'];
subsToDisplay = {};
for (i = 0; i < subChartNames.length; i++) {
subName = subChartNames[i];
subsToDisplay[subName] = false;
}
const sortingOptions = [
'Unsorted', 'Date of Sampling', 'Latitude', 'Longitude', 'Total Area',
'Total Solids', 'Organic Matter', 'Silt', 'Silt and Sand', 'Sand', 'Gravel',
'Total Hydrocarbon', 'Gorham LMW Sum', 'Gorham HMW Sum', 'ICES7 PCB Sum'
];
const primarySortingOptions = [
'None', 'Date of Sampling', 'Sample Name', 'Date & Sample Name', 'Sample Name & Date',
'Dataset Name', 'Dataset Name & Sample Name ', 'Sample Name & Dataset Name'];
const secondarySortingOptions = [
'Latitude', 'Longitude', 'Min Depth', 'Max Depth', 'Mean Depth',
'Total Area', 'Total Solids', 'Organic Matter',
'Silt', 'Silt and Sand', 'Sand', 'Gravel', 'Total Hydrocarbon',
'Gorham LMW Sum', 'Gorham HMW Sum', 'ICES7 PCB Sum', 'All PCBs Sum'
];
const sortOptionDependencies = {
'totalsolids': 'Physical Data',
'organicmatter': 'Physical Data',
'silt': 'Physical Data',
'siltsand': 'Physical Data',
'sand': 'Physical Data',
'gravel': 'Physical Data',
'totalhydrocarbon': 'PAH data',
'gorhamlmwsum': 'PAH data',
'gorhamhmwsum': 'PAH data',
'ices7pcbsum': 'PCB data',
'allpcbssum': 'PCB data'
// Add any other dependencies here.
// Options like 'Latitude', 'Longitude', etc., don't need to be listed
// as they are always available.
};
// sortingOptions = ['unsorted', 'normal', 'datelatitude', 'datelongitude', 'datetotalarea', 'latitude', 'longitude', 'totalarea', 'totalsolids', 'organicmatter', 'silt', 'siltsand', 'sand', 'gravel',
// 'totalhcsort', 'lmw', 'hmw', 'ices7', 'allpcbs', 'datelmw', 'datehmw', 'dateices7', 'dateallpcbs'];
lookOptions = ['colour', 'blackandwhite'];
sortButtonGroups['area'] = [...sortingOptions.filter(option => option.includes('area')), ...subChartNames.filter(option => option.includes('area'))];
sortButtonGroups['PCB data'] = [...sortingOptions.filter(option => option.includes('pcb') || option.includes('ices7'))];/*,
...subChartNames.filter(option => option.includes('congener'))];*/
sortButtonGroups['PAH data'] = [...sortingOptions.filter(option => option.includes('hc') || option.includes('mw') || option.includes('pah')),
...subChartNames.filter(option => option.includes('pah') || option.includes('hc') || option.includes('gorham') || option.includes('ratios')
|| option.includes('ring') || option.includes('totalhc'))];
sortButtonGroups['Physical Data'] = [...sortingOptions.filter(option => option.includes('silt') || option.includes('sand') || option.includes('area') || option.includes('gravel')),
...subChartNames.filter(option => option.includes('area') || option.includes('solid') || option.includes('organic'))];
// ...relationNames.filter(option => option.includes('area') || option.includes('solid'))];
populateSortDropdowns();
for (group in sortButtonGroups) {
//console.log(group);
disableRadioButtons(sortButtonGroups[group], false);
}
let map; // Declare map as a global variable
let fred ='waiting';
let sampleMeasurements = {};
let selectedSampleMeasurements = {};
let sampleInfo = {};
let selectedSampleInfo = {};
let blankMeasurements = {};
let namedLocations = {};
let chemInfo = {};
//All actions level mg/kg
const actionLevels = {};
actionLevels['Trace metal data'] = {
'Arsenic (As)':[20,100],
'Cadmium (Cd)': [0.4,5],
'Chromium (Cr)': [40,400],
'Copper (Cu)': [40,400],
'Mercury (Hg)': [0.3,3],
'Nickel (Ni)': [20,200],
'Lead (Pb)': [50,500],
'Zinc (Zn)': [130,800]
};
actionLevels['Organotins data'] = {
'Dibutyltine (DBT)': [0.1,1],
'Tributyltin (TBT)': [0.1,1]
};
actionLevels['PAH data'] = {
'Acenapthene': [0.1,0],
'Acenapthylene': [0.1,0],
'Anthracene': [0.1,0],
'Benz[a]anthracene': [0.1,0],
'Benzo[a]pyrene': [0.1,0],
'Benzo[b]fluoranthene': [0.1,0],
'Benzo[g,h,i]perylene': [0.1,0],
'Benzo[e]pyrene': [0.1,0],
'Benzo[k]fluoranthene': [0.1,0],
'C1-Napthalenes': [0.1,0],
'C1-Phenanthrenes': [0.1,0],
'C2-Napthalenes': [0.1,0],
'C3-Napthalenes': [0.1,0],
'Chrysene': [0.1,0],
'Dibenz[a,h]anthracene': [0.01,0],
'Fluoranthene': [0.1,0],
'Fluorene': [0.1,0],
'Indeno[123-c,d]pyrene': [0.1,0],
'Napthalene': [0.1,0],
'Perylene': [0.1,0],
'Phenanthrene': [0.1,0],
'Pyrene': [0.1,0]
};
actionLevels['Organochlorine data'] = {
'Dieldrin': [0.005,0],
'Dichlorodiphenyltrichloroethane (PPDDT)': [0.001,0.2]
};
let actionLevelColors = ['rgba(255, 255, 0, 1)','rgba(255, 0, 0, 0.5)'];
let actionLevelDashes = [[3,3],[5,5]];
firstTime = true;
const ccontainer = document.getElementById('radarPlots');
radarPlotTypes = [];
// radarPlotTypes[0] = "None";;
// radarPlotTypes = join(radarPlotTypes,dataSheetNames);
//let radarPlotTypes = dataSheetNames;
radarPlotTypes[0] = "None";
for (i = 1; i < dataSheetNames.length; i++) {
radarPlotTypes[i] = dataSheetNames[i];
}
radarPlotTypes.forEach((name, index) => {
const radio = document.createElement('input');
radio.type = 'radio';
radio.id = `radio${index}`;
radio.name = 'dataSheet';
radio.value = name;
if (name === "None") {
radio.checked = true;
} /*else {
radio.checked = false;
}*/
const label = document.createElement('label');
label.htmlFor = `radio${index}`;
label.appendChild(document.createTextNode(name));
// Attach event listener to each radio button
radio.addEventListener('change', function() {
if (this.checked) {
radarPlot = this.value; // Set radarPlot to the selected value
console.log('Selected radar plot:', radarPlot);
}
});
ccontainer.appendChild(radio);
ccontainer.appendChild(label);
});
/*standards = {};
document.addEventListener('DOMContentLoaded', async () => {
const dataUrl = 'https://northeastfc.uk/Supporting/quality_standards.sdes';
const parsedData = await readQualityStandards(dataUrl);
const outputElement = document.getElementById('output');
standards = parsedData;
});*/
completeStandards();
importData();
function parseDates(dateString) {
//console.log('dateString pd', dateString);
// Check if the date field is empty
if (!dateString) {
return ['Missing'];
}
const dates = [];
// Split the input by commas or hyphens
const dateParts = dateString.split('/,|-/');
dateParts.forEach(part => {
// Trim leading/trailing spaces
const trimmedPart = part.trim();
// Check if it's a range (contains a hyphen)
if (trimmedPart.includes('/')) {
const ukDate = convertToUKFormat(trimmedPart);
if (ukDate) {
dates.push(ukDate);
}
} else {
// Single date
const ukDate = convertToUKFormat(trimmedPart);
if (ukDate) {
dates.push(ukDate);
}
}
});
return dates.length > 0 ? dates : ['Missing'];
}
function convertToUKFormat(dateString) {
//console.log('dateString cUKf',dateString);
const parts = dateString.split('/');
//console.log('parts cUKf',parts);
if (parts.length === 3) {
if (parts[2].length === 2) {
// Assuming the format is mm/dd/yy
const mm = parts[0].padStart(2, '0');
const dd = parts[1].padStart(2, '0');
const yy = parts[2].padStart(2, '0');
// Construct the UK format: dd/mm/yy
//console.log('return',`20${yy}/${mm}/${dd}`);
return `20${yy}/${mm}/${dd}`;
} else {
if (parts[2].length === 4) {
// Assuming the format is mm/dd/yy
const dd = parts[0].padStart(2, '0');
const mm = parts[1].padStart(2, '0');
const yy = parts[2].padStart(2, '0');
// Construct the UK format: dd/mm/yy
//console.log('return',`${yy}/${mm}/${dd}`);
return `${yy}/${mm}/${dd}`;
}
}
}
// Return null for invalid date formats
return null;
}
function saveSnapShot() {
const fileSave = document.getElementById('fileSave');
const fileName = fileSave.value;
saveStatus(fileName);
}
function postLoadSnapShot() {
for (dateSampled in sampleMeasurements) {
// console.log('looking for labels');
if (!(sampleInfo[dateSampled].hasOwnProperty('label'))) {
//console.log('sampleInfo',dateSampled, 'adding label');
sampleInfo[dateSampled].label = dateSampled;
}
if ((sampleInfo[dateSampled].hasOwnProperty('Date Sampled'))) {
//console.log('sampleInfo',dateSampled, 'corrected missing Date sampled');
sampleInfo[dateSampled]['Date sampled'] = sampleInfo[dateSampled]['Date Sampled'];
}
for (sample in sampleInfo[dateSampled].position) {
if (!(sampleInfo[dateSampled].position[sample].hasOwnProperty('label'))) {
sampleInfo[dateSampled].position[sample].label = sample;
}
}
if ('Physical Data' in sampleMeasurements[dateSampled]) {
for (sample in sampleMeasurements[dateSampled]['Physical Data'].samples) {
if (!('totalArea' in sampleMeasurements[dateSampled]['Physical Data'].samples[sample])) {
currentPsd = sampleMeasurements[dateSampled]['Physical Data'].samples[sample].psd;
retData = psdPostProcess(currentPsd, sampleMeasurements[dateSampled]['Physical Data'].sizes);
sampleMeasurements[dateSampled]['Physical Data'].samples[sample].psd = [...retData['currentPsd'],0];
sampleMeasurements[dateSampled]['Physical Data'].samples[sample].psdAreas = retData['areas'];
sampleMeasurements[dateSampled]['Physical Data'].samples[sample].psdRelaitveAreas = retData['realtiveAreas'];
sampleMeasurements[dateSampled]['Physical Data'].samples[sample].splitWeights = retData['splitWeights'];
sampleMeasurements[dateSampled]['Physical Data'].samples[sample].splitAreas = retData['splitAreas'];
sampleMeasurements[dateSampled]['Physical Data'].samples[sample].splitRelativeAreas = retData['splitRelativeAreas'];
sampleMeasurements[dateSampled]['Physical Data'].samples[sample].cumAreas = retData['cumAreas'];
sampleMeasurements[dateSampled]['Physical Data'].samples[sample].cumWeights = retData['cumWeights'];
sampleMeasurements[dateSampled]['Physical Data'].samples[sample].totalArea = retData['totalArea'];
}
}
sampleMeasurements[dateSampled]['Physical Data'].sizes = [...standard_phiSizes, 0];
}
}
for (dateSampled in selectedSampleMeasurements) {
if (!(selectedSampleInfo[dateSampled].hasOwnProperty('label'))) {
selectedSampleInfo[dateSampled].label = dateSampled;
}
if ((selectedSampleInfo[dateSampled].hasOwnProperty('Date Sampled'))) {
selectedSampleInfo[dateSampled]['Date sampled'] = sampleInfo[dateSampled]['Date sampled'];
}
for (sample in selectedSampleInfo[dateSampled].position) {
if (!(selectedSampleInfo[dateSampled].position[sample].hasOwnProperty('label'))) {
selectedSampleInfo[dateSampled].position[sample].label = sample;
}
}
if ('Physical Data' in selectedSampleMeasurements[dateSampled]) {
for (sample in selectedSampleMeasurements[dateSampled]['Physical Data'].samples) {
if (!('totalArea' in selectedSampleMeasurements[dateSampled]['Physical Data'].samples[sample])) {
selectedSampleMeasurements[dateSampled]['Physical Data'].samples[sample] = sampleMeasurements[dateSampled]['Physical Data'].samples[sample];
}
}
}
}
}
function loadSnapShotURL() {
const urlLoad = document.getElementById('urlLoad');
const fileUrl = urlLoad.value;
loadStatus(fileUrl);
postLoadSnapShot();
}
function loadSnapShotFile() {
const fileInput = document.getElementById('fileLoad');
const file = fileInput.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function (e) {
// Read file as text
const textData = e.target.result;
// Decode the base64 data (if it was encoded)
const decodedData = decodeURIComponent(escape(atob(textData)));
// Parse the JSON data
const jsonData = JSON.parse(decodedData);
// Use the loaded data
// Now jsonData contains the loaded data
sampleInfo = jsonData.sampleInfo;
sampleMeasurements = jsonData.sampleMeasurements;
selectedSampleInfo = jsonData.selectedSampleInfo;
selectedSampleMeasurements = jsonData.selectedSampleMeasurements;
postLoadSnapShot();
updateChart();
};
reader.readAsText(file);
}
}
function saveStatus(fileName) {
// Save data to a file
const dataBlob = new Blob([btoa(unescape(encodeURIComponent(JSON.stringify({ sampleInfo, sampleMeasurements, selectedSampleInfo, selectedSampleMeasurements }))))], { type: 'application/octet-stream' });
const downloadLink = document.createElement('a');
downloadLink.href = URL.createObjectURL(dataBlob);
downloadLink.download = fileName;
downloadLink.click();
}
// Function to load data from a file URL
async function loadStatus(fileURL) {
try {
// Fetch the data from the URL
const response = await fetch(fileURL);
// Check if the fetch was successful (status code 200)
if (!response.ok) {
throw new Error(`Failed to fetch data. Status: ${response.status}`);
}
// Read the response as text
const textData = await response.text();
// Decode the base64 data (if it was encoded)
const decodedData = decodeURIComponent(escape(atob(textData)));
// Parse the JSON data
const jsonData = JSON.parse(decodedData);
// Now jsonData contains the loaded data
/* sampleInfo = jsonData.sampleInfo;
sampleMeasurements = jsonData.sampleMeasurements;
selectedSampleInfo = jsonData.selectedSampleInfo;
selectedSampleMeasurements = jsonData.selectedSampleMeasurements;*/
Object.assign(sampleInfo, jsonData.sampleInfo);
Object.assign(sampleMeasurements, jsonData.sampleMeasurements);
Object.assign(selectedSampleInfo, jsonData.selectedSampleInfo);
Object.assign(selectedSampleMeasurements, jsonData.selectedSampleMeasurements);
postLoadSnapShot();
updateChart();
return jsonData;
} catch (error) {
console.error('Error loading data:', error.message);
}
}
function clearData() {
/* if (map) {
map.remove();
}*/
sampleMeasurements = {};
selectedSampleMeasurements = {};
sampleInfo = {};
selectedSampleInfo = {};
for (group in sortButtonGroups) {
disableRadioButtons(sortButtonGroups[group], false);
}
/* if (map) {
map.remove();
}*/
const canvas = [];
for (i = 1; i < noInstances; i++) {
canvas[i] = document.getElementById('chart' + i);
clearCanvasAndChart(canvas[i], i);
}
}
function importChemInfo() {
urls = {};
//console.log('importChemInfo');
if (firstTime) {
firstTime = false;
files = {};
// Get the current URL
const currentURL = window.location.href;
// Parse the URL to get the search parameters
const suppliedParams = new URLSearchParams(window.location.search);
// Get the value of the 'cheminfo' parameter
const cheminfoParam = suppliedParams.get('cheminfo');
if (!cheminfoParam) {
return;
} else {
urls = cheminfoParam.split(',').map(url => url.trim()); // Split comma-separated URLs
}
} else {
const fileInput = document.getElementById('fileChemInfo');
const urlInput = document.getElementById('urlChemInfo');
const files = fileInput.files; // Files is now a FileList object containing multiple files
const urls = urlInput.value.trim().split(',').map(url => url.trim()); // Split comma-separated URLs
if (files.length === 0 && urls.length === 0) {
alert('Please select files or enter URLs.');
return;
}
// Process files
for (let i = 0; i < files.length; i++) {
filename = files[i].name;
const reader = new FileReader();
reader.onload = function (e) {
const data = new Uint8Array(e.target.result);
processExcelChemInfo(data,filename);
};
reader.readAsArrayBuffer(files[i]);
}
}
// Process URLs only if URLs are supplied
if (urls.length > 0) {
urls.forEach(url => {
// Check if the URL is a valid URL before fetching
if (!/^https?:\/\//i.test(url)) {
console.error('Invalid URL:', url);
return;
}
fetch(url)
.then(response => response.arrayBuffer())
.then(data => {
processExcelChemInfo(new Uint8Array(data),url);
})
.catch(error => {
console.error('Error fetching the chemInfo file:', error);
});
});
}
// Clear the input field after reading locations
fileInput.value = '';
urlInput.value = '';
}
function processExcelChemInfo(data,url) {
// Based on simple Excel data in first sheet
// row 1 column titles
// column 1 compound name
// column 2 - n property
const workbook = XLSX.read(data, { type: 'array' });
//console.log(workbook);
sheetData = workbook.Sheets['Sheet1'];
//console.log(sheetData);
const df = XLSX.utils.sheet_to_json(sheetData, { header: 1 });
for (let r = 1; r < df.length; r++) {
const chemical = df[r][0];
chemInfo[chemical] = {};
for (let c = 1; c < df[r].length; c++) {
const property = df[0][c];
chemInfo[chemical][property] = df[r][c];
}
//console.log(chemInfo[chemical]);
}
//console.log('End of processChemInfo');
}
function importLocations() {
urls = {};
if (firstTime) {
firstTime = false;
files = {};
// Get the current URL
const currentURL = window.location.href;
// Parse the URL to get the search parameters
const suppliedParams = new URLSearchParams(window.location.search);
// Get the value of the 'locations' parameter
const locationsParam = suppliedParams.get('locations');
if (!locationsParam) {
return;
} else {
urls = locationsParam.split(',').map(url => url.trim()); // Split comma-separated URLs
}
} else {
const fileInput = document.getElementById('fileLocations');
const urlInput = document.getElementById('urlLocations');
const files = fileInput.files; // Files is now a FileList object containing multiple files
urls = urlInput.value.trim().split(',').map(url => url.trim()); // Split comma-separated URLs
if (files.length === 0 && urls.length === 0) {
alert('Please select files or enter URLs.');
return;
}
// Process files
for (let i = 0; i < files.length; i++) {
filename = files[i].name;
const reader = new FileReader();
reader.onload = function (e) {
const data = new Uint8Array(e.target.result);
processExcelLocations(data,filename);
};
reader.readAsArrayBuffer(files[i]);
}
}
// Process URLs only if URLs are supplied
if (urls.length > 0) {
urls.forEach(url => {
// Check if the URL is a valid URL before fetching
if (!/^https?:\/\//i.test(url)) {
console.error('Invalid URL:', url);
return;
}
fetch(url)
.then(response => response.arrayBuffer())
.then(data => {
processExcelLocations(new Uint8Array(data),url);
})
.catch(error => {
console.error('Error fetching the locations file:', error);
});
});
}
// Clear the input field after reading locations
fileInput.value = '';
urlInput.value = '';
}
function importShapes() {
let urls = [];
if (firstTime) {
// Get the current URL
const currentURL = window.location.href;
// Parse the URL to get the search parameters
const suppliedParams = new URLSearchParams(window.location.search);
// Get the value of the 'locations' parameter
const shapesParam = suppliedParams.get('shapes');
if (shapesParam) {
urls = shapesParam.split(',').map(url => url.trim()); // Split comma-separated URLs
}
} else {
const fileInput = document.getElementById('fileShapes');
const urlInput = document.getElementById('urlShapes');
const files = fileInput.files; // Files is now a FileList object containing multiple files
const urlVal = urlInput.value.trim();
if (urlVal) {
urls = urlVal.split(',').map(url => url.trim()); // Split comma-separated URLs
}
if (files.length === 0 && urls.length === 0) {
alert('Please select files or enter URLs.');
return;
}
// Process files
for (let i = 0; i < files.length; i++) {
const filename = files[i].name;
const reader = new FileReader();
reader.onload = function (e) {
const content = e.target.result;
const blob = new Blob([content], {type: 'application/vnd.google-earth.kml+xml'});
const url = URL.createObjectURL(blob);
kmlLayers[filename] = url;
};
reader.readAsText(files[i]);
}
// Clear the input field after reading locations
fileInput.value = '';
urlInput.value = '';
}
// Process URLs only if URLs are supplied
if (urls.length > 0) {
urls.forEach(url => {
// Check if the URL is a valid URL before fetching
if (!/^https?:\/\//i.test(url)) {
console.error('Invalid URL:', url);
return;
}
const filename = url.split('/').pop();
console.log(filename); // Output: MLA_2015_00088-LOCATIONS.kml
//"https://northeastfc.uk/RiverTees/Planning/MLA_2015_00088/MLA_2015_00088-LOCATIONS.kml"
// kmlLayers[filename] = new L.KML(url, {async: true});
kmlLayers[filename] = url;
/* fetch(url)
.then(response => response.arrayBuffer())
.then(data => {
processExcelLocations(new Uint8Array(data),url);
})
.catch(error => {
console.error('Error fetching the locations file:', error);
});*/
});
}
}
function processExcelLocations(data,url) {
// Based on simple Excel data in first sheet
// row 1 column titles
// column 1 location as per name used as sample in MMO templates
// column 2 latitude in decimal degrees
// column 3 longitude in decimal degrees
// console.log('processexcellocations',url);
//console.log('prcoessing ',url);
const workbook = XLSX.read(data, { type: 'array' });
//console.log(workbook);
sheetData = workbook.Sheets['Sheet1'];
//console.log(sheetData);
const df = XLSX.utils.sheet_to_json(sheetData, { header: 1 });
for (let r = 1; r < df.length; r++) {
const sample = df[r][0];
//console.log('|',sample,'|',sample.trim(),'|');
cleanSample = sample.replace(/\s+/g, '').toLowerCase();
namedLocations[cleanSample] = {};
namedLocations[cleanSample].label = sample;
namedLocations[cleanSample].latitude = parseFloat(df[r][1]);
namedLocations[cleanSample].longitude = parseFloat(df[r][2]);
//console.log(sample,namedLocations[sample]);
}
//console.log('End of processExcelLocations');
}
function checkboxParameters(suppliedParams, paramName, checkboxNames) {
const param = suppliedParams.get(paramName);
if (param) {
sels = param.split(',').map(sel => sel.trim()); // Split comma-separated URLs
if (sels) {
// Blank all the checkboxes
for (let i = 0; i < checkboxNames.length; i++) {
const checkbox = document.getElementById(checkboxNames[i]);
checkbox.checked = false;
}
// Check all the boxes set in url
for (let i = 0; i < sels.length; i++) {
//console.log(i);
//console.log(sels[i]);
const checkbox = document.getElementById(sels[i].toLowerCase());
checkbox.checked = true;
}
}
}
}
function cleanChemicalString(chemical) {
return chemical
.replace(/[\r]/g, '') // Remove \r
.replace(/[\n]/g, '') // Remove \n
.replace(/\s*-\s*/g, '-') // Remove spaces around dashes
.replace(/\s+/g, ' ') // Replace multiple spaces with a single space
.trim(); // Remove spaces at the beginning and end of the string
}
// --- Sidebar Toggle ---
function toggleSidebar() {
const sidebar = document.getElementById('controls-sidebar');
const toggleBtn = document.getElementById('sidebar-toggle');
sidebar.classList.toggle('collapsed');
toggleBtn.innerHTML = sidebar.classList.contains('collapsed') ? '▶' : '◀';
}
function generateURL() {
const params = new URLSearchParams();
// 1. Data URLs
const dataUrls = new Set();
if (typeof sampleInfo !== 'undefined') {
Object.values(sampleInfo).forEach(info => {
if (info.fileURL && /^https?:\/\//i.test(info.fileURL)) {
dataUrls.add(info.fileURL);
}
});
}
if (dataUrls.size > 0) {
params.set('urls', Array.from(dataUrls).join(','));
}
// 2. Shapes
const shapeUrls = new Set();
if (typeof kmlLayers !== 'undefined') {
Object.values(kmlLayers).forEach(url => {
if (typeof url === 'string' && /^https?:\/\//i.test(url)) {
shapeUrls.add(url);
}
});
}
if (shapeUrls.size > 0) {
params.set('shapes', Array.from(shapeUrls).join(','));
}
// 3. Selected Charts
const selCharts = [];
if (typeof dataSheetNamesCheckboxes !== 'undefined') {
dataSheetNamesCheckboxes.forEach(id => {
const checkbox = document.getElementById(id);
if (checkbox && checkbox.checked) {
selCharts.push(id);
}
});
}
if (selCharts.length > 0) {
params.set('selcharts', selCharts.join(','));
}
// 4. Sub Charts
const subCharts = [];
if (typeof subChartNames !== 'undefined') {
subChartNames.forEach(id => {
const checkbox = document.getElementById(id);
if (checkbox && checkbox.checked) {
subCharts.push(id);
}
});
}
if (subCharts.length > 0) {
params.set('subcharts', subCharts.join(','));
}
// 5. Sort
if (typeof xAxisSort !== 'undefined' && xAxisSort !== 'normal') {
params.set('sort', xAxisSort);
}
// 6. Look
if (typeof lookSetting !== 'undefined' && lookSetting !== 'colour') {
params.set('look', lookSetting);
}
// 7. Dredge Data
if (typeof CEFASfilename !== 'undefined' && CEFASfilename && /^https?:\/\//i.test(CEFASfilename)) {
params.set('durl', CEFASfilename);
const lat = document.getElementById('centreLatitude')?.value;
if (lat) params.set('dlat', lat);
const lon = document.getElementById('centreLongitude')?.value;
if (lon) params.set('dlon', lon);
const rad = document.getElementById('radius')?.value;
if (rad) params.set('drad', rad);
const start = document.getElementById('startDate')?.value;
if (start) params.set('dstart', start);
const finish = document.getElementById('finishDate')?.value;
if (finish) params.set('dfinish', finish);
const lics = document.getElementById('mlApplications')?.value;
if (lics) params.set('dlics', lics);
}
// 8. Dredge Volume Data URL
if (window.dredgeVolumeData && window.dredgeVolumeData.sourceUrl) {
params.set('dredgevol', window.dredgeVolumeData.sourceUrl);
}
// 9. Dredge Volume Year Range
const dStart = document.getElementById('dredgeStartYear')?.value;
if (dStart) params.set('dvolstart', dStart);
const dEnd = document.getElementById('dredgeEndYear')?.value;
if (dEnd) params.set('dvolend', dEnd);
const baseUrl = window.location.origin + window.location.pathname;
// Decode URI component to show spaces instead of %20 or +
const newUrl = decodeURIComponent(baseUrl + '?' + params.toString().replace(/\+/g, ' '));
navigator.clipboard.writeText(newUrl).then(() => {
alert('URL copied to clipboard:\n' + newUrl);
}, (err) => {
console.error('Could not copy text: ', err);
prompt("Copy this URL:", newUrl);
});
}
function createControlButtons() {
const sidebar = document.getElementById('controls-sidebar');
if (sidebar) {
const button = document.createElement('button');
button.textContent = 'Export Data to CSV';
button.style.marginTop = '10px';
button.style.marginBottom = '10px';
button.style.width = '95%';
button.style.padding = '5px';
button.style.cursor = 'pointer';
button.onclick = exportToCSV;
sidebar.insertBefore(button, sidebar.firstChild);
const buttonFiltered = document.createElement('button');
buttonFiltered.textContent = 'Export Filtered Data to CSV';
buttonFiltered.style.marginTop = '10px';
buttonFiltered.style.marginBottom = '10px';
buttonFiltered.style.width = '95%';
buttonFiltered.style.padding = '5px';
buttonFiltered.style.cursor = 'pointer';
buttonFiltered.onclick = exportFilteredToCSV;
sidebar.insertBefore(buttonFiltered, sidebar.firstChild);
const buttonCopy = document.createElement('button');
buttonCopy.textContent = 'Copy Settings URL';
buttonCopy.style.marginTop = '10px';
buttonCopy.style.marginBottom = '10px';
buttonCopy.style.width = '95%';
buttonCopy.style.padding = '5px';
buttonCopy.style.cursor = 'pointer';
buttonCopy.onclick = generateURL;
sidebar.insertBefore(buttonCopy, sidebar.firstChild);
const buttonFD = document.createElement('button');
buttonFD.textContent = 'Toggle File Display';
buttonFD.style.marginTop = '10px';
buttonFD.style.marginBottom = '10px';
buttonFD.style.width = '95%';
buttonFD.style.padding = '5px';
buttonFD.style.cursor = 'pointer';
buttonFD.onclick = toggleFileDisplay;
sidebar.insertBefore(buttonFD, sidebar.firstChild);
const buttonSS = document.createElement('button');
buttonSS.id = 'toggleStaticShapesBtn';
buttonSS.textContent = 'Static Maps Shapes: Off';
buttonSS.style.marginTop = '10px';
buttonSS.style.marginBottom = '10px';
buttonSS.style.width = '95%';
buttonSS.style.padding = '5px';
buttonSS.style.cursor = 'pointer';
buttonSS.onclick = function() {
if (window.toggleStaticShapes) window.toggleStaticShapes();
};
sidebar.insertBefore(buttonSS, sidebar.firstChild);
// --- Dredge Data Input Section ---
const dredgeContainer = document.createElement('div');
dredgeContainer.style.marginTop = '10px';
dredgeContainer.style.padding = '5px';
dredgeContainer.style.borderTop = '1px solid #ccc';
dredgeContainer.style.borderBottom = '1px solid #ccc';
const dredgeLabel = document.createElement('div');
dredgeLabel.innerHTML = '<b>Dredge Volumes (xlsx/ods)</b>';
dredgeContainer.appendChild(dredgeLabel);
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = '.xlsx, .ods';
fileInput.style.width = '95%';
fileInput.style.marginTop = '5px';
fileInput.addEventListener('change', handleDredgeVolumeUpload);
dredgeContainer.appendChild(fileInput);
// URL Input
const urlContainer = document.createElement('div');
urlContainer.style.marginTop = '5px';
const urlInput = document.createElement('input');
urlInput.type = 'text';
urlInput.id = 'dredgeVolUrl';
urlInput.placeholder = 'URL to Dredge Data';
urlInput.style.width = '70%';
urlContainer.appendChild(urlInput);
const loadBtn = document.createElement('button');
loadBtn.textContent = 'Load';
loadBtn.style.width = '25%';
loadBtn.onclick = function() {
const url = document.getElementById('dredgeVolUrl').value;
if (url) loadDredgeVolumeFromUrl(url);
};
urlContainer.appendChild(loadBtn);
dredgeContainer.appendChild(urlContainer);
const densityContainer = document.createElement('div');
densityContainer.style.marginTop = '5px';
densityContainer.innerHTML = 'Density (T/m³): ';