"""Right Marchenko diagonal at x=0 for one pole and Gaussian reflection.

Python 3 + NumPy. Compare the analytic derivative at zero reflection against
independent Gaussian quadrature of the full integral equation at +/-epsilon.
"""
from math import e, erfc, pi, sqrt

import numpy as np


def diagonal(strength, cutoff, order):
    z, weight = np.polynomial.legendre.leggauss(order)
    z, weight = cutoff*(z+1)/2, cutoff*weight/2

    def kernel(s):
        return 2*np.exp(-s) + strength*np.exp(-s*s/4)/(2*sqrt(pi))

    matrix = np.eye(order) + kernel(z[:, None]+z[None, :])*weight
    k = np.linalg.solve(matrix, -kernel(z))
    return -kernel(0) - np.dot(weight*kernel(z), k)


if __name__ == "__main__":
    target = 2*e*erfc(1)-3/(2*sqrt(pi))
    print("exact slope:", target)
    for cutoff, order in [(16, 48), (22, 80)]:
        for step in [0.02, 0.01, 0.005]:
            slope = (diagonal(step, cutoff, order)-diagonal(-step, cutoff, order))/(2*step)
            print(cutoff, order, step, slope, abs(slope-target))
