-
Notifications
You must be signed in to change notification settings - Fork 142
Integrates risk trajectories within climada #1037
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
spjuhel
wants to merge
90
commits into
develop
Choose a base branch
from
feature/risk_trajectory
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 71 commits
Commits
Show all changes
90 commits
Select commit
Hold shift + click to select a range
3692813
Implements equality methods for impf and impfset
spjuhel 1606896
adds a few tests
spjuhel a8b45c6
Merge remote-tracking branch 'origin/develop' into feature/eq_methods…
spjuhel 3776228
updates changelog
spjuhel f6d9feb
Improves dict comparison
spjuhel 222644d
Applies suggestion from Lukas (1)
spjuhel 29ecee4
init commit
spjuhel d7c0f23
Pushes tutorial notebook
spjuhel 31ef976
Working tutorial
spjuhel 10ca243
fixes a typo from mass edit
spjuhel 389787e
Refactor to a more object-oriented design
spjuhel 4ea685d
fixes some bugs
spjuhel 0d6335b
fixses some linter issues
spjuhel 31ea96d
feat(trajectory): interpolation and impactcalc files, eai_gdf metric
spjuhel 3f13c2e
impact func __eq__
spjuhel 519c9af
feat(test): adds test for ImpactFuncSet
spjuhel adfc7e2
fix(format): removes trailing whitespace
spjuhel 6856117
Merge branch 'feature/eq_methods_for_impf' into feature/risk_trajectory
spjuhel 9c358ca
fix: npv arg not considered in .all_risk_metrics()
spjuhel b7bf68b
refactor: enforce kwargs in RiskTrajectory init
spjuhel b75ab91
refactor: adds consistency between attribute
spjuhel e12b2c4
refactor(risktraj): lays better foundations for MeasureAppraiser
spjuhel 8666197
minor additions, refactors and fixes
spjuhel 9711379
format,doc: cleans up code, adds docstrings
spjuhel 9aec92f
test: adds lots of unittests, and placeholders
spjuhel 7387165
feature(Traj): fixes metrics generic and removes storing values
spjuhel 20befdf
updates tutorial
spjuhel e06a3e7
doc(risk_traj): adds some docstrings
spjuhel 924bb35
doc(module desc): improves top file desc
spjuhel 6595e13
fix(log) : Removes endless logs
spjuhel 94bd00e
fix(risk_traj): Fixes problems with >2 snapshots
spjuhel 4921528
doc(notebook): adds disclaimers
spjuhel 02244cb
fix(CalcRiskPeriod): fixes problem with undefined group_id
spjuhel b0a9f6d
fix(calcriskperiod): further fix for no group defined
spjuhel 06afe2f
fix(groups): still fixing groups
spjuhel eceeba0
fix(groups): final fix (on the correct branch)
spjuhel a7dd0f7
Applies suggestion from Lucas (j/n)
spjuhel 7989c71
Applies suggestion from Lucas (j/n)
spjuhel 399572e
Applies suggestion from Lucas (j/n)
spjuhel 3db32ca
Applies suggestion from Lucas (j/n)
spjuhel d2b0f6b
refactor(impact strat): Clarifies/Simplified computation
spjuhel 3f0dfc6
feat(interpolation): Vastly improves interpolation of metrics
spjuhel d24a5b8
test(naming): updates names
spjuhel 304a641
Squashed commit of the following:
spjuhel 4ef643f
fix(plot, groups): improves plot, fixes group in eai
spjuhel bc38525
Merge remote-tracking branch 'origin/develop' into feature/risk_traje…
spjuhel 33cfff4
fix(RiskPCalc): sorts the snapshots
spjuhel dd21493
doc(risk transfer): Improves clarity of risk transfer mechanism
spjuhel f4db1d0
format(docstring)
spjuhel c6e147e
test: fix for coverage
spjuhel 25d0d0a
fix,doc(interpolation): minor improvements and fixes
spjuhel 9634bd9
fix: minor fixes from testing
spjuhel d4af1a7
test: Updates test (98pct coverage o7)
spjuhel 7e8df85
fix(group id): fix categories problem
spjuhel 1bae9ad
still fixing groups
spjuhel b946f9b
group fixing
spjuhel 622c8f6
fix(tests): fix tests with groups_id attr
spjuhel 9c94c9f
tests: cleaning up
spjuhel 953a5cf
updates notebook
spjuhel 59bb831
more logical placement
spjuhel 0a3a301
removes risk transfer mechanism (for now)
spjuhel b5f0bfc
doc(docstrings): Massive docstrings update + some renaming
spjuhel 1fbe437
test: updates with new names and removing of risk transfer
spjuhel 56966ca
Polishes names, plots, fixes minor bugs, fixes multiple snapshots
spjuhel a11a630
Updates tutorial
spjuhel 6c8dd15
fix(RP impacts for periods): fixes aggregation (sum -> mean)
spjuhel 3609471
drops unwanted col
spjuhel 6eaf095
less confusing naming
spjuhel 5ab8bda
improves structure
spjuhel 21cc433
Improves for CB
spjuhel 0a04ab9
Use of PeriodIndex instead of DateTimeIndex
spjuhel 2bf7768
Big refactoring to include "static" (non-interpolated) trajectories
spjuhel e2fd678
Refactoring continued (Also now includes the new files)
spjuhel 252e68e
fixes attachement/cover comment
spjuhel d694c64
Refactoring continued
spjuhel eadcb97
typing consistency
spjuhel fa17a48
fix apply_measure
spjuhel b4316d7
fixes Snapshot doc, makes measure and date immutable properties
spjuhel 3a026cd
risk_disc -> risk_disc_rates, fixes return period mechanism
spjuhel 3f0c5f9
Improves docstrings, typehint
spjuhel 26bb85d
adds list comprehensions, fixes typo
spjuhel 6e12608
improves docstring for calc strategies
spjuhel 67641e0
first part of fix for cash_flows
spjuhel a68b79a
fixes cash_flow problem
spjuhel cbaca3c
force keyword args to avoid errors
spjuhel 56f3715
fixes risk_contribution problem with multiple snapshot
spjuhel 0234238
fix aggressive caching
spjuhel 195a50f
fix missing group in exposure
spjuhel f14c9c1
Merge remote-tracking branch 'origin/develop' into feature/risk_traje…
spjuhel fe50ac1
adds risk metric unit based on exposure `value_unit`
spjuhel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
# 100% Coverage goal: | ||
## Integration test for risk period with periods and freq defined |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
""" | ||
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/>. | ||
|
||
--- | ||
""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,163 @@ | ||
""" | ||
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/>. | ||
|
||
--- | ||
|
||
This modules implements the Snapshot and SnapshotsCollection classes. | ||
|
||
""" | ||
|
||
import copy | ||
from abc import ABC, abstractmethod | ||
|
||
import numpy as np | ||
|
||
from climada.engine.impact import Impact | ||
from climada.engine.impact_calc import ImpactCalc | ||
from climada.trajectories.snapshot import Snapshot | ||
|
||
|
||
class ImpactComputationStrategy(ABC): | ||
"""Interface for impact computation strategies.""" | ||
|
||
@abstractmethod | ||
def compute_impacts( | ||
self, | ||
snapshot0: Snapshot, | ||
snapshot1: Snapshot, | ||
future: tuple[int, int, int], | ||
risk_transf_attach: float | None = None, | ||
risk_transf_cover: float | None = None, | ||
calc_residual: bool = True, | ||
) -> Impact: | ||
"""Method used to compute impact from the snapshots.""" | ||
|
||
|
||
class ImpactCalcComputation(ImpactComputationStrategy): | ||
"""Default impact computation strategy.""" | ||
|
||
def compute_impacts( | ||
self, | ||
snapshot0: Snapshot, | ||
snapshot1: Snapshot, | ||
future: tuple[int, int, int], | ||
risk_transf_attach: float | None = None, | ||
risk_transf_cover: float | None = None, | ||
calc_residual: bool = False, | ||
): | ||
impact = self.compute_impacts_pre_transfer(snapshot0, snapshot1, future) | ||
self._apply_risk_transfer( | ||
impact, risk_transf_attach, risk_transf_cover, calc_residual | ||
) | ||
return impact | ||
|
||
def compute_impacts_pre_transfer( | ||
self, | ||
snapshot0: Snapshot, | ||
snapshot1: Snapshot, | ||
future: tuple[int, int, int], | ||
) -> Impact: | ||
exp = snapshot1.exposure if future[0] else snapshot0.exposure | ||
haz = snapshot1.hazard if future[1] else snapshot0.hazard | ||
vul = snapshot1.impfset if future[2] else snapshot0.impfset | ||
spjuhel marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
return ImpactCalc(exposures=exp, impfset=vul, hazard=haz).impact() | ||
|
||
def _apply_risk_transfer( | ||
self, | ||
impact: Impact, | ||
risk_transf_attach: float | None, | ||
risk_transf_cover: float | None, | ||
calc_residual: bool, | ||
): | ||
"""Apply risk transfer to the calculated impacts.""" | ||
if risk_transf_attach is not None and risk_transf_cover is not None: | ||
spjuhel marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
impact.imp_mat = self.calculate_residual_or_risk_transfer_impact_matrix( | ||
impact.imp_mat, risk_transf_attach, risk_transf_cover, calc_residual | ||
) | ||
|
||
def calculate_residual_or_risk_transfer_impact_matrix( | ||
Check warning on line 91 in climada/trajectories/impact_calc_strat.py
|
||
self, imp_mat, attachement, cover, calc_residual | ||
): | ||
"""Calculate either the residual or the risk transfer impact matrix | ||
from a global risk transfer mechanism. | ||
|
||
To compute the transfered risk, the function first computes for each event, | ||
the (positive) difference between their total impact and `attachment`. | ||
The transfered risk for each event is then defined as the minimum between | ||
this value and `cover`. The residual impact is the total impact minus | ||
the transfered risk. | ||
The impact matrix is then adjusted by multiply impact per centroids | ||
by the ratio between residual risk and total impact for each event. | ||
As such, the risk transfer is shared among all impacted exposure points | ||
and equaly distributed. | ||
|
||
If `calc_residual` is False, the function returns the transfered risk | ||
at each points instead of the residual risk by using the ratio between | ||
transfered risk and total impact instead. | ||
|
||
Parameters | ||
---------- | ||
imp_mat : scipy.sparse.csr_matrix | ||
The original impact matrix to be scaled. | ||
attachment : float | ||
The attachment point for the risk layer. | ||
cover : float | ||
The maximum coverage for the risk layer. | ||
calc_residual : bool, default=True | ||
Determines if the function calculates the residual (if True) or the | ||
risk layer (if False). | ||
|
||
Returns | ||
------- | ||
scipy.sparse.csr_matrix | ||
The adjusted impact matrix, either residual or risk transfer. | ||
|
||
Warnings | ||
-------- | ||
|
||
This transfer capability is different and not exclusive with the one | ||
implemented in ImpactCalc, which is defined at the centroid level. | ||
The mechanism here corresponds to a global cover applied to the whole | ||
region studied. | ||
|
||
""" | ||
imp_mat = copy.deepcopy(imp_mat) | ||
# Calculate the total impact per event | ||
total_at_event = imp_mat.sum(axis=1).A1 | ||
# Risk layer at event | ||
transfer_at_event = np.minimum( | ||
np.maximum(total_at_event - attachement, 0), cover | ||
) | ||
residual_at_event = np.maximum(total_at_event - transfer_at_event, 0) | ||
|
||
# Calculate either the residual or transfer impact matrix | ||
# Choose the denominator to rescale the impact values | ||
if calc_residual: | ||
numerator = residual_at_event | ||
else: | ||
numerator = transfer_at_event | ||
|
||
rescale_impact_values = np.divide( | ||
numerator, | ||
total_at_event, | ||
out=np.zeros_like(numerator, dtype=float), | ||
where=total_at_event != 0, | ||
) | ||
|
||
# The multiplication is broadcasted across the columns for each row | ||
result_matrix = imp_mat.multiply(rescale_impact_values[:, np.newaxis]) | ||
|
||
return result_matrix |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.