File size: 15,346 Bytes
cdfc1f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**

 * Particle Sampler

 * Generates particle positions using CDF sampling of quantum probability distributions

 * Based on the approach from https://github.com/kavan010/Atoms

 */

class ParticleSampler {
    constructor(quantumEngine) {
        this.quantumEngine = quantumEngine;
        
        // Pre-calculated particle cache for common orbitals
        // Stores normalized particle positions (0-1 range) that can be scaled
        this.particleCache = null;
        this.initializeCache();
    }
    
    /**

     * Initialize pre-calculated particle cache for common orbitals

     * This significantly speeds up loading for frequently used orbitals

     */
    initializeCache() {
        console.log('Initializing particle cache for common orbitals...');
        
        // Pre-generate particles for common orbitals with a base count
        const baseCount = 10000; // Base particle count for cache
        
        this.particleCache = {
            // 1s orbital (most common)
            '1_0_0': this.generateAndNormalizeParticles(1, 0, 0, baseCount),
            // 2s orbital
            '2_0_0': this.generateAndNormalizeParticles(2, 0, 0, baseCount),
            // 2p orbitals
            '2_1_-1': this.generateAndNormalizeParticles(2, 1, -1, baseCount),
            '2_1_0': this.generateAndNormalizeParticles(2, 1, 0, baseCount),
            '2_1_1': this.generateAndNormalizeParticles(2, 1, 1, baseCount),
            // 3s orbital
            '3_0_0': this.generateAndNormalizeParticles(3, 0, 0, baseCount),
            // 3p orbitals
            '3_1_-1': this.generateAndNormalizeParticles(3, 1, -1, baseCount),
            '3_1_0': this.generateAndNormalizeParticles(3, 1, 0, baseCount),
            '3_1_1': this.generateAndNormalizeParticles(3, 1, 1, baseCount),
            // 3d orbitals
            '3_2_-2': this.generateAndNormalizeParticles(3, 2, -2, baseCount),
            '3_2_-1': this.generateAndNormalizeParticles(3, 2, -1, baseCount),
            '3_2_0': this.generateAndNormalizeParticles(3, 2, 0, baseCount),
            '3_2_1': this.generateAndNormalizeParticles(3, 2, 1, baseCount),
            '3_2_2': this.generateAndNormalizeParticles(3, 2, 2, baseCount)
        };
        
        console.log('Particle cache initialized with', Object.keys(this.particleCache).length, 'orbitals');
    }
    
    /**

     * Generate and normalize particles for caching

     * @param {number} n - Principal quantum number

     * @param {number} l - Azimuthal quantum number

     * @param {number} m - Magnetic quantum number

     * @param {number} count - Number of particles

     * @returns {Array} Normalized particle data

     */
    generateAndNormalizeParticles(n, l, m, count) {
        const particles = [];
        
        // Pre-calculate max probability for normalization
        const sampleSize = 100;
        let maxProb = 0;
        
        for (let i = 0; i < sampleSize; i++) {
            const r = this.sampleRadius(n, l);
            const theta = this.sampleTheta(l, m);
            const phi = this.samplePhi(m);
            const prob = this.quantumEngine.probabilityDensity(n, l, m, r, theta, phi);
            if (prob > maxProb) maxProb = prob;
        }
        
        // Generate particles
        for (let i = 0; i < count; i++) {
            const r = this.sampleRadius(n, l);
            const theta = this.sampleTheta(l, m);
            const phi = this.samplePhi(m);
            
            const cartesian = this.sphericalToCartesian(
                r * CONSTANTS.SCALE_FACTOR,
                theta,
                phi
            );
            
            const probability = this.quantumEngine.probabilityDensity(n, l, m, r, theta, phi);
            
            particles.push({
                position: cartesian,
                probability: maxProb > 0 ? probability / maxProb : 0
            });
        }
        
        return particles;
    }
    
    /**

     * Get particles from cache or generate new ones

     * @param {number} n - Principal quantum number

     * @param {number} l - Azimuthal quantum number

     * @param {number} m - Magnetic quantum number

     * @param {number} particleCount - Desired particle count

     * @returns {Array} Particle data

     */
    getParticlesFromCache(n, l, m, particleCount) {
        const key = `${n}_${l}_${m}`;
        
        // Check if orbital is in cache
        if (this.particleCache && this.particleCache[key]) {
            const cached = this.particleCache[key];
            const baseCount = cached.length;
            
            console.log(`Using cached particles for orbital (${n},${l},${m})`);
            
            // If requested count is close to base count, return cached particles
            if (particleCount <= baseCount * 1.2) {
                // Return subset or all cached particles
                if (particleCount >= baseCount) {
                    return cached;
                } else {
                    // Return random subset
                    const step = Math.floor(baseCount / particleCount);
                    return cached.filter((_, i) => i % step === 0).slice(0, particleCount);
                }
            } else {
                // Need more particles - use cached as base and add more
                const additionalCount = particleCount - baseCount;
                const additional = this.generateOrbitalParticlesInternal(n, l, m, additionalCount);
                return [...cached, ...additional];
            }
        }
        
        // Not in cache, generate normally
        return null;
    }
    
