Skip to content

Commit

Permalink
Remove attribute-style accesses in hazard module
Browse files Browse the repository at this point in the history
  • Loading branch information
luseverin committed Aug 9, 2024
1 parent f4aa977 commit 9c6c769
Show file tree
Hide file tree
Showing 7 changed files with 240 additions and 240 deletions.
8 changes: 4 additions & 4 deletions climada/hazard/centroids/centr.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,14 +138,14 @@ def geometry(self):
@property
def on_land(self):
""" Get the on_land property """
if self.gdf.on_land.isna().all():
if self.gdf['on_land'].isna().all():
return None
return self.gdf['on_land'].values

@property
def region_id(self):
""" Get the assigned region_id """
if self.gdf.region_id.isna().all():
if self.gdf['region_id'].isna().all():
return None
return self.gdf['region_id'].values

Expand Down Expand Up @@ -479,7 +479,7 @@ def select_mask(self, sel_cen=None, reg_id=None, extent=None):
(self.lat >= lat_min) & (self.lat <= lat_max)
)
return sel_cen

def plot(self, *, axis=None, figsize=(9, 13), **kwargs):
"""Plot centroids geodataframe using geopandas and cartopy plotting functions.
Expand All @@ -494,7 +494,7 @@ def plot(self, *, axis=None, figsize=(9, 13), **kwargs):
positional arguments for geopandas.GeoDataFrame.plot
kwargs : optional
keyword arguments for geopandas.GeoDataFrame.plot
Returns
-------
ax : cartopy.mpl.geoaxes.GeoAxes instance
Expand Down
2 changes: 1 addition & 1 deletion climada/hazard/isimip_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,6 @@ def _read_one_nc(file_name, bbox=None, years=None):
if not years:
return data.sel(lat=slice(bbox[3], bbox[1]), lon=slice(bbox[0], bbox[2]))

time_id = years - int(data.time.units[12:16])
time_id = years - int(data['time'].units[12:16])
return data.sel(lat=slice(bbox[3], bbox[1]), lon=slice(bbox[0], bbox[2]),
time=slice(time_id[0], time_id[1]))
64 changes: 32 additions & 32 deletions climada/hazard/storm_europe.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,18 +334,18 @@ def from_cosmoe_file(cls, fp_file, run_datetime, event_date=None,
.stack(intensity=('y_1', 'x_1'))
considered_dates = stacked['date'].values
stacked = stacked.stack(date_ensemble=('date', 'epsd_1'))
stacked = stacked.where(stacked.VMAX_10M > intensity_thres)
stacked = stacked.where(stacked['VMAX_10M'] > intensity_thres)
stacked = stacked.fillna(0)

# fill in values from netCDF
intensity = sparse.csr_matrix(stacked.VMAX_10M.T)
event_id = np.arange(stacked.date_ensemble.size) + 1
intensity = sparse.csr_matrix(stacked['VMAX_10M'].T)
event_id = np.arange(stacked['date_ensemble'].size) + 1
date = np.repeat(
np.array(datetime64_to_ordinal(considered_dates)),
np.unique(ncdf.epsd_1).size
np.unique(ncdf['epsd_1']).size
)
orig = np.full_like(event_id, False)
orig[(stacked.epsd_1 == 0).values] = True
orig[(stacked['epsd_1'] == 0).values] = True
if description is None:
description = (model_name +
' weather forecast windfield ' +
Expand All @@ -362,10 +362,10 @@ def from_cosmoe_file(cls, fp_file, run_datetime, event_date=None,
date=date,
event_name=[date_i + '_ens' + str(ens_i)
for date_i, ens_i
in zip(date_to_str(date), stacked.epsd_1.values + 1)],
in zip(date_to_str(date), stacked['epsd_1'].values + 1)],
frequency=np.divide(
np.ones_like(event_id),
np.unique(ncdf.epsd_1).size),
np.unique(ncdf['epsd_1']).size),
)

# close netcdf file
Expand Down Expand Up @@ -477,30 +477,30 @@ def from_icon_grib(cls, run_datetime, event_date=None, model_name='icon-eu-eps',
stacked = stacked.where(stacked > intensity_thres)
stacked = stacked.fillna(0)

event_id = np.arange(stacked.date_ensemble.size) + 1
event_id = np.arange(stacked['date_ensemble'].size) + 1
date = np.repeat(
np.array(datetime64_to_ordinal(considered_dates)),
np.unique(stacked.number).size
np.unique(stacked['number']).size
)
orig = np.full_like(event_id, False)
orig[(stacked.number == 1).values] = True
orig[(stacked['number'] == 1).values] = True
if description is None:
description = ('icon weather forecast windfield for run started at ' +
run_datetime.strftime('%Y%m%d%H'))

# Create Hazard
haz = cls(
intensity=sparse.csr_matrix(stacked.gust.T),
intensity=sparse.csr_matrix(stacked['gust'].T),
centroids=cls._centroids_from_nc(nc_centroids_file),
event_id=event_id,
date=date,
orig=orig,
event_name=[date_i + '_ens' + str(ens_i)
for date_i, ens_i
in zip(date_to_str(date), stacked.number.values)],
in zip(date_to_str(date), stacked['number'].values)],
frequency=np.divide(
np.ones_like(event_id),
np.unique(stacked.number).size),
np.unique(stacked['number']).size),
)
haz.check()

Expand All @@ -527,25 +527,25 @@ def _centroids_from_nc(file_name):
ncdf = xr.open_dataset(file_name)
create_meshgrid = True
if hasattr(ncdf, 'latitude'):
lats = ncdf.latitude.data
lons = ncdf.longitude.data
lats = ncdf['latitude'].data
lons = ncdf['longitude'].data
elif hasattr(ncdf, 'lat'):
lats = ncdf.lat.data
lons = ncdf.lon.data
lats = ncdf['lat'].data
lons = ncdf['lon'].data
elif hasattr(ncdf, 'lat_1'):
if len(ncdf.lon_1.shape)>1 & \
(ncdf.lon_1.shape == ncdf.lat_1.shape) \
if len(ncdf['lon_1'].shape)>1 & \
(ncdf['lon_1'].shape == ncdf['lat_1'].shape) \
:
lats = ncdf.lat_1.data.flatten()
lons = ncdf.lon_1.data.flatten()
lats = ncdf['lat_1'].data.flatten()
lons = ncdf['lon_1'].data.flatten()
create_meshgrid = False
else:
lats = ncdf.lat_1.data
lons = ncdf.lon_1.data
lats = ncdf['lat_1'].data
lons = ncdf['lon_1'].data
elif hasattr(ncdf, 'clat'):
lats = ncdf.clat.data
lons = ncdf.clon.data
if ncdf.clat.attrs['units']=='radian':
lats = ncdf['clat'].data
lons = ncdf['clon'].data
if ncdf['clat'].attrs['units']=='radian':
lats = np.rad2deg(lats)
lons = np.rad2deg(lons)
create_meshgrid = False
Expand Down Expand Up @@ -713,16 +713,16 @@ def plot_ssi(self, full_area=False):
'orig': self.orig,
})
ssi_freq = ssi_freq.sort_values('ssi', ascending=False)
ssi_freq['freq_cum'] = np.cumsum(ssi_freq.freq)
ssi_freq['freq_cum'] = np.cumsum(ssi_freq['freq'])

ssi_hist = ssi_freq.loc[ssi_freq.orig].copy()
ssi_hist.freq = ssi_hist.freq * self.orig.size / self.orig.sum()
ssi_hist['freq_cum'] = np.cumsum(ssi_hist.freq)
ssi_hist = ssi_freq.loc[ssi_freq['orig']].copy()
ssi_hist['freq'] = ssi_hist['freq'] * self.orig.size / self.orig.sum()
ssi_hist['freq_cum'] = np.cumsum(ssi_hist['freq'])

# plotting
fig, axs = plt.subplots()
axs.plot(ssi_freq.freq_cum, ssi_freq.ssi, label='All Events')
axs.scatter(ssi_hist.freq_cum, ssi_hist.ssi,
axs.plot(ssi_freq['freq_cum'], ssi_freq['ssi'], label='All Events')
axs.scatter(ssi_hist['freq_cum'], ssi_hist['ssi'],
color='red', label='Historic Events')
axs.legend()
axs.set_xlabel('Exceedance Frequency [1/a]')
Expand Down
2 changes: 1 addition & 1 deletion climada/hazard/tc_clim_change.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ def calc_scale_knutson(ref_year=2050, rcp_scenario=45):
rad_force = pd.read_excel(TOT_RADIATIVE_FORCE)
years = np.array([year for year in rad_force.columns if isinstance(year, int)])
rad_rcp = np.array([int(float(sce[sce.index('.') - 1:sce.index('.') + 2]) * 10)
for sce in rad_force.Scenario if isinstance(sce, str)])
for sce in rad_force['Scenario'] if isinstance(sce, str)])

# mean values for Knutson values
rf_vals = np.argwhere(rad_rcp == rcp_knu).reshape(-1)[0]
Expand Down
Loading

0 comments on commit 9c6c769

Please sign in to comment.