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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Originally, I repurposed the 3dmol.js parser for when plugins need to access
// information about atoms. But I came to realize that this is overkill. I'm now
// going to create a minimal parser for PDB and MOL2 files instead, since these
// are the formats that molmoda uses internally for protein and compound files,
// respectively. It doens't need to have a lot of functionality. It just needs
// to be light on memory.

import { IFileInfo } from "@/FileSystem/Types";
import { IAtom } from "@/UI/Navigation/TreeView/TreeInterfaces";
import { GLModel } from "@/UI/Panels/Viewer/GLModelType";

/** Interface for bounding box */
interface IBounds {
    minX: number;
    minY: number;
    minZ: number;
    maxX: number;
    maxY: number;
    maxZ: number;
}

/**
 * A parent class for easy parsers.
 */
export abstract class EasyParserParent {
    /**
     * Create a new EasyParserParent. Set it to undefined if you want to call
     * _load elsewhere (e.g., in subclass constructor; see EasyParserSDF).
     *
     * @param {IFileInfo | GLModel | IAtom[]} src The source to parse.
     */
    constructor(src: IFileInfo | GLModel | IAtom[] | undefined) {
        if (src !== undefined) {
            this._load(src);
        }
    }
    protected _atoms: (string | IAtom)[] = [];

    /**
     * Load the source.
     *
     * @param {IFileInfo | GLModel | IAtom[]} src  The source to parse.
     */
    abstract _load(src: IFileInfo | GLModel | IAtom[]): void;

    /**
     * Parse an atom.
     *
     * @param {string} atomStr The string to parse.
     * @param {number} [atomParserIndex] Optional: The 0-based index of this
     *                                   atom in the parser's internal list.
     *                                   Useful for parsers that need context
     *                                   (e.g., SDF bond parsing).
     * @returns {IAtom | undefined} The parsed atom, or undefined if not
     *  parsable or function not used.
     */
    abstract _parseAtomStr(
        atomStr: string,
        atomParserIndex?: number
    ): IAtom | undefined;
    /**
     * Get the atom at the given index.
     *
     * @param {number} idx  The index.
     * @returns {IAtom} The atom.
     */
    getAtom(idx: number): IAtom {
        const atom = this._atoms[idx];

        // If it's not a string, it's already been parsed.
        if (typeof atom !== "string") {
            return atom as IAtom;
        }
        const parsedAtom = this._parseAtomStr(atom as string, idx); // Pass the index here
        if (parsedAtom === undefined) {
            throw new Error("Failed to parse atom.");
        }
        this._atoms[idx] = parsedAtom; // Cache the parsed atom
        return parsedAtom;
    }

    /**
     * The number of atoms.
     *
     * @returns {number} The number of atoms.
     */
    get length(): number {
        return this._atoms.length;
    }

    /**
     * The atoms.
     *
     * @returns {IAtom[]} The atoms.
     */
    get atoms(): IAtom[] {
        return this._atoms.map((atom, idx) => {
            return this.getAtom(idx);
        });
    }

    /**
     * Get the selected atoms.
     *
     * @param {object}  sel              The selection.
     * @param {boolean} [extract=false]  Whether to extract the selected atoms.
     * @returns {IAtom[]} The selected atoms.
     */
    selectedAtoms(sel: { [key: string]: string[] }, extract = false): IAtom[] {
        // NOTE: If there are multiple keys, logical OR is applied. So this
        // differs from the 3dmol selectedAtoms function.

        // Not going to support full selectedAtoms available in 3dmol parser.
        // Just bare-bones minimum.

        // You'll need to parse all the atoms.
        let atoms: [number, IAtom][] = [];
        for (let i = 0; i < this.length; i++) {
            atoms.push([i, this.getAtom(i)]);
        }

        const keys = Object.keys(sel);

        // If there are no keys, return all the atoms.
        if (keys.length === 0) {
            if (extract) {
                this._atoms = [];
            }
            return atoms.map(([idx, atom]) => atom);
        }

        let matchingAtoms: [number, IAtom][] = [];

        for (const key of keys) {
            const val = sel[key];

            let filterFunc: (atom: IAtom) => boolean = (atom: IAtom) => true;

            switch (key) {
                case "resn":
                    filterFunc = (atom) => val.includes(atom.resn);
                    break;
                case "chain":
                    filterFunc = (atom) => val.includes(atom.chain);
                    break;
                case "elem":
                    filterFunc = (atom) => {
                        if (atom.elem === undefined) {
                            return false;
                        }
                        return val.includes(atom.elem);
                    };
                    break;
                default:
                    // Should never get here.
                    debugger;
            }

            matchingAtoms = matchingAtoms.concat(
                atoms.filter(([idx, atom]) => filterFunc(atom))
            );

            // Remove matches from atoms.
            atoms = atoms.filter(([idx, atom]) => !filterFunc(atom));
        }

        if (extract) {
            // sort by index
            matchingAtoms.sort(([idx1, atom1], [idx2, atom2]) => idx1 - idx2);
            this._atoms = atoms.map(([idx, atom]) => atom);
        }

        // sort by index
        matchingAtoms.sort(([idx1, atom1], [idx2, atom2]) => idx1 - idx2);
        return matchingAtoms.map(([idx, atom]) => atom);
    }

