Skip to content

Commit

Permalink
Merge pull request #248 from ArtesiaWater/codacy
Browse files Browse the repository at this point in the history
codacy suggestions
  • Loading branch information
dbrakenhoff authored Aug 25, 2023
2 parents 1961dfd + b25a209 commit 9161091
Show file tree
Hide file tree
Showing 22 changed files with 71 additions and 63 deletions.
12 changes: 6 additions & 6 deletions nlmod/dims/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ def extrapolate_ds(ds, mask=None):
# all of the model cells are is inside the known area
return ds
if mask.all():
raise (Exception("The model only contains NaNs"))
raise (ValueError("The model only contains NaNs"))
if "gridtype" in ds.attrs and ds.gridtype == "vertex":
x = ds.x.data
y = ds.y.data
Expand Down Expand Up @@ -453,10 +453,10 @@ def _get_vertex_grid_ds(
coords = {"layer": layers, "y": y, "x": x}
dims = ("layer", "icell2d")
ds = xr.Dataset(
data_vars=dict(
top=(dims[1:], top),
botm=(dims, botm),
),
data_vars={
"top": (dims[1:], top),
"botm": (dims, botm),
},
coords=coords,
attrs=attrs,
)
Expand Down Expand Up @@ -606,7 +606,7 @@ def get_ds(

resample._set_angrot_attributes(extent, xorigin, yorigin, angrot, attrs)
x, y = resample.get_xy_mid_structured(attrs["extent"], delr, delc)
coords = dict(x=x, y=y, layer=layer)
coords = {"x": x, "y": y, "layer": layer}
if angrot != 0.0:
affine = resample.get_affine_mod_to_world(attrs)
xc, yc = affine * np.meshgrid(x, y)
Expand Down
10 changes: 7 additions & 3 deletions nlmod/dims/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,9 @@ def refine(
ds_has_rotation = "angrot" in ds.attrs and ds.attrs["angrot"] != 0.0
if model_coordinates:
if not ds_has_rotation:
raise (Exception("The supplied shapes need to be in realworld coordinates"))
raise (
ValueError("The supplied shapes need to be in realworld coordinates")
)
elif ds_has_rotation:
affine_matrix = get_affine_world_to_mod(ds).to_shapely()

Expand All @@ -394,7 +396,9 @@ def refine(
fname, geom_type, level = refinement_feature
if not model_coordinates and ds_has_rotation:
raise (
Exception("Converting files to model coordinates not supported")
NotImplementedError(
"Converting files to model coordinates not supported"
)
)
g.add_refinement_features(fname, geom_type, level, layers=[0])
elif len(refinement_feature) == 2:
Expand Down Expand Up @@ -1418,7 +1422,7 @@ def gdf_to_grid(
The GeoDataFrame with the geometries per grid-cell.
"""
if ml is None and ix is None:
raise (Exception("Either specify ml or ix"))
raise (ValueError("Either specify ml or ix"))

if ml is not None:
if isinstance(ml, xr.Dataset):
Expand Down
4 changes: 2 additions & 2 deletions nlmod/dims/layers.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def calculate_thickness(ds, top="top", bot="botm"):
if ds[top].shape[-1] == ds[bot].shape[-1]:
# top is only top of first layer
thickness = xr.zeros_like(ds[bot])
for lay in range(len(thickness)):
for lay, _ in enumerate(thickness):
if lay == 0:
thickness[lay] = ds[top] - ds[bot][lay]
else:
Expand Down Expand Up @@ -242,7 +242,7 @@ def split_layers_ds(
layers_org = layers.copy()
# add extra layers (keep the original ones for now, as we will copy data first)
for lay0 in split_dict:
for i in range(len(split_dict[lay0])):
for i, _ in enumerate(split_dict[lay0]):
index = layers.index(lay0)
layers.insert(index, lay0 + "_" + str(i + 1))
layers_org.insert(index, lay0)
Expand Down
12 changes: 6 additions & 6 deletions nlmod/dims/resample.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,13 +203,13 @@ def _set_angrot_attributes(extent, xorigin, yorigin, angrot, attrs):
extent[0] = 0.0
extent[1] = extent[1] - xorigin
elif extent[0] != 0.0:
raise (Exception("Either extent[0] or xorigin needs to be 0.0"))
raise (ValueError("Either extent[0] or xorigin needs to be 0.0"))
if yorigin == 0.0:
yorigin = extent[2]
extent[2] = 0.0
extent[3] = extent[3] - yorigin
elif extent[2] != 0.0:
raise (Exception("Either extent[2] or yorigin needs to be 0.0"))
raise (ValueError("Either extent[2] or yorigin needs to be 0.0"))
attrs["extent"] = extent
attrs["xorigin"] = xorigin
attrs["yorigin"] = yorigin
Expand Down Expand Up @@ -436,7 +436,7 @@ def dim_to_regular_dim(da, dims, z):
# just use griddata
z = griddata(points, da.data, xi, method=method)
dims = ["y", "x"]
coords = dict(x=ds.x, y=ds.y)
coords = {"x": ds.x, "y": ds.y}
return xr.DataArray(z, dims=dims, coords=coords)


Expand Down Expand Up @@ -481,7 +481,7 @@ def structured_da_to_ds(da, ds, method="average", nodata=np.NaN):
if hasattr(rasterio.enums.Resampling, method):
resampling = getattr(rasterio.enums.Resampling, method)
else:
raise (Exception(f"Unknown resample method: {method}"))
raise ValueError(f"Unknown resample method: {method}")
# fill crs if it is None for da or ds
if ds.rio.crs is None and da.rio.crs is None:
logger.info("No crs in da and ds. Assuming ds and da are both in EPSG:28992")
Expand Down Expand Up @@ -528,11 +528,11 @@ def structured_da_to_ds(da, ds, method="average", nodata=np.NaN):
da_temp = da_temp.assign_coords(x=x, y=y)

mask = ds["area"] == area
da_out.loc[dict(icell2d=mask)] = da_temp.sel(
da_out.loc[{"icell2d": mask}] = da_temp.sel(
y=ds["y"][mask], x=ds["x"][mask]
)
else:
raise (Exception(f"Gridtype {ds.gridtype} not supported"))
raise (NotImplementedError(f"Gridtype {ds.gridtype} not supported"))

# some stuff is added by the reproject_match function that should not be there
added_coords = set(da_out.coords) - set(ds.coords)
Expand Down
6 changes: 5 additions & 1 deletion nlmod/gwf/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,11 @@ def get_head_at_point(head, x, y, ds=None, gi=None, drop_nan_layers=True):
if "icell2d" in head.dims:
if gi is None:
if ds is None:
raise (Exception("Please supply either gi or ds for a vertex grid"))
raise (
ValueError(
"Please supply either gi (GridIntersect) or ds for a vertex grid"
)
)
gi = flopy.utils.GridIntersect(modelgrid_from_ds(ds), method="vertex")
icelld2 = gi.intersect(Point(x, y))["cellids"][0]
head_point = head[:, :, icelld2]
Expand Down
2 changes: 1 addition & 1 deletion nlmod/gwf/recharge.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def ds_to_evt(gwf, ds, pname="evt", nseg=1, surface=None, depth=None, **kwargs):
"""
assert nseg == 1, "More than one evaporation segment not yet supported"
if "surf_rate_specified" in kwargs:
raise (Exception("surf_rate_specified not yet supported"))
raise (NotImplementedError("surf_rate_specified not yet supported"))
if surface is None:
logger.info("Setting evaporation surface to 1 meter below top")
surface = ds["top"] - 1.0
Expand Down
12 changes: 6 additions & 6 deletions nlmod/gwf/surface_water.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import logging
import warnings
from functools import partial

import flopy
import numpy as np
Expand Down Expand Up @@ -461,12 +462,12 @@ def build_spd(
mask = (stage > botm_cell) & (idomain_cell > 0)
if not mask.any():
raise (
Exception("rbot and stage are below the bottom of the model")
ValueError("rbot and stage are below the bottom of the model")
)
lays = [np.where(mask)[0][0]]
conds = [cond]
else:
raise (Exception(f"Method {layer_method} unknown"))
raise (ValueError(f"Method {layer_method} unknown"))

auxlist = []
if "aux" in row:
Expand Down Expand Up @@ -519,7 +520,7 @@ def add_info_to_gdf(
measure = overlap.length
else:
msg = f"Unsupported geometry type: {geom_type}"
raise (Exception(msg))
raise TypeError(msg)

if np.any(measure.sum() > min_total_overlap * measure_org):
# take the largest
Expand Down Expand Up @@ -806,7 +807,7 @@ def get_gdf(ds=None, extent=None, fname_ahn=None, ahn=None, buffer=0.0):
"""
if extent is None:
if ds is None:
raise (Exception("Please supply either ds or extent to get_gdf"))
raise (ValueError("Please supply either ds or extent to get_gdf"))
extent = get_extent_polygon(ds)
gdf = bgt.get_bgt(extent)
if fname_ahn is not None:
Expand Down Expand Up @@ -851,7 +852,6 @@ def add_min_ahn_to_gdf(gdf, ahn, buffer=0.0, column="ahn_min"):
A GeoDataFrame with surface water features, with an added column containing the
minimum surface level height near the features.
"""
from functools import partial

from geocube.api.core import make_geocube
from geocube.rasterize import rasterize_image
Expand Down Expand Up @@ -1001,7 +1001,7 @@ def gdf_to_seasonal_pkg(
elif pkg == "GHB":
cl = flopy.mf6.ModflowGwfghb
else:
raise (Exception(f"Unknown package: {pkg}"))
raise (ValueError(f"Unknown package: {pkg}"))
package = cl(
gwf,
stress_period_data={0: spd},
Expand Down
1 change: 0 additions & 1 deletion nlmod/plot/flopy.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import os
from functools import partial

import flopy
Expand Down
2 changes: 1 addition & 1 deletion nlmod/plot/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ def data_array(da, ds=None, ax=None, rotated=False, edgecolor=None, **kwargs):
ax = plt.gca()
if "icell2d" in da.dims:
if ds is None:
raise (Exception("Supply model dataset (ds) for grid information"))
raise (ValueError("Supply model dataset (ds) for grid information"))
if isinstance(ds, list):
patches = ds
else:
Expand Down
4 changes: 2 additions & 2 deletions nlmod/plot/plotutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ def colorbar_inside(
cax.yaxis.tick_left()
cax.yaxis.set_label_position("left")
if isinstance(bbox_labels, bool) and bbox_labels is True:
bbox_labels = dict(facecolor="w", alpha=0.5)
bbox_labels = {"facecolor": "w", "alpha": 0.5}
if isinstance(bbox_labels, dict):
for label in cb.ax.yaxis.get_ticklabels():
label.set_bbox(bbox_labels)
Expand All @@ -239,7 +239,7 @@ def title_inside(
ax = plt.gca()
if isinstance(bbox, bool):
if bbox:
bbox = dict(facecolor="w", alpha=0.5)
bbox = {"facecolor": "w", "alpha": 0.5}
else:
bbox = None
return ax.text(
Expand Down
4 changes: 2 additions & 2 deletions nlmod/read/ahn.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def get_ahn(ds=None, identifier="AHN4_DTM_5m", method="average", extent=None):
elif version == 4:
ahn_ds_raw = get_ahn4(extent, identifier=identifier)
else:
raise (Exception(f"Unknown ahn-version: {version}"))
raise (ValueError(f"Unknown ahn-version: {version}"))

ahn_ds_raw = ahn_ds_raw.drop_vars("band")

Expand Down Expand Up @@ -98,7 +98,7 @@ def _infer_url(identifier=None):
if "ahn3" in identifier:
url = "https://service.pdok.nl/rws/ahn3/wcs/v1_0?service=wcs"
else:
ValueError(f"unknown identifier -> {identifier}")
raise ValueError(f"unknown identifier -> {identifier}")

return url

Expand Down
10 changes: 5 additions & 5 deletions nlmod/read/bgt.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import json
import time
import xml.etree.ElementTree as ET
from io import BytesIO
from xml.etree import ElementTree
from zipfile import ZipFile

import geopandas as gpd
Expand Down Expand Up @@ -246,7 +246,7 @@ def read_label(child, d):
d["label_plaatsingspunt"] = Point(xy)
d["label_hoek"] = float(positie.find(f"{ns}hoek").text)

tree = ET.parse(fname)
tree = ElementTree.parse(fname)
ns = "{http://www.opengis.net/citygml/2.0}"
data = []
for com in tree.findall(f".//{ns}cityObjectMember"):
Expand Down Expand Up @@ -286,7 +286,7 @@ def read_label(child, d):
elif child[0].tag == f"{ns}Point":
d[key] = Point(read_point(child[0]))
else:
raise (Exception((f"Unsupported tag: {child[0].tag}")))
raise (ValueError((f"Unsupported tag: {child[0].tag}")))
elif key == "nummeraanduidingreeks":
ns = "{http://www.geostandaarden.nl/imgeo/2.1}"
nar = child.find(f"{ns}Nummeraanduidingreeks").find(
Expand All @@ -301,11 +301,11 @@ def read_label(child, d):
elif child[0].tag == f"{ns}Curve":
d[key] = LineString(read_curve(child[0]))
else:
raise (Exception((f"Unsupported tag: {child[0].tag}")))
raise (ValueError((f"Unsupported tag: {child[0].tag}")))
elif key == "openbareRuimteNaam":
read_label(child, d)
else:
raise (Exception((f"Unknown key: {key}")))
raise (KeyError((f"Unknown key: {key}")))
data.append(d)
if len(data) > 0:
if geometry is None:
Expand Down
2 changes: 1 addition & 1 deletion nlmod/read/boundaries.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def get_provinces(source="cbs", **kwargs):
gdf = webservices.wfs(url, layer, **kwargs)
gdf = gdf.set_index("statnaam")
else:
raise (Exception(f"Unknown source: {source}"))
raise (ValueError(f"Unknown source: {source}"))
return gdf


Expand Down
2 changes: 1 addition & 1 deletion nlmod/read/brp.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def get_percelen(extent, year=None):
gdf = gdf.set_index("fuuid")
else:
if year < 2009 or year > 2021:
raise (Exception("Only data available from 2009 up to and including 2021"))
raise (ValueError("Only data available from 2009 up to and including 2021"))
url = f"https://services.arcgis.com/nSZVuSZjHpEZZbRo/ArcGIS/rest/services/BRP_{year}/FeatureServer"
gdf = webservices.arcrest(url, 0, extent=extent)
return gdf
2 changes: 1 addition & 1 deletion nlmod/read/geotop.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def get_lithok_colors():
8: (216, 163, 32),
9: (95, 95, 255),
}
colors = {key: tuple([x / 255 for x in colors[key]]) for key in colors}
colors = {key: tuple([x / 255 for x in color]) for key, color in colors.items()}
return colors


Expand Down
2 changes: 1 addition & 1 deletion nlmod/read/jarkus.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ def get_jarkus_tilenames(extent, kind="jarkus"):
elif kind == "vaklodingen":
url = "http://opendap.deltares.nl/thredds/dodsC/opendap/rijkswaterstaat/vaklodingen/catalog.nc"
else:
raise (Exception(f"Unsupported kind: {kind}"))
raise (ValueError(f"Unsupported kind: {kind}"))

ds_jarkus_catalog = xr.open_dataset(url)
ew_x = ds_jarkus_catalog["projectionCoverage_x"].values
Expand Down
4 changes: 2 additions & 2 deletions nlmod/read/knmi.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def get_recharge(ds, method="linear", most_common_station=False):
loc_sel = locations.loc[(locations["stn_ev24"] == stn)]
_add_ts_to_ds(ts, loc_sel, "evaporation", ds_out)
else:
raise (Exception(f"Unknown method: {method}"))
raise (ValueError(f"Unknown method: {method}"))
for datavar in ds_out:
ds_out[datavar].attrs["source"] = "KNMI"
ds_out[datavar].attrs["date"] = dt.datetime.now().strftime("%Y%m%d")
Expand Down Expand Up @@ -145,7 +145,7 @@ def _add_ts_to_ds(timeseries, loc_sel, variable, ds):
# there will be NaN's, which we fill by backfill
model_recharge = model_recharge.fillna(method="bfill")
if model_recharge.isna().any():
raise (Exception("There are NaN-values in {variable}"))
raise (ValueError(f"There are NaN-values in {variable}."))

# add data to ds
values = np.repeat(model_recharge.values[:, np.newaxis], loc_sel.shape[0], 1)
Expand Down
10 changes: 5 additions & 5 deletions nlmod/read/meteobase.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,11 +231,11 @@ def read_meteobase_ascii(
da = DataArray(
data_array,
dims=["time", "y", "x"],
coords=dict(
time=times,
x=x,
y=y,
),
coords={
"time": times,
"x": x,
"y": y,
},
attrs=meta,
name=foldername,
)
Expand Down
2 changes: 1 addition & 1 deletion nlmod/read/regis.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ def get_regis(

if len(ds.x) == 0 or len(ds.y) == 0:
msg = "No data found. Please supply valid extent in the Netherlands in RD-coordinates"
raise (Exception(msg))
raise (ValueError(msg))

# make sure layer names are regular strings
ds["layer"] = ds["layer"].astype(str)
Expand Down
4 changes: 2 additions & 2 deletions nlmod/read/rws.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,8 @@ def calculate_sea_coverage(
# determine the closest x and y in the dtm grid
x_sea = dtm.x.sel(x=xy_sea[0], method="nearest")
y_sea = dtm.y.sel(y=xy_sea[1], method="nearest")
dtm.loc[dict(x=x_sea, y=y_sea)] = dtm.min()
seed.loc[dict(x=x_sea, y=y_sea)] = dtm.min()
dtm.loc[{"x": x_sea, "y": y_sea}] = dtm.min()
seed.loc[{"x": x_sea, "y": y_sea}] = dtm.min()
seed = seed.data

footprint = np.ones((3, 3), dtype="bool")
Expand Down
Loading

0 comments on commit 9161091

Please sign in to comment.