ubuntu2404
#!/usr/bin/env python31"""2Condensed Matter Physics Simulations3=====================================45This module implements fundamental condensed matter physics calculations:6- Electronic band structure using tight-binding models7- Fermi surface calculations and visualization8- Phonon dispersion relations9- Many-body systems (Hubbard model)1011Keywords: band structure calculation python, tight binding model, fermi surface calculation,12phonon dispersion python, hubbard model simulation, electronic properties condensed matter1314Author: CoCalc Scientific Templates15License: MIT16"""1718import numpy as np19import matplotlib.pyplot as plt20from scipy.linalg import eigh2122# Set reproducible random seed23np.random.seed(42)2425class TightBindingModel:26"""27Tight-binding model for electronic band structure calculations.2829Supports various lattice geometries and can calculate:30- Energy dispersion relations E(k)31- Density of states32- Fermi surfaces33"""3435def __init__(self, lattice_type='square'):36"""37Parameters:38-----------39lattice_type : str40Type of lattice ('square', 'triangular', 'honeycomb')41"""42self.lattice_type = lattice_type4344def dispersion_square_2d(self, kx, ky, t=1.0, epsilon_0=0.0):45"""46Energy dispersion for 2D square lattice.4748E(k) = ε₀ - 2t(cos(kₓ) + cos(kᵧ))4950Parameters:51-----------52kx, ky : array53k-space coordinates54t : float55Hopping parameter56epsilon_0 : float57On-site energy58"""59return epsilon_0 - 2*t*(np.cos(kx) + np.cos(ky))6061def dispersion_graphene(self, kx, ky, t=1.0):62"""63Energy dispersion for graphene (honeycomb lattice).6465Returns both conduction and valence bands.6667Parameters:68-----------69kx, ky : array70k-space coordinates71t : float72Hopping parameter73"""74# Phase factor for nearest neighbors75f = 1 + np.exp(1j * kx) + np.exp(1j * (kx/2 + np.sqrt(3)*ky/2))76energy_magnitude = t * np.abs(f)7778return energy_magnitude, -energy_magnitude # Conduction, valence bands7980def density_of_states(self, energies, n_bins=200, broadening=0.01):81"""82Calculate density of states with optional Gaussian broadening.8384Parameters:85-----------86energies : array87Energy values from band calculation88n_bins : int89Number of energy bins90broadening : float91Gaussian broadening width92"""93E_flat = energies.flatten()94E_min, E_max = E_flat.min() - 3*broadening, E_flat.max() + 3*broadening95E_grid = np.linspace(E_min, E_max, n_bins)9697if broadening > 0:98# Gaussian broadened DOS99dos = np.zeros_like(E_grid)100for E in E_flat:101dos += np.exp(-(E_grid - E)**2 / (2*broadening**2))102dos /= (np.sqrt(2*np.pi) * broadening * len(E_flat))103else:104# Histogram DOS105hist, bin_edges = np.histogram(E_flat, bins=E_grid)106dos = hist / (E_grid[1] - E_grid[0]) / len(E_flat)107E_grid = (bin_edges[:-1] + bin_edges[1:]) / 2108109return E_grid, dos110111def fermi_surface(self, kx, ky, mu, temperature=0.01):112"""113Calculate Fermi surface and electron occupation.114115Parameters:116-----------117kx, ky : array118k-space grid119mu : float120Chemical potential121temperature : float122Temperature for Fermi-Dirac distribution123124Returns:125--------126energy : array127Energy dispersion128occupation : array129Fermi-Dirac occupation function130"""131energy = self.dispersion_square_2d(kx, ky)132133# Fermi-Dirac distribution134if temperature > 0:135occupation = 1.0 / (1.0 + np.exp((energy - mu) / temperature))136else:137occupation = (energy < mu).astype(float)138139return energy, occupation140141class PhononModel:142"""143Phonon dispersion calculations for various lattice models.144145Implements:146- 1D monoatomic chain147- 1D diatomic chain148- Density of phonon states149"""150151@staticmethod152def monoatomic_chain_1d(k, K=1.0, M=1.0):153"""154Phonon frequency for 1D monoatomic chain.155156ω(k) = √(4K/M) |sin(k/2)|157158Parameters:159-----------160k : array161Wave vector162K : float163Spring constant164M : float165Atomic mass166"""167return np.sqrt(4*K/M) * np.abs(np.sin(k/2))168169@staticmethod170def diatomic_chain_1d(k, K=1.0, M1=1.0, M2=2.0):171"""172Phonon frequencies for 1D diatomic chain.173174Returns both optical and acoustic branches.175176Parameters:177-----------178k : array179Wave vector180K : float181Spring constant182M1, M2 : float183Masses of the two atoms184"""185M_sum = M1 + M2186M_prod = M1 * M2187188# Discriminant for eigenvalue equation189discriminant = M_sum**2 - 4*M_prod*np.cos(k)**2190191# Optical and acoustic branches192omega_optical = np.sqrt(K * (M_sum + np.sqrt(discriminant)) / (2*M_prod))193omega_acoustic = np.sqrt(K * (M_sum - np.sqrt(discriminant)) / (2*M_prod))194195return omega_optical, omega_acoustic196197class HubbardModel:198"""199Mean-field solution of the Hubbard model.200201H = -t Σ⟨i,j⟩σ (c†ᵢσ cⱼσ + h.c.) + U Σᵢ nᵢ↑ nᵢ↓202203Implements self-consistent mean-field approximation to study204magnetic instabilities and correlation effects.205"""206207def __init__(self, lattice_type='square_2d'):208"""209Parameters:210-----------211lattice_type : str212Lattice geometry213"""214self.lattice_type = lattice_type215216def mean_field_bands(self, kx, ky, t, mu, U, m):217"""218Mean-field energy bands for 2D square lattice.219220Parameters:221-----------222kx, ky : array223k-space coordinates224t : float225Hopping parameter226mu : float227Chemical potential228U : float229On-site interaction230m : float231Magnetization (order parameter)232"""233# Non-interacting dispersion234epsilon_k = -2*t*(np.cos(kx) + np.cos(ky))235236# Mean-field bands237E_up = epsilon_k - mu + U*m/2 # Spin-up band238E_down = epsilon_k - mu - U*m/2 # Spin-down band239240return E_up, E_down241242def self_consistent_solution(self, t, U, n_target, T=0.1, max_iter=1000, tol=1e-6):243"""244Solve mean-field equations self-consistently.245246Parameters:247-----------248t : float249Hopping parameter250U : float251Interaction strength252n_target : float253Target electron density254T : float255Temperature256max_iter : int257Maximum iterations258tol : float259Convergence tolerance260261Returns:262--------263mu : float264Converged chemical potential265m : float266Converged magnetization267converged : bool268Whether solution converged269"""270# Initial guess271mu = U * n_target / 2272m = 0.1 # Small initial magnetization273274# k-space grid275k_mesh = 64276kx = np.linspace(-np.pi, np.pi, k_mesh)277ky = np.linspace(-np.pi, np.pi, k_mesh)278KX, KY = np.meshgrid(kx, ky)279280for iteration in range(max_iter):281# Calculate mean-field bands282E_up, E_down = self.mean_field_bands(KX, KY, t, mu, U, m)283284# Fermi-Dirac distributions285f_up = 1.0 / (1.0 + np.exp(E_up / T))286f_down = 1.0 / (1.0 + np.exp(E_down / T))287288# New density and magnetization289n_new = np.mean(f_up + f_down)290m_new = np.mean(f_up - f_down)291292# Check convergence293if abs(m_new - m) < tol:294return mu, m_new, True295296# Update with mixing for stability297m = 0.7 * m + 0.3 * m_new298299# Adjust chemical potential to maintain target density300mu = mu + 0.1 * (n_target - n_new)301302return mu, m, False303304def band_structure_comparison():305"""306Compare band structures of different lattice types.307"""308print("=== Band Structure Comparison ===")309310tb = TightBindingModel()311312# k-space grid313k_points = 100314kx = np.linspace(-np.pi, np.pi, k_points)315ky = np.linspace(-np.pi, np.pi, k_points)316KX, KY = np.meshgrid(kx, ky)317318# Calculate dispersions319E_square = tb.dispersion_square_2d(KX, KY, t=1.0)320E_graphene_c, E_graphene_v = tb.dispersion_graphene(KX, KY, t=1.0)321322# Calculate density of states323E_dos_square, dos_square = tb.density_of_states(E_square, broadening=0.05)324E_dos_graphene, dos_graphene = tb.density_of_states(325np.concatenate([E_graphene_c.flatten(), E_graphene_v.flatten()]),326broadening=0.05327)328329print(f"Square lattice bandwidth: {E_square.max() - E_square.min():.3f}")330print(f"Graphene bandwidth: {E_graphene_c.max() - E_graphene_v.min():.3f}")331332return {333'square': {'energy': E_square, 'dos_E': E_dos_square, 'dos': dos_square},334'graphene': {'energy_c': E_graphene_c, 'energy_v': E_graphene_v,335'dos_E': E_dos_graphene, 'dos': dos_graphene},336'kx': KX, 'ky': KY337}338339def fermi_surface_evolution():340"""341Study evolution of Fermi surface with chemical potential.342"""343print("=== Fermi Surface Evolution ===")344345tb = TightBindingModel()346347# High-resolution k-space grid348k_res = 200349kx = np.linspace(-np.pi, np.pi, k_res)350ky = np.linspace(-np.pi, np.pi, k_res)351KX, KY = np.meshgrid(kx, ky)352353# Different chemical potentials (filling levels)354mu_values = [-3.0, -2.0, 0.0, 2.0]355fermi_data = []356357for mu in mu_values:358energy, occupation = tb.fermi_surface(KX, KY, mu, temperature=0.1)359fermi_data.append({'mu': mu, 'energy': energy, 'occupation': occupation})360361print(f"Calculated Fermi surfaces for μ = {mu_values}")362return fermi_data, KX, KY363364def phonon_comparison():365"""366Compare phonon dispersions for different chain types.367"""368print("=== Phonon Dispersion Comparison ===")369370phonon = PhononModel()371372# k-point path373k = np.linspace(-np.pi, np.pi, 500)374375# Calculate dispersions376omega_mono = phonon.monoatomic_chain_1d(k, K=1.0, M=1.0)377omega_opt, omega_ac = phonon.diatomic_chain_1d(k, K=1.0, M1=1.0, M2=2.0)378379print(f"Monoatomic max frequency: {omega_mono.max():.3f}")380print(f"Diatomic optical max: {omega_opt.max():.3f}")381print(f"Diatomic acoustic max: {omega_ac.max():.3f}")382383return {384'k': k,385'monoatomic': omega_mono,386'optical': omega_opt,387'acoustic': omega_ac388}389390def hubbard_magnetic_transition():391"""392Study magnetic transition in Hubbard model.393"""394print("=== Hubbard Model Magnetic Transition ===")395396hubbard = HubbardModel()397398# Parameters399t = 1.0400density = 0.8401U_values = [0.0, 2.0, 4.0, 6.0]402403results = []404for U in U_values:405mu, m, converged = hubbard.self_consistent_solution(t, U, density, T=0.1)406407result = {408'U': U,409'mu': mu,410'magnetization': abs(m), # Take absolute value411'converged': converged412}413results.append(result)414415status = "converged" if converged else "not converged"416print(f"U/t = {U/t:.1f}: μ = {mu:.3f}, |m| = {abs(m):.4f} ({status})")417418return results419420def calculate_transport_properties(band_data):421"""422Calculate basic transport properties from band structure.423424This is a simplified demonstration - real transport calculations425require more sophisticated methods.426"""427print("=== Transport Properties Calculation ===")428429# Extract band data430energy = band_data['square']['energy']431kx = band_data['kx']432ky = band_data['ky']433434# Calculate group velocity (simplified)435dk = kx[0, 1] - kx[0, 0] # Grid spacing436437# Numerical derivatives for group velocity438vx = -np.gradient(energy, dk, axis=1) # vₓ = -∂E/∂kₓ439vy = -np.gradient(energy, dk, axis=0) # vᵧ = -∂E/∂kᵧ440441# Speed442speed = np.sqrt(vx**2 + vy**2)443444print(f"Maximum group velocity: {speed.max():.3f}")445print(f"Average group velocity: {np.mean(speed):.3f}")446447return {'vx': vx, 'vy': vy, 'speed': speed}448449if __name__ == "__main__":450# Run all demonstrations451band_data = band_structure_comparison()452fermi_data, KX, KY = fermi_surface_evolution()453phonon_data = phonon_comparison()454hubbard_results = hubbard_magnetic_transition()455transport = calculate_transport_properties(band_data)456457print("\n=== Summary ===")458print(f"Completed all condensed matter physics calculations")459print(f"Band structure: {band_data['square']['energy'].shape} k-points")460print(f"Fermi surfaces: {len(fermi_data)} chemical potentials")461print(f"Phonon modes: {len(phonon_data['k'])} k-points")462print(f"Hubbard model: {len(hubbard_results)} interaction strengths")463464