import type { Shape1DWithFWHM } from 'ml-peak-shape-generator'; import { getShape1D } from 'ml-peak-shape-generator'; import type { GSDBroadenPeak } from '../GSDBroadenPeak.ts'; import type { GSDPeak } from '../GSDPeak.ts'; type GSDPeakOptionalShape = GSDPeak & { shape?: Shape1DWithFWHM }; type GSDBroadenPeakWithID = GSDBroadenPeak & { id: string }; type GSDBroadenPeakWithShape = GSDBroadenPeak & { shape: Shape1DWithFWHM }; type GSDBroadenPeakWithShapeID = GSDBroadenPeakWithID & { shape: Shape1DWithFWHM; }; export type WithOrWithout = T extends ToExtends ? TrueType : FalseType; export type WithIDOrShape = T extends { id: string } ? WithOrWithout : WithOrWithout; export interface BroadenPeaksOptions { /** * Width multiplier applied to each peak. * @default 2 */ factor?: number; /** * Whether to allow overlap between adjacent broadened peaks. * @default false */ overlap?: boolean; } /** * Enlarge peaks while preventing overlap between them. * A typical application is chromatography peak picking. * We should not make the hypothesis that `x` is equidistant, because peaks * may not be symmetric once we add the `from` and `to` properties. * @param peakList - Peaks to broaden. * @param options - Broadening options. * @returns The broadened peaks. */ export function broadenPeaks( peakList: T[], options: BroadenPeaksOptions = {}, ) { const { factor = 2, overlap = false } = options; const peaks = mapPeaks(peakList, factor); if (!overlap) { for (let i = 0; i < peaks.length - 1; i++) { const peak = peaks[i]; const nextPeak = peaks[i + 1]; if (peak.to.x > nextPeak.from.x) { // we do it proportional to the width of the peaks peak.to.x = (peak.width / (nextPeak.width + peak.width)) * (nextPeak.x - peak.x) + peak.x; nextPeak.from.x = peak.to.x; } } } for (const peak of peaks) { peak.width = peak.to.x - peak.from.x; if (peak.shape) { const { shape, width } = peak; if (shape.fwhm !== undefined) { const shapeFct = getShape1D(shape); shape.fwhm = shapeFct.widthToFWHM(width); } } } return peaks; } function mapPeaks( peaks: T[], factor: number, ): Array> { return peaks.map((peak) => { const { id, shape, x, y, index, inflectionPoints } = peak; const xFrom = x - (x - inflectionPoints.from.x) * factor; const xTo = x + (inflectionPoints.to.x - x) * factor; let result = { x, y, index, width: xTo - xFrom, from: { x: xFrom }, to: { x: xTo }, } as GSDBroadenPeak; if (id) { result = { ...result, id }; } if (shape) { result = { ...result, shape }; } return result as WithIDOrShape; }); }