"""Dressed charge, physical velocity and independent response. Python 3 + NumPy."""
from math import pi
import numpy as np
from numpy.polynomial.legendre import leggauss


def ground_state(edge, coupling=2.0, order=48):
    nodes,weights=leggauss(order)
    nodes,weights=edge*nodes,edge*weights
    def kernel(diff):
        return coupling/(pi*(coupling**2+diff**2))
    matrix=np.eye(order)-kernel(nodes[:,None]-nodes)*weights
    z=np.linalg.solve(matrix,np.ones(order))
    e2=np.linalg.solve(matrix,nodes**2)
    eprime=np.linalg.solve(matrix,2*nodes)
    boundary=kernel(edge-nodes)*weights
    Z=1+boundary@z
    mu=(edge**2+boundary@e2)/Z
    speed=(2*edge+boundary@eprime)/Z
    return weights@z/(2*pi),mu,Z,speed


if __name__=="__main__":
    for order in (12,24,48):
        n,mu,Z,v=ground_state(1,order=order)
        print("order, n, mu, Z(Q), K, v, Galilean",order,n,mu,Z,Z*Z,v,v*Z*Z-2*pi*n)
    for h in (0.01,0.001,0.0001):
        above,below=ground_state(1+h),ground_state(1-h)
        susceptibility=(above[0]-below[0])/(above[1]-below[1])
        print("dQ, response, target",h,susceptibility,Z*Z/(pi*v))
    assert abs(v*Z*Z-2*pi*n)<1e-12
    assert abs(susceptibility-Z*Z/(pi*v))<1e-8
