Hydrograph#

class mhm_tools.post.hydrograph.Hydrograph(simulation=None, observation=None, calc_stats=True)[source]#

Bases: object

Represent a hydrograph and provide methods for calculating metrics and generating plots.

Variables:
  • (dict) (levels)

  • (list) (plots)

  • (logging.Logger) (logger)

  • (list)

  • (Catchment) (catchment)

  • (xarray.Dataset) (discharge_data)

  • (Objectives) (objectives)

__init__(self): Initializes the Hydrograph object with the specified log level.
remove_empty_values(arr1, arr2): Removes empty values from two arrays and returns the cleaned data.
calc_kling_gupta_efficiency(observed, simulated): Calculates the Kling-Gupta efficiency metric.
calc_nash_sutcliff_efficiency(observed, simulated): Calculates the Nash-Sutcliffe efficiency metric.
calc_objectives(observed, simulated): Calculates various metrics based on observed and simulated data.
get_row_col(self): Finds the first unused gridcell for the next plot.
is_last_plot(self, n): Checks if the given plot is the last one.
get_catchment_area(self, path, ndecimal=0): Retrieves the catchment area from a config file.
get_long_time_monthly_mean(variable): Calculates the long-term average value for each month of the year.
plot_on_axis(function, xvalues, yvalues, colors=None, labels=None, \*\*arguments): Plots multiple graphs.
check_which_plots_to_create(self, code): Determines which plots to create based on the given code.
raise_if_not_directory(path): Raises an exception if the given path is not a directory.
load_data_from_discharge_nc(self, path): Loads discharge data from the specified path.
load_precipiation_data(self, path): Loads precipitation data from the specified path.
gen_hydrograph(self, input_path, output_file, show, save, title, plot_code, prec_path): Generates a hydrograph.
Attributes:
grid
obs_discharge_data
obs_discharge_data_clean
obs_discharge_data_nonan
output_file
pre
sim_colors
sim_discharge_data
sim_discharge_data_clean
sim_discharge_data_nonan
sim_name
sim_names
title

Methods

calc_kling_gupta_efficiency(observed, simulated)

Calculate the Kling-Gupta efficiency and store its components in objectives.

calc_nash_sutcliff_efficiency(observed, ...)

Calculate the Nash-Sutcliffe efficiency and store it in objectives.

calc_objectives(observed, simulated)

Clean the input arrays and calculate all objective metrics.

check_which_plots_to_create(code)

Determine which plots to create based on the given code.

create_plot_at_timestep(fig, gs)

Create a discharge plot at the native temporal resolution (daily or hourly).

create_plot_flow_duration(fig, gs)

Create a flow duration plot.

create_plot_scatter(fig, gs)

Create a discharge plot at the native temporal resolution (daily or hourly).

create_plot_seasonality(fig, gs, pre)

Generate a discharge seasonality plot.

create_plot_yearly(fig, gs, pre)

Generate a yearly discharge plot.

crop_data_to_overlapping_time()

Crop data to overlapping time.

get_catchment_area(path[, ndecimal])

Retrieve the catchment area from the given mHM ConfigFile.log.

get_hydrograph()

Generate the hydrograph from the data stored in member variables.

get_long_time_monthly_mean(variable[, long])

Calculate long-term monthly means for a time-indexed variable.

get_row_col()

Find the first unused gridcell for the next plot.

has_multi_sim()

Return True if multiple simulation series are configured.

is_last_plot(n)

Check if the given plot index is the last plot.

load_data_from_discharge_nc(path)

Load discharge data from the specified path.

load_precipiation_data(path)

Load precipitation data from a given file or directory path.

plot_on_axis(function, yvalues[, xvalues, ...])

Plot multiple graphs for specified function.

raise_if_not_directory(path)

Raise a NotADirectoryError if the given path is not a directory.

remove_empty_values(arr1, arr2[, recursive])

Remove empty values from two arrays and return the cleaned data.

set_discharge([simulation, observation])

Set the discharge variables and remove nan values.

write_output()

Write calculated objective metrics to CSV.

static get_long_time_monthly_mean(variable, long=False)[source]#

Calculate long-term monthly means for a time-indexed variable.

Parameters:
  • variable (xarray.DataArray) – Data with a ‘time’ coordinate.

  • long (bool, default False) – If True, prepend last month and append first month (for cyclic plots).

Returns:

Twelve monthly means (or 14 if long is True).

Return type:

numpy.ndarray

static plot_on_axis(function, yvalues: list, xvalues=None, colors=None, labels=None, **arguments)[source]#

Plot multiple graphs for specified function.

Parameters:
  • function – matplotlib plot function e.g. ax.plot, plt.plot, ax.scatter, ax.errorbar, …

  • xvalues – list of x values

  • yvalues – list of arrays with the y values

  • colors – optional list of colors (default red, blue)

  • labels – optional list of labels (default simulated discharge, observed discharge)

  • arguments – other arguments relevant for the given input function. e.g. linewidth=0.5 for ‘plt.plot’

static raise_if_not_directory(path)[source]#

Raise a NotADirectoryError if the given path is not a directory.

Parameters:

path (str) – The path to check.

Raises:

NotADirectoryError – If the given path is not a directory.:

calc_kling_gupta_efficiency(observed, simulated)[source]#

Calculate the Kling-Gupta efficiency and store its components in objectives.

