Skip to content

Commit de9f532

Browse files
Merge pull request #92 from MET-OM/namespaces
New organization of imports and namespaces
2 parents 73f40ff + 4b4ff1e commit de9f532

20 files changed

+473
-600
lines changed

metocean_stats/maps/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,5 @@
55
"""
66

77
from ..stats.general import *
8-
from ..stats.dir import *
98
from ..stats.extreme import *
109
from .maps import *

metocean_stats/maps/maps.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -259,8 +259,11 @@ def plot_mean_air_temperature_map(product='NORA3', title='empty title', set_exte
259259
The figure object containing the plot.
260260
"""
261261
if product == 'NORA3':
262-
ds = xr.open_dataset(f'https://thredds.met.no/thredds/dodsC/nora3_subset_stats/atm/CF_Overall_Mean_AirTemperature2m_1991_2020.nc')
263-
#standard_lon, standard_lat, _ = get_transformed_coordinates(ds, 'x', 'y', projection_type='lambert_conformal')
262+
ds = xr.open_dataset('https://thredds.met.no/thredds/dodsC/nora3_subset_stats/atm/CF_Overall_Mean_AirTemperature2m_1991_2020.nc')
263+
## The code `standard_lon` appears to be a variable name in Python. It is not assigned any
264+
# value or operation in the provided snippet, so it is not doing anything specific in this
265+
# context.
266+
standard_lon, standard_lat, _ = get_transformed_coordinates(ds, 'x', 'y', projection_type='lambert_conformal')
264267
hs_flat = ds['air_temperature_2m'].isel(time=0).values.flatten()
265268
lon_flat = ds['longitude'].values.flatten()
266269
lat_flat = ds['latitude'].values.flatten()

metocean_stats/plots/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
"""
66

77
from ..stats.general import *
8-
from ..stats.dir import *
98
from ..stats.extreme import *
109
from .dir import *
1110
from .extreme import *

metocean_stats/plots/dir.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
import matplotlib.pyplot as plt
22
import numpy as np
3-
import pandas as pd
43
import windrose
5-
import matplotlib.cm as cm
6-
import os
74

85
def rose(data,
96
var_dir,
@@ -103,7 +100,7 @@ def monthly_var_rose(data,
103100
dic_intensity[months[m_idx]].append(intensity.iloc[i])
104101
dic_direction[months[m_idx]].append(direction.iloc[i])
105102

106-
if single_figure==False:
103+
if single_figure is False:
107104
for j in range(12):
108105
fig = plt.figure(figsize = (8,8))
109106
ax = fig.add_subplot(111, projection="windrose")

metocean_stats/plots/extreme.py

Lines changed: 89 additions & 101 deletions
Large diffs are not rendered by default.

metocean_stats/plots/general.py

Lines changed: 49 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
1-
import os
2-
import math
31
import numpy as np
42
import pandas as pd
53
import seaborn as sns
4+
import scipy.stats as st
65
import matplotlib.pyplot as plt
7-
import scipy.stats as stats
6+
87
from matplotlib.dates import MonthLocator, DateFormatter
9-
import calendar
10-
from math import floor,ceil
11-
from ..stats.general import *
12-
from ..tables.general import *
8+
import matplotlib.ticker as mticker
9+
import matplotlib.patches as mpatches
10+
from cycler import cycler
11+
12+
from .. import stats
13+
from .. import tables
1314

1415

1516
def plot_scatter_diagram(data: pd.DataFrame, var1: str, step_var1: float, var2: str, step_var2: float, output_file):
@@ -21,7 +22,7 @@ def plot_scatter_diagram(data: pd.DataFrame, var1: str, step_var1: float, var2:
2122
outputfile: name of output file with extrensition e.g., png, eps or pdf
2223
"""
2324

24-
sd = calculate_scatter(data, var1, step_var1, var2, step_var2)
25+
sd = tables.calculate_scatter(data, var1, step_var1, var2, step_var2)
2526

