r"""
Fractional Chern Insulator in a Flat Chern Band
=====================================================

A nearly flat band with Chern number :math:`C = \pm1`, filled to one third
with spinless fermions that repel on nearest-neighbour bonds, behaves like
the lowest Landau level at :math:`\nu = 1/3`: the ground state is a
Laughlin-like liquid with no magnetic field at all (Neupert, Santos,
Chamon and Mudry; Sheng, Gu, Sun and Sheng; Regnault and Bernevig, all
2011). On a torus its fingerprints are

* **three** nearly degenerate ground states, separated by a gap from the
  rest of the spectrum, in the momentum sectors that the counting of
  the :math:`\nu = 1/3` state predicts;
* **spectral flow**: threading one flux quantum through a cycle of the
  torus carries each ground state into another, and three flux quanta
  bring them back, while the gap stays open.

The interaction is projected onto the flat band (Regnault and Bernevig),
so that a :math:`4\times6` torus with 8 fermions -- 735471 states, split
into 24 momentum sectors -- is diagonalized exactly by
:func:`~tbkit.manybody.exact_diagonalization`.
"""
import numpy as np
import matplotlib.pyplot as plt

from tbkit.kspace import KSpace, reciprocal_vectors
from tbkit.lattice import Lattice
from tbkit.manybody import exact_diagonalization, project_interaction


# %%
# The checkerboard flat Chern band
# -----------------------------------
# Two sites per square cell. Nearest-neighbour hoppings
# :math:`te^{\pm i\phi}` (the sign alternating between the two diagonals),
# second neighbours :math:`\pm t'` (opposite on the two sublattices and on
# the two axes) and third neighbours :math:`t''`, with :math:`\phi = \pi/4`,
# :math:`t' = t/(2+\sqrt2)` and :math:`t'' = t/(2+2\sqrt2)`: the lower band
# is nearly flat and carries a Chern number.

lat = Lattice([{'tag': 'a', 'r0': (0., 0.)}, {'tag': 'b', 'r0': (.5, .5)}], [(1., 0.), (0., 1.)])
t, t1, t2, phi = 1., 1 / (2 + np.sqrt(2)), 1 / (2 + 2 * np.sqrt(2)), np.pi / 4
ks = KSpace(lat)
ks.set_hopping([{'i': 0, 'j': 1, 'R': R, 't': t * np.exp(-1j * phi)} for R in ((0, 0), (-1, -1))]
               + [{'i': 0, 'j': 1, 'R': R, 't': t * np.exp(1j * phi)} for R in ((-1, 0), (0, -1))]
               + [{'i': 0, 'j': 0, 'R': (1, 0), 't': t1}, {'i': 0, 'j': 0, 'R': (0, 1), 't': -t1},
                  {'i': 1, 'j': 1, 'R': (1, 0), 't': -t1}, {'i': 1, 'j': 1, 'R': (0, 1), 't': t1}]
               + [{'i': o, 'j': o, 'R': R, 't': t2} for o in (0, 1) for R in ((1, 1), (1, -1))])

b = np.array(reciprocal_vectors(lat.prim_vec))
grid = np.linspace(0., 1., 61)
mesh = np.array([u * b[0] + v * b[1] for u in grid for v in grid])
bands = np.array([np.linalg.eigvalsh(ks.get_ham(k)) for k in mesh])
width, gap = np.ptp(bands[:, 0]), bands[:, 1].min() - bands[:, 0].max()
chern = ks.chern_number([0], nk=30)
print('Lower band: width {:.3f}t, gap {:.3f}t (flatness {:.0f}), C = {:+.0f}.'.format(width, gap, gap / width, chern))
assert gap / width > 25 and abs(abs(chern) - 1) < 1e-6

# %%
# The interaction projected onto the flat band
# ------------------------------------------------
# On the :math:`N_1\times N_2 = 4\times6` torus the band holds one Bloch
# state per cell, :math:`\phi_{\mathbf k}(\mathbf R, o) = e^{i\mathbf k\cdot\mathbf R}u_{\mathbf k}(o)/\sqrt N`,
# with :math:`\mathbf k = \sum_\alpha (m_\alpha + \theta_\alpha/2\pi)\,\mathbf b_\alpha/N_\alpha`
# for twisted boundary conditions :math:`\theta`. They are eigenstates of
# the real-space torus of :meth:`~tbkit.kspace.KSpace.finite_ham` with the
# same *twist*. The repulsion :math:`V = t` on the nearest-neighbour bonds
# becomes a two-body interaction between them
# (:func:`~tbkit.manybody.project_interaction`); it conserves the total
# momentum :math:`\sum m \bmod (N_1, N_2)`, which labels the sectors.

