-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsdeCharts.js
More file actions
3676 lines (3384 loc) · 159 KB
/
sdeCharts.js
File metadata and controls
3676 lines (3384 loc) · 159 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
/**
* Enables or disables sorting options based on available data.
*/
chartNameSep = ' '// Three spaces to separate dataset name from sample name for point labels
// Mapping of sorting options to required data sheets
window.areaStats = [];
let summaryChartInstanceNoTotal = -1;
let summaryChartInstanceNoUnique = -1;
let summaryChartInstanceNoAvg = -1;
let summaryChartInstanceNoMax = -1;
let summaryChartInstanceNoDredge = -1;
let summaryChartInstanceNoDredgeArea = -1;
let summaryChartInstanceNoDredgeVolYear = -1;
let summaryChartInstanceNoDredgeVolArea = -1;
const sheetColors = {
'Trace metal data': '#e41a1c', // Red
'PAH data': '#377eb8', // Blue
'PCB data': '#4daf4a', // Green
'BDE data': '#984ea3', // Purple
'Organotins data': '#ff7f00', // Orange
'Organochlorine data': '#ffff33', // Yellow
'Physical Data': '#a65628', // Brown
'Other': '#999999' // Grey
};
function updateSortingOptionsState() {
const primarySelect = document.getElementById('primary-sorting-select');
const secondarySelect = document.getElementById('secondary-sorting-select');
// First, enable all options by default
for (const option of primarySelect.options) {
option.disabled = false;
}
for (const option of secondarySelect.options) {
option.disabled = false;
}
// Now, disable options based on missing data
for (const sortValue in sortOptionDependencies) {
const requiredSheet = sortOptionDependencies[sortValue];
// Check if the required sheet data is NOT complete/available
if (!completeSheet[requiredSheet]) {
// Find and disable the option in both dropdowns
const primaryOption = primarySelect.querySelector(`option[value="${sortValue}"]`);
if (primaryOption) {
primaryOption.disabled = true;
}
const secondaryOption = secondarySelect.querySelector(`option[value="${sortValue}"]`);
if (secondaryOption) {
secondaryOption.disabled = true;
}
}
}
}
function updateOptions() {
// This part checks which data sheets are complete
dataSheetNames.forEach(sheetName => {
completeSheet[sheetName] = true;
for(const dateSampled in selectedSampleMeasurements) {
if (!selectedSampleMeasurements[dateSampled][sheetName]){
completeSheet[sheetName] = false;
break;
}
}
});
// --- ADD THIS CALL ---
// After determining which sheets are complete, update the dropdowns
updateSortingOptionsState();
const msfInput = document.getElementById('markerScaling');
if (msfInput) {
const val = parseFloat(msfInput.value);
if (!isNaN(val) && val > 0) {
markerScaling = val;
}
}
const primarySort = document.getElementById('primary-sorting-select').value;
const secondarySort = document.getElementById('secondary-sorting-select').value;
// Combine the values. You will need to update your sorting logic
// to handle this new combined format (e.g., "latitude-longitude").
if (secondarySort !== 'none') {
xAxisSort = `${primarySort}-${secondarySort}`;
} else {
xAxisSort = primarySort;
}
//console.log('xAxisSort', xAxisSort);
for (let i = 0; i < dataSheetNames.length; i++) {
const sheetName = dataSheetNames[i];
sheetsToDisplay[dataSheetNames[i]] = document.getElementById(dataSheetNamesCheckboxes[i]).checked ? true : false; // Check the checkbox state
}
for (let i = 0; i < subChartNames.length; i++) {
const subName = subChartNames[i];
subsToDisplay[subName] = document.getElementById(subName).checked ? true : false; // Check the checkbox state
}
// xAxisSort = document.querySelector('input[name="sorting"]:checked').value; //radio buttons
// xAxisSort = document.getElementById('sorting-select').value; //dropdown
lookSetting = document.querySelector('input[name="look"]:checked').value;
resuspensionSize = parseFloat(document.getElementById('resuspensionsize').value);
if (isNaN(resuspensionSize)) {
resuspensionSize = 0;
} else {
if (resuspensionSize > 0 ) {
resuspensionSize = resuspensionSize / 1000000;
}
}
const useTabs = document.getElementById('useTabs').checked;
const mainChartContainer = document.getElementById('chartContainer');
if (useTabs) {
let tabButtonsContainer = document.getElementById('chart-tab-buttons');
if (tabButtonsContainer) {
// Clear existing tab buttons to avoid duplicates
tabButtonsContainer.innerHTML = '';
}
}
}
function updateChart(){
updateOptions();
//SRG 250728 Removed loosing data, not sure why or why in in first place wrangleData();
//console.log('UPDATECHART*******************');
if (lastInstanceNo > 0) {
const canvas = [];
removeScatterTables();
for (i = 1; i < lastInstanceNo + 1; i++) {
canvas[i] = document.getElementById('chart' + i);
clearCanvasAndChart(canvas[i], i);
}
}
lastInstanceNo = 0;
blankSheets = {};
setBlanksForCharting();
allMapData.isReady = false; // Force regeneration of map layers
createGlobalLayers();
//console.log(sheetsToDisplay);
for (const sheetName in sheetsToDisplay) {
//console.log(sheetName, sheetsToDisplay[sheetName], chemicalTypeHasData(sheetName));
if (sheetsToDisplay[sheetName] && chemicalTypeHasData(sheetName)) {
lastInstanceNo = displayCharts(sheetName, lastInstanceNo);
}
}
if (!(radarPlot === "None")) {
retData = dataForCharting(radarPlot);
unitTitle = retData['unitTitle'];
selectedMeas = retData['measChart'];
createRadarPlot(selectedMeas, radarPlot);
}
//console.log('lastInstanceNo ',lastInstanceNo);
lastInstanceNo = displaySummaryChart(lastInstanceNo);
//console.log(selectedMeas);
console.log('about to display sample map');
sampleMap();
//srg260408 sampleMap(selectedMeas);
filenameDisplay();
}
function displayPsdSplits(sortedSamples, sums, sheetName, instanceNo, unitTitle, subTitle) {
// console.log(sums);
//console.log(sortedSamples, sums, sheetName, instanceNo, unitTitle, subTitle);
createCanvas(instanceNo);
//Bodge lost data for unitTitle
if (unitTitle === undefined || unitTitle === null) {
unitTitle = 'Particle size distribution (% at 0.5 phi intervals)'; //bodge
}
const convas = document.getElementById("chart" + instanceNo);
convas.style.display = "block";
instanceType[instanceNo] = 'PSD splits by ' + subTitle;
instanceSheet[instanceNo] = sheetName;
// const allSamples = Object.keys(sums);
// const allSamples = sortedSamples; // Use the sorted samples from the retData
const allSamples = Object.keys(sums); // Use the sums from the retData
//console.log('allSamples',allSamples);
const allParticles = Object.keys(sums[allSamples[0]]); // Assuming all samples have the particles
//console.log('allParticles',allParticles);
const datasets = allParticles.map((particle, index) => {
const data = allSamples.map(sample => sums[sample][particle]);
return {
label: particle,
data: data,
borderWidth: 1,
yAxisID: 'y',
};
});
displayAnySampleChart(sums, allSamples, datasets, instanceNo, sheetName + ': PSD splits by ' + subTitle, unitTitle + ' by ' + subTitle, true);
y1Title = 'PSD Split by ' + subTitle;
chartInstance[instanceNo].options.plugins.annotation.annotations = {};
chartInstance[instanceNo].options.plugins.legend.display = true;
legends[instanceNo] = true;
// Update the chart
chartInstance[instanceNo].options.scales.x.stacked = true;
chartInstance[instanceNo].options.scales.y.stacked = true;
chartInstance[instanceNo].update();
}
// Function to toggle dataset visibility
function toggleDataset(instanceNo, chemicalGroup) {
const chart = chartInstance[instanceNo];
if (!chart) return;
dataset = chart.data.datasets.forEach((ds, index) => {
if (!determinands.pah[chemicalGroup.toLowerCase()].includes(ds.label)) {
ds.hidden = true;
// Ensure internal Chart.js tracking is also updated
if (chart._metasets && chart._metasets[index]) {
chart._metasets[index].hidden = true;
}
}
});
chart.update();
document.getElementById('button'+chemicalGroup.toLowerCase()+instanceNo).disabled = true;
}
// Function to create a button for resetting samples in a chart
function createDisplayChemicals(instanceNo,chemicalGroup) {
//console.log('creating zoom buttom',instanceNo);
let chart = chartInstance[instanceNo];
const container = document.getElementById('chartContainer');
const button = document.createElement('button');
button.id = 'button'+chemicalGroup.toLowerCase()+instanceNo
button.textContent = 'Select ' + chemicalGroup;
button.addEventListener('click', () => {
toggleDataset(instanceNo,chemicalGroup);
});
container.appendChild(button);
}
// Function to reset chart (show all chemical
// s)
function resetDataset(instanceNo) {
const chart = chartInstance[instanceNo];
if (!chart) {
console.log('Chart not found');
return;
}
chart.data.datasets.forEach((ds, index) => {
if (ds.hidden) {
ds.hidden = false;
}
});
// Reset internal Chart.js hidden state (for legend toggling)
if (chart._metasets) {
chart._metasets.forEach(meta => {
meta.hidden = false;
});
}
enableDataButtons(instanceNo,['epa','lmw','hmw','smallpts','organicc']);
chart.update();
}
function enableDataButtons(instanceNo,chemicalGroups) {
for (let i = 0; i < chemicalGroups.length; i++) {
document.getElementById('button'+chemicalGroups[i].toLowerCase()+instanceNo).disabled = false;
}
}
//document.getElementById(id).disabled = false;
// Function to create a button for resetting samples in a chart
function createResetChart(instanceNo) {
//console.log('creating zoom buttom',instanceNo);
let chart = chartInstance[instanceNo];
const container = document.getElementById('chartContainer');
const button = document.createElement('button');
button.id = 'buttonr'+instanceNo
button.textContent = 'Reset Dataset';
button.addEventListener('click', () => {
resetDataset(instanceNo);
});
container.appendChild(button);
}
function displayCharts(sheetName, instanceNo) {
if (instanceNo === 0) {
document.getElementById('chartContainer').innerHTML = '';
}
const useTabs = document.getElementById('useTabs').checked;
const mainChartContainer = document.getElementById('chartContainer');
let targetContainer;
if (useTabs) {
let tabButtonsContainer = document.getElementById('chart-tab-buttons');
if (!tabButtonsContainer) {
tabButtonsContainer = document.createElement('div');
tabButtonsContainer.id = 'chart-tab-buttons';
tabButtonsContainer.className = 'tab-buttons';
mainChartContainer.appendChild(tabButtonsContainer);
}
const sanitizedSheetName = sheetName.replace(/[^a-zA-Z0-9]/g, '-');
const tabContentId = 'tab-' + sanitizedSheetName;
const tabButton = document.createElement('button');
tabButton.className = 'tab-button';
tabButton.textContent = sheetName;
tabButton.onclick = (event) => openTab(event, tabContentId);
tabButtonsContainer.appendChild(tabButton);
const tabContentPanel = document.createElement('div');
tabContentPanel.id = tabContentId;
tabContentPanel.className = 'tab-content';
mainChartContainer.appendChild(tabContentPanel);
if (tabButtonsContainer.children.length === 1) {
tabButton.classList.add('active');
tabContentPanel.classList.add('active');
}
targetContainer = tabContentPanel;
} else {
targetContainer = document.createElement('div');
targetContainer.className = 'chart-sheet-container';
targetContainer.innerHTML = `<h2 style="padding-top: 2rem; border-bottom: 1px solid #ccc;">${sheetName}</h2>`;
mainChartContainer.appendChild(targetContainer);
}
const originalChartContainerId = 'chartContainer';
mainChartContainer.id = 'chartContainer-placeholder';
targetContainer.id = originalChartContainerId;
let scatterData = {};
if(sheetName === 'Physical Data') {
retData = dataForPSDCharting(sheetName);
unitTitle = retData['unitTitle'];
sizes = retData['ptsSizes'];
selectedMeas = retData['measChart'];
selectedMeasRelativeArea = retData['measChartRelativeArea'];
selectedMeasArea = retData['measChartArea'];
splitWeights = retData['splitWeights'];
splitRelativeAreas = retData['splitRelativeAreas'];
splitAreas = retData['splitAreas'];
cumWeights = retData['cumWeights'];
cumAreas = retData['cumAreas'];
sortedSamples = retData['allSamples'];
instanceNo += 1;
displayPSDChart(sizes, selectedMeas, sheetName, instanceNo, unitTitle, 'Relative Weight');
instanceNo += 1;
displayPSDChart(sizes, selectedMeasRelativeArea, sheetName, instanceNo, unitTitle, 'Relative Area');
instanceNo += 1;
displayPSDChart(sizes, selectedMeasArea, sheetName, instanceNo, unitTitle, 'Absolute Area');
if (subsToDisplay['cumulative']) {
instanceNo += 1;
displayPSDChart(sizes, cumWeights, sheetName, instanceNo, unitTitle, 'Cumlative by Weight');
instanceNo += 1;
displayPSDChart(sizes, cumAreas, sheetName, instanceNo, unitTitle, 'Cumulative by Area');
}
if (subsToDisplay['splitbyweight']) {
instanceNo += 1;
displayPsdSplits(sortedSamples, splitWeights, sheetName, instanceNo, unitTitle, 'Weight');
}
if (subsToDisplay['splitbyarea']) {
instanceNo += 1;
displayPsdSplits(sortedSamples, splitRelativeAreas, sheetName, instanceNo, unitTitle, 'Relative Area');
instanceNo += 1;
displayPsdSplits(sortedSamples, splitAreas, sheetName, instanceNo, unitTitle, 'Absolute Area');
}
if (subsToDisplay['totalsolidsandtotalcarbon']) {
instanceNo += 1;
displayTotalSolidOrganicC(sortedSamples, sheetName, instanceNo, unitTitle, 'Total Solids % and Organic Carbon %');
}
if (resuspensionSize>0) {
instanceNo += 1;
displayResuspensionFractions(sizes, cumWeights, cumAreas, sheetName, instanceNo, unitTitle, 'Fractions');
}
} else {
retData = dataForCharting(sheetName);
unitTitle = retData['unitTitle'];
selectedMeas = retData['measChart'];
selectedMeasArea = {};
concentrateMeas = {};
concentrateFactor = {};
if (completeSheet['Physical Data']) {
if (resuspensionSize > 0) {
retData= recalculateConcentration(selectedMeas);
concentrateMeas = retData['concentrateMeas'];
concentrateFactor = retData['concentrateFactor'];
}
if (subsToDisplay['relationareadensity']) {
for (const chemical in selectedMeas) {
selectedMeasArea[chemical] = {};
for (const sample in selectedMeas[chemical]) {
let parts = sample.split(": ");
if (parts.length>2) {
parts[1] = parts[1] + ': ' + parts[2];
}
if (selectedSampleMeasurements?.[parts[0]]?.['Physical Data']?.samples[parts[1]]?.totalArea !== undefined) {
if (selectedSampleMeasurements[parts[0]]['Physical Data'].samples[parts[1]].totalArea > 0) {
const totalArea = selectedSampleMeasurements[parts[0]]['Physical Data'].samples[parts[1]].totalArea;
selectedMeasArea[chemical][sample] = selectedMeas[chemical][sample] / totalArea;
}
}
}
}
}
}
if (subsToDisplay['samplegroup']) {
instanceNo += 1;
displaySampleChart(selectedMeas, sheetName, instanceNo, unitTitle);
if (sheetName === 'BDE data') {
let organicCPresent = true;
let selectedMeasOrganicC = selectedMeas;
for (const chemical in selectedMeasOrganicC) {
for (const sample in selectedMeasOrganicC[chemical]) {
let parts = sample.split(": ");
if (parts.length > 2) {
parts[1] = parts[1] + ': ' + parts[2];
}
if (selectedSampleMeasurements?.[parts[0]]?.['Physical Data']?.samples[parts[1]]?.['Organic matter (total organic carbon)'] !== undefined) {
if (selectedSampleMeasurements[parts[0]]['Physical Data'].samples[parts[1]]['Organic matter (total organic carbon)'] > 0) {
let organicC = selectedSampleMeasurements[parts[0]]['Physical Data'].samples[parts[1]]['Organic matter (total organic carbon)'];
selectedMeasOrganicC[chemical][sample] = 2.5 * selectedMeas[chemical][sample] / organicC;
}
}
else {
organicCPresent = false;
break;
}
}
}
if (organicCPresent) {
instanceNo += 1;
displaySampleChart(selectedMeasOrganicC, sheetName + ' Organic Carbon Normalised', instanceNo, unitTitle + ' / Organic Carbon');
}
}
if (completeSheet['Physical Data']) {
if (resuspensionSize > 0) {
instanceNo += 1;
displaySampleChart(concentrateMeas, sheetName, instanceNo, unitTitle + ' < ' + resuspensionSize * 1000000 + 'µm');
}
if (subsToDisplay['relationareadensity']) {
instanceNo += 1;
displaySampleChart(selectedMeasArea, sheetName, instanceNo, unitTitle + ' / Area');
}
}
}
if (subsToDisplay['chemicalgroup']) {
instanceNo += 1;
displayChemicalChart(selectedMeas, sheetName, instanceNo, unitTitle,true);
if (completeSheet['Physical Data']) {
if (resuspensionSize > 0) {
instanceNo += 1;
displayChemicalChart(concentrateMeas, sheetName, instanceNo, unitTitle + ' < ' + resuspensionSize * 1000000 + 'µm', true);
}
if (subsToDisplay['relationareadensity']) {
instanceNo += 1;
displayChemicalChart(selectedMeas, sheetName, instanceNo, unitTitle + ' / Area', false);
}
}
}
if (subsToDisplay['pcaanalysis']) {
instanceNo += 1;
pcaChart(selectedMeas, sheetName, determinands[sheetName], instanceNo);
if (sheetName === 'PAH data') {
if (subsToDisplay['pcalmw']) {
instanceNo += 1;
pcaChart(selectedMeas, sheetName + ' LMW Subset', determinands.pah.lmw, instanceNo);
}
if (subsToDisplay['pcahmw']) {
instanceNo += 1;
pcaChart(selectedMeas, sheetName + ' HMW Subset', determinands.pah.hmw, instanceNo);
}
if (subsToDisplay['pcaepa']) {
instanceNo += 1;
pcaChart(selectedMeas, sheetName + ' EPA Subset', determinands.pah.epa, instanceNo);
}
if (subsToDisplay['pcasmallpts']) {
instanceNo += 1;
pcaChart(selectedMeas, sheetName + ' Small Particles Subset', determinands.pah.smallpts, instanceNo);
}
if (subsToDisplay['pcaorganiccarbon']) {
instanceNo += 1;
pcaChart(selectedMeas, sheetName + ' Organic Carbon Subset', determinands.pah.organicc, instanceNo);
}
}
}
largeInstanceNo = -1;
if (subsToDisplay['mapgrid']) {
//{if (subsToDisplay['positionplace']) {
const allContaminants = Object.keys(selectedMeas);
if (allContaminants.length > 0) {
// 1. Create a large container for the main map
const largeMapContainer = document.createElement('div');
// const largeContaminantMapId = 'large-contaminant-map';
const largeContaminantMapId = `largemap-${sheetName.replace(/[^a-zA-Z0-9]/g, '')}`;
largeMapContainer.id = largeContaminantMapId;
largeMapContainer.style.width = '100%';
largeMapContainer.style.height = '600px';
largeMapContainer.style.border = '2px solid #ccc';
targetContainer.appendChild(largeMapContainer);
// 2. Create the grid container for small maps
const gridContainer = document.createElement('div');
gridContainer.id = 'small-contaminant-map-grid';
gridContainer.style.display = 'grid';
gridContainer.style.gridTemplateColumns = 'repeat(auto-fill, minmax(250px, 1fr))';
gridContainer.style.gap = '1rem';
gridContainer.style.marginTop = '2rem';
gridContainer.innerHTML = '<h3 style="grid-column: 1 / -1;">' + sheetName + '</h3>';
targetContainer.appendChild(gridContainer);
const firstContaminant = allContaminants[0];
// Create the large map - try ResizeObserver first, then fallback
createStaticContaminantMap(largeContaminantMapId, firstContaminant, 'points', true);
// Fallback: if large map doesn't appear after 2 seconds, force create it
setTimeout(() => {
const container = document.getElementById(largeContaminantMapId);
if (container && !container._leaflet_map) {
console.log('Large map not created by ResizeObserver, forcing creation...');
// Force create without size checking
const staticMap = L.map(largeContaminantMapId, {
center: [54.596, -1.177],
zoom: 13,
zoomControl: false,
attributionControl: false,
scrollWheelZoom: false,
doubleClickZoom: false,
boxZoom: false,
keyboard: false,
dragging: false,
});
container._leaflet_map = staticMap;
const baseLayerInstance = baseLayers['OpenStreetMap'];
L.tileLayer(baseLayerInstance._url, baseLayerInstance.options).addTo(staticMap);
const layerToAdd = contaminantLayers[firstContaminant];
if (layerToAdd) {
layerToAdd.addTo(staticMap);
const bounds = new L.LatLngBounds([]);
layerToAdd.eachLayer(layer => {
if (layer.getLatLng) {
bounds.extend(layer.getLatLng());
}
});
if (bounds.isValid()) {
setTimeout(() => {
staticMap.invalidateSize();
staticMap.fitBounds(bounds, { padding: [20, 20] });
}, 100);
}
}
}
}, 2000);
// Generate small maps for all contaminants
allContaminants.forEach((contaminantName, index) => {
const mapWrapper = document.createElement('div');
const mapId = `map-${contaminantName.replace(/[^a-zA-Z0-9]/g, '')}`;
// const mapId = `smallmap-${index}`;
mapWrapper.className = 'small-map-wrapper';
mapWrapper.style.border = '1px solid #ddd';
mapWrapper.style.padding = '5px';
mapWrapper.style.textAlign = 'center';
mapWrapper.style.height = '280px';
mapWrapper.style.minWidth = '250px';
// Add Flexbox properties to arrange children vertically
mapWrapper.style.display = 'flex';
mapWrapper.style.flexDirection = 'column';
const stats = contaminantStats[contaminantName];
const min = stats ? (stats.valueMin*stats.rescale).toFixed(2) : 'N/A';
const max = stats ? (stats.valueMax*stats.rescale).toFixed(2) : 'N/A';
const unit = stats ? stats.unit : '';
let standardsText = '';
if (typeof colorMode !== 'undefined' && colorMode === 'standards' && typeof standards !== 'undefined' && typeof chosenStandard !== 'undefined') {
let levels = null;
if (standards[chosenStandard]?.chemicals?.[contaminantName]) {
if(!standards[chosenStandard].chemicals[contaminantName]?.definition) {
levels = standards[chosenStandard].chemicals[contaminantName];
} else {
if(standards[chosenStandard].chemicals[contaminantName]?.levels){
levels = standards[chosenStandard].chemicals[contaminantName].levels;
}
}
}
if (levels) {
let displayLevels = [...levels];
if (typeof factorUnit === 'function' && typeof extractUnit === 'function' && stats) {
const unitAlign = factorUnit(stats.unit, extractUnit(standards[chosenStandard].unit));
if (unitAlign !== 1) {
displayLevels = displayLevels.map(l => l !== null ? l / unitAlign : null);
}
}
if (displayLevels[0] !== null && displayLevels[0] !== undefined) standardsText += ` AL1: ${displayLevels[0].toFixed(2)}`;
if (displayLevels[1] !== null && displayLevels[1] !== undefined) standardsText += ` AL2: ${displayLevels[1].toFixed(2)}`;
}
}
const titleElement = document.createElement('h4');
titleElement.style.margin = '0';
titleElement.style.padding = '5px';
titleElement.style.backgroundColor = '#f0f0f0';
titleElement.style.cursor = 'pointer';
titleElement.style.fontSize = '14px';
titleElement.innerHTML = `${contaminantName}<br><span style="font-size: smaller;">(${min} - ${max} ${unit})${standardsText}</span>`;
mapWrapper.appendChild(titleElement);
const mapElement = document.createElement('div');
mapElement.id = mapId;
mapElement.style.width = '100%';
mapElement.style.flexGrow = '1';
// mapElement.style.height = 'calc(100% - 50px)';
mapElement.style.minHeight = '200px';
mapWrapper.appendChild(mapElement);
gridContainer.appendChild(mapWrapper);
// Create small maps with staggered delays
setTimeout(() => {
createStaticContaminantMap(mapId, contaminantName, 'points');
}, 300 + (index * 50));
titleElement.addEventListener('click', () => {
// Should be removed inside createStaticContaminantMap
// const existingLargeMap = document.getElementById(largeContaminantMapId)._leaflet_map;
// if (existingLargeMap) existingLargeMap.remove();
setTimeout(() => {
createStaticContaminantMap(largeContaminantMapId, contaminantName, 'points', true);
}, 100);
targetContainer.scrollTop = 0;
});
});
} else {
console.warn(sheetName, ': No contaminant layers available for mapping.');
}
}
if (subsToDisplay['correlationplots']) {
if (subsToDisplay['relationareadensity']) {
instanceNo = displayScatterCharts(sheetName, { key: 'totalArea', sheetKey: 'Physical Data' }, 'relationareadensity', 'Total Area', 'Concentration', targetContainer, instanceNo);
}
if (subsToDisplay['relationhc']) {
instanceNo = displayScatterCharts(sheetName, { key: 'totalHC', sheetKey: 'PAH data' }, 'relationhc', 'Total Hydrocarbon', 'Concentration', targetContainer, instanceNo);
}
if (subsToDisplay['relationtotalsolids']) {
instanceNo = displayScatterCharts(sheetName, { key: 'totalSolids', sheetKey: 'Physical Data' }, 'relationtotalsolids', 'Total Solids %', 'Concentration', targetContainer, instanceNo);
}
if (subsToDisplay['relationorganiccarbon']) {
instanceNo = displayScatterCharts(sheetName, { key: 'organicCarbon', sheetKey: 'Physical Data' }, 'relationorganiccarbon', 'Organic Carbon %', 'Concentration', targetContainer, instanceNo);
}
}
if (sheetName == 'PAH data' && Object.keys(chemInfo).length != 0) {
const chemicalNames = Object.keys(chemInfo);
const properties = Object.keys(chemInfo[chemicalNames[0]]);
for (i = 0; i<14 ; i++) {
chemicalNames.sort((a, b) => chemInfo[a][properties[i]] - chemInfo[b][properties[i]]);
const sortedSelectedMeas = {};
chemicalNames.forEach((chemical) => {
if (selectedMeas[chemical]) {
sortedSelectedMeas[chemical] = selectedMeas[chemical];
}
});
instanceNo += 1;
displaySampleChart(sortedSelectedMeas, sheetName + ': Sorted by ' + properties[i], instanceNo, unitTitle);
instanceNo += 1;
displayChemicalChart(sortedSelectedMeas, sheetName + ': Sorted by ' + properties[i], instanceNo, unitTitle);
}
}
if (sheetName === 'PAH data' && subsToDisplay['gorhamtest']) {
unitTitle = retData['unitTitle'];
selectedSums = sumsForGorhamCharting();
instanceNo += 1;
displayGorhamTest(selectedSums, sheetName, instanceNo, unitTitle);
if (resuspensionSize > 0 && completeSheet['Physical Data']) {
retData = recalculateConcentrationComplex(selectedSums);
concentrateSums = retData['concentrateMeas'];
concentrateFactor = retData['concentrateFactor'];
instanceNo += 1;
displayGorhamTest(concentrateSums, sheetName, instanceNo, unitTitle + ' < ' + resuspensionSize * 1000000 + 'µm');
}
}
if (sheetName === 'PAH data' && subsToDisplay['totalhc']) {
instanceNo += 1;
retData = sumsForTotalHCCharting();
unitTitle = retData['unitTitle'];
selectedSums = retData['measChart'];
displayTotalHC(selectedSums, sheetName, instanceNo, unitTitle);
}
if (sheetName === 'PAH data' && subsToDisplay['pahratios']) {
instanceNo += 1;
retData = ratiosForPAHs();
unitTitle = retData['unitTitle'];
selectedSums = retData['measChart'];
displayPAHRatios(selectedSums, sheetName, instanceNo, unitTitle);
}
if (sheetName === 'PAH data' && subsToDisplay['ringfractions']) {
instanceNo += 1;
retData = ringFractionsForPAHs();
unitTitle = retData['unitTitle'];
selectedSums = retData['measChart'];
displayRingFractions(selectedSums, sheetName, instanceNo, unitTitle);
}
if (sheetName === 'PAH data' && subsToDisplay['eparatios']) {
instanceNo += 1;
retData = epaRatiosForPAHs();
unitTitle = retData['unitTitle'];
selectedSums = retData['measChart'];
displayEpaRatios(selectedSums, sheetName, instanceNo, unitTitle);
}
if (sheetName === 'PAH data' && subsToDisplay['simpleratios']) {
instanceNo += 1;
retData = simpleRatiosForPAHs();
unitTitle = retData['unitTitle'];
selectedSums = retData['measChart'];
displaySimpleRatios(selectedSums, sheetName, instanceNo, unitTitle);
}
if (sheetName === 'PCB data' && subsToDisplay['congenertest']) {
instanceNo += 1;
selectedSums = sumsForCongenerCharting();
displayCongener(selectedSums, sheetName, instanceNo, unitTitle);
if (resuspensionSize > 0 && completeSheet['Physical Data']) {
retData = recalculateConcentrationComplex(selectedSums);
concentrateSums = retData['concentrateMeas'];
concentrateFactor = retData['concentrateFactor'];
instanceNo += 1;
displayCongener(concentrateSums, sheetName, instanceNo, unitTitle + ' < ' + resuspensionSize * 1000000 + 'µm');
}
}
}
document.getElementById('chartContainer-placeholder').id = originalChartContainerId;
targetContainer.id = useTabs ? 'tab-' + sheetName.replace(/[^a-zA-Z0-9]/g, '-') : '';
return instanceNo;
}
function removeScatterTables() {
const chartContainer = document.getElementById('chartContainer');
// Remove all tables inside chartContainer
const tables = chartContainer.getElementsByTagName('table');
while (tables.length > 0) {
tables[0].remove();
}
// Optionally, remove the button container if it exists
const buttonContainer = document.getElementById('chartButtons');
if (buttonContainer) {
buttonContainer.remove();
}
}
function displayScatterCharts(sheetName, chartType, subsKey, xAxisLabel, yAxisLabel, containerElement, instanceNo) {
if (subsToDisplay[subsKey] && completeSheet[chartType.sheetKey]) {
const retData = dataForTotalScatterCharting(sheetName, chartType.key);
const { unitTitle, scatterData, chemicalData, fitConcentration, fitPredictors } = retData;
if (unitTitle === 'No data') {
return instanceNo;
}
const allChemicals = Object.keys(chemicalData);
instanceNo += 1;
const combinedCanvas = document.createElement('canvas');
combinedCanvas.id = 'chart' + instanceNo;
containerElement.appendChild(combinedCanvas);
displayCombinedScatterChart(scatterData, sheetName, instanceNo, 'fred');
let largeInstanceNo = instanceNo;
const scatterContainer = document.createElement('div');
scatterContainer.className = 'scatter-flex-container';
const startInstanceNo = instanceNo;
for (let i = 0; i < allChemicals.length; i++) {
instanceNo += 1;
// Create a wrapper for each chart
const chartWrapper = document.createElement('div');
chartWrapper.className = 'scatter-chart-wrapper';
const canvas = document.createElement('canvas');
canvas.id = `chart${instanceNo}`;
chartWrapper.appendChild(canvas);
scatterContainer.appendChild(chartWrapper);
}
const chartContainer = containerElement;
if (largeInstanceNo > 1) {
const divContainer = document.createElement('div');
divContainer.id = 'chartButtons';
chartContainer.appendChild(divContainer);
}
chartContainer.appendChild(scatterContainer); // Add the new flex container
instanceNo = startInstanceNo;
for (const c in chemicalData) {
let sampleNames = Object.keys(fitConcentration[c]);
const data = fitConcentration ?
concentrationFitter(fitConcentration[c], fitPredictors[c], 'Chart Analysis') :
{ beta: 0, R_squared: 0 };
instanceNo += 1;
//console.log(scatterData[c], chemicalData[c], sampleNames);
displayScatterChart(
scatterData[c],
chemicalData[c],
sampleNames,
sheetName,
instanceNo,
`${c} : ${data.R_squared.toFixed(4)}`,
xAxisLabel,
yAxisLabel,
largeInstanceNo
);
}
}
return instanceNo;
}
function setBlanksForCharting() {
let datesSampled = Object.keys(selectedSampleMeasurements);
// Have to deal with samples without measurements set everything to zero
for (const ds in selectedSampleMeasurements) {
for (const ct in selectedSampleMeasurements[ds]) {
if (blankSheets[ct] == null || blankSheets[ct] == undefined) {
if (!(selectedSampleMeasurements[ds][ct] == undefined || selectedSampleMeasurements[ds][ct] == null)) {
blankSheets[ct] = selectedSampleMeasurements[ds][ct];
}
}
}
}
return
}
function heatmapColor(value, alpha = 1) {
// Clamp value to [0, 1]
value = Math.max(0, Math.min(1, value));
let r = 0, g = 0, b = 0;
if (value <= 0.25) {
// Blue to Cyan
let t = value / 0.25;
r = 0;
g = Math.round(255 * t);
b = 255;
} else if (value <= 0.5) {
// Cyan to Green
let t = (value - 0.25) / 0.25;
r = 0;
g = 255;
b = Math.round(255 * (1 - t));
} else if (value <= 0.75) {
// Green to Yellow
let t = (value - 0.5) / 0.25;
r = Math.round(255 * t);
g = 255;
b = 0;
} else {
// Yellow to Red
let t = (value - 0.75) / 0.25;
r = 255;
g = Math.round(255 * (1 - t));
b = 0;
}
return `rgb(${r}, ${g}, ${b}, ${alpha})`;
}
function heatColor(value, alpha = 1) {
// Clamp value to [0, 1]
value = Math.max(0, Math.min(1, value));
let r, g, b;
if (value < 0.5) {
// Green to Orange
// Green: (0, 255, 0)
// Orange: (255, 165, 0)
let t = value / 0.5;
r = Math.round(255 * t);
g = Math.round(255 - (90 * t)); // from 255 to 165
b = 0;
} else {
// Orange to Red
// Orange: (255, 165, 0)
// Red: (255, 0, 0)
let t = (value - 0.5) / 0.5;
r = 255;
g = Math.round(165 * (1 - t));
b = 0;
}
return `rgb(${r}, ${g}, ${b}, ${alpha})`;
}
// Function to interpolate between two colors based on the value
function colorGradient(value, color1, color2) {
// Ensure the value is between 0 and 1
value = Math.max(0, Math.min(1, value));
// Convert colors from hex to RGB
const color1RGB = hexToRgb(color1);
const color2RGB = hexToRgb(color2);
// Calculate the interpolated color
const r = Math.round(color1RGB.r + value * (color2RGB.r - color1RGB.r));
const g = Math.round(color1RGB.g + value * (color2RGB.g - color1RGB.g));
const b = Math.round(color1RGB.b + value * (color2RGB.b - color1RGB.b));
// Return the color in 'rgb(r,g,b)' format
return `rgb(${r},${g},${b},0.5)`;
}
// Helper function to convert hex color to RGB
function hexToRgb(hex) {
// Remove the hash symbol if present
hex = hex.replace(/^#/, '');
// Parse the red, green, and blue components
const bigint = parseInt(hex, 16);
return {
r: (bigint >> 16) & 255,
g: (bigint >> 8) & 255,
b: bigint & 255
};
}
function resizeChart(chart) {
// Get the parent container of the chart
var container = chart.canvas.parentNode;
// Toggle the class to resize the chart
container.classList.toggle('large-chart');
// Update the chart to reflect the new size
chart.resize();
}
function displayCombinedScatterChart(meas, sheetName, instanceNo, unitTitle) {
legends[instanceNo] = true;
ylinlog[instanceNo] = false;
stacked[instanceNo] = false;
// createCanvas(instanceNo); //Already done in displayCharts
const convas = document.getElementById("chart" + instanceNo);
if (!convas) {
console.error(`Canvas with ID "chart${instanceNo}" not found for displayCombinedScatterChart.`);
return;
}
convas.style.display = "block";
// instanceType[instanceNo] = 'combinedscatter';
instanceType[instanceNo] = 'scatter';
instanceSheet[instanceNo] = sheetName;
//console.log(meas);
//console.log(meas, sheetName, instanceNo, unitTitle);
const allChemicals = Object.keys(meas);
const allSamples = Object.keys(meas[allChemicals[0]]); // Assuming all samples have the same chemicals // Using the first concentration value for simplicity
const datasets = allChemicals.map((chemical, index) => {
const data = meas[chemical];
return {
label: chemical,
data: data,
borderWidth: 1,
yAxisID: 'y',
};
});
//console.log(datasets);
const chartConfig = {
type: 'scatter',
data:
{
datasets: datasets
}
};
const ctx = document.getElementById('chart' + instanceNo).getContext('2d');
//console.log(instanceNo,ctx,chartConfig);
chartInstance[instanceNo] = new Chart(ctx, chartConfig);
// console.log(ddatasets);
}
function displayScatterChart(scatterData, oneChemical, sampleNames, sheetName, instanceNo, unitTitle, xAxisTitle, yAxisTitle, largeInstanceNo) {
console.log('displayScatterChart', scatterData, oneChemical, sampleNames, sheetName, instanceNo, unitTitle, xAxisTitle, yAxisTitle, largeInstanceNo);
lastScatterInstanceNo = instanceNo;
legends[instanceNo] = false;
ylinlog[instanceNo] = false;