import matplotlib.pyplot as plt
import numpy as np
from matplotlib import rcParams

# Use a commonly available serif font
rcParams.update({
    "font.family": "serif",
    "font.serif": ["DejaVu Serif"],
    "font.size": 12,
    "axes.labelsize": 14,
    "axes.titlesize": 16,
    "xtick.labelsize": 12,
    "ytick.labelsize": 12,
    "legend.fontsize": 11,
    "lines.linewidth": 1.8,
    "axes.linewidth": 1.5,
    "xtick.major.width": 1.2,
    "ytick.major.width": 1.2,
    "text.usetex": False,
    "figure.dpi": 600,
    "savefig.dpi": 600,
    "figure.autolayout": True
})

# Load band data
try:
    data = np.loadtxt('ti3in_bands.dat.gnu')
    k = np.unique(data[:, 0])
    bands = data[:, 1].reshape(-1, len(k))
except FileNotFoundError:
    raise FileNotFoundError("Band structure data file 'ti3in_bands.dat.gnu' not found.")

# Fermi energy
fermi_energy = 13.7295

# High-symmetry points
sym_indices = [0, 40, 80, 120, 160, 200, 240, 280]
sym_points = [k[i] for i in sym_indices]
sym_labels = [r'Γ', 'M', 'K', r'Γ', 'A', 'L', 'H', 'A']

fig, ax = plt.subplots(figsize=(8, 6))

# Colormap for highlighted bands (crossing)
cmap = plt.get_cmap('tab20')
num_colors = cmap.N  # 20 distinct colors

# Identify bands crossing the Fermi energy
crossing_bands_indices = []
for i, band in enumerate(bands):
    # Check if band crosses Fermi energy: i.e.,
    # minimum < E_F < maximum OR maximum < E_F < minimum (bands can be decreasing)
    if np.min(band) <= fermi_energy <= np.max(band):
        crossing_bands_indices.append(i)

# Plot all bands in light gray (background)
for i, band in enumerate(bands):
    band_clipped = np.clip(band, 11, 16)
    ax.plot(k, band_clipped-fermi_energy, color='olive', alpha=0.8, linewidth=1)

# Plot crossing bands with distinct colors and stronger alpha
for idx_i, i in enumerate(crossing_bands_indices):
    band = bands[i]
    band_clipped = np.clip(band, 11, 16)
    color = cmap(idx_i % num_colors)
    ax.plot(k, band_clipped-fermi_energy, color=color, alpha=1, linewidth=2.2, label=f'Band {i+1}')

# Fermi energy line
ax.axhline(fermi_energy, linestyle='--', color='red', linewidth=1.5)
ax.text(k[0] - 0.13, fermi_energy-0.02, r'$E_\mathrm{F}$', color='red', fontsize=12)

# Vertical lines for symmetry points, excluding first and last
for point in sym_points[1:-1]:
    ax.axvline(point, color='gray', linestyle=':', linewidth=1)

ax.set_xticks(sym_points)
ax.set_xticklabels(sym_labels)
ax.set_xlabel("Wave Vector")
ax.set_ylabel("E-$E_F$(eV)")
ax.set_title(r"Electronic Band Structure of Ti$_3$In")

ax.set_ylim(-4,4)
ax.set_xlim(k[0], k[-1])
ax.grid(axis='y', linestyle=':', alpha=1)

# Optional: Add legend for crossing bands (can become crowded if many bands cross)
if len(crossing_bands_indices) > 0:
    ax.legend(loc='upper right', ncol=1, title="Bands crossing $E_F$", fontsize=9)

plt.tight_layout()
#plt.savefig('Ti3In_Bands_HighlightCrossing.png', dpi=2300)
plt.show()             /tmp/ipykernel_7858/1591399396.py:89: UserWarning: Tight layout not applied. The bottom and top margins cannot be made large enough to accommodate all axes decorations.
  plt.tight_layout()
/usr/lib/python3/dist-packages/IPython/core/pylabtools.py:152: UserWarning: Tight layout not applied. The bottom and top margins cannot be made large enough to accommodate all axes decorations.
  fig.canvas.print_figure(bytes_io, **kw)