Parameters:
  • observed – list The observed discharge data.

  • simulated – list The simulated discharge data.

Return type:

None

calc_nash_sutcliff_efficiency(observed, simulated)[source]#

Calculate the Nash-Sutcliffe efficiency and store it in objectives.

Parameters:
  • observed – list The observed discharge data.

  • simulated – list The simulated discharge data.

Return type:

None

calc_objectives(observed, simulated)[source]#

Clean the input arrays and calculate all objective metrics.

Parameters:
  • observed – list The observed discharge data.

  • simulated – list The simulated discharge data.

Return type:

None

check_which_plots_to_create(code)[source]#

Determine which plots to create based on the given code.

A tuple is produced and saved as member variable. It has a one at the index of the selected plots and a zero otherwise. The indices of the plots are: model timestep (0), yearly (1), seasonality (2), flow duration (3), scatter (4)

Parameters:

code (str) – A string indicating which plots to create.

Return type:

None

create_plot_at_timestep(fig, gs)[source]#

Create a discharge plot at the native temporal resolution (daily or hourly).

Parameters:
  • fig (matplotlib.figure.Figure) – The figure object to add the plot to.

  • gs (matplotlib.gridspec.GridSpec) – The gridspec object specifying the subplot layout.

Return type:

None

create_plot_flow_duration(fig, gs)[source]#

Create a flow duration plot.

Parameters:
  • fig (matplotlib.figure.Figure) – The figure object to add the plot to.

  • gs (matplotlib.gridspec.GridSpec) – The gridspec object specifying the subplot layout.

Return type:

None

create_plot_scatter(fig, gs)[source]#

Create a discharge plot at the native temporal resolution (daily or hourly).

Parameters:
  • fig (matplotlib.figure.Figure) – The figure object to add the plot to.

  • gs (matplotlib.gridspec.GridSpec) – The gridspec object specifying the subplot layout.

Return type:

None

create_plot_seasonality(fig, gs, pre)[source]#

Generate a discharge seasonality plot.

Parameters:
  • fig (matplotlib.figure.Figure) – The figure object to add the plot to.

  • gs (matplotlib.gridspec.GridSpec) – The grid specification for the plot layout.

  • pre (dict) – The precipitation data.

Return type:

None

create_plot_yearly(fig, gs, pre)[source]#

Generate a yearly discharge plot.

Parameters:
  • fig (matplotlib.figure.Figure) – The figure object to add the plot to.

  • gs (matplotlib.gridspec.GridSpec) – The grid specification for the plot layout.

  • pre (xarray.DataArray) – The precipitation data.

Return type:

None

crop_data_to_overlapping_time()[source]#

Crop data to overlapping time.

get_catchment_area(path, ndecimal=0)[source]#

Retrieve the catchment area from the given mHM ConfigFile.log.

Parameters:
  • path (str) – The path to the file.

  • ndecimal (int, optional) – The number of decimal places to round the catchment area to. Defaults to 0.

Return type:

None

Raises:

None

get_hydrograph()[source]#

Generate the hydrograph from the data stored in member variables.

Returns:

True on success, False/None if no plots are created or data are insufficient.

Return type:

bool | None

get_row_col()[source]#

Find the first unused gridcell for the next plot.

Returns:

Tuple[int, int]

Return type:

The row and column indices of the first unused gridcell.

Raises:

ValueError – If there are no unused gridcells left.:

has_multi_sim()[source]#

Return True if multiple simulation series are configured.

is_last_plot(n)[source]#

Check if the given plot index is the last plot.

Args: - n (int): The plot index to check.

Returns:

- bool

Return type:

True if the given plot index is the last plot, False otherwise.

load_data_from_discharge_nc(path)[source]#

Load discharge data from the specified path.

Parameters:

path (str) – The path to the directory containing the discharge data.

Raises:

TypeError – If the variable name in the discharge dataset is not a string.:

load_precipiation_data(path)[source]#

Load precipitation data from a given file or directory path.

Parameters:

path (str) – The path to the file or directory containing the precipitation data.

Returns:

xr.Dataset – Returns None if no precipitation file is found or if the path is invalid.

Return type:

The loaded precipitation data as an xarray Dataset object.

remove_empty_values(arr1, arr2, recursive=True)[source]#

Remove empty values from two arrays and return the cleaned data.

Parameters:
  • arr1 – list The first array.

  • arr2 – list The second array.

Returns:

A tuple containing the cleaned data arrays in the order they were given as arguments.

Return type:

tuple

set_discharge(simulation=None, observation=None)[source]#

Set the discharge variables and remove nan values.

write_output()[source]#

Write calculated objective metrics to CSV.

OBS_COLOR = '#D55E00'#
SIM_COLOR = '#0072B2'#
calc_stats = False#
catchment = <mhm_tools.post.hydrograph.Catchment object>#
grid = None#
logger = <Logger mhm_tools.post.hydrograph (WARNING)>#
multi_sim_named = False#
objectives = <mhm_tools.post.hydrograph.Objectives object>#
obs_discharge_data = None#
obs_discharge_data_clean = None#
obs_discharge_data_nonan = None#
output_file = None#
pre = None#
save = False#
show = False#
sim_colors = None#
sim_discharge_data = None#
sim_discharge_data_clean = None#
sim_discharge_data_nonan = None#
sim_name = None#
sim_names = None#
title = None#