n1, n2 = 4, 6
n_cells, n_particles = n1 * n2, n1 * n2 // 3
cells = np.array([(c % n1, c // n1) for c in range(n_cells)])   # cell (n1, n2) of finite_ham row c
labels = cells.copy()                                           # momentum (m1, m2) of Bloch state q
positions = cells @ np.array(lat.prim_vec)
torus = ks.finite_ham((n1, n2), periodic=True)
bonds = (np.abs(np.abs(torus) - t) < 1e-9).astype(float)        # the |t| = 1 bonds: nearest neighbours


def flat_band(theta):
    '''Energies and real-space Bloch states of the lower band, twist theta.'''
    k = (labels + np.asarray(theta) / (2 * np.pi)) / (n1, n2) @ b
    energies, states = np.zeros(n_cells), np.zeros((2 * n_cells, n_cells), complex)
    for q in range(n_cells):
        e, u = np.linalg.eigh(ks.get_ham(k[q]))
        energies[q] = e[0]
        states[:, q] = np.kron(np.exp(1j * positions @ k[q]) / np.sqrt(n_cells), u[:, 0])
    return energies, states


def sector(theta, K, n_states):
    '''Lowest many-body energies of the momentum sector K.'''
    energies, states = flat_band(theta)
    w = project_interaction(states, 1. * bonds)
    return exact_diagonalization(np.diag(energies), n_particles, W=w, n_states=n_states,
                                 momentum=(labels, (n1, n2), K)).energies


energies, states = flat_band((0.3, -0.5))
twisted = ks.finite_ham((n1, n2), periodic=True, twist=(0.3, -0.5))
assert np.allclose(twisted @ states, states * energies)

# %%
# Three ground states and a gap
# --------------------------------
# The three lowest states of each of the 24 momentum sectors, at zero flux:

sectors = [(K1, K2) for K1 in range(n1) for K2 in range(n2)]
spectrum = {K: sector((0., 0.), K, 3) for K in sectors}
e0 = min(e[0] for e in spectrum.values())
levels = sorted((e - e0, K) for K, es in spectrum.items() for e in es)
ground = [K for _, K in levels[:3]]
spread, fci_gap = levels[2][0], levels[3][0] - levels[2][0]
print('Ground states in sectors {}, spread {:.4f}t, gap {:.4f}t above them.'.format(ground, spread, fci_gap))
assert sorted(ground) == [(0, 0), (0, 2), (0, 4)]
assert fci_gap > 20 * spread

# %%
# Spectral flow under flux insertion
# -------------------------------------
# A twist :math:`\theta_2` threads the flux :math:`\theta_2/2\pi` through
# the :math:`\mathbf a_2` cycle. Following each Bloch state continuously,
# the sector labelled *K* at :math:`\theta_2 = 2\pi` is the sector
# :math:`K + (0, N)` of zero flux, with :math:`N = 8 \equiv 2 \bmod 6`: one
# flux quantum moves the ground state of :math:`(0, 0)` to :math:`(0, 2)`,
# of :math:`(0, 2)` to :math:`(0, 4)` and of :math:`(0, 4)` back to
# :math:`(0, 0)`.

thetas = np.linspace(0., 2 * np.pi, 7)
flow = np.array([[sector((0., th), K, 2) for K in ground] for th in thetas])   # (theta, K, state)
for g, K in enumerate(ground):
    moved = ground.index((0, (K[1] + n_particles) % n2))
    assert np.allclose(flow[-1, g], flow[0, moved], atol=1e-8)
assert not np.isclose(flow[-1, ground.index((0, 0)), 0], flow[0, ground.index((0, 0)), 0], atol=1e-5)
assert flow[:, :, 1].min() - flow[:, :, 0].max() > 0.05     # the gap stays open in these sectors
print('After one flux quantum each ground state sits in the next sector; the gap stays above {:.3f}t.'
      .format(flow[:, :, 1].min() - flow[:, :, 0].max()))

# sphinx_gallery_thumbnail_number = 1
fig, axes = plt.subplots(1, 2, figsize=(11, 4.2))
for e, K in levels:
    axes[0].plot(K[0] * n2 + K[1], e, '_', ms=14, mew=2, color='r' if (e, K) in levels[:3] else 'k')
axes[0].set_xlabel(r'momentum sector $K_1N_2 + K_2$')
axes[0].set_ylabel(r'$E - E_0$ ($t$)')
axes[0].set_ylim(-0.01, 0.2)
axes[0].set_title(r'$\nu = 1/3$, $4\times6$ torus: three ground states (red)')
for g, K in enumerate(ground):
    for s in range(2):
        axes[1].plot(thetas / (2 * np.pi), flow[:, g, s] - e0, 'o-', color='C{}'.format(g),
                     label='sector {}'.format(K) if s == 0 else None)
axes[1].set_xlabel(r'flux $\theta_2/2\pi$')
axes[1].set_ylabel(r'$E - E_0$ ($t$)')
axes[1].set_title('Spectral flow: the ground states exchange')
axes[1].legend()
fig.set_layout_engine('tight')
