From 7d6831d6421c4f98683e5c13f924b57ebb87ec1e Mon Sep 17 00:00:00 2001 From: Ana Ordonez Date: Mon, 23 Oct 2023 10:03:20 -0700 Subject: [PATCH] ran flake8 --- pcmdi_metrics/extremes/lib/plot_extremes.py | 11 ++---- .../extremes/lib/region_utilities.py | 2 - pcmdi_metrics/extremes/lib/return_value.py | 15 ++++---- pcmdi_metrics/extremes/lib/utilities.py | 38 +++++++++---------- 4 files changed, 29 insertions(+), 37 deletions(-) diff --git a/pcmdi_metrics/extremes/lib/plot_extremes.py b/pcmdi_metrics/extremes/lib/plot_extremes.py index e345670f6..a8d74358c 100644 --- a/pcmdi_metrics/extremes/lib/plot_extremes.py +++ b/pcmdi_metrics/extremes/lib/plot_extremes.py @@ -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 @@ -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) @@ -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) diff --git a/pcmdi_metrics/extremes/lib/region_utilities.py b/pcmdi_metrics/extremes/lib/region_utilities.py index 69b585d51..d2f599a55 100644 --- a/pcmdi_metrics/extremes/lib/region_utilities.py +++ b/pcmdi_metrics/extremes/lib/region_utilities.py @@ -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): diff --git a/pcmdi_metrics/extremes/lib/return_value.py b/pcmdi_metrics/extremes/lib/return_value.py index bf7b022ce..376d00b9c 100644 --- a/pcmdi_metrics/extremes/lib/return_value.py +++ b/pcmdi_metrics/extremes/lib/return_value.py @@ -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: @@ -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" @@ -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 @@ -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") @@ -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) @@ -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) @@ -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() @@ -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 @@ -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 +""" diff --git a/pcmdi_metrics/extremes/lib/utilities.py b/pcmdi_metrics/extremes/lib/utilities.py index 6cac6d756..6328fe375 100644 --- a/pcmdi_metrics/extremes/lib/utilities.py +++ b/pcmdi_metrics/extremes/lib/utilities.py @@ -1,7 +1,5 @@ #!/usr/bin/env python import datetime -import glob -import json import os import sys @@ -9,8 +7,8 @@ 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 @@ -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.") @@ -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() @@ -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