Skip to content

Commit d94a6e9

Browse files
authored
Merge pull request #8 from ClimateImpactLab/flake8fixes
Flake8fixes
2 parents 55ed71b + a6881b8 commit d94a6e9

36 files changed

+215
-179
lines changed

.github/workflows/pythonpackage.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ on:
44
pull_request:
55
push:
66
branches:
7-
- main
7+
- flake8fixes
88

99
jobs:
1010

dscim/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,6 @@ def menu_factory(self, menu_key, sector, kwargs=None):
201201
climate_options.update(**climate_kwargs)
202202

203203
# Set up
204-
dir_name = os.path.dirname(os.path.abspath(__file__))
205204
sector_config = self.param_dict["sectors"].get(sector)
206205
sector_config.update({k: v for k, v in global_options.items()})
207206
sector_config.update(

dscim/cli.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ def cli(config_file, menu_order, log_level, local, pro=False):
7878
path_to_scheduler = os.path.join(os.getenv("SCRATCH"), "scheduler.json")
7979
client = Client(scheduler_file=path_to_scheduler)
8080

81+
print(logger, client)
82+
8183
if menu_order == "":
8284
waiter.execute_order()
8385
else:
@@ -86,12 +88,9 @@ def cli(config_file, menu_order, log_level, local, pro=False):
8688

8789
menus = global_parameters["menu_type"]
8890
discounts = global_parameters["discounting_type"]
89-
course = global_parameters["course"]
9091
pulse_year = waiter.param_dict["climate"]["pulse_year"]
9192

92-
for menu, discount, sector, level in itertools.product(
93-
menus, discounts, sectors, levels
94-
):
93+
for menu, discount, sector in itertools.product(menus, discounts, sectors):
9594
obj = waiter.menu_factory(
9695
menu_key=menu,
9796
sector=sector,

dscim/diagnostics/batch_maps.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def make_map(
3131
# create figure
3232
fig, ax = plt.subplots(figsize=figsize, facecolor="white")
3333

34-
if color_max == None:
34+
if color_max is None:
3535
max_val = max(abs(df[colname].max()), abs(df[colname].min()))
3636
color_min, color_max = -max_val, max_val
3737

@@ -54,15 +54,15 @@ def make_map(
5454
fig.text(0.5, 0.08, title, ha="center", va="center", rotation=0, fontsize=18)
5555

5656
ax.set_axis_off()
57-
if maxmin == True:
57+
if maxmin:
5858
plt.annotate(
5959
text=f"min: {df[colname].min()}, max: {df[colname].max()}",
6060
xy=location,
6161
xycoords="axes fraction",
6262
fontsize=10,
6363
)
6464

65-
if save_path != None:
65+
if save_path is not None:
6666
os.makedirs(save_path, exist_ok=True)
6767
fig.savefig(f"{save_path}/{name_file}", dpi=200, bbox_inches="tight")
6868

@@ -119,22 +119,22 @@ def batch_maps(
119119
if gcm == "mean":
120120
damages = damages.weighted(weights).mean(dim="gcm")
121121
elif gcm == "ce":
122-
damages = c_equivalence(risk.damages, dims=["gcm"])
122+
damages = c_equivalence(damages, dims=["gcm"])
123123
else:
124124
damages = damages.sel({"gcm": gcm})
125125

126126
merged = xr.merge([damages, gdppc]).to_dataframe().reset_index()
127127

128128
shp_file = gpd.read_file(
129-
f"/shares/gcp/climate/_spatial_data/world-combo-new-nytimes/new_shapefile.shp"
129+
"/shares/gcp/climate/_spatial_data/world-combo-new-nytimes/new_shapefile.shp"
130130
)
131131

132132
data = shp_file.merge(merged, left_on=["hierid"], right_on=["region"])
133133

134134
# generate variables of interest
135135
data["damages_inc_share"] = data["damages"] / data["gdppc"] * 100
136136

137-
if plot == False:
137+
if not plot:
138138
return data
139139
else:
140140

dscim/diagnostics/compare_sccs.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def compare_sccs(
2525
this = this.sel(
2626
gas="CO2_Fossil", model="IIASA GDP", rcp="ssp370", drop=True
2727
).rename({"simulation": "runid"})
28-
except:
28+
except KeyError:
2929
# for rff calculations
3030
if ("simulation" in this.dims) and (len(this.simulation) == 1):
3131
this = this.sel(simulation=1, drop=True)
@@ -37,9 +37,9 @@ def compare_sccs(
3737
else:
3838
this = this.quantile(quantiles, "runid")
3939

40-
try:
40+
if "discrate" in this.dims:
4141
this = this.sel(discrate=0.02, drop=True)
42-
except:
42+
else:
4343
pass
4444

4545
this = this.sel(weitzman_parameter=wp, drop=True)

dscim/diagnostics/crayola_plots.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def crayola_plots(
106106
["year", "ssp", "rcp", "model", "temp_bins"], as_index=False
107107
)[damages_col_name].mean()
108108
else:
109-
raise NotImplemented(f"{var} is not a defined option")
109+
raise NotImplementedError(f"{var} is not a defined option")
110110

111111
with sns.plotting_context("paper", font_scale=1.3):
112112
sns.set_style("white")
@@ -180,4 +180,4 @@ def crayola_plots(
180180
title = f"{var}_{recipe.discounting_type}_{recipe.NAME}_{recipe.sector}_{ssp}.png"
181181
g.savefig(os.path.join(save_plot_path, title))
182182

183-
return (global_damages, global_consumption)
183+
return (global_damages, recipe.global_consumption)

dscim/diagnostics/damage_function.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def get_legacy(sector, filepath, scale):
5555
coefs = temps.join(coefs).reset_index().rename(columns={"index": "year"})
5656

5757
# Predict y_hat
58-
coefs[f"y_hat"] = (
58+
coefs["y_hat"] = (
5959
coefs.cons + coefs.anomaly * coefs.beta_1 + coefs.anomaly**2 * coefs.beta_2
6060
)
6161

@@ -136,7 +136,7 @@ def damage_function(
136136
)
137137

138138
# subset
139-
if subset_dict != None:
139+
if subset_dict is not None:
140140
for col, val in subset_dict.items():
141141
points_file = points_file.loc[points_file[col].isin(val)]
142142
fit_file = fit_file.sel(subset_dict)
@@ -174,7 +174,7 @@ def damage_function(
174174
)
175175

176176
# grab legacy function if passed
177-
if legacy != None:
177+
if legacy is not None:
178178
fit["legacy"] = get_legacy(sector, filepath=legacy[0], scale=legacy[1])
179179
fit["legacy"] = fit["legacy"].loc[fit["legacy"].year == year]
180180
fit["legacy"]["y_hat_scaled"] = fit["legacy"]["y_hat"].apply(
@@ -195,7 +195,7 @@ def damage_function(
195195

196196
print(f"{recipe} : # of points is {len(points[recipe])}")
197197

198-
if scatter == True:
198+
if scatter:
199199

200200
sns.scatterplot(
201201
data=points[recipe]
@@ -207,7 +207,7 @@ def damage_function(
207207
]
208208
.sort_values("hue"),
209209
x=x_var,
210-
y=f"damages_scaled",
210+
y="damages_scaled",
211211
hue="hue",
212212
palette=palette,
213213
s=6,
@@ -230,7 +230,7 @@ def damage_function(
230230
ax=ax[0][i],
231231
)
232232

233-
if legacy != None:
233+
if legacy is not None:
234234

235235
sns.lineplot(
236236
data=fit["legacy"],
@@ -243,19 +243,19 @@ def damage_function(
243243

244244
ax[0][i].set_xlabel(x_var)
245245
ax[0][i].set_title(f"Recipe: {recipe}")
246-
if attributes == True:
246+
if attributes:
247247
ax[0][i].annotate(
248248
attrs[recipe], (0.0, -0.1), xycoords="axes fraction", fontsize=6
249249
)
250250

251-
ltext = "\n paper damage function = grey dotted" if legacy != None else ""
251+
ltext = "\n paper damage function = grey dotted" if legacy is not None else ""
252252
fig.suptitle(
253253
f"{sector}: {discounting} discounting \n Damage functions in {year} {ltext}"
254254
)
255255

256256
ax[0][0].set_ylabel(f'Damages in {"{:.0e}".format(scale)} 2019 USD')
257257

258-
if save_path != None:
258+
if save_path is not None:
259259

260260
os.makedirs(save_path, exist_ok=True)
261261
plt.savefig(f"{save_path}/{sector}_{discounting}_{year}_damage_function.pdf")

dscim/diagnostics/damage_inc_share_boxplots.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import xarray as xr
22
import pandas as pd
3-
import os, sys, yaml
3+
import os
4+
import sys
5+
import yaml
46

57
USER = os.getenv("USER")
68
from dscim.utils.functions import get_model_weights, US_territories
@@ -34,7 +36,7 @@ def income_boxplot(
3436
delta_var
3537
]
3638

37-
if USA == True:
39+
if USA:
3840
# subset US data
3941
US_IRs = [
4042
i for i in socioec.region.values if any(j in i for j in US_territories())
@@ -104,7 +106,7 @@ def income_boxplot(
104106
}
105107
)
106108

107-
bxp = ax.bxp(stats, showmeans=True, meanline=False)
109+
ax.bxp(stats, showmeans=True, meanline=False)
108110
ax.set_ylabel(f"{year} damages as a share of present-day GDP")
109111
ax.set_xlabel("Decile of present-day GDP per capita")
110112
ax.spines["top"].set_visible(False)

dscim/diagnostics/discount_rates.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
import pandas as pd
33
import seaborn as sns
44
import matplotlib.pyplot as plt
5-
import os, sys
5+
import os
6+
import sys
67

78

89
def plot_implicit_rates(

dscim/diagnostics/equity_risk_premiums.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import os, sys
1+
import os
2+
import sys
23
import numpy as np
34
import pandas as pd
45
import xarray as xr
@@ -169,7 +170,7 @@ def mumbai_plots(
169170
for ax in g.axes:
170171
ax.set_ylabel("2019 PPP-adjusted USD")
171172
ax.set_xlabel("GMST")
172-
if (premium == "equity") or (title == False):
173+
if (premium == "equity") or (not title):
173174
ax.set_title("")
174175

175176
title_items = "_".join([ssp, model, str(year)]).replace(" ", "_")

0 commit comments

Comments
 (0)