physics

HYDROGEN ORBITALS

Visualize electron probability density in hydrogen atom orbitals. Explore quantum states with interactive controls.

Display Options

Select Orbital

Quantum Numbers

Energy Levels

Orbital Info

Orbital 1s
Energy
-13.6
eV
Radial Nodes
0
Angular Nodes
0
Description
Spherically symmetric ground state
Developer Reference

Core Algorithm & Standalone Script

Standalone, zero-dependency JavaScript implementation powering this tool. Free to inspect, copy, and build upon.

// Constants
    const BOHR_RADIUS = 1; // normalized to 1
    const RYDBERG_ENERGY = 13.6; // eV

    // Orbital data
    const orbitals = [
      { n: 1, l: 0, m: 0, name: '1s' },
      { n: 2, l: 0, m: 0, name: '2s' },
      { n: 2, l: 1, m: -1, name: '2p' },
      { n: 2, l: 1, m: 0, name: '2p' },
      { n: 2, l: 1, m: 1, name: '2p' },
      { n: 3, l: 0, m: 0, name: '3s' },
      { n: 3, l: 1, m: -1, name: '3p' },
      { n: 3, l: 1, m: 0, name: '3p' },
      { n: 3, l: 1, m: 1, name: '3p' },
      { n: 3, l: 2, m: -2, name: '3d' },
      { n: 3, l: 2, m: -1, name: '3d' },
      { n: 3, l: 2, m: 0, name: '3d' },
      { n: 3, l: 2, m: 1, name: '3d' },
      { n: 3, l: 2, m: 2, name: '3d' },
      { n: 4, l: 0, m: 0, name: '4s' },
      { n: 4, l: 1, m: -1, name: '4p' },
      { n: 4, l: 1, m: 0, name: '4p' },
      { n: 4, l: 1, m: 1, name: '4p' },
      { n: 4, l: 2, m: -2, name: '4d' },
      { n: 4, l: 2, m: -1, name: '4d' },
      { n: 4, l: 2, m: 0, name: '4d' },
      { n: 4, l: 2, m: 1, name: '4d' },
      { n: 4, l: 2, m: 2, name: '4d' },
      { n: 4, l: 3, m: -3, name: '4f' },
      { n: 4, l: 3, m: -2, name: '4f' },
      { n: 4, l: 3, m: -1, name: '4f' },
      { n: 4, l: 3, m: 0, name: '4f' },
      { n: 4, l: 3, m: 1, name: '4f' },
      { n: 4, l: 3, m: 2, name: '4f' },
      { n: 4, l: 3, m: 3, name: '4f' },
    ];

    const descriptions = {
      '1s': 'Spherically symmetric ground state',
      '2s': 'Radial node present, symmetric shell',
      '2p': 'Dumbbell-shaped, angular node at origin',
      '3s': 'Two radial nodes, spherically symmetric',
      '3p': 'Dumbbell with nodal planes, larger than 2p',
      '3d': 'Four-lobed cloverleaf pattern',
      '4s': 'Three radial nodes, spherically symmetric',
      '4p': 'Dumbbell with multiple nodes, diffuse',
      '4d': 'Four-lobed pattern, complex node structure',
      '4f': 'Eight-lobed flower pattern'
    };

    // State
    let state = {
      n: 1,
      l: 0,
      m: 0,
      colorScheme: 'hot',
      resolution: 200,
      showNodes: true,
      angle: 0,
      zoom: 15
    };

    // Factorial function
    function factorial(n) {
      if (n <= 1) return 1;
      let result = 1;
      for (let i = 2; i <= n; i++) result *= i;
      return result;
    }

    // Generalized Laguerre polynomial L_n^k(x)
    function laguerrePolynomial(n, k, x) {
      if (n === 0) return 1;
      if (n === 1) return 1 + k - x;
      let lm1 = 1;
      let lm2 = 1 + k - x;
      for (let i = 2; i <= n; i++) {
        const l = ((2 * i - 1 + k - x) * lm2 - (i - 1 + k) * lm1) / i;
        lm1 = lm2;
        lm2 = l;
      }
      return lm2;
    }

    // Associated Legendre polynomial P_l^m(x)
    function legendrePolynomial(l, m, x) {
      const absm = Math.abs(m);
      if (absm > l) return 0;

      // Calculate P_l^|m|(x)
      let pmm = Math.pow(1 - x * x, absm / 2);
      if (absm > 0) {
        const fact = 1;
        for (let i = 1; i <= absm; i++) {
          pmm *= -(2 * i - 1);
        }
      }

      if (l === absm) return pmm;

      let pmp1m = x * (2 * absm + 1) * pmm;
      if (l === absm + 1) return pmp1m;

      let plm = 0;
      for (let ll = absm + 2; ll <= l; ll++) {
        plm = ((2 * ll - 1) * x * pmp1m - (ll + absm - 1) * pmm) / (ll - absm);
        pmm = pmp1m;
        pmp1m = plm;
      }

      // Apply (-1)^|m| * |m|! factor for negative m
      if (m < 0) {
        const fact = 1;
        for (let i = 1; i <= absm; i++) {
          plm /= i;
        }
        plm *= Math.pow(-1, m);
      }

      return plm;
    }

    // Radial wavefunction R_nl(r)
    function radialWavefunction(n, l, r) {
      if (r < 0) return 0;

      const rho = 2 * r / n;
      const norm = Math.sqrt(
        Math.pow(2 / n, 3) * factorial(n - l - 1) / (2 * n * factorial(n + l))
      );
      const exp = Math.exp(-rho / 2);
      const poly = Math.pow(rho, l) * laguerrePolynomial(n - l - 1, 2 * l + 1, rho);

      return norm * exp * poly;
    }

    // Spherical harmonic Y_lm(θ, φ) - real version
    function sphericalHarmonic(l, m, theta, phi) {
      const costheta = Math.cos(theta);
      const absmFactorial = factorial(Math.abs(m));
      const fact = Math.sqrt(
        (2 * l + 1) * factorial(l - Math.abs(m)) / (4 * Math.PI * factorial(l + Math.abs(m)))
      );
      const legendre = legendrePolynomial(l, m, costheta);

      if (m === 0) {
        return fact * legendre;
      } else if (m > 0) {
        return Math.sqrt(2) * fact * Math.cos(m * phi) * legendre;
      } else {
        return Math.sqrt(2) * fact * Math.sin(-m * phi) * legendre;
      }
    }

    // Compute probability density |ψ|² at (r, θ)
    function probabilityDensity(n, l, m, r, theta) {
      const R = radialWavefunction(n, l, r);
      const Y = sphericalHarmonic(l, m, theta, 0);
      return R * R * Y * Y;
    }

    // Color mapping functions
    function colorHot(value) {
      value = Math.min(1, Math.max(0, value));
      if (value < 0.33) {
        const t = value / 0.33;
        const r = Math.floor(t * 255);
        return [r, 0, 0, 255];
      } else if (value < 0.66) {
        const t = (value - 0.33) / 0.33;
        const r = 255;
        const g = Math.floor(t * 255);
        return [r, g, 0, 255];
      } else {
        const t = (value - 0.66) / 0.34;
        const r = 255;
        const g = 255;
        const b = Math.floor(t * 255);
        return [r, g, b, 255];
      }
    }

    function colorCool(value) {
      value = Math.min(1, Math.max(0, value));
      if (value < 0.33) {
        const t = value / 0.33;
        const b = Math.floor(100 + t * 155);
        return [0, 0, b, 255];
      } else if (value < 0.66) {
        const t = (value - 0.33) / 0.33;
        const g = Math.floor(t * 255);
        const b = 255;
        return [0, g, b, 255];
      } else {
        const t = (value - 0.66) / 0.34;
        const g = 255;
        const b = 255 - Math.floor(t * 100);
        return [0, g, b, 255];
      }
    }

    function colorPhase(sign, value) {
      value = Math.min(1, Math.max(0, value));
      if (sign > 0) {
        // Positive: red
        const r = 255;
        const g = Math.floor((1 - value) * 100);
        const b = Math.floor((1 - value) * 100);
        return [r, g, b, 255];
      } else {
        // Negative: blue
        const r = Math.floor((1 - value) * 100);
        const g = Math.floor((1 - value) * 100);
        const b = 255;
        return [r, g, b, 255];
      }
    }

    function getColor(value, scheme) {
      if (scheme === 'hot') return colorHot(value);
      if (scheme === 'cool') return colorCool(value);
      return colorHot(value);
    }

    // Render orbital
    function renderOrbital() {
      const canvas = document.getElementById('orbitalCanvas');
      const ctx = canvas.getContext('2d');
      const width = canvas.width;
      const height = canvas.height;

      const resolution = state.resolution;
      const pixelSize = width / resolution;

      const imageData = ctx.createImageData(width, height);
      const data = imageData.data;

      const centerX = width / 2;
      const centerY = height / 2;
      const scale = pixelSize / state.zoom; // Convert pixels to Bohr radii

      let maxDensity = 0;
      const densities = [];

      // First pass: compute densities
      for (let y = 0; y < resolution; y++) {
        for (let x = 0; x < resolution; x++) {
          const px = (x + 0.5) * pixelSize - centerX;
          const py = (y + 0.5) * pixelSize - centerY;

          const r = Math.sqrt(px * px + py * py) * scale;
          let theta = Math.atan2(py, px) + state.angle * Math.PI / 180;

          const density = Math.abs(probabilityDensity(state.n, state.l, state.m, r, theta));
          densities.push(density);
          maxDensity = Math.max(maxDensity, density);
        }
      }

      // Second pass: map to colors
      for (let i = 0; i < resolution * resolution; i++) {
        const x = i % resolution;
        const y = Math.floor(i / resolution);
        const px = (x + 0.5) * pixelSize - centerX;
        const py = (y + 0.5) * pixelSize - centerY;

        const normalized = maxDensity > 0 ? densities[i] / maxDensity : 0;
        const color = getColor(normalized, state.colorScheme);

        const idx = (y * resolution + x) * 4;
        data[idx] = color[0];
        data[idx + 1] = color[1];
        data[idx + 2] = color[2];
        data[idx + 3] = color[3];
      }

      // Upscale imageData to canvas size if resolution < width
      ctx.putImageData(imageData, 0, 0);

      // Draw nodal surfaces (approximated)
      if (state.showNodes && state.l > 0) {
        ctx.strokeStyle = 'rgba(0, 255, 0, 0.2)';
        ctx.lineWidth = 1;

        // Draw angular nodes as lines through origin
        for (let i = 0; i < state.l; i++) {
          const angle = (Math.PI * i) / state.l + state.angle * Math.PI / 180;
          const x1 = centerX + Math.cos(angle) * width * 0.4;
          const y1 = centerY + Math.sin(angle) * height * 0.4;
          const x2 = centerX - Math.cos(angle) * width * 0.4;
          const y2 = centerY - Math.sin(angle) * height * 0.4;
          ctx.beginPath();
          ctx.moveTo(x1, y1);
          ctx.lineTo(x2, y2);
          ctx.stroke();
        }
      }
    }

    // Update orbital selector grid
    function updateOrbitalGrid() {
      const grid = document.getElementById('orbitalSelector');
      grid.innerHTML = '';

      const uniqueOrbitalNames = {};
      orbitals.forEach(o => {
        const key = `${o.n}${o.name}`;
        if (!uniqueOrbitalNames[key]) {
          uniqueOrbitalNames[key] = [];
        }
        uniqueOrbitalNames[key].push(o);
      });

      for (let n = 1; n <= 4; n++) {
        for (let l = 0; l < n; l++) {
          const orbitalName = ['s', 'p', 'd', 'f'][l];
          const key = `${n}${orbitalName}`;
          if (uniqueOrbitalNames[key]) {
            const button = document.createElement('button');
            button.className = 'orbital-btn';
            if (state.n === n && state.l === l) {
              button.classList.add('active');
            }
            button.textContent = key;
            button.onclick = () => {
              state.n = n;
              state.l = l;
              state.m = Math.min(state.m, l);
              state.m = Math.max(state.m, -l);
              updateAll();
            };
            grid.appendChild(button);
          }
        }
      }
    }

    // Update energy level diagram
    function updateEnergyLevels() {
      const container = document.getElementById('energyLevels');
      container.innerHTML = '';

      for (let n = 1; n <= 4; n++) {
        const energy = -RYDBERG_ENERGY / (n * n);
        const degeneracy = n * n;

        const level = document.createElement('div');
        level.className = 'energy-level';
        if (state.n === n) {
          level.classList.add('active');
        }

        level.innerHTML = `
          <div class="energy-line"></div>
          <div class="energy-info">
            <div class="energy-n">n = ${n}</div>
            <div class="energy-value">${energy.toFixed(2)} eV</div>
          </div>
          <div class="energy-degen">2n² = ${degeneracy}</div>
        `;

        level.onclick = () => {
          state.n = n;
          state.l = Math.min(state.l, n - 1);
          state.m = Math.min(state.m, state.l);
          state.m = Math.max(state.m, -state.l);
          updateAll();
        };

        container.appendChild(level);
      }
    }

    // Update stats panel
    function updateStats() {
      const orbital = `${state.n}${['s', 'p', 'd', 'f'][state.l]}`;
      const energy = -RYDBERG_ENERGY / (state.n * state.n);
      const radialNodes = state.n - state.l - 1;
      const angularNodes = state.l;

      document.getElementById('orbitalNameDisplay').textContent = orbital;
      document.getElementById('energyDisplay').textContent = energy.toFixed(1);
      document.getElementById('radialNodes').textContent = radialNodes;
      document.getElementById('angularNodes').textContent = angularNodes;
      document.getElementById('orbitalDesc').textContent =
        descriptions[orbital] || 'Complex orbital shape';
    }

    // Update all controls
    function updateAll() {
      // Update sliders
      document.getElementById('sliderN').value = state.n;
      document.getElementById('sliderL').value = state.l;
      document.getElementById('sliderM').value = state.m;
      document.getElementById('sliderAngle').value = state.angle;
      document.getElementById('sliderZoom').value = state.zoom;

      // Update value displays
      document.getElementById('valueN').textContent = state.n;
      document.getElementById('valueL').textContent = state.l;
      document.getElementById('valueM').textContent = state.m;
      document.getElementById('valueAngle').textContent = state.angle + '°';
      document.getElementById('valueZoom').textContent = state.zoom.toFixed(1);

      // Update L slider max
      document.getElementById('sliderL').max = state.n - 1;

      // Update M slider range
      document.getElementById('sliderM').min = -state.l;
      document.getElementById('sliderM').max = state.l;
      document.getElementById('sliderM').value = Math.max(-state.l, Math.min(state.l, state.m));
      state.m = Math.max(-state.l, Math.min(state.l, state.m));

      // Update orbital grid active button
      const buttons = document.querySelectorAll('.orbital-btn');
      buttons.forEach(btn => btn.classList.remove('active'));
      const orbitalName = `${state.n}${['s', 'p', 'd', 'f'][state.l]}`;
      const activeBtn = Array.from(buttons).find(btn => btn.textContent === orbitalName);
      if (activeBtn) activeBtn.classList.add('active');

      // Update color scheme buttons
      document.querySelectorAll('.color-btn').forEach(btn => {
        btn.classList.remove('active');
        if (btn.dataset.scheme === state.colorScheme) {
          btn.classList.add('active');
        }
      });

      // Update resolution buttons
      document.querySelectorAll('.resolution-btn').forEach(btn => {
        btn.classList.remove('active');
        if (parseInt(btn.dataset.resolution) === state.resolution) {
          btn.classList.add('active');
        }
      });

      updateOrbitalGrid();
      updateEnergyLevels();
      updateStats();
      renderOrbital();
    }

    // Event listeners
    document.getElementById('sliderN').addEventListener('input', (e) => {
      state.n = parseInt(e.target.value);
      state.l = Math.min(state.l, state.n - 1);
      state.m = Math.max(-state.l, Math.min(state.l, state.m));
      updateAll();
    });

    document.getElementById('sliderL').addEventListener('input', (e) => {
      state.l = parseInt(e.target.value);
      state.m = Math.max(-state.l, Math.min(state.l, state.m));
      updateAll();
    });

    document.getElementById('sliderM').addEventListener('input', (e) => {
      state.m = parseInt(e.target.value);
      updateAll();
    });

    document.getElementById('sliderAngle').addEventListener('input', (e) => {
      state.angle = parseInt(e.target.value);
      renderOrbital();
      document.getElementById('valueAngle').textContent = state.angle + '°';
    });

    document.getElementById('sliderZoom').addEventListener('input', (e) => {
      state.zoom = parseFloat(e.target.value);
      renderOrbital();
      document.getElementById('valueZoom').textContent = state.zoom.toFixed(1);
    });

    document.querySelectorAll('.color-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        state.colorScheme = e.target.dataset.scheme;
        updateAll();
      });
    });

    document.querySelectorAll('.resolution-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        state.resolution = parseInt(e.target.dataset.resolution);
        updateAll();
      });
    });

    document.getElementById('showNodes').addEventListener('change', (e) => {
      state.showNodes = e.target.checked;
      renderOrbital();
    });

    // Initial render
    updateAll();