|
21 | 21 | """ |
22 | 22 |
|
23 | 23 | import logging |
24 | | -from abc import ABC, abstractmethod |
| 24 | +from abc import ABC |
| 25 | +from typing import Callable |
25 | 26 |
|
26 | 27 | import numpy as np |
27 | | -from scipy.sparse import csr_matrix, lil_matrix |
28 | 28 |
|
29 | 29 | LOGGER = logging.getLogger(__name__) |
30 | 30 |
|
31 | 31 |
|
32 | | -class InterpolationStrategy(ABC): |
33 | | - """Interface for interpolation strategies.""" |
34 | | - |
35 | | - @abstractmethod |
36 | | - def interpolate(self, imp_E0, imp_E1, time_points: int) -> list: ... |
37 | | - |
38 | | - |
39 | | -class LinearInterpolation(InterpolationStrategy): |
40 | | - """Linear interpolation strategy.""" |
41 | | - |
42 | | - def interpolate(self, imp_E0, imp_E1, time_points: int): |
| 32 | +def linear_interp_imp_mat(mat_start, mat_end, interpolation_range) -> list: |
| 33 | + """Linearly interpolates between two impact matrices over an interpolation range. |
| 34 | +
|
| 35 | + Returns a list of `interpolation_range` matrices linearly interpolated between |
| 36 | + `mat_start` and `mat_end`. |
| 37 | + """ |
| 38 | + res = [] |
| 39 | + for point in range(interpolation_range): |
| 40 | + ratio = point / (interpolation_range - 1) |
| 41 | + mat_interpolated = mat_start + ratio * (mat_end - mat_start) |
| 42 | + res.append(mat_interpolated) |
| 43 | + return res |
| 44 | + |
| 45 | + |
| 46 | +def exponential_interp_imp_mat(mat_start, mat_end, interpolation_range, rate) -> list: |
| 47 | + """Exponentially interpolates between two impact matrices over an interpolation range with a growth rate `rate`. |
| 48 | +
|
| 49 | + Returns a list of `interpolation_range` matrices exponentially (with growth rate `rate`) interpolated between |
| 50 | + `mat_start` and `mat_end`. |
| 51 | + """ |
| 52 | + # Convert matrices to logarithmic domain |
| 53 | + mat_start = mat_start.copy() |
| 54 | + mat_end = mat_end.copy() |
| 55 | + mat_start.data = np.log(mat_start.data + np.finfo(float).eps) / np.log(rate) |
| 56 | + mat_end.data = np.log(mat_end.data + np.finfo(float).eps) / np.log(rate) |
| 57 | + |
| 58 | + # Perform linear interpolation in the logarithmic domain |
| 59 | + res = [] |
| 60 | + for point in range(interpolation_range): |
| 61 | + ratio = point / (interpolation_range - 1) |
| 62 | + mat_interpolated = mat_start * (1 - ratio) + ratio * mat_end |
| 63 | + mat_interpolated.data = np.exp(mat_interpolated.data * np.log(rate)) |
| 64 | + res.append(mat_interpolated) |
| 65 | + return res |
| 66 | + |
| 67 | + |
| 68 | +def linear_interp_arrays(arr_start, arr_end, interpolation_range): |
| 69 | + """Perform linear interpolation between two arrays (of a scalar metric) over an interpolation range.""" |
| 70 | + prop1 = np.linspace(0, 1, interpolation_range) |
| 71 | + prop0 = 1 - prop1 |
| 72 | + if arr_start.ndim > 1: |
| 73 | + prop0, prop1 = prop0.reshape(-1, 1), prop1.reshape(-1, 1) |
| 74 | + |
| 75 | + return np.multiply(arr_start, prop0) + np.multiply(arr_end, prop1) |
| 76 | + |
| 77 | + |
| 78 | +def exponential_interp_arrays(arr_start, arr_end, interpolation_range, rate): |
| 79 | + """Perform exponential interpolation between two arrays (of a scalar metric) over an interpolation range with a growth rate `rate`.""" |
| 80 | + prop1 = np.linspace(0, 1, interpolation_range) |
| 81 | + prop0 = 1 - prop1 |
| 82 | + if arr_start.ndim > 1: |
| 83 | + prop0, prop1 = prop0.reshape(-1, 1), prop1.reshape(-1, 1) |
| 84 | + |
| 85 | + return np.exp( |
| 86 | + ( |
| 87 | + np.multiply(np.log(arr_start) / np.log(rate), prop0) |
| 88 | + + np.multiply(np.log(arr_end) / np.log(rate), prop1) |
| 89 | + ) |
| 90 | + * np.log(rate) |
| 91 | + ) |
| 92 | + |
| 93 | + |
| 94 | +def logarithmic_interp_arrays(arr_start, arr_end, interpolation_range): |
| 95 | + """Perform logarithmic (natural logarithm) interpolation between two arrays (of a scalar metric) over an interpolation range.""" |
| 96 | + prop1 = np.logspace(0, 1, interpolation_range) |
| 97 | + prop0 = 1 - prop1 |
| 98 | + if arr_start.ndim > 1: |
| 99 | + prop0, prop1 = prop0.reshape(-1, 1), prop1.reshape(-1, 1) |
| 100 | + |
| 101 | + return np.multiply(arr_start, prop0) + np.multiply(arr_end, prop1) |
| 102 | + |
| 103 | + |
| 104 | +class InterpolationStrategyBase(ABC): |
| 105 | + exposure_interp: Callable |
| 106 | + hazard_interp: Callable |
| 107 | + vulnerability_interp: Callable |
| 108 | + |
| 109 | + def interp_exposure_dim( |
| 110 | + self, imp_E0, imp_E1, interpolation_range: int, **kwargs |
| 111 | + ) -> list: |
| 112 | + """Interpolates along the exposure change between two impact matrices. |
| 113 | +
|
| 114 | + Returns a list of `interpolation_range` matrices linearly interpolated between |
| 115 | + `mat_start` and `mat_end`. |
| 116 | + """ |
43 | 117 | try: |
44 | | - return self.interpolate_imp_mat(imp_E0, imp_E1, time_points) |
45 | | - except ValueError as e: |
46 | | - if str(e) == "inconsistent shapes": |
| 118 | + res = self.exposure_interp(imp_E0, imp_E1, interpolation_range, **kwargs) |
| 119 | + except ValueError as err: |
| 120 | + if str(err) == "inconsistent shapes": |
47 | 121 | raise ValueError( |
48 | | - "Interpolation between impact matrices of different shapes" |
| 122 | + "Tried to interpolate impact matrices of different shape. A possible reason could be Exposures of different shapes." |
49 | 123 | ) |
50 | | - else: |
51 | | - raise e |
52 | | - |
53 | | - @staticmethod |
54 | | - def interpolate_imp_mat(imp0, imp1, time_points): |
55 | | - """Interpolate between two impact matrices over a specified time range. |
56 | | -
|
57 | | - Parameters |
58 | | - ---------- |
59 | | - imp0 : ImpactCalc |
60 | | - The impact calculation for the starting time. |
61 | | - imp1 : ImpactCalc |
62 | | - The impact calculation for the ending time. |
63 | | - time_points: |
64 | | - The number of points to interpolate. |
65 | | -
|
66 | | - Returns |
67 | | - ------- |
68 | | - list of np.ndarray |
69 | | - List of interpolated impact matrices for each time points in the specified range. |
70 | | - """ |
71 | 124 |
|
72 | | - def interpolate_sm(mat_start, mat_end, time, time_points): |
73 | | - """Perform linear interpolation between two matrices for a specified time point.""" |
74 | | - if time > time_points: |
75 | | - raise ValueError("time point must be within the range") |
| 125 | + raise err |
76 | 126 |
|
77 | | - ratio = time / (time_points - 1) |
| 127 | + return res |
78 | 128 |
|
79 | | - # Convert the input matrices to a format that allows efficient modification of its elements |
80 | | - mat_start = lil_matrix(mat_start) |
81 | | - mat_end = lil_matrix(mat_end) |
| 129 | + def interp_hazard_dim( |
| 130 | + self, metric_0, metric_1, interpolation_range: int, **kwargs |
| 131 | + ) -> np.ndarray: |
| 132 | + return self.hazard_interp(metric_0, metric_1, interpolation_range, **kwargs) |
82 | 133 |
|
83 | | - # Perform the linear interpolation |
84 | | - mat_interpolated = mat_start + ratio * (mat_end - mat_start) |
| 134 | + def interp_vulnerability_dim( |
| 135 | + self, metric_0, metric_1, interpolation_range: int, **kwargs |
| 136 | + ) -> np.ndarray: |
| 137 | + return self.vulnerability_interp( |
| 138 | + metric_0, metric_1, interpolation_range, **kwargs |
| 139 | + ) |
85 | 140 |
|
86 | | - return csr_matrix(mat_interpolated) |
87 | | - |
88 | | - LOGGER.debug(f"imp0: {imp0.imp_mat.data[0]}, imp1: {imp1.imp_mat.data[0]}") |
89 | | - return [ |
90 | | - interpolate_sm(imp0.imp_mat, imp1.imp_mat, time, time_points) |
91 | | - for time in range(time_points) |
92 | | - ] |
93 | 141 |
|
| 142 | +class InterpolationStrategy(InterpolationStrategyBase): |
| 143 | + """Interface for interpolation strategies.""" |
94 | 144 |
|
95 | | -class ExponentialInterpolation(InterpolationStrategy): |
96 | | - """Exponential interpolation strategy.""" |
| 145 | + def __init__(self, exposure_interp, hazard_interp, vulnerability_interp) -> None: |
| 146 | + super().__init__() |
| 147 | + self.exposure_interp = exposure_interp |
| 148 | + self.hazard_interp = hazard_interp |
| 149 | + self.vulnerability_interp = vulnerability_interp |
97 | 150 |
|
98 | | - def interpolate(self, imp_E0, imp_E1, time_points: int): |
99 | | - return self.interpolate_imp_mat(imp_E0, imp_E1, time_points) |
100 | | - |
101 | | - @staticmethod |
102 | | - def interpolate_imp_mat(imp0, imp1, time_points): |
103 | | - """Interpolate between two impact matrices over a specified time range. |
104 | | -
|
105 | | - Parameters |
106 | | - ---------- |
107 | | - imp0 : ImpactCalc |
108 | | - The impact calculation for the starting time. |
109 | | - imp1 : ImpactCalc |
110 | | - The impact calculation for the ending time. |
111 | | - time_points: |
112 | | - The number of points to interpolate. |
113 | | -
|
114 | | - Returns |
115 | | - ------- |
116 | | - list of np.ndarray |
117 | | - List of interpolated impact matrices for each time points in the specified range. |
118 | | - """ |
119 | 151 |
|
120 | | - def interpolate_sm(mat_start, mat_end, time, time_points): |
121 | | - """Perform exponential interpolation between two matrices for a specified time point.""" |
122 | | - if time > time_points: |
123 | | - raise ValueError("time point must be within the range") |
124 | | - |
125 | | - # Convert matrices to logarithmic domain |
126 | | - log_mat_start = np.log(mat_start.toarray() + np.finfo(float).eps) |
127 | | - log_mat_end = np.log(mat_end.toarray() + np.finfo(float).eps) |
| 152 | +class AllLinearStrategy(InterpolationStrategyBase): |
| 153 | + """Linear interpolation strategy.""" |
128 | 154 |
|
129 | | - # Perform linear interpolation in the logarithmic domain |
130 | | - ratio = time / (time_points - 1) |
131 | | - log_mat_interpolated = log_mat_start + ratio * (log_mat_end - log_mat_start) |
| 155 | + def __init__(self) -> None: |
| 156 | + super().__init__() |
| 157 | + self.exposure_interp = linear_interp_imp_mat |
| 158 | + self.hazard_interp = linear_interp_arrays |
| 159 | + self.vulnerability_interp = linear_interp_arrays |
132 | 160 |
|
133 | | - # Convert back to the original domain using the exponential function |
134 | | - mat_interpolated = np.exp(log_mat_interpolated) |
135 | 161 |
|
136 | | - return csr_matrix(mat_interpolated) |
| 162 | +class ExponentialExposureInterpolation(InterpolationStrategyBase): |
| 163 | + """Exponential interpolation strategy.""" |
137 | 164 |
|
138 | | - return [ |
139 | | - interpolate_sm(imp0.imp_mat, imp1.imp_mat, time, time_points) |
140 | | - for time in range(time_points) |
141 | | - ] |
| 165 | + def __init__(self) -> None: |
| 166 | + super().__init__() |
| 167 | + self.exposure_interp = exponential_interp_imp_mat |
| 168 | + self.hazard_interp = linear_interp_arrays |
| 169 | + self.vulnerability_interp = linear_interp_arrays |
0 commit comments