From 12b11ae579142da99a8e341f8b3fe8b13fe3ab33 Mon Sep 17 00:00:00 2001 From: Danilo Ferreira de Lima <danilo.enoque.ferreira.de.lima@xfel.de> Date: Mon, 14 Aug 2023 17:33:26 +0200 Subject: [PATCH] Added script to only do plots. --- pes_to_spec/test/prepare_plots.py | 142 ++++++++++++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100755 pes_to_spec/test/prepare_plots.py diff --git a/pes_to_spec/test/prepare_plots.py b/pes_to_spec/test/prepare_plots.py new file mode 100755 index 0000000..a348a88 --- /dev/null +++ b/pes_to_spec/test/prepare_plots.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python + +import pandas as pd +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.gridspec import GridSpec +import seaborn as sns + +def plot_final(df: pd.DataFrame, filename: str): + fig = plt.figure(figsize=(12, 8)) + gs = GridSpec(1, 1) + ax = fig.add_subplot(gs[0, 0]) + ax.plot(df.energy, df.spec, c='b', lw=3, label="Grating spectrometer") + ax.plot(df.energy, df.prediction, c='r', ls='--', lw=3, label="Prediction") + ax.fill_between(df.energy, df.prediction - df.unc, df.prediction + df.unc, facecolor='gold', alpha=0.5, label="68% unc. (total)") + ax.fill_between(df.energy, df.prediction - df.unc_pca, df.prediction + df.unc_pca, facecolor='magenta', alpha=0.5, label="68% unc. (PCA only)") + Y = np.amax(df.spec) + ax.legend(frameon=False, borderaxespad=0, loc='upper left') + ax.set_title(f"Beam intensity: {df.beam_intensity.iloc[0]*1e-3:.1f} mJ", loc="left") + ax.spines['top'].set_visible(False) + ax.spines['right'].set_visible(False) + ax.set( + xlabel="Photon energy [eV]", + ylabel="Intensity [a.u.]", + ylim=(0, 1.3*Y)) + fig.savefig(filename) + plt.close(fig) + +def plot_chi2(df: pd.DataFrame, filename: str): + fig = plt.figure(figsize=(12, 8)) + gs = GridSpec(1, 1) + ax = fig.add_subplot(gs[0, 0]) + sns.histplot(x=df.chi2_prepca/df.ndof.iloc[0], kde=True, linewidth=3, ax=ax) + ax.set(title=f"", + xlabel=r"$\chi^2/$ndof", + ylabel="Counts [a.u.]", + xlim=(0, 5), + ) + fig.savefig(filename) + plt.close(fig) + +def plot_rmse_intensity(df: pd.DataFrame, filename: str): + fig = plt.figure(figsize=(12, 8)) + gs = GridSpec(1, 1) + ax = fig.add_subplot(gs[0, 0]) + ax.scatter(df.rmse, df.xgm_flux_t, c='r', s=30) + ax = plt.gca() + ax.set(title=f"", + xlabel=r"Root-mean-squared error", + ylabel="Beam intensity [uJ]", + ) + fig.savefig(filename) + plt.close(fig) + +def plot_chi2_intensity(df: pd.DataFrame, filename: str): + fig = plt.figure(figsize=(12, 8)) + gs = GridSpec(1, 1) + ax = fig.add_subplot(gs[0, 0]) + ax.scatter(df.chi2_prepca/df.ndof.iloc[0], df.xgm_flux_t, c='r', s=30) + ax = plt.gca() + ax.set(title=f"", + xlabel=r"$\chi^2/$ndof", + ylabel="Beam intensity [uJ]", + xlim=(0, 5), + ylim=(0, df.xgm_flux_t.mean() + 3*df.xgm_flux_t.std()) + ) + fig.savefig(filename) + plt.close(fig) + +def pca_variance_plot(df: pd.DataFrame, filename: str): + """ + Plot variance contribution. + + Args: + filename: Output file name. + variance_ratio: Contribution of each component's variance. + + """ + fig = plt.figure(figsize=(8, 8)) + gs = GridSpec(1, 1) + ax = fig.add_subplot(gs[0, 0]) + c = np.cumsum(df.variance_ratio) + n_comp = df.n_comp.iloc[0] + ax.bar(1+np.arange(len(df.variance_ratio)), df.variance_ratio*100, color='tab:red', alpha=0.3, label="Per component") + ax.plot(1+np.arange(len(df.variance_ratio)), c*100, c='tab:blue', lw=5, label="Cumulative") + ax.plot([n_comp, n_comp], [0, c[n_comp]*100], lw=3, ls='--', c='m', label="Components kept") + ax.plot([0, n_comp], [c[n_comp]*100, c[n_comp]*100], lw=3, ls='--', c='m') + ax.legend(frameon=False) + print(f"PCA plot: total n. components: {len(df.variance_ratio)}") + x_max = np.where(c > 0.99)[0][0] + print(f"Fraction of variance: {c[n_comp]}") + ax.set_yscale('log') + ax.set(title=f"", + xlabel="Component", + ylabel="Variance [%]", + xlim=(1, x_max), + ylim=(0.1, 100)) + ax.spines['top'].set_visible(False) + ax.spines['right'].set_visible(False) + plt.tight_layout() + fig.savefig(filename) + plt.close(fig) + +def plot_pes(df: pd.DataFrame, channel:str, filename: str): + """ + Plot low-resolution spectrum. + + Args: + filename: Output file name. + pes_raw_int: Low-resolution spectrum. + + """ + fig = plt.figure(figsize=(16, 8)) + gs = GridSpec(1, 1) + ax = fig.add_subplot(gs[0, 0]) + ax.plot(df.bin[df.range], df.loc[:, channel], c='b', lw=3) + #ax.legend() + ax.set(title=f"", + xlabel="Time-of-flight index", + ylabel="Counts [a.u.]") + ax.spines['top'].set_visible(False) + ax.spines['right'].set_visible(False) + fig.savefig(filename) + plt.close(fig) + +if __name__ == '__main__': + channel = 'channel_4_A' + fname = 'test_q100_1724098413' + plot_final(pd.read_csv(f'{fname}.csv'), f'{fname}.pdf') + plot_pes(pd.read_csv(f'{fname}_pes.csv'), channel, f'{fname}_{channel}.pdf') + + fname = 'test_q100_1724098596' + plot_final(pd.read_csv(f'{fname}.csv'), f'{fname}.pdf') + plot_pes(pd.read_csv(f'{fname}_pes.csv'), channel, f'{fname}_{channel}.pdf') + + plot_chi2(pd.read_csv(f'quality.csv'), f'chi2_prepca.pdf') + plot_chi2_intensity(pd.read_csv(f'quality.csv'), f'intensity_vs_chi2_prepca.pdf') + plot_rmse_intensity(pd.read_csv(f'quality.csv'), f'intensity_vs_rmse.pdf') + + pca_variance_plot(pd.read_csv(f'pca_spec.csv'), f'pca_spec.pdf') + pca_variance_plot(pd.read_csv(f'pca_pes.csv'), f'pca_pes.pdf') + -- GitLab