|
| 1 | +import { defineStore } from 'pinia'; |
| 2 | +import { reactive, watch, computed, MaybeRef, unref } from 'vue'; |
| 3 | +import * as Comlink from 'comlink'; |
| 4 | +import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray'; |
| 5 | +import { vtkFieldRef } from '@/src/core/vtk/vtkFieldRef'; |
| 6 | +import { WLAutoRanges, WL_HIST_BINS } from '@/src/constants'; |
| 7 | +import { HistogramWorker } from '@/src/utils/histogram.worker'; |
| 8 | +import { Maybe } from '@/src/types'; |
| 9 | +import { useImage } from '@/src/composables/useCurrentImage'; |
| 10 | +import { useImageCacheStore } from './image-cache'; |
| 11 | +import { useMessageStore } from './messages'; |
| 12 | + |
| 13 | +export type ImageStats = { |
| 14 | + scalarMin: number; |
| 15 | + scalarMax: number; |
| 16 | + autoRangeValues?: Record<string, [number, number]>; |
| 17 | +}; |
| 18 | + |
| 19 | +// Helper function to compute auto range values, similar to the original useAutoRangeValues |
| 20 | +async function computeAutoRangeValues( |
| 21 | + imageData: ReturnType<typeof useImage>['imageData']['value'], |
| 22 | + isImageLoading: ReturnType<typeof useImage>['isLoading']['value'] |
| 23 | +): Promise<Record<string, [number, number]>> { |
| 24 | + if (isImageLoading || !imageData) { |
| 25 | + return {}; |
| 26 | + } |
| 27 | + |
| 28 | + const scalars = imageData.getPointData()?.getScalars(); |
| 29 | + if (!scalars) { |
| 30 | + return {}; |
| 31 | + } |
| 32 | + |
| 33 | + const worker = Comlink.wrap<HistogramWorker>( |
| 34 | + new Worker(new URL('@/src/utils/histogram.worker.ts', import.meta.url), { |
| 35 | + type: 'module', |
| 36 | + }) |
| 37 | + ); |
| 38 | + |
| 39 | + const scalarData = scalars.getData() as number[]; |
| 40 | + const { min, max } = vtkDataArray.fastComputeRange(scalarData, 0, 1); |
| 41 | + const hist = await worker.histogram(scalarData, [min, max], WL_HIST_BINS); |
| 42 | + worker[Comlink.releaseProxy](); |
| 43 | + |
| 44 | + const cumulativeHist: number[] = []; |
| 45 | + hist.reduce((acc, val) => { |
| 46 | + const currentSum = acc + val; |
| 47 | + cumulativeHist.push(currentSum); |
| 48 | + return currentSum; |
| 49 | + }, 0); |
| 50 | + |
| 51 | + const width = (max - min + 1) / WL_HIST_BINS; |
| 52 | + const totalCount = scalarData.length; |
| 53 | + |
| 54 | + return Object.fromEntries( |
| 55 | + Object.entries(WLAutoRanges).map(([key, percentage]) => { |
| 56 | + const lowerBound = percentage * 0.01 * totalCount; |
| 57 | + const upperBound = (1 - percentage * 0.01) * totalCount; |
| 58 | + |
| 59 | + const startIdx = cumulativeHist.findIndex((v) => v >= lowerBound); |
| 60 | + const endIdx = cumulativeHist.findIndex((v) => v >= upperBound); |
| 61 | + |
| 62 | + const start = Math.max(min, min + width * startIdx); |
| 63 | + const end = Math.min(max, min + width * (endIdx + 1)); // Adjusted end calculation |
| 64 | + return [key, [start, end] as [number, number]]; |
| 65 | + }) |
| 66 | + ); |
| 67 | +} |
| 68 | + |
| 69 | +export const useImageStatsStore = defineStore('image-stats', () => { |
| 70 | + const stats = reactive<Record<string, ImageStats>>({}); |
| 71 | + const imageCacheStore = useImageCacheStore(); |
| 72 | + const messageStore = useMessageStore(); |
| 73 | + |
| 74 | + const scalarRangeWatchers: Record<string, () => void> = {}; |
| 75 | + const autoRangeComputations: Record< |
| 76 | + string, |
| 77 | + Promise<Record<string, [number, number]>> |
| 78 | + > = {}; |
| 79 | + |
| 80 | + const internalSetScalarRange = ( |
| 81 | + imageID: string, |
| 82 | + min: number, |
| 83 | + max: number |
| 84 | + ) => { |
| 85 | + stats[imageID] = { |
| 86 | + ...stats[imageID], // preserve existing autoRangeValues |
| 87 | + scalarMin: min, |
| 88 | + scalarMax: max, |
| 89 | + }; |
| 90 | + }; |
| 91 | + |
| 92 | + const internalSetAutoRangeValues = ( |
| 93 | + imageID: string, |
| 94 | + autoValues: Record<string, [number, number]> |
| 95 | + ) => { |
| 96 | + stats[imageID] = { |
| 97 | + ...(stats[imageID] ?? { scalarMin: 0, scalarMax: 0 }), |
| 98 | + autoRangeValues: autoValues, |
| 99 | + }; |
| 100 | + }; |
| 101 | + |
| 102 | + const internalRemoveStats = (imageID: string) => { |
| 103 | + delete stats[imageID]; |
| 104 | + }; |
| 105 | + |
| 106 | + const setupImageWatcher = (id: string) => { |
| 107 | + if (scalarRangeWatchers[id]) { |
| 108 | + scalarRangeWatchers[id](); |
| 109 | + } |
| 110 | + |
| 111 | + const { imageData, isLoading: isImageLoading } = useImage( |
| 112 | + computed(() => id) |
| 113 | + ); |
| 114 | + |
| 115 | + const activeScalars = computed(() => |
| 116 | + imageData.value?.getPointData()?.getScalars() |
| 117 | + ); |
| 118 | + const scalarRange = vtkFieldRef(activeScalars, 'range'); |
| 119 | + |
| 120 | + scalarRangeWatchers[id] = watch( |
| 121 | + scalarRange, |
| 122 | + (range) => { |
| 123 | + if (imageData.value && range) { |
| 124 | + internalSetScalarRange(id, range[0], range[1]); |
| 125 | + } else { |
| 126 | + internalRemoveStats(id); |
| 127 | + } |
| 128 | + }, |
| 129 | + { immediate: true } |
| 130 | + ); |
| 131 | + |
| 132 | + const updateAutoRangeValuesIfNeeded = () => { |
| 133 | + const currentImageData = imageData.value; |
| 134 | + const currentIsLoading = isImageLoading.value; |
| 135 | + |
| 136 | + if (!currentIsLoading && currentImageData) { |
| 137 | + if (id in autoRangeComputations) { |
| 138 | + return; |
| 139 | + } |
| 140 | + autoRangeComputations[id] = computeAutoRangeValues( |
| 141 | + currentImageData, |
| 142 | + currentIsLoading |
| 143 | + ); |
| 144 | + |
| 145 | + autoRangeComputations[id] |
| 146 | + .then((autoValues) => { |
| 147 | + if (imageCacheStore.imageIds.includes(id)) { |
| 148 | + internalSetAutoRangeValues(id, autoValues); |
| 149 | + } |
| 150 | + }) |
| 151 | + .catch((error) => { |
| 152 | + console.error( |
| 153 | + `[ImageStatsStore] Auto range computation for image ${id} FAILED:`, |
| 154 | + error |
| 155 | + ); |
| 156 | + messageStore.addError( |
| 157 | + `Auto range computation failed for image ${id}`, |
| 158 | + error instanceof Error ? error : String(error) |
| 159 | + ); |
| 160 | + if (imageCacheStore.imageIds.includes(id)) { |
| 161 | + internalSetAutoRangeValues(id, {}); |
| 162 | + } |
| 163 | + }) |
| 164 | + .finally(() => { |
| 165 | + delete autoRangeComputations[id]; |
| 166 | + }); |
| 167 | + } else if (!currentImageData) { |
| 168 | + internalSetAutoRangeValues(id, {}); |
| 169 | + if (id in autoRangeComputations) { |
| 170 | + delete autoRangeComputations[id]; |
| 171 | + } |
| 172 | + } |
| 173 | + }; |
| 174 | + |
| 175 | + watch( |
| 176 | + [imageData, isImageLoading], |
| 177 | + () => { |
| 178 | + updateAutoRangeValuesIfNeeded(); |
| 179 | + }, |
| 180 | + { immediate: true, deep: false } |
| 181 | + ); |
| 182 | + }; |
| 183 | + |
| 184 | + const cleanupImageWatcher = (id: string) => { |
| 185 | + internalRemoveStats(id); |
| 186 | + if (scalarRangeWatchers[id]) { |
| 187 | + scalarRangeWatchers[id](); |
| 188 | + delete scalarRangeWatchers[id]; |
| 189 | + } |
| 190 | + delete autoRangeComputations[id]; |
| 191 | + }; |
| 192 | + |
| 193 | + watch( |
| 194 | + () => [...imageCacheStore.imageIds], |
| 195 | + (currentImageIds, previousImageIds = []) => { |
| 196 | + const addedIds = currentImageIds.filter( |
| 197 | + (id) => !previousImageIds.includes(id) |
| 198 | + ); |
| 199 | + const removedIds = previousImageIds.filter( |
| 200 | + (id) => !currentImageIds.includes(id) |
| 201 | + ); |
| 202 | + |
| 203 | + removedIds.forEach(cleanupImageWatcher); |
| 204 | + addedIds.forEach(setupImageWatcher); |
| 205 | + }, |
| 206 | + { immediate: true } |
| 207 | + ); |
| 208 | + |
| 209 | + // Getter for autoRangeValues, returning a computed ref |
| 210 | + const getAutoRangeValues = (imageID: MaybeRef<Maybe<string>>) => { |
| 211 | + return computed(() => { |
| 212 | + const id = unref(imageID); // Use unref to get value from MaybeRef |
| 213 | + if (id && stats[id]) { |
| 214 | + return stats[id].autoRangeValues ?? {}; |
| 215 | + } |
| 216 | + return {}; |
| 217 | + }); |
| 218 | + }; |
| 219 | + |
| 220 | + return { |
| 221 | + stats, |
| 222 | + getAutoRangeValues, // Expose the getter |
| 223 | + }; |
| 224 | +}); |
0 commit comments