2627
# Convert to percentage
2728
tbl = sd.values
@@ -67,31 +68,24 @@ def plot_scatter_diagram(data: pd.DataFrame, var1: str, step_var1: float, var2:
6768

6869
def plot_pdf_all(data, var, bins=70, output_file='pdf_all.png'): #pdf_all(data, bins=70)
6970

70-
import matplotlib.pyplot as plt
71-
from scipy.stats import expon
72-
from scipy.stats import genextreme
73-
from scipy.stats import gumbel_r
74-
from scipy.stats import lognorm
75-
from scipy.stats import weibull_min
76-
7771
data = data[var].values
7872

7973
x=np.linspace(min(data),max(data),100)
8074

81-
param = weibull_min.fit(data) # shape, loc, scale
82-
pdf_weibull = weibull_min.pdf(x, param[0], loc=param[1], scale=param[2])
75+
param = st.weibull_min.fit(data) # shape, loc, scale
76+
pdf_weibull = st.weibull_min.pdf(x, param[0], loc=param[1], scale=param[2])
8377

84-
param = expon.fit(data) # loc, scale
85-
pdf_expon = expon.pdf(x, loc=param[0], scale=param[1])
78+
# param = expon.fit(data) # loc, scale
79+
# pdf_expon = expon.pdf(x, loc=param[0], scale=param[1])
8680

87-
param = genextreme.fit(data) # shape, loc, scale
88-
pdf_gev = genextreme.pdf(x, param[0], loc=param[1], scale=param[2])
81+
param = st.genextreme.fit(data) # shape, loc, scale
82+
pdf_gev = st.genextreme.pdf(x, param[0], loc=param[1], scale=param[2])
8983

90-
param = gumbel_r.fit(data) # loc, scale
91-
pdf_gumbel = gumbel_r.pdf(x, loc=param[0], scale=param[1])
84+
param = st.gumbel_r.fit(data) # loc, scale
85+
pdf_gumbel = st.gumbel_r.pdf(x, loc=param[0], scale=param[1])
9286

93-
param = lognorm.fit(data) # shape, loc, scale
94-
pdf_lognorm = lognorm.pdf(x, param[0], loc=param[1], scale=param[2])
87+
param = st.lognorm.fit(data) # shape, loc, scale
88+
pdf_lognorm = st.lognorm.pdf(x, param[0], loc=param[1], scale=param[2])
9589

9690
fig, ax = plt.subplots(1, 1)
9791
#ax.plot(x, pdf_expon, label='pdf-expon')
@@ -127,7 +121,7 @@ def strconv(name:str):
127121
return mapping[name]
128122
else: return name
129123

130-
if type(percentiles)==str: return strconv(percentiles)
124+
if type(percentiles) is str: return strconv(percentiles)
131125
else: return [strconv(p) for p in percentiles]
132126

133127
def plot_monthly_stats(data: pd.DataFrame,
@@ -285,7 +279,7 @@ def plot_directional_stats(data: pd.DataFrame, var: str, step_var: float, var_di
285279
plot_directional_stats(data, 'hs', 0.1, 'Pdir', title='Directional Wave Statistics', output_file='directional_hs_stats.png')
286280
"""
287281
fig, ax = plt.subplots()
288-
cumulative_percentage = table_directional_non_exceedance(data,var,step_var,var_dir)
282+
cumulative_percentage = tables.table_directional_non_exceedance(data,var,step_var,var_dir)
289283
for i in show:
290284
cumulative_percentage.loc[i][:-1].plot(marker = 'o')
291285
#cumulative_percentage.loc['Maximum'][:-1].plot(marker = 'o')
@@ -300,7 +294,7 @@ def plot_directional_stats(data: pd.DataFrame, var: str, step_var: float, var_di
300294
return fig
301295

302296
def plot_monthly_weather_window(data: pd.DataFrame, var: str,threshold=5, window_size=12,add_table=True, output_file: str = 'monthly_weather_window_plot.png'):
303-
results_df = calculate_monthly_weather_window(data=data, var=var, threshold=threshold, window_size=window_size)
297+
results_df = stats.calculate_monthly_weather_window(data=data, var=var, threshold=threshold, window_size=window_size)
304298
# Plot the results
305299
fig, ax = plt.subplots(figsize=(12, 6))
306300
results_df.T.plot(marker='o')
@@ -335,39 +329,40 @@ def plot_monthly_weather_window(data: pd.DataFrame, var: str,threshold=5, window
335329

336330
return fig, table
337331

338-
339-
def plot_monthly_max_mean_min(df,var='T2m',out_file='plot_monthly_max_min_min.png'):
340-
out = sort_by_month(df)
341-
df2 = pd.DataFrame()
342-
months = calendar.month_name[1:] # eliminate the first insane one
343-
df2['month']=[x[:3] for x in months] # get the three first letters
344-
df2['Min']=[np.min(out[m][var]) for m in out]
345-
df2['Mean']=[np.mean(out[m][var]) for m in out]
346-
df2['Max']=[np.max(out[m][var]) for m in out]
332+
# This function doesn't work, because sort_by_month is not defined.
333+
# Therefore it's commented out. Maybe plot_monthly_stats above is a replacement.
334+
335+
# def plot_monthly_max_mean_min(df,var='T2m',out_file='plot_monthly_max_min_min.png'):
336+
# out = sort_by_month(df)
337+
# df2 = pd.DataFrame()
338+
# months = calendar.month_name[1:] # eliminate the first insane one
339+
# df2['month']=[x[:3] for x in months] # get the three first letters
340+
# df2['Min']=[np.min(out[m][var]) for m in out]
341+
# df2['Mean']=[np.mean(out[m][var]) for m in out]
342+
# df2['Max']=[np.max(out[m][var]) for m in out]
347343

348-
plt.plot(df2['month'],df2['Min'])
349-
plt.plot(df2['month'],df2['Mean'])
350-
plt.plot(df2['month'],df2['Max'])
351-
plt.ylabel('Temperature [℃]')
352-
plt.grid()
353-
plt.savefig(out_file,dpi=100,facecolor='white',bbox_inches='tight')
344+
# plt.plot(df2['month'],df2['Min'])
345+
# plt.plot(df2['month'],df2['Mean'])
346+
# plt.plot(df2['month'],df2['Max'])
347+
# plt.ylabel('Temperature [℃]')
348+
# plt.grid()
349+
# plt.savefig(out_file,dpi=100,facecolor='white',bbox_inches='tight')
354350

355-
return df2
351+
# return df2
356352

357353

358354
def plot_profile_stats(data,var=['W10','W50','W80','W100','W150'], z=[10, 50, 80, 100, 150],reverse_yaxis=False, output_file='stats_profile.png'):
359-
import matplotlib.ticker as ticker
360-
df = table_profile_stats(data=data, var=var, z=z, output_file=None)
355+
df = tables.table_profile_stats(data=data, var=var, z=z, output_file=None)
361356
df = df.drop(['Std.dev', 'Max Speed Event'],axis=1)
362357
fig, ax = plt.subplots()
363358
plt.yticks(z) # Set yticks to be the values in z
364-
ax.yaxis.set_major_locator(ticker.MultipleLocator(int(max(z)/4))) # Set major y-ticks at intervals of 10
359+
ax.yaxis.set_major_locator(mticker.MultipleLocator(int(max(z)/4))) # Set major y-ticks at intervals of 10
365360

366361
for column in df.columns[1:]:
367362
plt.plot(df[column][1:],z,marker='.', label=column)
368363
plt.ylabel('z[m]')
369364
plt.xlabel('[m/s]')
370-
if reverse_yaxis == True:
365+
if reverse_yaxis:
371366
plt.gca().invert_yaxis()
372367
plt.legend()
373368
plt.grid(True)
@@ -387,15 +382,12 @@ def plot_profile_monthly_stats(
387382
reverse_yaxis=True,
388383
output_file='table_profile_monthly_stats.png',
389384
include_year=True):
390-
import matplotlib.pyplot as plt
391-
import matplotlib.ticker as ticker
392-
from cycler import cycler
393385

394386
# Custom color cycle
395387
custom_cycler = cycler(color=['b', 'g', 'r', 'c', 'm', 'y', 'k'])
396388

397389
# Get the data
398-
df = table_profile_monthly_stats(data=data, var=var, z=z, method=method, output_file=None, rounding=None)
390+
df = tables.table_profile_monthly_stats(data=data, var=var, z=z, method=method, output_file=None, rounding=None)
399391
# Create a plot
400392
fig, ax = plt.subplots()
401393
# Set the custom color cycle
@@ -404,7 +396,7 @@ def plot_profile_monthly_stats(
404396
plt.yticks(z)
405397

406398
# Set major y-ticks at intervals of max(z)/4
407-
ax.yaxis.set_major_locator(ticker.MultipleLocator(int(max(z)/4)))
399+
ax.yaxis.set_major_locator(mticker.MultipleLocator(int(max(z)/4)))
408400

409401
# Only plot specified variables.
410402
if months == []:
@@ -434,7 +426,7 @@ def plot_profile_monthly_stats(
434426

435427

436428
def plot_tidal_levels(data, var='tide',start_time=None , end_time=None ,output_file='tidal_levels.png'):
437-
df = table_tidal_levels(data=data, var=var, output_file=None)
429+
df = tables.table_tidal_levels(data=data, var=var, output_file=None)
438430
if start_time and end_time is None:
439431
data = data[var]
440432
else:
@@ -469,13 +461,13 @@ def plot_nb_hours_below_threshold(df,var='hs',thr_arr=(np.arange(0.05,20.05,0.05
469461
# 2) var: a string
470462
# 3) thr_arr: list of thresholds (should be a lot for smooth curve)
471463
# 4) String with filename without extension
472-
nbhr_arr=nb_hours_below_threshold(df,var,thr_arr)
464+
nbhr_arr=stats.nb_hours_below_threshold(df,var,thr_arr)
473465
years=df.index.year.to_numpy()
474466
years_unique=np.unique(years)
475467
yr1=int(years_unique[0])
476468
yr2=int(years_unique[-1])
477469
del df,years,years_unique
478-
from matplotlib.patches import Patch
470+
479471
fig, ax = plt.subplots(figsize=(10, 8))
480472
ax.fill_between(thr_arr,np.min(nbhr_arr,axis=1),np.max(nbhr_arr,axis=1),color='lightgray')
481473
ax.plot(thr_arr,np.mean(nbhr_arr,axis=1),linewidth=2,color='k')
@@ -486,7 +478,7 @@ def plot_nb_hours_below_threshold(df,var='hs',thr_arr=(np.arange(0.05,20.05,0.05
486478
ax.set_ylabel('Number of hours',fontsize=20)
487479
ax.tick_params(axis='both', which='major', labelsize=18)
488480
ax.set_title('Mean number of hours per year with '+var+' < threshold\n'+str(yr1)+'-'+str(yr2),fontsize=20)
489-
legend_elements = [Patch(facecolor='lightgray', edgecolor=None, label='Min-Max range')]
481+
legend_elements = [mpatches.Patch(facecolor='lightgray', edgecolor=None, label='Min-Max range')]
490482
ax.legend(handles=legend_elements, loc='lower right', prop={'size': 20})
491483
plt.savefig(output_file, dpi=150, bbox_inches='tight')
492484
plt.close()

0 commit comments

Comments
 (0)