Skip to content

Commit

Permalink
style: tqdm as optional package that when installed, shows a progress…
Browse files Browse the repository at this point in the history
…bar and if not, doesn't show anything
  • Loading branch information
MarkusPic committed Nov 12, 2024
1 parent 4da1308 commit e287186
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 29 deletions.
12 changes: 5 additions & 7 deletions idf_analysis/idf_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

from .definitions import SERIES, METHOD, PARAM
from .in_out import write_yaml, read_yaml
from .little_helpers import duration_steps_readable, minutes_readable
from .little_helpers import duration_steps_readable, minutes_readable, get_progress_bar
from .parameter_formulas import FORMULA_REGISTER, _Formula, register_formulas_to_yaml, LinearFormula
from .sww_utils import year_delta, guess_freq, rain_events, agg_events

Expand Down Expand Up @@ -436,14 +436,12 @@ def evaluate(self, series_kind: str or Literal['partial', 'annual'] = SERIES.PAR
Args:
series_kind (str): which kind of series should be used to evaluate the extreme values.
"""
try:
from tqdm.auto import tqdm
pbar = tqdm(self.duration_steps, desc='Calculating Parameters u and w')
except ModuleNotFoundError:
pbar = self.duration_steps
pbar = get_progress_bar(self.duration_steps, desc='Calculating Parameters u and w')

for duration_integer in pbar:
pbar.set_description(f'Calculating Parameters u and w for duration {duration_integer:0.0f}')
try:
pbar.set_description(f'Calculating Parameters u and w for duration {duration_integer:0.0f}')
except: ...

if series_kind == SERIES.ANNUAL:
x, y = self.annual_series(duration_integer)
Expand Down
25 changes: 8 additions & 17 deletions idf_analysis/idf_class.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import math
import warnings
from pathlib import Path
from webbrowser import open as show_file
import webbrowser

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.optimize import newton
import scipy.optimize as spo
from matplotlib.backends.backend_pdf import PdfPages

from .arg_parser import heavy_rain_parser
from .definitions import *
from .idf_backend import IdfParameters
from .in_out import import_series
from .little_helpers import minutes_readable, height2rate, delta2min, rate2height, frame_looper, event_caption, \
event_caption_ger, duration_steps_readable
event_caption_ger, duration_steps_readable, get_progress_bar
from .plot_helpers import idf_bar_axes
from .sww_utils import guess_freq, rain_events, agg_events, event_duration, resample_rain_series, rain_bar_plot, IdfError
from .synthetic_rainseries import _BlockRain, _EulerRain
Expand Down Expand Up @@ -280,7 +281,7 @@ def get_duration(self, height_of_rainfall, return_period):
Returns:
float: duration in minutes
"""
return newton(lambda d: self.depth_of_rainfall(d, return_period) - height_of_rainfall, x0=1)
return spo.newton(lambda d: self.depth_of_rainfall(d, return_period) - height_of_rainfall, x0=1)

# __________________________________________________________________________________________________________________
def result_table(self, durations=None, return_periods=None, add_names=False, add_unit=True, as_intensity=False):
Expand Down Expand Up @@ -471,7 +472,7 @@ def command_line_tool(cls):
plot_fn = out / f'{prefix}curves_plot.png'
fig.savefig(plot_fn, dpi=260)
plt.close(fig)
show_file(str(plot_fn))
webbrowser.open(str(plot_fn))
print(f'Created the IDF-curves-plot and saved the file as "{plot_fn}".')

# --------------------------------------------------
Expand Down Expand Up @@ -712,10 +713,6 @@ def event_report(self, filename, min_event_rain_sum=25, min_return_period=0.5, d
durations (list[int]): analysed durations
(default: [5, 10, 15, 20, 30, 45, 60, 90, 120, 180, 240, 360, 540, 720, 1080, 1440, 2880, 4320])
"""
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from tqdm.auto import tqdm

events = self.rain_events
self.add_max_return_periods_to_events(events)

Expand All @@ -727,7 +724,7 @@ def event_report(self, filename, min_event_rain_sum=25, min_return_period=0.5, d

pdf = PdfPages(filename)

for _, event in tqdm(main_events.items()):
for _, event in get_progress_bar(main_events.items()):
fig, caption = self.event_plot(event, min_return_period=min_return_period,
unit=unit, column_name=column_name)

Expand All @@ -743,7 +740,6 @@ def event_report(self, filename, min_event_rain_sum=25, min_return_period=0.5, d
pdf.close()

def event_plot(self, event, durations=None, unit='mm', column_name='Precipitation', min_return_period=1., german_caption=False, max_duration=None):
import matplotlib.pyplot as plt
if isinstance(event, pd.Series):
event = event.to_dict()

Expand Down Expand Up @@ -794,18 +790,14 @@ def event_plot(self, event, durations=None, unit='mm', column_name='Precipitatio

####################################################################################################################
def event_return_period_report(self, filename, min_return_period=1):
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from tqdm.auto import tqdm

events = self.rain_events
self.add_max_return_periods_to_events(events)

main_events = events[events[COL.MAX_PERIOD] > min_return_period].sort_values(by=COL.MAX_PERIOD, ascending=False)

pdf = PdfPages(filename)

for _, event in tqdm(main_events.to_dict(orient='index').items()):
for _, event in get_progress_bar(main_events.to_dict(orient='index').items()):
fig, ax = self.return_period_event_figure(event)

# -------------------------------------
Expand All @@ -818,7 +810,6 @@ def event_return_period_report(self, filename, min_return_period=1):
pdf.close()

def return_period_event_figure(self, event):
import matplotlib.pyplot as plt
period_line = self.return_periods_frame[event[COL.START]:event[COL.END]].max()

# period_line[period_line < 0.75] = np.nan
Expand Down
14 changes: 9 additions & 5 deletions idf_analysis/little_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,13 +95,17 @@ def rate2height(rain_flow_rate, duration):
return rain_flow_rate * duration / (1000 / 6)


def get_progress_bar(iterator, desc=None):
try:
from tqdm.auto import tqdm
return tqdm(iterator, desc=desc)
except ModuleNotFoundError:
return iterator


def frame_looper(size, columns, label='return periods'):
if size > 30000: # if > 3 weeks, use a progressbar
try:
from tqdm.auto import tqdm
return tqdm(columns, desc=f'calculating {label} data-frame')
except ModuleNotFoundError:
return columns
return get_progress_bar(columns, desc=f'calculating {label} data-frame')
else:
return columns

Expand Down

0 comments on commit e287186

Please sign in to comment.