-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplotUtils.ts
More file actions
2411 lines (2238 loc) · 88.5 KB
/
Copy pathplotUtils.ts
File metadata and controls
2411 lines (2238 loc) · 88.5 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
import { useChartStore } from '@/stores/chartStore'
import { useGlobalChartStore } from '@/stores/globalChartStore'
import { db as indexedDb } from '@/db/SlideRuleDb'
import { fetchScatterData, setDataOrder, getAtl06SlopeSegments } from '@/utils/SrDuckDbUtils'
import { type EChartsOption, type LegendComponentOption } from 'echarts'
import { createWhereClause } from './spotUtils'
import type { ECharts } from 'echarts/core'
import { duckDbReadAndUpdateSelectedLayer } from '@/utils/SrDuckDbUtils'
import { type SrRunContext } from '@/db/SlideRuleDb'
import type { SrScatterChartDataArray, FetchScatterDataOptions } from '@/utils/SrDuckDbUtils'
import type { WritableComputedRef } from 'vue'
import { reactive, computed } from 'vue'
import { useAtlChartFilterStore } from '@/stores/atlChartFilterStore'
import { useRecTreeStore } from '@/stores/recTreeStore'
import { useRequestsStore } from '@/stores/requestsStore'
import { useGradientColorMapStore } from '@/stores/gradientColorMapStore'
import { useAtl03CnfColorMapStore } from '@/stores/atl03CnfColorMapStore'
import { useAtl08ClassColorMapStore } from '@/stores/atl08ClassColorMapStore'
import { useAtl24ClassColorMapStore } from '@/stores/atl24ClassColorMapStore'
import { formatKeyValuePair, formatTime } from '@/utils/formatUtils'
import {
SELECTED_LAYER_NAME_PREFIX,
type MinMaxLowHigh,
type AtlReqParams,
type SrSvrParmsUsed
} from '@/types/SrTypes'
import { useSymbolStore } from '@/stores/symbolStore'
import { usePlotConfigStore } from '@/stores/plotConfigStore'
import { useFieldNameStore } from '@/stores/fieldNameStore'
import { useArrayColumnStore } from '@/stores/arrayColumnStore'
import { useSrcIdTblStore } from '@/stores/srcIdTblStore'
import { createDuckDbClient } from '@/utils/SrDuckDb'
import { useActiveTabStore } from '@/stores/activeTabStore'
import { useDeckStore } from '@/stores/deckStore'
import { SC_BACKWARD, SC_FORWARD } from '@/sliderule/icesat2'
import { resetFilterUsingSelectedRec } from '@/utils/SrMapUtils'
import {
extractCrsFromGeoMetadata,
transformCoordinate,
needsTransformation
} from '@/utils/SrCrsTransform'
import { createLogger } from '@/utils/logger'
import { getGeometryInfo, buildColumnExpressions } from '@/utils/duckAgg'
const logger = createLogger('PlotUtils')
export const yDataBindingsReactive = reactive<{ [key: string]: WritableComputedRef<string[]> }>({})
export const yDataSelectedReactive = reactive<{ [key: string]: WritableComputedRef<string> }>({})
export const yColorEncodeSelectedReactive = reactive<{
[key: string]: WritableComputedRef<string>
}>({})
// Cache for coordinate transformation info per request
let cachedReqIdForTransform: number | null = null
let cachedSourceCrs: string | null = null
let cachedNeedsTransformation: boolean = false
export const solidColorSelectedReactive = reactive<{ [key: string]: WritableComputedRef<string> }>(
{}
)
export const showYDataMenuReactive = reactive<{ [key: string]: WritableComputedRef<boolean> }>({})
export const useGlobalMinMaxReactive = reactive<{ [key: string]: WritableComputedRef<boolean> }>({})
export const selectedCyclesReactive = computed({
get: (): number[] => {
const value = useGlobalChartStore().getCycles()
//logger.debug(`selectedCyclesReactive[${reqId}] get:`, value);
return value
},
set: (values: number[]): void => {
//logger.debug(`selectedCyclesReactive[${reqId}] set:`, values);
useGlobalChartStore().setCycles(values)
}
})
export const selectedRgtReactive = computed({
get: (): number => {
const value = useGlobalChartStore().getRgt()
//logger.debug(`selectedRgtsReactive[${reqId}] get:`, value);
return value ? value : 0
},
set: (value: number): void => {
//logger.debug(`selectedRgtsReactive[${reqId}] set:`, values);
useGlobalChartStore().setRgt(value)
}
})
export interface SrScatterSeriesData {
series: {
name: string
type: string
data: (number | string)[][]
dimensions?: string[]
large?: boolean
largeThreshold?: number
animation?: boolean
yAxisIndex?: number
symbolSize?: number
progressive?: number
progressiveThreshold?: number
progressiveChunkMode?: string
itemStyle?: {
color: string | ((_params: any) => string)
}
emphasis?: {
scale?: boolean
itemStyle?: {
borderColor?: string
borderWidth?: number
shadowBlur?: number
shadowColor?: string
}
}
encode?: {
x: number
y: number
}
z?: number
// the following is for line series:
lineStyle?: {
color: string
width: number
}
symbol?: string
polyline?: boolean
}
min: number | null
max: number | null
}
export function getDefaultColorEncoding(reqId: number, parentFuncStr?: string) {
if (reqId > 0) {
// A photon-cloud overlay (signalled by parentFuncStr) is always an atl03x record.
// The rec tree may not yet contain a freshly-created overlay node — it is rebuilt
// asynchronously once the OPFS file is ready — so fall back to atl03x rather than
// emitting a misleading "solid" default and warning during that window.
const func = useRecTreeStore().findApiForReqId(reqId) || (parentFuncStr ? 'atl03x' : '')
if (func) {
const fieldNameStore = useFieldNameStore()
// Special cases that use non-height field for color encoding
if (func === 'atl03sp') {
return 'atl03_cnf'
} else if (func === 'atl03x') {
if (parentFuncStr === 'atl24x') return 'atl24_class'
else return 'atl03_cnf'
} else {
// For all other APIs, use the height field (checks metadata cache first)
return fieldNameStore.getHFieldName(reqId)
}
} else {
logger.warn('No function found for reqId, returning solid color encoding', { reqId })
return 'solid' // default color encoding
}
} else {
logger.warn('Invalid reqId, returning solid color encoding', { reqId })
return 'solid' // default color encoding
}
}
export function initializeColorEncoding(reqId: number, parentFuncStr?: string) {
const reqIdStr = reqId.toString()
const chartStore = useChartStore()
if (reqId > 0) {
chartStore.setSelectedColorEncodeData(reqIdStr, getDefaultColorEncoding(reqId, parentFuncStr))
}
//logger.debug(`initializeColorEncoding reqId:${reqIdStr} parentFuncStr:${parentFuncStr} chartStore.getSelectedColorEncodeData:`, chartStore.getSelectedColorEncodeData(reqIdStr));
}
export function initDataBindingsToChartStore(reqIds: string[]) {
//logger.debug('initDataBindingsToChartStore:', reqIds);
const chartStore = useChartStore()
reqIds.forEach((reqId) => {
if (!(reqId in yDataBindingsReactive)) {
yDataBindingsReactive[reqId] = computed({
get: () => chartStore.getYDataOptions(reqId),
set: (value: string[]) => chartStore.setYDataOptions(reqId, value)
})
}
if (!(reqId in yDataSelectedReactive)) {
yDataSelectedReactive[reqId] = computed({
get: () => chartStore.getSelectedYData(reqId),
set: (value: string) => chartStore.setSelectedYData(reqId, value)
})
}
if (!(reqId in yColorEncodeSelectedReactive)) {
yColorEncodeSelectedReactive[reqId] = computed({
get: () => chartStore.getSelectedColorEncodeData(reqId),
set: (value: string) => chartStore.setSelectedColorEncodeData(reqId, value)
})
}
if (!(reqId in solidColorSelectedReactive)) {
solidColorSelectedReactive[reqId] = computed({
get: () => chartStore.getSolidSymbolColor(reqId),
set: (value: string) => chartStore.setSolidSymbolColor(reqId, value)
})
}
if (!(reqId in showYDataMenuReactive)) {
showYDataMenuReactive[reqId] = computed({
get: () => chartStore.getShowYDataMenu(reqId),
set: (value: boolean) => chartStore.setShowYDataMenu(reqId, value)
})
}
if (!(reqId in useGlobalMinMaxReactive)) {
useGlobalMinMaxReactive[reqId] = computed({
get: () => !chartStore.getUseSelectedMinMax(reqId),
set: (value: boolean) => chartStore.setUseSelectedMinMax(reqId, !value)
})
}
})
}
interface GetSeriesParams {
reqIdStr: string
fileName: string
x: string
y: string[]
fetchOptions: FetchScatterDataOptions
// The name of the function to fetch data:
fetchData: (
_reqIdStr: string,
_fileName: string,
_x: string,
_y: string[],
_fetchOptions: FetchScatterDataOptions
) => Promise<{
chartData: Record<string, SrScatterChartDataArray>
minMaxLowHigh: MinMaxLowHigh
normalizedMinMaxValues: MinMaxLowHigh
dataOrderNdx: Record<string, number>
}>
// The property name for minMax or normalizedMinMax
minMaxProperty: 'minMaxLowHigh' | 'normalizedMinMaxValues'
// A function or color for the series item style
colorFunction?: (_params: any) => string
// Additional ECharts config
zValue: number
// Logging prefix for console
functionName: string
}
/**
* A generic helper for building scatter series.
*/
async function getGenericSeries({
reqIdStr,
fileName,
x,
y,
fetchOptions,
fetchData,
minMaxProperty,
colorFunction,
zValue,
functionName
}: GetSeriesParams): Promise<SrScatterSeriesData[]> {
const startTime = performance.now()
let yItems: SrScatterSeriesData[] = []
const plotConfigStore = usePlotConfigStore()
const progressiveChunkSize = plotConfigStore.progressiveChunkSize
const progressiveThreshold = plotConfigStore.progressiveChunkThreshold
const progressiveChunkMode = plotConfigStore.progressiveChunkMode
try {
// Ensure lat/lon are always included for location finder, even if not displayed
const reqId = parseInt(reqIdStr)
const fieldNameStore = useFieldNameStore()
const latFieldName = fieldNameStore.getLatFieldName(reqId)
const lonFieldName = fieldNameStore.getLonFieldName(reqId)
// Add lat/lon to extraSelectColumns if not already in y array
const extraCols = fetchOptions.extraSelectColumns || []
if (!y.includes(latFieldName) && !extraCols.includes(latFieldName)) {
extraCols.push(latFieldName)
}
if (!y.includes(lonFieldName) && !extraCols.includes(lonFieldName)) {
extraCols.push(lonFieldName)
}
fetchOptions.extraSelectColumns = extraCols
// Get array column configuration from store if available
const arrayColumnStore = useArrayColumnStore()
const arrayConfig = arrayColumnStore.getActiveConfig(reqIdStr)
if (arrayConfig) {
fetchOptions.arrayColumnConfig = {
columnName: arrayConfig.columnName,
mode: arrayConfig.mode,
aggregations: arrayConfig.aggregations
}
logger.debug('Array column config applied', { reqIdStr, arrayConfig })
}
const { chartData = {}, ...rest } = await fetchData(reqIdStr, fileName, x, y, fetchOptions)
//logger.debug(`${functionName} ${reqIdStr} ${y}: chartData:`, chartData, 'fetchOptions:', fetchOptions);
// e.g. choose minMax based on minMaxProperty
const minMaxLowHigh = rest['minMaxLowHigh'] || {}
const minMaxValues = rest[minMaxProperty] || {}
//logger.debug(`getGenericSeries ${functionName}: minMaxValues:`, minMaxValues);
const chartStore = useChartStore()
chartStore.setMinMaxValues(reqIdStr, minMaxValues)
chartStore.setMinMaxLowHigh(reqIdStr, minMaxLowHigh)
chartStore.setDataOrderNdx(reqIdStr, rest['dataOrderNdx'] || {})
const gradientColorMapStore = useGradientColorMapStore(reqIdStr)
gradientColorMapStore.setDataOrderNdx(rest['dataOrderNdx'] || {})
const atl03CnfColorMapStore = useAtl03CnfColorMapStore(reqIdStr)
atl03CnfColorMapStore.setDataOrderNdx(rest['dataOrderNdx'] || {})
const atl08ClassColorMapStore = useAtl08ClassColorMapStore(reqIdStr)
atl08ClassColorMapStore.setDataOrderNdx(rest['dataOrderNdx'] || {})
const atl24ClassColorMapStore = useAtl24ClassColorMapStore(reqIdStr)
atl24ClassColorMapStore.setDataOrderNdx(rest['dataOrderNdx'] || {})
if (Object.keys(chartData).length === 0 || Object.keys(minMaxValues).length === 0) {
logger.warn('Chart data or minMax is empty, skipping processing', { functionName, reqIdStr })
return yItems
}
if (!colorFunction) {
const cedk = chartStore.getSelectedColorEncodeData(reqIdStr)
let thisColorFunction
if (cedk === 'solid') {
thisColorFunction = (_params: any) => chartStore.getSolidSymbolColor(reqIdStr)
} else {
//logger.debug(`getGenericSeries: chartStore.getSelectedColorEncodeData(reqIdStr):`, chartStore.getSelectedColorEncodeData(reqIdStr));
//logger.debug(`getGenericSeries: chartStore.getMinMaxValues(reqIdStr):`, chartStore.getMinMaxValues(reqIdStr));
let minValue = chartStore.getLow(reqIdStr, cedk)
let maxValue = chartStore.getHigh(reqIdStr, cedk)
if (!chartStore.getUseSelectedMinMax(reqIdStr)) {
//i.e. use global min/max
minValue = useGlobalChartStore().getLow(cedk)
maxValue = useGlobalChartStore().getHigh(cedk)
}
thisColorFunction = gradientColorMapStore.createGradientColorFunction(
cedk,
minValue,
maxValue
)
}
colorFunction = thisColorFunction
}
//logger.debug(`${functionName}: colorFunction:`, colorFunction);
// Get the selected Y data name
const ySelectedName = chartStore.getSelectedYData(reqIdStr)
// Handle race condition: if selectedYData is not yet set (empty string),
// skip plotting and return empty array to avoid unnecessary redraw
if (!ySelectedName) {
logger.debug('selectedYData not yet initialized, skipping plot until data is ready', {
functionName,
reqIdStr
})
return yItems
}
if (y.includes(ySelectedName)) {
const yIndex = gradientColorMapStore.getDataOrderNdx()[ySelectedName]
const data = chartData[reqIdStr].data // get raw number[][] data
const min = minMaxValues[ySelectedName]?.min ?? null
const max = minMaxValues[ySelectedName]?.max ?? null
//logger.debug(`${functionName}: Index of selected Y data "${ySelectedName}" in Y array is ${yIndex}. Min: ${min}, Max: ${max}`, data);
yItems.push({
series: {
name: ySelectedName,
type: 'scatter',
data: data,
dimensions: [...gradientColorMapStore.getDimensions()],
encode: { x: 0, y: yIndex },
itemStyle: { color: colorFunction },
emphasis: {
scale: true,
itemStyle: {
borderColor: '#ff0000',
borderWidth: 2,
shadowBlur: 10,
shadowColor: 'rgba(255, 0, 0, 0.5)'
}
},
z: zValue,
large: useAtlChartFilterStore().getLargeData(),
largeThreshold: useAtlChartFilterStore().getLargeDataThreshold(),
progressive: progressiveChunkSize,
progressiveThreshold,
progressiveChunkMode,
animation: false,
yAxisIndex: 0, // only plotting one series i.e. y-axis 0
symbolSize: useSymbolStore().getSize(reqIdStr)
},
min,
max
})
const totalPoints = data.length
chartStore.setNumOfPlottedPnts(reqIdStr, totalPoints)
} else {
logger.warn('Selected Y data not found in provided Y array', {
functionName,
reqIdStr,
ySelectedName
})
}
} catch (error) {
logger.error('Error in getGenericSeries', {
functionName,
reqIdStr,
error: error instanceof Error ? error.message : String(error)
})
} finally {
const endTime = performance.now()
logger.debug('getGenericSeries completed', {
functionName,
reqIdStr,
duration: `${endTime - startTime}ms`
})
}
return yItems
}
export async function getSeriesForAtl03sp(
reqIdStr: string,
fileName: string,
x: string,
y: string[]
): Promise<SrScatterSeriesData[]> {
//logger.debug('getSeriesForAtl03sp reqIdStr:', reqIdStr,'x:',x,'y:',y);
const chartStore = useChartStore()
const atl03CnfColorMapStore = useAtl03CnfColorMapStore(reqIdStr)
const atl08ClassColorMapStore = useAtl08ClassColorMapStore(reqIdStr)
const fetchOptions: FetchScatterDataOptions = {
normalizeX: false,
extraSelectColumns: ['segment_dist'],
/**
* handleMinMaxRow:
* Called once for the “min/max” result row. We replicate the logic:
* minX = 0
* maxX = max_x + max_segment_dist - min_segment_dist - min_x
* Store it in chartStore, or anywhere you like.
*/
handleMinMaxRow: (reqId, row) => {
chartStore.setMinX(reqId, 0)
chartStore.setMaxX(reqId, row.max_x + row.max_segment_dist - row.min_segment_dist - row.min_x)
},
/**
* transformRow:
* Called for each record in the main query. Return an array of numbers:
* e.g. [ xOffset, y1, y2?, atl03_cnf, atl08_class, yapc_score ]
*
* xOffset = row[x] + row.segment_dist - min_segment_dist
* (We rely on the minMaxValues passed in. By default, fetchScatterData
* fills minMaxValues['segment_dist'] from the MIN/MAX query.)
*/
transformRow: (row, xCol, yCols, minMaxLowHigh, dataOrderNdx, orderNdx) => {
// figure out the offset for X
const segMin = minMaxLowHigh['segment_dist']?.min || 0
const xVal = row[xCol] + row.segment_dist - segMin
orderNdx = setDataOrder(dataOrderNdx, 'x', orderNdx)
// Start with [xVal], then push each y
const out = [xVal]
for (const yName of yCols) {
// If one of the yCols is actually "segment_dist" skip it.
if (yName !== 'segment_dist') {
out.push(row[yName])
orderNdx = setDataOrder(dataOrderNdx, yName, orderNdx)
}
}
return [out, orderNdx]
}
}
const cedk = chartStore.getSelectedColorEncodeData(reqIdStr)
let thisColorFunction // generic will set it if is not set here
if (cedk === 'atl03_cnf') {
thisColorFunction = atl03CnfColorMapStore.cachedColorFunction
// test the color function
//logger.debug(`getSeriesForAtl03sp ${reqIdStr} cedk:`,cedk,'thisColorFunction:',thisColorFunction);
//const c1 = thisColorFunction({data:[-2]});
} else if (cedk === 'atl08_class') {
thisColorFunction = atl08ClassColorMapStore.cachedColorFunction
}
//logger.debug(`getSeriesForAtl03sp ${reqIdStr} cedk:`,cedk,'thisColorFunction:',thisColorFunction);
return await getGenericSeries({
reqIdStr,
fileName,
x,
y,
fetchOptions, // pass the specialized logic above
fetchData: fetchScatterData,
minMaxProperty: 'minMaxLowHigh', // read from minMaxValues rather than normalizedMinMaxValues
colorFunction: thisColorFunction,
zValue: 0,
functionName: 'getSeriesForAtl03sp' // for the log
})
}
export async function getSeriesForAtl03x(
reqIdStr: string,
fileName: string,
x: string,
y: string[],
parentMinX?: number
): Promise<SrScatterSeriesData[]> {
//logger.debug('getSeriesForAtl03sp reqIdStr:', reqIdStr,'x:',x,'y:',y);
const chartStore = useChartStore()
const atl03CnfColorMapStore = useAtl03CnfColorMapStore(reqIdStr)
const atl24ClassColorMapStore = useAtl24ClassColorMapStore(reqIdStr)
const atl08ClassColorMapStore = useAtl08ClassColorMapStore(reqIdStr)
const fetchOptions: FetchScatterDataOptions = { normalizeX: true, parentMinX: parentMinX }
const cedk = chartStore.getSelectedColorEncodeData(reqIdStr)
let thisColorFunction // generic will set it if is not set here
if (cedk === 'atl03_cnf') {
thisColorFunction = atl03CnfColorMapStore.cachedColorFunction
// test the color function
//logger.debug(`getSeriesForAtl03sp ${reqIdStr} cedk:`,cedk,'thisColorFunction:',thisColorFunction);
//const c1 = thisColorFunction({data:[-2]});
} else if (cedk === 'atl08_class') {
thisColorFunction = atl08ClassColorMapStore.cachedColorFunction
} else if (cedk === 'atl24_class') {
thisColorFunction = atl24ClassColorMapStore.cachedColorFunction
}
//logger.debug(`getSeriesForAtl03sp ${reqIdStr} cedk:`,cedk,'thisColorFunction:',thisColorFunction);
return await getGenericSeries({
reqIdStr,
fileName,
x,
y,
fetchOptions, // pass the specialized logic above
fetchData: fetchScatterData,
minMaxProperty: 'minMaxLowHigh', // read from minMaxValues rather than normalizedMinMaxValues
colorFunction: thisColorFunction,
zValue: 0,
functionName: 'getSeriesForAtl03x' // for the log
})
}
async function getSeriesForAtl03vp(
reqIdStr: string,
fileName: string,
x: string,
y: string[]
): Promise<SrScatterSeriesData[]> {
const fetchOptions: FetchScatterDataOptions = { normalizeX: true }
return await getGenericSeries({
reqIdStr,
fileName,
x,
y,
fetchOptions,
fetchData: fetchScatterData,
minMaxProperty: 'minMaxLowHigh', // note the difference
zValue: 10,
functionName: 'getSeriesForAtl03vp'
})
}
async function getSeriesForAtl06(
reqIdStr: string,
fileName: string,
x: string,
y: string[]
): Promise<SrScatterSeriesData[]> {
const fetchOptions: FetchScatterDataOptions = { normalizeX: true }
return await getGenericSeries({
reqIdStr,
fileName,
x,
y,
fetchOptions,
fetchData: fetchScatterData, // function to fetch data
minMaxProperty: 'normalizedMinMaxValues', // note the difference
zValue: 10, // z value for ATL06
functionName: 'getSeriesForAtl06'
})
}
async function getSeriesForAtl08(
reqIdStr: string,
fileName: string,
x: string,
y: string[]
): Promise<SrScatterSeriesData[]> {
const fetchOptions: FetchScatterDataOptions = { normalizeX: true }
return await getGenericSeries({
reqIdStr,
fileName,
x,
y,
fetchOptions,
fetchData: fetchScatterData, // function to fetch data
minMaxProperty: 'normalizedMinMaxValues',
zValue: 10, // z value for ATL06
functionName: 'getSeriesForAtl08'
})
}
async function getSeriesForAtl24(
reqIdStr: string,
fileName: string,
x: string,
y: string[]
): Promise<SrScatterSeriesData[]> {
const fetchOptions: FetchScatterDataOptions = { normalizeX: true }
return await getGenericSeries({
reqIdStr,
fileName,
x,
y,
fetchOptions,
fetchData: fetchScatterData, // function to fetch data
minMaxProperty: 'normalizedMinMaxValues',
zValue: 10, // z value for ATL24
functionName: 'getSeriesForAtl24'
})
}
async function getSeriesForAtl13(
reqIdStr: string,
fileName: string,
x: string,
y: string[]
): Promise<SrScatterSeriesData[]> {
const fetchOptions: FetchScatterDataOptions = { normalizeX: true }
return await getGenericSeries({
reqIdStr,
fileName,
x,
y,
fetchOptions,
fetchData: fetchScatterData, // function to fetch data
minMaxProperty: 'normalizedMinMaxValues',
zValue: 10, // z value for ATL13
functionName: 'getSeriesForAtl13'
})
}
async function getSeriesForGedi(
reqIdStr: string,
fileName: string,
x: string,
y: string[]
): Promise<SrScatterSeriesData[]> {
logger.debug('getSeriesForGedi', { reqIdStr, fileName })
const fetchOptions: FetchScatterDataOptions = { normalizeX: true }
return await getGenericSeries({
reqIdStr,
fileName,
x,
y,
fetchOptions,
fetchData: fetchScatterData, // function to fetch data
minMaxProperty: 'normalizedMinMaxValues', // note the difference
zValue: 10, // z value for ATL06
functionName: 'getSeriesForGedi'
})
}
export function clearPlot() {
const atlChartFilterStore = useAtlChartFilterStore()
const plotRef = atlChartFilterStore.getPlotRef()
if (plotRef) {
if (plotRef.chart) {
plotRef.chart.clear()
logger.debug('Plot chart cleared')
} else {
logger.debug('Plot chart is undefined, skipping clear')
}
} else {
// Plot component hasn't mounted yet - this is normal during initialization
logger.debug('Plot ref not yet initialized, skipping clear')
}
}
async function ensureTransformCache(reqId: number): Promise<void> {
if (cachedReqIdForTransform === reqId) {
return // Already cached
}
try {
const request = await indexedDb.getRequest(reqId)
const geoMetadata = request?.geo_metadata
cachedSourceCrs = extractCrsFromGeoMetadata(geoMetadata)
cachedNeedsTransformation = needsTransformation(cachedSourceCrs)
cachedReqIdForTransform = reqId
logger.debug('Location Finder: Cached transform info', {
reqId,
cachedSourceCrs,
cachedNeedsTransformation
})
} catch (error) {
logger.warn('Could not load geo metadata for coordinate transformation', {
error: error instanceof Error ? error.message : String(error)
})
cachedSourceCrs = null
cachedNeedsTransformation = false
cachedReqIdForTransform = reqId
}
}
// Store raw coordinates temporarily before transformation
let rawLat: number | null = null
let rawLon: number | null = null
function filterDataForPos(label: any, data: any, lat: string, lon: string) {
//logger.debug('filterDataForPos label:', label, 'data:', data);
const globalChartStore = useGlobalChartStore()
// Store raw values
if (label === lat) {
rawLat = data
} else if (label === lon) {
rawLon = data
}
// Only process when we have both valid coordinates
if (
rawLat !== null &&
rawLon !== null &&
typeof rawLat === 'number' &&
typeof rawLon === 'number' &&
isFinite(rawLat) &&
isFinite(rawLon)
) {
let finalLat = rawLat
let finalLon = rawLon
// Apply transformation if needed
if (cachedNeedsTransformation && cachedSourceCrs) {
try {
const [transformedLon, transformedLat] = transformCoordinate(
rawLon,
rawLat,
cachedSourceCrs
)
finalLon = transformedLon
finalLat = transformedLat
//logger.debug(`Location Finder: Transformed: (${rawLon}, ${rawLat}) -> (${transformedLon}, ${transformedLat})`);
} catch (error) {
logger.warn('Failed to transform coordinates for location finder', {
error: error instanceof Error ? error.message : String(error)
})
// Use raw coordinates if transformation fails
}
}
// Set the final coordinates
globalChartStore.locationFinderLon = finalLon
globalChartStore.locationFinderLat = finalLat
//logger.debug(`Location Finder: Set coordinates lat=${finalLat}, lon=${finalLon}`);
// Reset raw values for next hover
rawLat = null
rawLon = null
}
//logger.debug('filterDataForPos AFTER lat:', globalChartStore.locationFinderLat, 'lon:', globalChartStore.locationFinderLon);
}
// Callback for storing tooltip content
let tooltipContentCallback: ((_text: string) => void) | null = null
export function setTooltipContentCallback(callback: ((_text: string) => void) | null) {
tooltipContentCallback = callback
}
// Update location finder from chart mouseover event (works even when tooltip is disabled)
export function updateLocationFinderFromEvent(
params: any,
latFieldName: string,
lonFieldName: string
) {
if (!params?.data || !params?.dimensionNames) return
const paramsData = params.data
const paramsDim = params.dimensionNames as string[]
paramsDim.forEach((dim, ndx) => {
const val = paramsData[ndx]
filterDataForPos(dim, val, latFieldName, lonFieldName)
})
}
export function formatTooltip(
params: any,
latFieldName: string,
lonFieldName: string,
reqIdStr: string
) {
const paramsData = params.data
const paramsDim = params.dimensionNames as string[]
const reqId = Number(reqIdStr)
// Build HTML with time_ns_fmt added after any time_ns fields
const htmlParts: string[] = []
for (let i = 0; i < paramsDim.length; i++) {
const dim = paramsDim[i]
const val = paramsData[i]
filterDataForPos(dim, val, latFieldName, lonFieldName)
htmlParts.push(formatKeyValuePair(dim, val, reqId))
// Add formatted time field after time_ns fields
// Check for number, bigint, or numeric string (echarts may convert bigint to string)
if (dim.includes('time_ns') && val != null) {
const numVal = typeof val === 'bigint' ? val : typeof val === 'number' ? val : BigInt(val)
const fmtKey = dim.replace('time_ns', 'time_ns_fmt')
htmlParts.push(formatKeyValuePair(fmtKey, formatTime(numVal), reqId))
}
}
const parms = htmlParts.join('<br>')
// Add record ID as the first line
const htmlWithRecordId = `<strong>Record ID</strong>: <em>${reqIdStr}</em><br>${parms}`
// Convert HTML to plain text for text export
const srcIdStore = useSrcIdTblStore()
const sourceTable = srcIdStore.getSourceTableForReqId(reqId)
const textParts: string[] = []
for (let i = 0; i < paramsDim.length; i++) {
const dim = paramsDim[i]
const val = paramsData[i]
const plainKey = dim === 'srcid' ? 'granule' : dim
let plainValue: string
if (dim === 'srcid') {
if (sourceTable.length - 1 >= val) {
plainValue = `${val}: ${sourceTable[val]}`
} else {
plainValue = `${val}: <unknown source>`
}
} else if (dim.includes('time_ns') && val != null) {
// Format time_ns as integer string (no decimal point, matching CSV format)
plainValue = typeof val === 'bigint' ? val.toString() : BigInt(val).toString()
} else {
plainValue = String(val)
}
textParts.push(`${plainKey}: ${plainValue}`)
// Add formatted time field after time_ns fields for text export
if (dim.includes('time_ns') && val != null) {
const numVal = typeof val === 'bigint' ? val : typeof val === 'number' ? val : BigInt(val)
const fmtKey = dim.replace('time_ns', 'time_ns_fmt')
textParts.push(`${fmtKey}: ${formatTime(numVal)}`)
}
}
const textContent = textParts.join('\n')
// Add record ID as the first line for text export
const textWithRecordId = `Record ID: ${reqIdStr}\n${textContent}`
// Call the callback with text version
if (tooltipContentCallback) {
tooltipContentCallback(textWithRecordId)
}
//logger.debug('formatTooltip parms:', parms);
return htmlWithRecordId
}
async function getSeriesFor(reqIdStr: string, isOverlay = false): Promise<SrScatterSeriesData[]> {
const chartStore = useChartStore()
const startTime = performance.now()
const fileName = chartStore.getFile(reqIdStr)
const reqId = Number(reqIdStr)
const func = useRecTreeStore().findApiForReqId(reqId)
const x = chartStore.getXDataForChart(reqIdStr)
const duckDbClient = await createDuckDbClient()
await duckDbClient.insertOpfsParquet(fileName)
let existingColumns = await duckDbClient.queryForColNames(fileName)
// Check if file has geometry column and add geometry-derived field names
// These fields (height, longitude, latitude) are extracted at query time using ST_Z, ST_X, ST_Y
// but don't exist as actual columns in the parquet file
const colTypes = await duckDbClient.queryColumnTypes(fileName)
const geometryInfo = getGeometryInfo(colTypes, reqId)
if (geometryInfo?.hasGeometry) {
// Always add longitude and latitude since they're always extracted from geometry
if (geometryInfo.xCol && !existingColumns.includes(geometryInfo.xCol)) {
existingColumns.push(geometryInfo.xCol)
}
if (geometryInfo.yCol && !existingColumns.includes(geometryInfo.yCol)) {
existingColumns.push(geometryInfo.yCol)
}
// Only add height if Z is stored in geometry (not as separate column)
if (geometryInfo.zCol && !existingColumns.includes(geometryInfo.zCol)) {
existingColumns.push(geometryInfo.zCol)
}
}
// Add derived array columns to existingColumns
// These columns are computed at query time (e.g., tx_waveform_mean from list_avg)
// but don't exist as actual columns in the parquet file
const derivedArrayColumns = chartStore.getDerivedArrayColumns(reqIdStr)
for (const derivedCol of derivedArrayColumns) {
if (!existingColumns.includes(derivedCol)) {
existingColumns.push(derivedCol)
}
}
const all_y = chartStore.getYDataOptions(reqIdStr)
const y = all_y.filter((col) => existingColumns.includes(col))
// logger.debug('all_y:', all_y);
// logger.debug('existingColumns:', existingColumns);
// logger.debug('Filtered y:', y);
// logger.debug('getSeriesFor Using y:',y);
if (y.length != all_y.length) {
const missing = all_y.filter((col) => !existingColumns.includes(col))
const apiMismatch = !func
? ' (API not yet loaded - possible race condition)'
: func
? ` (API: ${func})`
: ''
logger.warn('Y-axis length mismatch', {
reqIdStr,
apiMismatch,
all_y_length: all_y.length,
existingColumns_length: existingColumns.length,
y_length: y.length
})
logger.warn('Missing Y-axis columns from file', {
reqIdStr,
missing_count: missing.length,
missing
})
logger.warn('Available columns in file', { reqIdStr, existingColumns })
}
let seriesData = [] as SrScatterSeriesData[]
let minXToUse
if (isOverlay) {
const rc = await indexedDb.getRunContext(reqId)
if (rc) {
if (rc.parentReqId) {
minXToUse = chartStore.getRawMinX(rc.parentReqId.toString())
logger.debug('Overlay mode: using parent minX', {
reqIdStr,
parentReqId: rc.parentReqId,
minXToUse
})
}
}
}
try {
if (fileName) {
if (func === 'atl03sp') {
seriesData = await getSeriesForAtl03sp(reqIdStr, fileName, x, y)
} else if (func === 'atl03vp') {
seriesData = await getSeriesForAtl03vp(reqIdStr, fileName, x, y)
} else if (func === 'atl03x') {
seriesData = await getSeriesForAtl03x(reqIdStr, fileName, x, y, minXToUse)
} else if (func.includes('atl06') || func.includes('atl03x-surface')) {
seriesData = await getSeriesForAtl06(reqIdStr, fileName, x, y)
} else if (func.includes('atl08') || func.includes('atl03x-phoreal')) {
seriesData = await getSeriesForAtl08(reqIdStr, fileName, x, y)
} else if (func.includes('atl24')) {
seriesData = await getSeriesForAtl24(reqIdStr, fileName, x, y)
} else if (func.includes('atl13')) {
seriesData = await getSeriesForAtl13(reqIdStr, fileName, x, y) // TBD??
} else if (func.includes('gedi')) {
seriesData = await getSeriesForGedi(reqIdStr, fileName, x, y)
} else {
logger.error('Invalid func', { reqIdStr, func })
}
if (seriesData.length === 0) {
logger.warn('seriesData is empty', { reqIdStr })
}
//logger.debug(`getSeriesFor ${reqIdStr} seriesData:`, seriesData);
} else {
logger.warn('fileName is null', { reqIdStr })
}
} catch (error) {
logger.error('getSeriesFor Error', {
error: error instanceof Error ? error.message : String(error)
})
} finally {
const endTime = performance.now()
logger.debug('getSeriesFor completed', {
reqIdStr,
fileName,
duration: `${endTime - startTime}ms`,
seriesDataLength: seriesData.length
})
//logger.debug(`getSeriesFor ${reqIdStr} seriesData:`, seriesData);
}
return seriesData
}
export async function initChartStoreFor(reqId: number): Promise<boolean> {
const chartStore = useChartStore()
const reqIdStr = reqId.toString()
let status = true
if (reqId <= 0) {
logger.warn('Invalid request ID', { reqId })
return false
}
try {
initializeColorEncoding(reqId)
const request = await indexedDb.getRequest(reqId)
if (!request) {
logger.error('No request found for reqId', { reqIdStr, request })
return false
}
const { file, description, num_bytes, cnt, parameters } = request
if (file) {
chartStore.setFile(reqIdStr, file)
} else {
logger.error('No file found for reqId', { reqIdStr, request })