-
Notifications
You must be signed in to change notification settings - Fork 154
Expand file tree
/
Copy pathimpact.py
More file actions
2421 lines (2158 loc) · 90.4 KB
/
impact.py
File metadata and controls
2421 lines (2158 loc) · 90.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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
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 Impact and ImpactFreqCurve classes.
"""
__all__ = ["ImpactFreqCurve", "Impact"]
import copy
import csv
import datetime as dt
import logging
import warnings
from collections.abc import Collection
from dataclasses import dataclass, field
from itertools import zip_longest
from pathlib import Path
from typing import Any, Iterable, Union
import contextily as ctx
import geopandas as gpd
import h5py
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import xlsxwriter
from deprecation import deprecated
from matplotlib.colors import Normalize
from pandas.api.types import is_string_dtype
from pyproj import CRS as pyprojCRS
from rasterio.crs import CRS as rasterioCRS # pylint: disable=no-name-in-module
from scipy import sparse
from tqdm import tqdm
import climada.util.coordinates as u_coord
import climada.util.dates_times as u_dt
import climada.util.interpolation as u_interp
import climada.util.plot as u_plot
from climada.entity import Exposures
from climada.util.constants import CMAP_IMPACT, DEF_CRS, DEF_FREQ_UNIT
from climada.util.select import get_attributes_with_matching_dimension
from climada.util.value_representation import safe_divide
LOGGER = logging.getLogger(__name__)
class Impact:
"""Impact definition. Compute from an entity (exposures and impact
functions) and hazard.
Attributes
----------
event_id : np.array
id (>0) of each hazard event
event_name : list
list name of each hazard event
date : np.array
date if events as integer date corresponding to the
proleptic Gregorian ordinal, where January 1 of year 1 has
ordinal 1 (ordinal format of datetime library)
coord_exp : np.array
exposures coordinates [lat, lon] (in degrees)
crs : str
WKT string of the impact's crs
eai_exp : np.array
expected impact for each exposure within a period of 1/frequency_unit
at_event : np.array
impact for each hazard event
frequency : np.array
frequency of event
frequency_unit : str
frequency unit used (given by hazard), default is '1/year'
aai_agg : float
average impact within a period of 1/frequency_unit (aggregated)
unit : str
value unit used (given by exposures unit)
imp_mat : sparse.csr_matrix
matrix num_events x num_exp with impacts.
only filled if save_mat is True in calc()
haz_type : str
the hazard type of the hazard
"""
def __init__(
self,
event_id=None,
event_name=None,
date=None,
frequency=None,
frequency_unit=DEF_FREQ_UNIT,
coord_exp=None,
crs=DEF_CRS,
eai_exp=None,
at_event=None,
tot_value=0.0,
aai_agg=0.0,
unit="",
imp_mat=None,
haz_type="",
):
"""
Init Impact object
Parameters
----------
event_id : np.array, optional
id (>0) of each hazard event
event_name : list, optional
list name of each hazard event
date : np.array, optional
date if events as integer date corresponding to the
proleptic Gregorian ordinal, where January 1 of year 1 has
ordinal 1 (ordinal format of datetime library)
frequency : np.array, optional
frequency of event impact for each hazard event
frequency_unit : np.array, optional
frequency unit, default: '1/year'
coord_exp : np.array, optional
exposures coordinates [lat, lon] (in degrees)
crs : Any, optional
Coordinate reference system. CRS instances from ``pyproj`` and ``rasterio``
will be transformed into WKT. Other types are not handled explicitly.
eai_exp : np.array, optional
expected impact for each exposure within a period of 1/frequency_unit
at_event : np.array, optional
impact for each hazard event
tot_value : float, optional
total exposure value affected
aai_agg : float, optional
average impact within a period of 1/frequency_unit (aggregated)
unit : str, optional
value unit used (given by exposures unit)
imp_mat : sparse.csr_matrix, optional
matrix num_events x num_exp with impacts.
haz_type : str, optional
the hazard type
"""
self.haz_type = haz_type
self.event_id = np.array([], int) if event_id is None else event_id
self.event_name = [] if event_name is None else event_name
self.date = np.array([], int) if date is None else date
self.coord_exp = np.array([], float) if coord_exp is None else coord_exp
self.crs = crs.to_wkt() if isinstance(crs, (pyprojCRS, rasterioCRS)) else crs
self.eai_exp = np.array([], float) if eai_exp is None else eai_exp
self.at_event = np.array([], float) if at_event is None else at_event
self.frequency = np.array([], float) if frequency is None else frequency
self.frequency_unit = frequency_unit
self._tot_value = tot_value
self.aai_agg = aai_agg
self.unit = unit
if len(self.event_id) != len(self.event_name):
raise AttributeError(
f"Hazard event ids {len(self.event_id)} and event names"
f" {len(self.event_name)} are not of the same length"
)
if len(self.event_id) != len(self.date):
raise AttributeError(
f"Hazard event ids {len(self.event_id)} and event dates"
f" {len(self.date)} are not of the same length"
)
if len(self.event_id) != len(self.frequency):
raise AttributeError(
f"Hazard event ids {len(self.event_id)} and event frequency"
f" {len(self.frequency)} are not of the same length"
)
if len(self.event_id) != len(self.at_event):
raise AttributeError(
f"Number of hazard event ids {len(self.event_id)} is different "
f"from number of at_event values {len(self.at_event)}"
)
if len(self.coord_exp) != len(self.eai_exp):
raise AttributeError(
"Number of exposures points is different from"
"number of eai_exp values"
)
if imp_mat is not None:
self.imp_mat = imp_mat
if self.imp_mat.size > 0:
if len(self.event_id) != self.imp_mat.shape[0]:
raise AttributeError(
f"The number of rows {imp_mat.shape[0]} of the impact "
+ f"matrix is inconsistent with the number {len(event_id)} "
"of hazard events."
)
if len(self.coord_exp) != self.imp_mat.shape[1]:
raise AttributeError(
f"The number of columns {imp_mat.shape[1]} of the impact"
+ f" matrix is inconsistent with the number {len(coord_exp)}"
" exposures points."
)
else:
self.imp_mat = sparse.csr_matrix(np.empty((0, 0)))
def calc(
self, exposures, impact_funcs, hazard, save_mat=False, assign_centroids=True
):
"""This function is deprecated, use ``ImpactCalc.impact`` instead."""
LOGGER.warning(
"The use of Impact().calc() is deprecated."
" Use ImpactCalc().impact() instead."
)
from climada.engine.impact_calc import ( # pylint: disable=import-outside-toplevel
ImpactCalc,
)
impcalc = ImpactCalc(exposures, impact_funcs, hazard)
self.__dict__ = impcalc.impact(
save_mat=save_mat, assign_centroids=assign_centroids
).__dict__
# TODO: new name
@classmethod
def from_eih(cls, exposures, hazard, at_event, eai_exp, aai_agg, imp_mat=None):
"""
Set Impact attributes from precalculated impact metrics.
.. versionchanged:: 3.3
The ``impfset`` argument was removed.
Parameters
----------
exposures : climada.entity.Exposures
exposure used to compute imp_mat
impfset: climada.entity.ImpactFuncSet
impact functions set used to compute imp_mat
hazard : climada.Hazard
hazard used to compute imp_mat
at_event : np.array
impact for each hazard event
eai_exp : np.array
expected impact for each exposure within a period of 1/frequency_unit
aai_agg : float
average impact within a period of 1/frequency_unit (aggregated)
imp_mat : sparse.csr_matrix, optional
matrix num_events x num_exp with impacts.
Default is None (empty sparse csr matrix).
Returns
-------
climada.engine.impact.Impact
impact with all risk metrics set based on the given impact matrix
"""
return cls(
event_id=hazard.event_id,
event_name=hazard.event_name,
date=hazard.date,
frequency=hazard.frequency,
frequency_unit=hazard.frequency_unit,
coord_exp=np.stack([exposures.latitude, exposures.longitude], axis=1),
crs=exposures.crs,
unit=exposures.value_unit,
tot_value=exposures.centroids_total_value(hazard),
eai_exp=eai_exp,
at_event=at_event,
aai_agg=aai_agg,
imp_mat=imp_mat if imp_mat is not None else sparse.csr_matrix((0, 0)),
haz_type=hazard.haz_type,
)
@property
def tot_value(self):
"""Return the total exposure value close to a hazard
.. deprecated:: 3.3
Use :py:meth:`climada.entity.exposures.base.Exposures.affected_total_value`
instead.
"""
LOGGER.warning(
"The Impact.tot_value attribute is deprecated."
"Use Exposures.affected_total_value to calculate the affected "
"total exposure value based on a specific hazard intensity "
"threshold"
)
return self._tot_value
@tot_value.setter
def tot_value(self, value):
"""Set the total exposure value close to a hazard"""
LOGGER.warning(
"The Impact.tot_value attribute is deprecated."
"Use Exposures.affected_total_value to calculate the affected "
"total exposure value based on a specific hazard intensity "
"threshold"
)
self._tot_value = value
def transfer_risk(self, attachment, cover):
"""Compute the risk transfer for the full portfolio. This is the risk
of the full portfolio summed over all events. For each
event, the transfered risk amounts to the impact minus the attachment
(but maximally equal to the cover) multiplied with the probability
of the event.
Parameters
----------
attachment : float
attachment per event for entire portfolio.
cover : float
cover per event for entire portfolio.
Returns
-------
transfer_at_event : np.array
risk transfered per event
transfer_aai_agg : float
average risk within a period of 1/frequency_unit, transfered
"""
transfer_at_event = np.minimum(np.maximum(self.at_event - attachment, 0), cover)
transfer_aai_agg = np.sum(transfer_at_event * self.frequency)
return transfer_at_event, transfer_aai_agg
def residual_risk(self, attachment, cover):
"""Compute the residual risk after application of insurance
attachment and cover to entire portfolio. This is the residual risk
of the full portfolio summed over all events. For each
event, the residual risk is obtained by subtracting the transfered risk
from the trom the total risk per event.
of the event.
Parameters
----------
attachment : float
attachment per event for entire portfolio.
cover : float
cover per event for entire portfolio.
Returns
-------
residual_at_event : np.array
residual risk per event
residual_aai_agg : float
average residual risk within a period of 1/frequency_unit
See also
--------
transfer_risk: compute the transfer risk per portfolio.
"""
transfer_at_event, _ = self.transfer_risk(attachment, cover)
residual_at_event = np.maximum(self.at_event - transfer_at_event, 0)
residual_aai_agg = np.sum(residual_at_event * self.frequency)
return residual_at_event, residual_aai_agg
# TODO: rewrite and deprecate method
def calc_risk_transfer(self, attachment, cover):
"""Compute traaditional risk transfer over impact. Returns new impact
with risk transfer applied and the insurance layer resulting
Impact metrics.
Parameters
----------
attachment : float
(deductible)
cover : float
Returns
-------
climada.engine.impact.Impact
"""
new_imp = copy.deepcopy(self)
if attachment or cover:
imp_layer = np.minimum(np.maximum(new_imp.at_event - attachment, 0), cover)
new_imp.at_event = np.maximum(new_imp.at_event - imp_layer, 0)
new_imp.aai_agg = np.sum(new_imp.at_event * new_imp.frequency)
# next values are no longer valid
new_imp.eai_exp = np.array([])
new_imp.coord_exp = np.array([])
new_imp.imp_mat = sparse.csr_matrix((0, 0))
# insurance layer metrics
risk_transfer = copy.deepcopy(new_imp)
risk_transfer.at_event = imp_layer
risk_transfer.aai_agg = np.sum(imp_layer * new_imp.frequency)
return new_imp, risk_transfer
return new_imp, Impact()
def impact_per_year(self, all_years=True, year_range=None):
"""Calculate yearly impact from impact data.
Note: the impact in a given year is summed over all events.
Thus, the impact in a given year can be larger than the
total affected exposure value.
Parameters
----------
all_years : boolean, optional
return values for all years between first and
last year with event, including years without any events.
Default: True
year_range : tuple or list with integers, optional
start and end year
Returns
-------
year_set : dict
Key=year, value=Summed impact per year.
"""
if year_range is None:
year_range = []
orig_year = np.array([dt.datetime.fromordinal(date).year for date in self.date])
if orig_year.size == 0 and len(year_range) == 0:
return dict()
if orig_year.size == 0 or (len(year_range) > 0 and all_years):
years = np.arange(min(year_range), max(year_range) + 1)
elif all_years:
years = np.arange(min(orig_year), max(orig_year) + 1)
else:
years = np.array(sorted(np.unique(orig_year)))
if not len(year_range) == 0:
years = years[years >= min(year_range)]
years = years[years <= max(year_range)]
year_set = dict()
for year in years:
year_set[year] = sum(self.at_event[orig_year == year])
return year_set
def impact_at_reg(self, agg_regions=None):
"""Aggregate impact on given aggregation regions. This method works
only if Impact.imp_mat was stored during the impact calculation.
Parameters
----------
agg_regions : np.array, list (optional)
The length of the array must equal the number of centroids in exposures.
It reports what macro-regions these centroids belong to. For example,
asuming there are three centroids and agg_regions = ['A', 'A', 'B']
then impact of the first and second centroids will be assigned to
region A, whereas impact from the third centroid will be assigned
to area B. If no aggregation regions are passed, the method aggregates
impact at the country (admin_0) level.
Default is None.
Returns
-------
pd.DataFrame
Contains the aggregated data per event.
Rows: Hazard events. Columns: Aggregation regions.
"""
if np.prod(self.imp_mat.shape) == 0:
raise ValueError(
"The aggregated impact cannot be computed as no Impact.imp_mat was "
"stored during the impact calculation"
)
if agg_regions is None:
agg_regions = u_coord.country_to_iso(
u_coord.get_country_code(self.coord_exp[:, 0], self.coord_exp[:, 1])
)
agg_regions = np.asanyarray(agg_regions)
agg_reg_unique = np.unique(agg_regions)
at_reg_event = np.hstack(
[
self.imp_mat[:, np.where(agg_regions == reg)[0]].sum(1)
for reg in agg_reg_unique
]
)
at_reg_event = pd.DataFrame(
at_reg_event, columns=agg_reg_unique, index=self.event_id
)
return at_reg_event
def calc_impact_year_set(self, all_years=True, year_range=None):
"""This function is deprecated, use Impact.impact_per_year instead."""
LOGGER.warning(
"The use of Impact.calc_impact_year_set is deprecated."
"Use Impact.impact_per_year instead."
)
return self.impact_per_year(all_years=all_years, year_range=year_range)
def local_exceedance_impact(
self,
return_periods=(25, 50, 100, 250),
method="interpolate",
min_impact=0,
log_frequency=True,
log_impact=True,
bin_decimals=None,
):
"""Compute local exceedance impact for given return periods. The default method
is fitting the ordered impacts per centroid to the corresponding cummulated
frequency with linear interpolation on log-log scale.
Parameters
----------
return_periods : array_like
User-specified return periods for which the exceedance intensity should be calculated
locally (at each centroid). Defaults to (25, 50, 100, 250).
method : str
Method to interpolate to new return periods. Currently available are "interpolate",
"extrapolate", "extrapolate_constant" and "stepfunction". If set to "interpolate",
return periods outside the range of the Impact object's observed local return periods
will be assigned NaN. If set to "extrapolate_constant" or "stepfunction",
return periods larger than the Impact object's observed local return periods will be
assigned the largest local impact, and return periods smaller than the Impact object's
observed local return periods will be assigned 0. If set to "extrapolate", local
exceedance impacts will be extrapolated (and interpolated). The extrapolation to
large return periods uses the two highest impacts of the centroid and their return
periods and extends the interpolation between these points to the given return period
(similar for small return periods). Defauls to "interpolate".
min_impact : float, optional
Minimum threshold to filter the impact. Defaults to 0.
log_frequency : bool, optional
If set to True, (cummulative) frequency values are converted to log scale before
inter- and extrapolation. Defaults to True.
log_impact : bool, optional
If set to True, impact values are converted to log scale before
inter- and extrapolation. Defaults to True.
bin_decimals : int, optional
Number of decimals to group and bin impact values. Binning results in smoother (and
coarser) interpolation and more stable extrapolation. For more details and sensible
values for bin_decimals, see Notes. If None, values are not binned. Defaults to None.
Returns
-------
gdf : gpd.GeoDataFrame
GeoDataFrame containing exeedance impacts for given return periods. Each column
corresponds to a return period, each row corresponds to a centroid. Values
in the gdf correspond to the exceedance impact for the given centroid and
return period
label : str
GeoDataFrame label, for reporting and plotting
column_label : function
Column-label-generating function, for reporting and plotting
See Also
--------
util.interpolation.preprocess_and_interpolate_ev :
inter- and extrapolation method
Notes
-------
If an integer bin_decimals is given, the impact values are binned according to their
bin_decimals decimals, and their corresponding frequencies are summed. This binning leads
to a smoother (and coarser) interpolation, and a more stable extrapolation. For instance,
if bin_decimals=1, the two values 12.01 and 11.97 with corresponding frequencies 0.1 and
0.2 are combined to a value 12.0 with frequency 0.3. The default bin_decimals=None results
in not binning the values.
E.g., if your impact range from 1 to 100, you could use bin_decimals=1, if your
impact range from 1e6 to 1e9, you could use bin_decimals=-5, if your impact
range from 0.0001 to .01, you could use bin_decimals=5.
"""
LOGGER.info(
"Computing exceedance impact map for return periods: %s", return_periods
)
if self.imp_mat.size == 0:
raise ValueError(
"Attribute imp_mat is empty. Recalculate Impact"
"instance with parameter save_mat=True"
)
# check frequency unit
return_period_unit = u_dt.convert_frequency_unit_to_time_unit(
self.frequency_unit
)
# calculate local exceedance impact
test_frequency = 1 / np.array(return_periods)
exceedance_impact = np.full(
(self.imp_mat.shape[1], len(test_frequency)),
np.nan if method == "interpolate" else 0.0,
)
nonzero_centroids = np.where(self.imp_mat.getnnz(axis=0) > 0)[0]
if not len(nonzero_centroids) == 0:
exceedance_impact[nonzero_centroids, :] = np.array(
[
u_interp.preprocess_and_interpolate_ev(
test_frequency,
None,
self.frequency,
self.imp_mat.getcol(i_centroid).toarray().flatten(),
log_frequency=log_frequency,
log_values=log_impact,
value_threshold=min_impact,
method=method,
y_asymptotic=0.0,
bin_decimals=bin_decimals,
)
for i_centroid in nonzero_centroids
]
)
# create the output GeoDataFrame
gdf = gpd.GeoDataFrame(
geometry=gpd.points_from_xy(self.coord_exp[:, 1], self.coord_exp[:, 0]),
crs=self.crs,
)
col_names = [f"{ret_per}" for ret_per in return_periods]
gdf[col_names] = exceedance_impact
# create label and column_label
label = f"Impact ({self.unit})"
def column_label(column_names):
return [
f"Return Period: {col} {return_period_unit}" for col in column_names
]
return gdf, label, column_label
@deprecated(
details="The use of Impact.local_exceedance_imp is deprecated. Use "
"Impact.local_exceedance_impact instead. Some errors in the previous calculation "
"in Impact.local_exceedance_imp have been corrected. To reproduce data with the "
"previous calculation, use CLIMADA v5.0.0 or less."
)
def local_exceedance_imp(self, return_periods=(25, 50, 100, 250)):
"""This function is deprecated, use Impact.local_exceedance_impact instead."""
return (
self.local_exceedance_impact(return_periods)[0]
.values[:, 1:]
.T.astype(float)
)
def local_return_period(
self,
threshold_impact=(1000.0, 10000.0),
method="interpolate",
min_impact=0,
log_frequency=True,
log_impact=True,
bin_decimals=None,
):
"""Compute local return periods for given threshold impacts. The default method
is fitting the ordered impacts per centroid to the corresponding cummulated
frequency with linear interpolation on log-log scale.
Parameters
----------
threshold_impact : array_like
User-specified impact values for which the return period should be calculated
locally (at each centroid). Defaults to (1000, 10000)
method : str
Method to interpolate to new threshold impacts. Currently available are
"interpolate", "extrapolate", "extrapolate_constant" and "stepfunction". If set to
"interpolate", threshold impacts outside the range of the Impact object's local
impacts will be assigned NaN. If set to "extrapolate_constant" or
"stepfunction", threshold impacts larger than the Impacts object's local
impacts will be assigned NaN, and threshold impacts smaller than the Impact
object's local impacts will be assigned the smallest observed local return period.
If set to "extrapolate", local return periods will be extrapolated (and interpolated).
The extrapolation to large threshold impacts uses the two highest impacts of
the centroid and their return periods and extends the interpolation between these
points to the given threshold imapct (similar for small large threshold impacts).
Defaults to "interpolate".
min_impacts : float, optional
Minimum threshold to filter the impact. Defaults to 0.
log_frequency : bool, optional
If set to True, (cummulative) frequency values are converted to log scale before
inter- and extrapolation. Defaults to True.
log_impact : bool, optional
If set to True, impact values are converted to log scale before
inter- and extrapolation. Defaults to True.
bin_decimals : int, optional
Number of decimals to group and bin impact values. Binning results in smoother (and
coarser) interpolation and more stable extrapolation. For more details and sensible
values for bin_decimals, see Notes. If None, values are not binned. Defaults to None.
Returns
-------
gdf : gpd.GeoDataFrame
GeoDataFrame containing return periods for given threshold impacts. Each column
corresponds to a threshold_impact value, each row corresponds to a centroid. Values
in the gdf correspond to the return period for the given centroid and
threshold_impact value
label : str
GeoDataFrame label, for reporting and plotting
column_label : function
Column-label-generating function, for reporting and plotting
See Also
--------
util.interpolation.preprocess_and_interpolate_ev :
inter- and extrapolation method
Notes
-------
If an integer bin_decimals is given, the impact values are binned according to their
bin_decimals decimals, and their corresponding frequencies are summed. This binning leads
to a smoother (and coarser) interpolation, and a more stable extrapolation. For instance,
if bin_decimals=1, the two values 12.01 and 11.97 with corresponding frequencies 0.1 and
0.2 are combined to a value 12.0 with frequency 0.3. The default bin_decimals=None results
in not binning the values.
E.g., if your impact range from 1 to 100, you could use bin_decimals=1, if your
impact range from 1e6 to 1e9, you could use bin_decimals=-5, if your impact
range from 0.0001 to .01, you could use bin_decimals=5.
"""
LOGGER.info("Computing return period map for impacts: %s", threshold_impact)
if self.imp_mat.size == 0:
raise ValueError(
"Attribute imp_mat is empty. Recalculate Impact"
"instance with parameter save_mat=True"
)
# check frequency unit
return_period_unit = u_dt.convert_frequency_unit_to_time_unit(
self.frequency_unit
)
return_periods = np.full((self.imp_mat.shape[1], len(threshold_impact)), np.nan)
nonzero_centroids = np.where(self.imp_mat.getnnz(axis=0) > 0)[0]
# calculate local return periods
if not len(nonzero_centroids) == 0:
return_periods[nonzero_centroids, :] = np.array(
[
u_interp.preprocess_and_interpolate_ev(
None,
np.array(threshold_impact),
self.frequency,
self.imp_mat.getcol(i_centroid).toarray().flatten(),
log_frequency=log_frequency,
log_values=log_impact,
value_threshold=min_impact,
method=method,
y_asymptotic=np.nan,
bin_decimals=bin_decimals,
)
for i_centroid in nonzero_centroids
]
)
return_periods = safe_divide(1.0, return_periods)
# create the output GeoDataFrame
gdf = gpd.GeoDataFrame(
geometry=gpd.points_from_xy(self.coord_exp[:, 1], self.coord_exp[:, 0]),
crs=self.crs,
)
col_names = [f"{thresh_impact}" for thresh_impact in threshold_impact]
gdf[col_names] = return_periods
# create label and column_label
label = f"Return Periods ({return_period_unit})"
def column_label(column_names):
return [f"Impact: {col} {self.unit}" for col in column_names]
return gdf, label, column_label
def calc_freq_curve(self, return_per=None):
"""Compute impact exceedance frequency curve.
Parameters
----------
return_per : np.array, optional
return periods where to compute
the exceedance impact. Use impact's frequencies if not provided
Returns
-------
ImpactFreqCurve
"""
# Sort descendingly the impacts per events
sort_idxs = np.argsort(self.at_event)[::-1]
# Calculate exceedence frequency
exceed_freq = np.cumsum(self.frequency[sort_idxs])
# Set return period and impact exceeding frequency
ifc_return_per = 1 / exceed_freq[::-1]
ifc_impact = self.at_event[sort_idxs][::-1]
if return_per is not None:
warnings.warn(
"Calculating the frequency curve on user-specified return periods is deprecated. "
"Use ImpactFreqCurve.calc_freq_curve().interpolate() instead.",
DeprecationWarning,
stacklevel=2,
)
interp_imp = np.interp(return_per, ifc_return_per, ifc_impact)
ifc_return_per = return_per
ifc_impact = interp_imp
return ImpactFreqCurve(
return_per=ifc_return_per,
impact=ifc_impact,
unit=self.unit,
frequency_unit=self.frequency_unit,
label="Exceedance frequency curve",
)
def _eai_title(self):
if self.frequency_unit in ["1/year", "annual", "1/y", "1/a"]:
return "Expected annual impact"
if self.frequency_unit in ["1/day", "daily", "1/d"]:
return "Expected daily impact"
if self.frequency_unit in ["1/month", "monthly", "1/m"]:
return "Expected monthly impact"
return f"Expected impact ({self.frequency_unit})"
def plot_scatter_eai_exposure(
self,
mask=None,
ignore_zero=False,
pop_name=True,
buffer=0.0,
extend="neither",
axis=None,
adapt_fontsize=True,
**kwargs,
):
"""Plot scatter expected impact within a period of 1/frequency_unit of each exposure.
Parameters
----------
mask : np.array, optional
mask to apply to eai_exp plotted.
ignore_zero : bool, optional
flag to indicate if zero and negative
values are ignored in plot. Default: False
pop_name : bool, optional
add names of the populated places
buffer : float, optional
border to add to coordinates.
Default: 1.0.
extend : str
optional extend border colorbar with arrows.
[ 'neither' | 'both' | 'min' | 'max' ]
axis : matplotlib.axes.Axes, optional
axis to use
adapt_fontsize : bool, optional
If set to true, the size of the fonts will be adapted to the size of the figure.
Otherwise the default matplotlib font size is used. Default is True.
kwargs : dict, optional
arguments for hexbin matplotlib function
Returns
-------
cartopy.mpl.geoaxes.GeoAxesSubplot
"""
if "cmap" not in kwargs:
kwargs["cmap"] = CMAP_IMPACT
eai_exp = self._build_exp()
axis = eai_exp.plot_scatter(
mask,
ignore_zero,
pop_name,
buffer,
extend,
axis=axis,
adapt_fontsize=adapt_fontsize,
**kwargs,
)
axis.set_title(self._eai_title())
return axis
def plot_hexbin_eai_exposure(
self,
mask=None,
ignore_zero=False,
pop_name=True,
buffer=0.0,
extend="neither",
axis=None,
adapt_fontsize=True,
**kwargs,
):
"""Plot hexbin expected impact within a period of 1/frequency_unit of each exposure.
Parameters
----------
mask : np.array, optional
mask to apply to eai_exp plotted.
ignore_zero : bool, optional
flag to indicate if zero and negative
values are ignored in plot. Default: False
pop_name : bool, optional
add names of the populated places
buffer : float, optional
border to add to coordinates.
Default: 1.0.
extend : str, optional
extend border colorbar with arrows.
[ 'neither' | 'both' | 'min' | 'max' ]
axis : matplotlib.axes.Axes, optional
axis to use
adapt_fontsize : bool, optional
If set to true, the size of the fonts will be adapted to the size of the figure.
Otherwise the default matplotlib font size is used. Default: True
kwargs : dict, optional
arguments for hexbin matplotlib function
Returns
-------
cartopy.mpl.geoaxes.GeoAxesSubplot
"""
if "cmap" not in kwargs:
kwargs["cmap"] = CMAP_IMPACT
eai_exp = self._build_exp()
axis = eai_exp.plot_hexbin(
mask,
ignore_zero,
pop_name,
buffer,
extend,
axis=axis,
adapt_fontsize=adapt_fontsize,
**kwargs,
)
axis.set_title(self._eai_title())
return axis
def plot_raster_eai_exposure(
self,
res=None,
raster_res=None,
save_tiff=None,
raster_f=lambda x: np.log10((np.fmax(x + 1, 1))),
label="value (log10)",
axis=None,
adapt_fontsize=True,
**kwargs,
):
"""Plot raster expected impact within a period of 1/frequency_unit of each exposure.
Parameters
----------
res : float, optional
resolution of current data in units of latitude
and longitude, approximated if not provided.
raster_res : float, optional
desired resolution of the raster
save_tiff : str, optional
file name to save the raster in tiff
format, if provided
raster_f : lambda function
transformation to use to data. Default: log10 adding 1.
label : str
colorbar label
axis : matplotlib.axes.Axes, optional
axis to use
adapt_fontsize : bool, optional
If set to true, the size of the fonts will be adapted to the size of the figure.
Otherwise the default matplotlib font size is used. Default is True.
kwargs : dict, optional
arguments for imshow matplotlib function
Returns
-------
cartopy.mpl.geoaxes.GeoAxesSubplot
"""
eai_exp = self._build_exp()
axis = eai_exp.plot_raster(
res,
raster_res,
save_tiff,
raster_f,
label,
axis=axis,
adapt_fontsize=adapt_fontsize,
**kwargs,
)
axis.set_title(self._eai_title())
return axis
def plot_basemap_eai_exposure(
self,
mask=None,
ignore_zero=False,
pop_name=True,
buffer=0.0,
extend="neither",
zoom=10,
url=ctx.providers.CartoDB.Positron,
axis=None,
**kwargs,
):
"""Plot basemap expected impact of each exposure within a period of 1/frequency_unit.
Parameters
----------
mask : np.array, optional
mask to apply to eai_exp plotted.