# ---
# jupyter:
#   jupytext:
#     formats: py:percent
#     text_representation:
#       extension: .py
#       format_name: percent
#       format_version: '1.3'
#       jupytext_version: 1.17.1
#   kernelspec:
#     display_name: Python 3 (ipykernel)
#     language: python
#     name: python3
# ---

# %%
import os
import sys

# %%
import git
import matplotlib as mpl
import numpy as np
import tabulate
import tqdm

from matplotlib import pyplot as plt

# %%
from finesse import BeamParam
from finesse.knm.tools import make_scatter_matrix

# %%
mpl.rcParams["text.latex.preamble"] = r"\usepackage{erewhon}\usepackage[utopia]{newtxmath}"

# %%
lambda0 = 1064e-9

# %%
qx0 = BeamParam(w0=0.41e-3, z=0, wavelength=lambda0)
qy0 = BeamParam(w0=0.48e-3, z=0, wavelength=lambda0)

# %%
xgamma = ygamma = 0

# %%
warr = np.geomspace(0.08e-3, 3e-3, 100)
zarr = np.linspace(-1, 1, 101)
tem00arr = np.zeros((warr.shape[0], zarr.shape[0]), dtype=complex)
tem02arr = np.zeros((warr.shape[0], zarr.shape[0]), dtype=complex)
tem20arr = np.zeros((warr.shape[0], zarr.shape[0]), dtype=complex)
tem022arr = np.zeros((warr.shape[0], zarr.shape[0]), dtype=complex)

# %%
with tqdm.tqdm(total=warr.shape[0] * zarr.shape[0]) as pbar:
    for ii, w in enumerate(warr):
        for jj, z in enumerate(zarr):
            qx1 = qy1 = BeamParam(w0=w, z=z, wavelength=lambda0)# * np.pi * w**2 / 1064e-9)
            kmat = make_scatter_matrix(
                "bayerhelms",
                qx0, qx1, qy0, qy1,
                xgamma, ygamma,
                maxtem=2,
                select="even",
            )
            tem00arr[ii, jj] = kmat[(0, 0, 0, 0, )]
            tem02arr[ii, jj] = kmat[(0, 0, 0, 2, )]
            tem20arr[ii, jj] = kmat[(0, 0, 2, 0, )]
            #tem022arr[ii, jj] = kmat[(0, 0, 0, 22, )]
            pbar.update()

# %%
pfmt = mpl.ticker.PercentFormatter(1)
pfmt.create_dummy_axis()

# %%
fig, (ax_00, ax_r02, ax_r20) = plt.subplots(1, 3, figsize=(9, 3))
for ax, mat, levels in zip(
    [ax_00, ax_r02, ax_r20],
    [tem00arr, tem02arr / tem00arr, tem20arr / tem00arr],
    [np.linspace(0.1, 0.9, 5), *2*[np.concatenate([[0.01, 0.05], np.linspace(0.1, 0.9, 9)])]],
):
    pc = ax.pcolormesh(1e3 * warr, zarr, np.abs(mat.T)**2,
                       cmap="inferno", vmin=-0.3, vmax=1.5, linewidth=0, rasterized=True)
    pc.set_edgecolor('face')
    ct = ax.contour(1e3 * warr, zarr, np.abs(mat.T)**2,
                    levels, colors="w")
    ax.set_xscale("log")
    ax.xaxis.set_major_formatter(mpl.ticker.FuncFormatter(lambda y, _: f"{y:g}"))
    ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.25))
    ax.set_xlabel("Input beam waist [mm]")
    ax.set_ylabel("Distance to input beam waist [m]")
    ct.clabel(fmt=pfmt.format_data)
ax_00.set_title("Power into TEM$_{00}$")
ax_r02.set_title("Power ratio TEM$_{02}$ / TEM$_{00}$")
ax_r20.set_title("Power ratio TEM$_{20}$ / TEM$_{00}$")
fig.tight_layout()
fig.savefig("tir_02_20_ratios.pdf")

# %%
