-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathplot.py
More file actions
392 lines (351 loc) · 14.4 KB
/
Copy pathplot.py
File metadata and controls
392 lines (351 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
"""
This file is part of CLIMADA.
Copyright (C) 2017 ETH Zurich, CLIMADA contributors listed in AUTHORS.
CLIMADA is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free
Software Foundation, version 3.
CLIMADA is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with CLIMADA. If not, see <https://www.gnu.org/licenses/>.
---
Define Hazard Plotting Methods.
"""
import logging
import matplotlib.pyplot as plt
import numpy as np
import climada.util.plot as u_plot
LOGGER = logging.getLogger(__name__)
# pylint: disable=no-member
class HazardPlot:
"""
Contains all plotting methods of the Hazard class
"""
def plot_rp_intensity(
self,
return_periods=(25, 50, 100, 250),
axis=None,
mask_relative_distance=None,
kwargs_local_exceedance_intensity=None,
**kwargs,
):
"""
Compute and plot hazard exceedance intensity maps for different
return periods. Calls local_exceedance_intensity. For handling large data sets and for
further options, see Notes.
Parameters
----------
return_periods: tuple(int), optional
return periods to consider
axis: matplotlib.axes._subplots.AxesSubplot, optional
axis to use
kwargs_local_exceedance_intensity: dict
Dictionary of keyword arguments for the method hazard.local_exceedance_intensity.
mask_relative_distance: float, optional
Relative distance (with respect to maximal map extent in longitude or latitude) to data
points above which plot should not display values. For instance, to only plot values
at the centroids, use mask_relative_distance=0.01. If None, the plot is not masked.
Default is None.
kwargs: optional
arguments for pcolormesh matplotlib function used in event plots
Returns
-------
axis, inten_stats: matplotlib.axes._subplots.AxesSubplot, np.ndarray
intenstats is return_periods.size x num_centroids
See Also
---------
hazard.local_exceedance_intensity: method to calculate local exceedance frequencies.
Notes
-----
For handling large data, and for more fleixble options in the exceedance
intensity computation and in the plotting, we recommend to use
gdf, title, labels = hazard.local_exceedance_intensity() and
util.plot.plot_from_gdf(gdf, title, labels) instead.
"""
LOGGER.info(
"Some errors in the previous calculation of local exceedance intensities have been "
"corrected, see Hazard.local_exceedance_intensity. To reproduce data with the "
"previous calculation, use CLIMADA v5.0.0 or less."
)
if kwargs_local_exceedance_intensity is None:
kwargs_local_exceedance_intensity = {}
inten_stats, title, column_labels = self.local_exceedance_intensity(
return_periods, **kwargs_local_exceedance_intensity
)
axis = u_plot.plot_from_gdf(
inten_stats,
title,
column_labels,
axis=axis,
mask_relative_distance=mask_relative_distance,
**kwargs,
)
return axis, inten_stats.values[:, 1:].T.astype(float)
def plot_intensity(
self,
event=None,
centr=None,
smooth=True,
axis=None,
adapt_fontsize=True,
mask_relative_distance=None,
**kwargs,
):
"""Plot intensity values for a selected event or centroid.
Parameters
----------
event: int or str, optional
If event > 0, plot intensities of
event with id = event. If event = 0, plot maximum intensity in
each centroid. If event < 0, plot abs(event)-largest event. If
event is string, plot events with that name.
centr: int or tuple, optional
If centr > 0, plot intensity
of all events at centroid with id = centr. If centr = 0,
plot maximum intensity of each event. If centr < 0,
plot abs(centr)-largest centroid where higher intensities
are reached. If tuple with (lat, lon) plot intensity of nearest
centroid.
smooth: bool, optional
Rescale data to RESOLUTIONxRESOLUTION pixels (see constant
in module `climada.util.plot`)
axis: matplotlib.axes._subplots.AxesSubplot, optional
axis to use
mask_relative_distance: float, optional
Relative distance (with respect to maximal map extent in longitude or latitude) to data
points above which plot should not display values. For instance, to only plot values
at the centroids, use mask_relative_distance=0.01. If None, the plot is not masked.
Default is None.
kwargs: optional
arguments for pcolormesh matplotlib function
used in event plots or for plot function used in centroids plots
Returns
-------
matplotlib.axes._subplots.AxesSubplot
Raises
------
ValueError
"""
col_label = f"Intensity ({self.units})"
crs_epsg, _ = u_plot.get_transformation(self.centroids.geometry.crs)
if event is not None:
if isinstance(event, str):
event = self.get_event_id(event)
return self._event_plot(
event,
self.intensity,
col_label,
smooth,
crs_epsg,
axis,
adapt_fontsize=adapt_fontsize,
mask_relative_distance=mask_relative_distance,
**kwargs,
)
if centr is not None:
if isinstance(centr, tuple):
_, _, centr = self.centroids.get_closest_point(centr[0], centr[1])
return self._centr_plot(centr, self.intensity, col_label, axis, **kwargs)
raise ValueError("Provide one event id or one centroid id.")
def plot_fraction(
self,
event=None,
centr=None,
smooth=True,
axis=None,
mask_relative_distance=None,
**kwargs,
):
"""Plot fraction values for a selected event or centroid.
Parameters
----------
event: int or str, optional
If event > 0, plot fraction of event
with id = event. If event = 0, plot maximum fraction in each
centroid. If event < 0, plot abs(event)-largest event. If event
is string, plot events with that name.
centr: int or tuple, optional
If centr > 0, plot fraction
of all events at centroid with id = centr. If centr = 0,
plot maximum fraction of each event. If centr < 0,
plot abs(centr)-largest centroid where highest fractions
are reached. If tuple with (lat, lon) plot fraction of nearest
centroid.
smooth: bool, optional
Rescale data to RESOLUTIONxRESOLUTION pixels (see constant
in module `climada.util.plot`)
axis: matplotlib.axes._subplots.AxesSubplot, optional
axis to use
mask_relative_distance: float, optional
Relative distance (with respect to maximal map extent in longitude or latitude) to data
points above which plot should not display values. For instance, to only plot values
at the centroids, use mask_relative_distance=0.01. If None, the plot is not masked.
Default is None.
kwargs: optional
arguments for pcolormesh matplotlib function
used in event plots or for plot function used in centroids plots
Returns
-------
matplotlib.axes._subplots.AxesSubplot
Raises
------
ValueError
"""
col_label = "Fraction"
if event is not None:
if isinstance(event, str):
event = self.get_event_id(event)
return self._event_plot(
event,
self.fraction,
col_label,
smooth,
axis,
mask_relative_distance=mask_relative_distance,
**kwargs,
)
if centr is not None:
if isinstance(centr, tuple):
_, _, centr = self.centroids.get_closest_point(centr[0], centr[1])
return self._centr_plot(centr, self.fraction, col_label, axis, **kwargs)
raise ValueError("Provide one event id or one centroid id.")
def _event_plot(
self,
event_id,
mat_var,
col_name,
smooth,
crs_espg,
axis=None,
figsize=(9, 13),
adapt_fontsize=True,
mask_relative_distance=None,
**kwargs,
):
"""Plot an event of the input matrix.
Parameters
----------
event_id: int or np.array(int)
If event_id > 0, plot mat_var of
event with id = event_id. If event_id = 0, plot maximum
mat_var in each centroid. If event_id < 0, plot
abs(event_id)-largest event.
mat_var: sparse matrix
Sparse matrix where each row is an event
col_name: sparse matrix
Colorbar label
smooth: bool, optional
smooth plot to plot.RESOLUTIONxplot.RESOLUTION
axis: matplotlib.axes._subplots.AxesSubplot, optional
axis to use
figsize: tuple, optional
figure size for plt.subplots
mask_relative_distance: float, optional
Relative distance (with respect to maximal map extent in longitude or latitude) to data
points above which plot should not display values. For instance, to only plot values
at the centroids, use mask_relative_distance=0.01. If None, the plot is not masked.
Default is None.
kwargs: optional
arguments for pcolormesh matplotlib function
Returns
-------
matplotlib.figure.Figure, matplotlib.axes._subplots.AxesSubplot
"""
if not isinstance(event_id, np.ndarray):
event_id = np.array([event_id])
array_val = list()
l_title = list()
for ev_id in event_id:
if ev_id > 0:
try:
event_pos = np.where(self.event_id == ev_id)[0][0]
except IndexError as err:
raise ValueError(f"Wrong event id: {ev_id}.") from err
im_val = mat_var[event_pos, :].toarray().transpose()
title = (
f"Event ID {self.event_id[event_pos]}: {self.event_name[event_pos]}"
)
elif ev_id < 0:
max_inten = np.asarray(np.sum(mat_var, axis=1)).reshape(-1)
event_pos = np.argpartition(max_inten, ev_id)[ev_id:]
event_pos = event_pos[np.argsort(max_inten[event_pos])][0]
im_val = mat_var[event_pos, :].toarray().transpose()
title = (
f"{np.abs(ev_id)}-largest Event. ID {self.event_id[event_pos]}:"
f" {self.event_name[event_pos]}"
)
else:
im_val = np.max(mat_var, axis=0).toarray().transpose()
title = f"{self.haz_type} max intensity at each point"
array_val.append(im_val)
l_title.append(title)
return u_plot.geo_im_from_array(
array_val,
self.centroids.coord,
col_name,
l_title,
smooth=smooth,
axes=axis,
figsize=figsize,
proj=crs_espg,
adapt_fontsize=adapt_fontsize,
mask_relative_distance=mask_relative_distance,
**kwargs,
)
def _centr_plot(self, centr_idx, mat_var, col_name, axis=None, **kwargs):
"""Plot a centroid of the input matrix.
Parameters
----------
centr_id: int
If centr_id > 0, plot mat_var
of all events at centroid with id = centr_id. If centr_id = 0,
plot maximum mat_var of each event. If centr_id < 0,
plot abs(centr_id)-largest centroid where highest mat_var
are reached.
mat_var: sparse matrix
Sparse matrix where each column represents
a centroid
col_name: sparse matrix
Colorbar label
axis: matplotlib.axes._subplots.AxesSubplot, optional
axis to use
kwargs: optional
arguments for plot matplotlib function
Returns
-------
matplotlib.figure.Figure, matplotlib.axes._subplots.AxesSubplot
"""
coord = self.centroids.coord
if centr_idx > 0:
try:
centr_pos = centr_idx
except IndexError as err:
raise ValueError(f"Wrong centroid id: {centr_idx}.") from err
array_val = mat_var[:, centr_pos].toarray()
title = (
f"Centroid {centr_idx}:"
f" ({np.around(coord[centr_pos, 0], 3)}, {np.around(coord[centr_pos, 1],3)})"
)
elif centr_idx < 0:
max_inten = np.asarray(np.sum(mat_var, axis=0)).reshape(-1)
centr_pos = np.argpartition(max_inten, centr_idx)[centr_idx:]
centr_pos = centr_pos[np.argsort(max_inten[centr_pos])][0]
array_val = mat_var[:, centr_pos].toarray()
title = (
f"{np.abs(centr_idx)}-largest Centroid. {centr_pos}:"
f" ({np.around(coord[centr_pos, 0], 3)}, {np.around(coord[centr_pos, 1], 3)})"
)
else:
array_val = np.max(mat_var, axis=1).toarray()
title = f"{self.haz_type} max intensity at each event"
if not axis:
_, axis = plt.subplots(1)
if "color" not in kwargs:
kwargs["color"] = "b"
axis.set_title(title)
axis.set_xlabel("Event number")
axis.set_ylabel(str(col_name))
axis.plot(range(len(array_val)), array_val, **kwargs)
axis.set_xlim([0, len(array_val)])
return axis