Code source de pyspc.plotting.peakflow

#!/usr/bin/python3
# -*- coding: utf-8 -*-
########################################################################
#
# This file is part of python module <pyspc>.
# Copyright (C) 2013-2021  R. Marty
#   (renaud.marty@developpement-durable.gouv.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program (see COPYING.txt).
# If not, see <http://www.gnu.org/licenses/>.
#
########################################################################
"""
Images - Peak Flow comparison
"""
import matplotlib.pyplot as mplt
import numpy as np
from scipy import stats as sps

from pyspc.core.parameter import Parameter


[docs] def plot_peakflow_analysis(data=None, fig_filename=None, upsta=None, downsta=None, param=None): """ Tracer l'analyse des pointes de crue amont et aval Parameters ---------- data : dict Dictionnaire des événements. - clé : (instant du pic amont, instant du pic aval) - valeur : (débit du pic amont, débit du pic aval) fig_filename : str Nom du fichier image upsta : str Identifiant du point amont downsta : str Identifiant du point aval Returns ------- dict Valeurs de la relation linéaire: - 'slope': pente de la relation linéaire - 'intercept': ordonnée à l'origine de la relation linéaire - 'r_value': coefficient de correlation - 'r_squared': coefficient de détermination - 'p_value': p-value - 'std_err': Erreur standard de l'ajustement - 'confidence_pct': Définition de l'intervalle de confiance - 'confidence_interval': Intervalle de confiance See Also -------- scipy.stats.linregress """ if fig_filename is None: fig_filename = 'peakflow_analysis.png' if not isinstance(param, Parameter): raise ValueError("Le paramètre est incorrect") unit = param.units tunits = param.timeunits timestep = param.timestep # ========================================================================= # --- TRACER FIGURE INITIALE # ========================================================================= fig = mplt.figure(dpi=300) ax = fig.add_axes((0.10, 0.12, 0.55, 0.80)) ax2 = fig.add_axes((0.75, 0.12, 0.20, 0.80)) # ========================================================================= # --- PREPARATION DONNEES # ========================================================================= boxplot_tdmax = [] x = [] y = [] for a in data: upt = a[0] dnt = a[1] upm = data[a][0] dnm = data[a][1] x.append(upm) y.append(dnm) tdmax = int((dnt - upt) / timestep) boxplot_tdmax.append(tdmax) # ========================================================================= # --- SCATTER PLOT DES POINTES # ========================================================================= x = np.asarray(x) y = np.asarray(y) sy = np.std(y) slope, intercept, r_value, p_value, std_err = sps.linregress(x, y) r_squared = r_value ** 2 confidence_interval = 1.28 * sy * np.sqrt(1 - r_squared) ax.plot(x, y, color='tab:blue', linestyle='', marker='+', label=f'maxis [{len(x)} valeurs]') ax.plot(x, intercept + slope * x, color='tab:red', label=f'{intercept:.3f} + {slope:.3f} * x [$R^2={r_squared:.3f}$]') ax.plot(x, intercept + slope * x - confidence_interval, color='tab:orange', label=r'intervalle à 80% [$\pm ' f'{confidence_interval:.1f} {unit}$]') ax.plot(x, intercept + slope * x + confidence_interval, color='tab:orange') ax.set_ylabel(f'Maxi aval ({downsta}) [${unit}$]', fontsize=10) ax.tick_params( axis='y', labelsize=8 ) ax.set_xlabel(f'Maxi amont ({upsta}) [${unit}$]', fontsize=10) ax.tick_params( axis='x', labelsize=8 ) ax.legend(loc=4, fontsize=8) # ========================================================================= # --- TRACER BOXPLOT TIME OF PEAK # ========================================================================= color = 'tab:blue' ax2.boxplot(boxplot_tdmax, widths=0.5, whis=(0, 100), patch_artist=True, boxprops={'facecolor': color, 'color': color}, capprops={'color': color}, whiskerprops={'color': color}, flierprops={'color': color, 'markeredgecolor': color}, medianprops={'color': 'black', 'linewidth': 2}) ax2.set_ylabel(f'Ecart Tmax [{tunits}]', fontsize=10) ax2.tick_params( axis='y', labelsize=8 ) ax2.tick_params( axis='x', labelsize=8 ) xlabels = [f'{upsta}' + r' $\Rightarrow$ ' + f'{downsta}'] ax2.set_xticks(list(range(1, len(xlabels)+1))) ax2.set_xticklabels(xlabels, horizontalalignment='center') # ========================================================================= # --- TRACER FIGURE FINALE # ========================================================================= fig.suptitle(f'Analyse des maxis {upsta} ' r'$\Rightarrow$ ' f'{downsta}', fontsize=12, fontweight='bold') mplt.savefig(fig_filename, dpi=300) mplt.close(fig) return { 'slope': slope, 'intercept': intercept, 'r_value': r_value, 'r_squared': r_squared, 'p_value': p_value, 'std_err': std_err, 'confidence_pct': 80, 'confidence_interval': confidence_interval, }