    /**
     * Append atoms to the molecule.
     *
     * @param {IAtom[]} atoms  The atoms to append.
     */
    appendAtoms(atoms: IAtom | IAtom[]): void {
        if (!Array.isArray(atoms)) {
            atoms = [atoms];
        }
        this._atoms = this._atoms.concat(atoms);
    }

    /**
     * Calculates the bounding box of the atoms in this parser, considering the stride.
     *
     * @param {number} [stride=1] The step size for iterating through atoms. Must be >= 1.
     * @returns {IBounds | null} The bounding box, or null if no atoms with coordinates are found.
     */
    getBounds(stride = 1): IBounds | null {
        if (stride < 1) {
            throw new Error("Stride must be >= 1");
        }

        let minX = Infinity;
        let minY = Infinity;
        let minZ = Infinity;
        let maxX = -Infinity;
        let maxY = -Infinity;
        let maxZ = -Infinity;
        let foundCoords = false;

        for (let i = 0; i < this.length; i += stride) {
            const atom = this.getAtom(i);
            if (
                atom.x !== undefined &&
                atom.y !== undefined &&
                atom.z !== undefined
            ) {
                foundCoords = true;
                minX = Math.min(minX, atom.x);
                minY = Math.min(minY, atom.y);
                minZ = Math.min(minZ, atom.z);
                maxX = Math.max(maxX, atom.x);
                maxY = Math.max(maxY, atom.y);
                maxZ = Math.max(maxZ, atom.z);
            }
        }

        if (!foundCoords) {
            return null; // No atoms with coordinates found
        }

        return { minX, minY, minZ, maxX, maxY, maxZ };
    }