    /**

     * Convert spherical coordinates to Cartesian

     * @param {number} r - Radius

     * @param {number} theta - Polar angle (0 to π)

     * @param {number} phi - Azimuthal angle (0 to 2π)

     * @returns {{x: number, y: number, z: number}}

     */
    sphericalToCartesian(r, theta, phi) {
        const x = r * Math.sin(theta) * Math.cos(phi);
        const y = r * Math.sin(theta) * Math.sin(phi);
        const z = r * Math.cos(theta);
        return { x, y, z };
    }
    
    /**

     * Sample radius using CDF (Cumulative Distribution Function) sampling

     * This is more efficient and accurate than rejection sampling

     * @param {number} n - Principal quantum number

     * @param {number} l - Azimuthal quantum number

     * @param {number} resolution - Number of samples for CDF (default 1000)

     * @returns {number} Sampled radius

     */
    sampleRadius(n, l, resolution = 1000) {
        // Maximum radius to sample (most probability within ~3n² Bohr radii)
        const maxR = 3 * n * n * CONSTANTS.BOHR_RADIUS;
        
        // Minimum radius to avoid singularities at origin
        const minR = 0.01 * CONSTANTS.BOHR_RADIUS;
        
        // Build CDF array
        const cdf = [];
        let sum = 0;
        
        for (let i = 0; i < resolution; i++) {
            // Start from minR instead of 0 to avoid origin
            const r = minR + (i / resolution) * (maxR - minR);
            
            // Radial probability: P(r) = r² |R(n,l,r)|²
            const R = this.quantumEngine.radialWaveFunction(n, l, r);
            const prob = r * r * R * R;
            
            sum += prob;
            cdf.push(sum);
        }
        
        // Check if sum is valid
        if (sum === 0 || !isFinite(sum)) {
            console.warn(`Invalid CDF sum for radius sampling: ${sum}`);
            return maxR / 2;
        }
        
        // Normalize CDF
        for (let i = 0; i < cdf.length; i++) {
            cdf[i] /= sum;
        }
        
        // Sample from CDF
        const rand = Math.random();
        for (let i = 0; i < cdf.length; i++) {
            if (rand <= cdf[i]) {
                return minR + (i / resolution) * (maxR - minR);
            }
        }
        
        return maxR;
    }
    
    /**

     * Sample theta (polar angle) using CDF sampling

     * @param {number} l - Azimuthal quantum number

     * @param {number} m - Magnetic quantum number

     * @param {number} resolution - Number of samples for CDF (default 500)

     * @returns {number} Sampled theta

     */
    sampleTheta(l, m, resolution = 500) {
        // Build CDF array for theta
        const cdf = [];
        let sum = 0;
        
        // Small epsilon to avoid exact 0 and PI
        const epsilon = 0.001;
        
        for (let i = 0; i < resolution; i++) {
            // Map to range [epsilon, PI - epsilon] to avoid poles
            const theta = epsilon + (i / resolution) * (CONSTANTS.PI - 2 * epsilon);
            
            // For theta distribution, we need to integrate over phi
            // |Y(l,m,θ,φ)|² integrated over φ gives us the theta-only distribution
            // For real spherical harmonics, the phi integral gives a constant factor
            const absM = Math.abs(m);
            const legendre = window.legendrePolynomial(l, absM, Math.cos(theta));
            const prob = legendre * legendre * Math.sin(theta); // sin(theta) is the Jacobian
            
            sum += prob;
            cdf.push(sum);
        }
        
        // Check if sum is valid
        if (sum === 0 || !isFinite(sum)) {
            console.warn(`Invalid CDF sum for theta sampling: ${sum}`);
            return CONSTANTS.PI / 2; // Return equator
        }
        
        // Normalize CDF
        for (let i = 0; i < cdf.length; i++) {
            cdf[i] /= sum;
        }
        
        // Sample from CDF
        const rand = Math.random();
        for (let i = 0; i < cdf.length; i++) {
            if (rand <= cdf[i]) {
                return epsilon + (i / resolution) * (CONSTANTS.PI - 2 * epsilon);
            }
        }
        
        return CONSTANTS.PI / 2;
    }
    
