Convergence Analysis

Find more background information on hydro-informatics.com.

Usage Example

Important

Requires a Telemac simulation with -s flag

The examples require that a Telemac2d simulation ran with telemac2d.py steady2d.cas -s and that the .cas file contained the keyword PRINTING CUMULATED FLOWRATES : YES.

Minimal

The quickest way to try pythomac is to use the example data shipped in the pythomac repository. You do not need to clone the whole repository or run a Telemac simulation; the example-simulation/ folder already contains a finished run (including the .sortie output file that pythomac reads).

  1. Install pythomac into your Python environment (if not yet done):

    pip install pythomac
    
  2. Download two items from the pythomac repository and keep them side by side:

    • the script example_flux_convergence.py

    • the folder example-simulation/ (with steady2d.cas and its steady2d.cas_*.sortie output file)

    So your local layout looks like this:

    my-folder/
    ├── example_flux_convergence.py
    └── example-simulation/
        ├── steady2d.cas
        └── steady2d.cas_2024-12-06-12h52min49s.sortie
    
  3. Run the script from my-folder/:

    python example_flux_convergence.py
    

    It resolves the example data relative to its own location, so no paths need editing. The run writes extracted_fluxes.csv, flux-convergence.png, convergence-rate.png, and convergence-rate.csv into example-simulation/.

To point the analysis at your own simulation instead, set simulation_dir to that simulation’s folder and telemac_cas to its steering file name, for instance:

from pythomac import extract_fluxes

simulation_dir = "/home/telemac-user/simulations/rhine/"
cas_name = "steady2d.cas"
extract_fluxes(simulation_dir, cas_name, plotting=False)

Full application

 1"""
 2This script features an example for flux extraction and convergence analysis with pythomac. It requires that a
 3    simulation ran with ``telemac2d.py steady2d.cas -s`` and that the .cas file contained the keyword
 4    ``PRINTING CUMULATED FLOWRATES : YES``.
 5
 6@author: Sebastian Schwindt
 7@year: 2023, 2026
 8
 9Usage:
10    This script should be placed relative to a Telemac simulation as follows:
11        + Simulation: HOME/hytelemac/steady2d-tutorial/steady2d.cas (ran with -s flag!)
12        + This script: HOME/postpro/example_flux_convergence.py
13        + To change this behavior, modify the variable simulation_dir
14
15Example:
16    Visit https://hydro-informatics.com/convergence
17
18"""
19import os
20from pathlib import Path
21from pythomac import extract_fluxes, calculate_convergence, get_convergence_time
22
23# set directories and define steering (cas) file name
24simulation_dir = os.path.join(str(Path(__file__).parent), "example-simulation")
25telemac_cas = "steady2d.cas"
26print(simulation_dir)
27
28# extract fluxes across boundaries
29fluxes_df = extract_fluxes(
30    model_directory=simulation_dir,
31    cas_name=telemac_cas,
32    plotting=True
33)
34
35# back-calculate Telemac timestep size
36timestep_in_cas = int(max(fluxes_df.index.values) / (len(fluxes_df.index.values) - 1))
37
38# plot convergence
39iota_t = calculate_convergence(
40    series_1=fluxes_df["Fluxes Boundary 1"][1:],  # remove first zero-entry
41    series_2=fluxes_df["Fluxes Boundary 2"][1:],  # remove first zero-entry
42    cas_timestep=timestep_in_cas,
43    plot_dir=simulation_dir
44)
45
46# write the result to a CSV file
47iota_t.to_csv(os.path.join(simulation_dir, "convergence-rate.csv"))
48
49# identify the timestep at which convergence was reached at a desired precision
50convergence_time_iteration = get_convergence_time(
51    relative_imbalance=iota_t["Relative imbalance"],
52    convergence_precision=1.0E-4
53)
54
55if not("nan" in str(convergence_time_iteration).lower()):
56    print("The simulation converged after {0} simulation seconds ({1}th printout).".format(
57        str(timestep_in_cas * convergence_time_iteration), str(convergence_time_iteration)))

Script and Function docs

Flux Analyst

Extract data from a Telemac simulation that has already been running.