    /**
     * Checks if the molecule is "flat", meaning all its atoms lie on one of the
     * cardinal planes (XY, XZ, or YZ). This is determined by checking if all atoms
     * have a Z, Y, or X coordinate of 0, respectively. This is a common
     * characteristic of 2D structure representations.
     *
     * @returns {boolean} True if the molecule is flat, false otherwise. Returns
     *          false if there are no atoms.
     */
    public isFlat(): boolean {
        if (this.length === 0) {
            return false;
        }
        const atoms = this.atoms; // This ensures all atoms are parsed
        if (atoms.length === 0) {
            return false;
        }
        // Collect all coordinates. It's safe to assume parsers provide x, y, z as numbers.
        // They might be undefined/NaN if parsing fails for a coordinate, which is fine.
        const xCoords = atoms.map((a) => a.x);
        const yCoords = atoms.map((a) => a.y);
        const zCoords = atoms.map((a) => a.z);
        // A file is flat if one of the coordinate axes is all zeros (or undefined/NaN for all atoms).
        // The .every check handles undefined and NaN correctly, as they are not equal to 0.
        const allXZero = xCoords.every((c) => c === 0);
        const allYZero = yCoords.every((c) => c === 0);
        const allZZero = zCoords.every((c) => c === 0);
        return allXZero || allYZero || allZZero;
    }
    /**
 * Builds a spatial grid for the atoms in this parser.
 *
 * @param {number} stride The stride to use when iterating atoms.
 * @param {number} cellSize The size of each grid cell (should match query distance).
 * @returns {Map<string, number[]>} A map where keys are "x,y,z" indices and values are arrays of atom indices.
 */
    private _buildSpatialGrid(stride: number, cellSize: number): Map<string, number[]> {
        const grid = new Map<string, number[]>();
        for (let i = 0; i < this.length; i += stride) {
            const atom = this.getAtom(i);
            if (
                atom.x === undefined ||
                atom.y === undefined ||
                atom.z === undefined
            ) {
                continue;
            }
            const cx = Math.floor(atom.x / cellSize);
            const cy = Math.floor(atom.y / cellSize);
            const cz = Math.floor(atom.z / cellSize);
            const key = `${cx},${cy},${cz}`;
            if (!grid.has(key)) {
                grid.set(key, []);
            }
            grid.get(key)!.push(i);
        }
        return grid;
    }
    /**
     * Checks if any atom in this parser is within a specified distance of any atom
     * in another parser, optionally using strides to speed up the check.
     * Optimized with bounding box check and early exit for distance components.
     *
     * @param {EasyParserParent} otherParser The other parser to compare against.
     * @param {number}           distance    The distance threshold in Angstroms.
     * @param {number}           [selfStride=1] The step size for iterating through
     *                           atoms in this parser. Must be >= 1.
     * @param {number}           [otherStride=1] The step size for iterating through
     *                           atoms in the other parser. Must be >= 1.
     * @returns {boolean} True if at least one pair of atoms (one from each parser,
     *          considering strides) is within the specified distance, false otherwise.
     */
    isWithinDistance(
        otherParser: EasyParserParent,
        distance: number,
        selfStride = 1,
        otherStride = 1
    ): boolean {
        // Validate strides
        if (selfStride < 1) {
            throw new Error("selfStride must be >= 1");
        }
        if (otherStride < 1) {
            throw new Error("otherStride must be >= 1");
        }

        const distanceSqThreshold = distance * distance; // Compare squared distances

        // *** Optimization 1: Bounding Box Check ***
        const bounds1 = this.getBounds(selfStride);
        const bounds2 = otherParser.getBounds(otherStride);

        // If either molecule has no coordinates, they can't be close
        if (!bounds1 || !bounds2) {
            return false;
        }

        // Check for non-overlap (expanded by distance)
        if (
            bounds1.maxX < bounds2.minX - distance ||
            bounds1.minX > bounds2.maxX + distance ||
            bounds1.maxY < bounds2.minY - distance ||
            bounds1.minY > bounds2.maxY + distance ||
            bounds1.maxZ < bounds2.minZ - distance ||
            bounds1.minZ > bounds2.maxZ + distance
        ) {
            return false; // Bounding boxes are too far apart
        }
        // *** End Bounding Box Check ***
        // *** Optimization 3: Spatial Hashing ***
        // Heuristic: If we have a lot of comparisons to make (NxM > ~5000), build a grid.
        // We build the grid on the larger molecule to minimize the overhead of grid construction
        // relative to the number of lookups. Actually, cost is approx (Build N) + (Query M * 27).
        // Minimizing (N + 27M) suggests we should build the grid on the larger set (N) so we only query 27*M times.
        const count1 = Math.ceil(this.length / selfStride);
        const count2 = Math.ceil(otherParser.length / otherStride);
        if (count1 * count2 > 5000) {
            // Identify which parser is larger to build the grid on it
            let gridParser: EasyParserParent;
            let queryParser: EasyParserParent;
            let gridStride: number;
            let queryStride: number;
            if (count1 >= count2) {
                // eslint-disable-next-line @typescript-eslint/no-this-alias
                gridParser = this;
                gridStride = selfStride;
                queryParser = otherParser;
                queryStride = otherStride;
            } else {
                gridParser = otherParser;
                gridStride = otherStride;
                // eslint-disable-next-line @typescript-eslint/no-this-alias
                queryParser = this;
                queryStride = selfStride;
            }
            const grid = gridParser._buildSpatialGrid(gridStride, distance);
            for (let i = 0; i < queryParser.length; i += queryStride) {
                const qAtom = queryParser.getAtom(i);
                if (qAtom.x === undefined || qAtom.y === undefined || qAtom.z === undefined) continue;
                const cx = Math.floor(qAtom.x / distance);
                const cy = Math.floor(qAtom.y / distance);
                const cz = Math.floor(qAtom.z / distance);
                // Check neighbors (3x3x3 block)
                for (let dx = -1; dx <= 1; dx++) {
                    for (let dy = -1; dy <= 1; dy++) {
                        for (let dz = -1; dz <= 1; dz++) {
                            const key = `${cx + dx},${cy + dy},${cz + dz}`;
                            const binIndices = grid.get(key);
                            if (!binIndices) continue;
                            // Check atoms in this bin
                            for (const idx of binIndices) {
                                const gAtom = gridParser.getAtom(idx);
                                const distSq =
                                    (qAtom.x - gAtom.x!) ** 2 +
                                    (qAtom.y - gAtom.y!) ** 2 +
                                    (qAtom.z - gAtom.z!) ** 2;
                                if (distSq <= distanceSqThreshold) {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
            return false;
        }
        // *** Fallback: Brute Force (Original Logic) ***
        for (let i = 0; i < this.length; i += selfStride) {
            const atom1 = this.getAtom(i);
            // Ensure atom1 has coordinates
            if (
                atom1.x === undefined ||
                atom1.y === undefined ||
                atom1.z === undefined
            ) {
                continue;
            }
            // *** Optimization 2: Cache atom1 coordinates ***
            const x1 = atom1.x;
            const y1 = atom1.y;
            const z1 = atom1.z;

            for (let j = 0; j < otherParser.length; j += otherStride) {
                const atom2 = otherParser.getAtom(j);
                // Ensure atom2 has coordinates
                if (
                    atom2.x === undefined ||
                    atom2.y === undefined ||
                    atom2.z === undefined
                ) {
                    continue;
                }
                const x2 = atom2.x; // Cache atom2 coordinate

                // Calculate squared distance component by component for early exit
                const dx = x1 - x2;
                const dxSq = dx * dx;
                if (dxSq > distanceSqThreshold) {
                    continue; // X distance alone is too large
                }

                const y2 = atom2.y; // Cache atom2 coordinate
                const dy = y1 - y2;
                const dySq = dy * dy;
                if (dxSq + dySq > distanceSqThreshold) {
                    continue; // X + Y distance is too large
                }

                const z2 = atom2.z; // Cache atom2 coordinate
                const dz = z1 - z2;
                const dzSq = dz * dz;
                const distanceSq = dxSq + dySq + dzSq;

                // Check if within threshold
                if (distanceSq <= distanceSqThreshold) {
                    return true; // Found a pair within distance
                }
            }
        }

        return false; // No pairs found within distance
    }

    /**
     * Extracts all unique residue names (resn) and residue IDs (resi) from the
     * atoms in this parser.
     *
     * @returns {{ names: Set<string>, ids: Set<number> }} An object containing a
     *  Set of unique residue names and a Set of unique residue IDs.
     */
    public getUniqueResidues(): { names: Set<string>; ids: Set<number> } {
        const residueNames = new Set<string>();
        const residueIds = new Set<number>();
        for (let i = 0; i < this.length; i++) {
            const atom = this.getAtom(i);
            if (atom.resn) {
                residueNames.add(atom.resn);
            }
            if (atom.resi !== undefined) {
                // Assuming resi is a number. If it could be a string, adjust accordingly.
                residueIds.add(atom.resi);
            }
        }
        return { names: residueNames, ids: residueIds };
    }

    /**
     * Checks if the molecule contains any hydrogen atoms.
     *
     * @returns {boolean} True if at least one hydrogen atom is found, false otherwise.
     */
    public hasHydrogens(): boolean {
        // Use .some for efficiency, as it will stop as soon as a hydrogen is found.
        return this.atoms.some((atom) => atom.elem?.toUpperCase() === "H");
    }

    /**
     * Get the approximate bounds of the molecule. NOTE: This code not used, but
     * could be useful in the future.
     *
     * @returns {number[]} The approximate bounds [minX, minY, minZ, maxX, maxY,
     *     maxZ].
     */
    //     getApproximateBounds(): [number, number, number, number, number, number] {
    //         let minX = Infinity;
    //         let minY = Infinity;
    //         let minZ = Infinity;
    //         let maxX = -Infinity;
    //         let maxY = -Infinity;
    //         let maxZ = -Infinity;

    //         const buffer = 5;
    //         const step = 10;

    //         for (let i = 0; i < this.length; i += step) {
    //             const atom = this.getAtom(i);

    //             minX = Math.min(minX, atom.x as number);
    //             minY = Math.min(minY, atom.y as number);
    //             minZ = Math.min(minZ, atom.z as number);
    //             maxX = Math.max(maxX, atom.x as number);
    //             maxY = Math.max(maxY, atom.y as number);
    //             maxZ = Math.max(maxZ, atom.z as number);
    //         }

    //         return [
    //             minX - buffer,
    //             minY - buffer,
    //             minZ - buffer,
    //             maxX + buffer,
    //             maxY + buffer,
    //             maxZ + buffer,
    //         ];
    //     }
}