    /**

     * Sample phi (azimuthal angle) using CDF sampling

     * For orbitals with m != 0, phi distribution depends on cos²(m*phi) or sin²(m*phi)

     * @param {number} m - Magnetic quantum number

     * @param {number} resolution - Number of samples for CDF (default 500)

     * @returns {number} Sampled phi

     */
    samplePhi(m, resolution = 500) {
        // For m = 0, phi is uniformly distributed
        if (m === 0) {
            return Math.random() * CONSTANTS.TWO_PI;
        }
        
        // For m != 0, we need to sample according to the phi distribution
        // Real spherical harmonics:
        // m > 0: proportional to cos²(m*phi)
        // m < 0: proportional to sin²(|m|*phi)
        
        const cdf = [];
        let sum = 0;
        const absM = Math.abs(m);
        
        for (let i = 0; i < resolution; i++) {
            const phi = (i / resolution) * CONSTANTS.TWO_PI;
            
            let prob;
            if (m > 0) {
                // cos²(m*phi) distribution
                const val = Math.cos(m * phi);
                prob = val * val;
            } else {
                // sin²(|m|*phi) distribution
                const val = Math.sin(absM * phi);
                prob = val * val;
            }
            
            sum += prob;
            cdf.push(sum);
        }
        
        // Check if sum is valid
        if (sum === 0 || !isFinite(sum)) {
            console.warn(`Invalid CDF sum for phi sampling: ${sum}`);
            return Math.random() * CONSTANTS.TWO_PI;
        }
        
        // Normalize CDF
        for (let i = 0; i < cdf.length; i++) {
            cdf[i] /= sum;
        }
        
        // Sample from CDF
        const rand = Math.random();
        for (let i = 0; i < cdf.length; i++) {
            if (rand <= cdf[i]) {
                return (i / resolution) * CONSTANTS.TWO_PI;
            }
        }
        
        return CONSTANTS.TWO_PI / 2;
    }
    
    /**

     * Generate particle positions for an orbital using CDF sampling

     * @param {number} n - Principal quantum number

     * @param {number} l - Azimuthal quantum number

     * @param {number} m - Magnetic quantum number

     * @param {number} particleCount - Number of particles to generate

     * @returns {Array<{position: {x, y, z}, probability: number}>}

     */
    generateOrbitalParticles(n, l, m, particleCount) {
        validateQuantumNumbers(n, l, m);
        
        const count = Math.max(CONSTANTS.MIN_PARTICLE_COUNT, 
                              Math.min(particleCount, CONSTANTS.MAX_PARTICLE_COUNT));
        
        console.log(`Generating ${count} particles for orbital (${n},${l},${m})`);
        
        // Try to get from cache first
        const cachedParticles = this.getParticlesFromCache(n, l, m, count);
        if (cachedParticles) {
            console.log(`Returned ${cachedParticles.length} particles from cache`);
            return cachedParticles;
        }
        
        // Not in cache, generate normally
        return this.generateOrbitalParticlesInternal(n, l, m, count);
    }
    
    /**

     * Internal method to generate particles (used when cache miss)

     * @param {number} n - Principal quantum number

     * @param {number} l - Azimuthal quantum number

     * @param {number} m - Magnetic quantum number

     * @param {number} count - Number of particles to generate

     * @returns {Array<{position: {x, y, z}, probability: number}>}

     */
    generateOrbitalParticlesInternal(n, l, m, count) {
        const particles = [];
        
        // Pre-calculate some particles to find max probability for normalization
        const sampleSize = Math.min(100, count);
        let maxProb = 0;
        
        for (let i = 0; i < sampleSize; i++) {
            const r = this.sampleRadius(n, l);
            const theta = this.sampleTheta(l, m);
            const phi = this.samplePhi(m);
            const prob = this.quantumEngine.probabilityDensity(n, l, m, r, theta, phi);
            if (prob > maxProb) maxProb = prob;
        }
        
        // Generate all particles
        for (let i = 0; i < count; i++) {
            // Sample spherical coordinates using CDF
            const r = this.sampleRadius(n, l);
            const theta = this.sampleTheta(l, m);
            const phi = this.samplePhi(m);
            
            // Convert to Cartesian coordinates with scaling
            const cartesian = this.sphericalToCartesian(
                r * CONSTANTS.SCALE_FACTOR,
                theta,
                phi
            );
            
            // Calculate probability density for color coding
            const probability = this.quantumEngine.probabilityDensity(n, l, m, r, theta, phi);
            
            particles.push({
                position: cartesian,
                probability: maxProb > 0 ? probability / maxProb : 0
            });
        }
        
        console.log(`Generated ${particles.length} particles successfully`);
        
        return particles;
    }
}

// Make class available globally
window.ParticleSampler = ParticleSampler;