The codes are inspired by the following jupyter notebook:

HOMETEL/notebooks/data_manip/extraction/output_file_extraction.ipynb

which uses the following example case:

/examples/telemac2d/bump/t2d_bump_FE.cas

@author: Sebastian Schwindt (July 2023; update: May 2026)

pythomac.flux_analyst.calculate_convergence(series_1, series_2, conv_constant=1.0, cas_timestep=1, plot_dir=None)[source]
Approximate convergence according to

https://hydro-informatics.com/convergence/#tm-calculate-convergence

Parameters:
  • series_1 (list or np.array) – inflow flux series Q_in; the relative imbalance is normalized by this series, which should converge toward series_2 (both must have the same length)

  • series_2 (list or np.array) – outflow flux series Q_out; should converge toward series_1 (both must have the same length)

  • conv_constant (float) – a convergence constant to reach (default is 1.0)

  • cas_timestep (int) – the timestep defined in the cas file

  • plot_dir (str) – if a directory is provided, a convergence plot will be saved here

Return pandas.DataFrame:

columns “Relative imbalance” (Delta_{Q,t}) and “Convergence rate” (iota), indexed by timestep

pythomac.flux_analyst.extract_fluxes(model_directory='', cas_name='steady2d.cas', plotting=True)[source]
This function writes a .csv file and an x-y plot of fluxes across the boundaries of a Telemac2d model. It auto-

matically place the .csv and .png plot files into the simulation directory (i.e., where the .cas file is).

Notes

  • The Telemac simulation must have been running with the ‘-s’ flag (telemac2d.py my.cas -s).

  • Make sure to activate the .cas keyword PRINTING CUMULATED FLOWRATES : YES

  • This script skips volume errors (search tags are not implemented).

  • Read more about this script at

    https://hydro-informatics.com/telemac2d-steady/#verify-steady-tm2d

Parameters:
  • model_directory (str) – the file directory where the simulation lives

  • cas_name (str) – name of the .cas steering file (without directory)

  • plotting (bool) – default (True) will place a figure called flux-convergence.png in the simulation directory

Return pandas.DataFrame:

time series of fluxes across boundaries (if Error int: -1)

pythomac.flux_analyst.get_convergence_time(relative_imbalance, convergence_precision=0.0001)[source]
Identify the optimum simulation length as the smallest output interval index beyond

which the relative flux imbalance Delta_{Q,t} (see calculate_convergence) remains permanently below the target tolerance. This implements the optimum-simulation- length criterion described at https://hydro-informatics.com/convergence.

Parameters:
  • relative_imbalance (numpy.array) – the Delta_{Q,t} series, e.g. the “Relative imbalance” column returned by calculate_convergence

  • convergence_precision (float) – target tolerance Delta_{Q,tar}; 1e-4 is typically acceptable for preliminary runs, while 1e-6 or smaller is warranted for validation and hotstart initialization runs

Return numpy.int64:

the time iteration number, or np.nan if the tolerance is never reached

Plotting

Plot functions based on matplotlib

pythomac.utils.plots.plot_df(df, file_name, x_label=None, y_label=None, column_keyword='', legend=True, tight_ylim=False, hline=None)[source]

Plot a pandas DataFrame as lines with markers. The dataframe index is used for the x-axis. The function can handle a maximum of twelve columns

Parameters:
  • df (pandas.DataFrame) – index serves for x-axis, columns containing a particular keyword are plotted on the y-axis (make sure these columns have the same units)

  • file_name (str) – full path and name of the plot to be created

  • x_label (str) – label for the x-axis

  • y_label (str) – label for the y-axis

  • column_keyword (str) – define a keyword that columns must contain to be plotted. The default ‘’ (empty string) plots all columns.

  • legend (bool) – place a legend (default is True).

  • tight_ylim (bool) – if True, set the y-limits to narrowly embrace the plotted data (with a small margin) instead of anchoring the bottom at zero. Useful when values cluster in a narrow band (e.g., convergence rates around 1.0).

  • hline (float) – if set, draw a dashed horizontal reference line at this y-value (excluded from the legend). The y-limits are widened to keep the line visible.

Returns: