Skip to content

Commit

Permalink
ran flake8
Browse files Browse the repository at this point in the history
  • Loading branch information
Ana Ordonez committed Oct 23, 2023
1 parent d9ecd9e commit 7d6831d
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 37 deletions.
11 changes: 3 additions & 8 deletions pcmdi_metrics/extremes/lib/plot_extremes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,10 @@
import json
import math
import os
import sys

import cartopy
import cartopy.crs as ccrs
import matplotlib.path as mpath
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np
from cartopy.mpl.gridliner import LATITUDE_FORMATTER, LONGITUDE_FORMATTER
from cartopy.mpl.ticker import LatitudeFormatter, LongitudeFormatter

from pcmdi_metrics.graphics import TaylorDiagram
Expand Down Expand Up @@ -110,7 +105,7 @@ def plot_map_cartopy(
if proj == "PlateCarree":
if data_area == "global":
if gridline:
gl = ax.gridlines(alpha=0.5, linestyle="--")
ax.gridlines(alpha=0.5, linestyle="--")
ax.set_xticks([0, 60, 120, 180, 240, 300, 360], crs=ccrs.PlateCarree())
ax.set_yticks([-90, -60, -30, 0, 30, 60, 90], crs=ccrs.PlateCarree())
lon_formatter = LongitudeFormatter(zero_direction_label=True)
Expand All @@ -119,10 +114,10 @@ def plot_map_cartopy(
ax.yaxis.set_major_formatter(lat_formatter)
else:
if gridline:
gl = ax.gridlines(draw_labels=True, alpha=0.5, linestyle="--")
ax.gridlines(draw_labels=True, alpha=0.5, linestyle="--")
elif proj == "Robinson":
if gridline:
gl = ax.gridlines(alpha=0.5, linestyle="--")
ax.gridlines(alpha=0.5, linestyle="--")

# Add title
plt.title(title, pad=15, fontsize=15)
Expand Down
2 changes: 0 additions & 2 deletions pcmdi_metrics/extremes/lib/region_utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
import geopandas as gpd
import numpy as np
import regionmask
import xarray as xr
import xcdat


def check_region_params(shp_path, coords, region_name, col, default):
Expand Down
15 changes: 7 additions & 8 deletions pcmdi_metrics/extremes/lib/return_value.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def compute_rv_from_file(
"Standard error for return value from stationary fit for single realization"
)
else:
desc = "Return value from nonstationary GEV fit for single realization"
desc1 = "Return value from nonstationary GEV fit for single realization"
desc2 = "Standard error for return value from nonstationary fit for single realization"

for ncfile in filelist:
Expand All @@ -41,7 +41,7 @@ def compute_rv_from_file(
os.path.basename(rv_file),
rv_file,
"return_value",
"return value for single realization",
desc1,
)

se_file = outdir + "/" + fname + "_standard_error.nc"
Expand All @@ -50,7 +50,7 @@ def compute_rv_from_file(
os.path.basename(se_file),
se_file,
"standard_error",
"standard error for return value",
desc2,
)

return meta
Expand All @@ -71,7 +71,6 @@ def compute_rv_for_model(
nreal = len(filelist)

ds = xc.open_dataset(filelist[0])
real_list = [os.path.basename(f).split("_")[1] for f in filelist]
units = ds.ANN.attrs["units"]

print("Return value for multiple realizations")
Expand Down Expand Up @@ -274,7 +273,6 @@ def get_dataset_rv(ds, cov_filepath, cov_varname, return_period=20, maxes=True):
lon = len(ds["lon"])
time = len(ds["time"])
dim2 = lat * lon
rep_ind = np.ones((time))

if nonstationary:
return_value = xr.zeros_like(ds)
Expand Down Expand Up @@ -302,7 +300,6 @@ def get_dataset_rv(ds, cov_filepath, cov_varname, return_period=20, maxes=True):
else:
rv_array = np.ones((dim2)) * np.nan
se_array = rv_array.copy()
success = np.zeros((dim2))

# Turn nans to zeros
data = np.nan_to_num(data)
Expand Down Expand Up @@ -485,7 +482,7 @@ def ll(params):
A = np.matmul(np.transpose(grad), vcov)
B = np.matmul(A, grad)
se = np.sqrt(np.diag(B))
except Exception as e:
except Exception:
se = np.ones(np.shape(return_value)) * np.nan

return return_value.squeeze(), se.squeeze()
Expand Down Expand Up @@ -528,13 +525,14 @@ def f(x):
else:
rv = tsorted[count]
break
except: # any issues, set to NaN
except Exception: # any issues, set to NaN
rv = np.nan
break
count += 1
return rv, np.nan


"""
def calc_rv_climex(data, covariate, return_period, nreplicates=1, maxes=True):
# Use climextRemes to get the return value and standard error
# This function exists for easy comparison with the pure Python
Expand Down Expand Up @@ -578,3 +576,4 @@ def calc_rv_climex(data, covariate, return_period, nreplicates=1, maxes=True):
return_value = tmp["returnValue"]
standard_error = tmp["se_returnValue"]
return return_value, standard_error
"""
38 changes: 19 additions & 19 deletions pcmdi_metrics/extremes/lib/utilities.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
#!/usr/bin/env python
import datetime
import glob
import json
import os
import sys

import cdms2
import cdutil
import cftime
import numpy as np
import xarray as xr
import xcdat
import xarray as xr
from pcmdi_utils import land_sea_mask

from pcmdi_metrics.io import xcdat_openxml
Expand Down Expand Up @@ -114,7 +112,7 @@ def verify_output_path(metrics_output_path, case_id):
print("Creating metrics output directory", metrics_output_path)
try:
os.makedirs(metrics_output_path)
except Error as e:
except Exception as e:
print("\nError: Could not create metrics output path", metrics_output_path)
print(e)
print("Exiting.")
Expand All @@ -140,7 +138,14 @@ def set_up_realizations(realization):

def generate_land_sea_mask(data, debug=False):
# generate sftlf if not provided.
"""Commenting out the cdutil version
mask = land_sea_mask.generate_land_sea_mask(data, tool="pcmdi", maskname="sftlf")
mask = mask * 100.0
mask = mask.to_dataset()

return mask


def generate_land_sea_mask_cdutil(data, debug=False):
latArray = data["lat"]
lat = cdms2.createAxis(latArray, id="latitude")
lat.designateLatitude()
Expand All @@ -151,24 +156,19 @@ def generate_land_sea_mask(data, debug=False):
lon.designateLongitude()
lon.units = "degrees_east"

t_grid_cdms2 = cdms2.grid.TransientRectGrid(lat, lon, 'yx', 'uniform')
t_grid_cdms2 = cdms2.grid.TransientRectGrid(lat, lon, "yx", "uniform")
sft = cdutil.generateLandSeaMask(t_grid_cdms2)

if debug:
print('sft:', sft)
print('sft.getAxisList():', sft.getAxisList())
print("sft:", sft)
print("sft.getAxisList():", sft.getAxisList())

# add sft to target grid dataset
t_grid = xr.DataArray(np.array(sft),
coords={'lat': latArray,'lon': lonArray},
dims=["lat", "lon"]).to_dataset(name="sftlf")
t_grid = xr.DataArray(
np.array(sft), coords={"lat": latArray, "lon": lonArray}, dims=["lat", "lon"]
).to_dataset(name="sftlf")
t_grid = t_grid * 100
if debug:
print('t_grid (after sftlf added):', t_grid)
t_grid.to_netcdf('target_grid.nc')
"""
mask = land_sea_mask.generate_land_sea_mask(data, tool="pcmdi", maskname="sftlf")
mask = mask * 100.0
mask = mask.to_dataset()

return mask
print("t_grid (after sftlf added):", t_grid)
t_grid.to_netcdf("target_grid.nc")
return t_grid

0 comments on commit 7d6831d

Please sign in to comment.