crc-framework 0.5.4__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. crc_framework/__init__.py +119 -0
  2. crc_framework/_core.cp313-win_amd64.pyd +0 -0
  3. crc_framework/_core.pyi +333 -0
  4. crc_framework/constants.py +134 -0
  5. crc_framework/contracts/__init__.py +93 -0
  6. crc_framework/contracts/impact/catalogs/error-codes.json +148 -0
  7. crc_framework/contracts/impact/catalogs/hazard-exposures.json +26 -0
  8. crc_framework/contracts/impact/catalogs/native-capabilities.json +49 -0
  9. crc_framework/contracts/impact/catalogs/registry-overrides.json +192 -0
  10. crc_framework/contracts/impact/catalogs/semantics-constants.json +156 -0
  11. crc_framework/contracts/impact/catalogs/unit-aliases.json +14 -0
  12. crc_framework/contracts/impact/fixtures/canonical-json.json +345 -0
  13. crc_framework/contracts/impact/fixtures/definitions.json +1006 -0
  14. crc_framework/contracts/impact/fixtures/evaluation-records.json +540 -0
  15. crc_framework/contracts/impact/fixtures/monotonicity.json +934 -0
  16. crc_framework/contracts/impact/fixtures/operations.json +1761 -0
  17. crc_framework/contracts/impact/fixtures/point-evaluations.json +1371 -0
  18. crc_framework/contracts/impact/fixtures/registry-references.json +232 -0
  19. crc_framework/contracts/impact/fixtures/spatial-policies.json +142 -0
  20. crc_framework/contracts/impact/fixtures/spatial-records.json +204 -0
  21. crc_framework/contracts/impact/manifest.json +139 -0
  22. crc_framework/contracts/impact/schemas/impact-definition-1.0.schema.json +1230 -0
  23. crc_framework/contracts/impact/schemas/impact-evaluation-record-1.0.schema.json +1499 -0
  24. crc_framework/contracts/impact/schemas/registry-impact-reference-1.0.schema.json +326 -0
  25. crc_framework/contracts/impact/schemas/spatial-combination-policy-1.0.schema.json +168 -0
  26. crc_framework/contracts/impact/schemas/spatial-impact-evaluation-record-1.0.schema.json +595 -0
  27. crc_framework/distributions/__init__.py +50 -0
  28. crc_framework/distributions/base.py +29 -0
  29. crc_framework/distributions/empirical.py +55 -0
  30. crc_framework/distributions/fitted.py +91 -0
  31. crc_framework/distributions/fitting.py +435 -0
  32. crc_framework/distributions/hurdle.py +84 -0
  33. crc_framework/distributions/point_mass.py +55 -0
  34. crc_framework/distributions/tabulated.py +109 -0
  35. crc_framework/impacts/__init__.py +805 -0
  36. crc_framework/metrics/__init__.py +33 -0
  37. crc_framework/metrics/distribution.py +32 -0
  38. crc_framework/metrics/microscores.py +142 -0
  39. crc_framework/metrics/risk.py +65 -0
  40. crc_framework/metrics/spanning.py +35 -0
  41. crc_framework/models.py +30 -0
  42. crc_framework/py.typed +1 -0
  43. crc_framework/spatial.py +30 -0
  44. crc_framework/transforms/__init__.py +38 -0
  45. crc_framework/transforms/base.py +93 -0
  46. crc_framework/transforms/builtin.py +144 -0
  47. crc_framework/transforms/climate.py +93 -0
  48. crc_framework-0.5.4.dist-info/METADATA +159 -0
  49. crc_framework-0.5.4.dist-info/RECORD +53 -0
  50. crc_framework-0.5.4.dist-info/WHEEL +4 -0
  51. crc_framework-0.5.4.dist-info/licenses/LICENSE +619 -0
  52. crc_framework-0.5.4.dist-info/licenses/THIRD_PARTY_NOTICES.md +70 -0
  53. crc_framework-0.5.4.dist-info/sboms/crc-framework-rs.cyclonedx.json +2035 -0
@@ -0,0 +1,119 @@
1
+ """Typed Python API for the CRC Framework computation core."""
2
+
3
+ from .constants import HORIZONS, PATHWAYS, RISK_FACTORS, Pathway, RiskFactor
4
+ from .distributions import (
5
+ CensoredQuantileFitDiagnostics,
6
+ CensoredQuantileFitResult,
7
+ Distribution,
8
+ EmpiricalDistribution,
9
+ FitConstraints,
10
+ FitDiagnostics,
11
+ FitResult,
12
+ FittedDistribution,
13
+ HurdleDistribution,
14
+ HurdleQuantileFitDiagnostics,
15
+ HurdleQuantileFitResult,
16
+ PointMassDistribution,
17
+ QuantileFitDiagnostics,
18
+ QuantileFitResult,
19
+ TabulatedDistribution,
20
+ fit_all,
21
+ fit_censored_quantiles,
22
+ fit_distribution,
23
+ fit_hurdle_quantiles,
24
+ fit_quantiles,
25
+ quality_metrics,
26
+ )
27
+ from .metrics import (
28
+ BinaryOutcome,
29
+ Microscore,
30
+ MicroscoreSuite,
31
+ RiskResult,
32
+ compute_risk,
33
+ compute_spanning_set,
34
+ generate_microscores,
35
+ )
36
+ from .models import Geography, ScenarioMetadata, TransformContext
37
+ from .spatial import lookup_continent, lookup_geography, lookup_ipcc_region
38
+ from .transforms import (
39
+ CallableImpact,
40
+ CallableTransform,
41
+ ClimateImpact,
42
+ DiscreteDistribution,
43
+ GaussKronrodOptions,
44
+ HistogramExposure,
45
+ ImpactDistribution,
46
+ ImpactError,
47
+ ImpactEvaluationRecord,
48
+ ImpactEvaluationResult,
49
+ ImpactExpression,
50
+ ImpactFunction,
51
+ ImpactRegistry,
52
+ LinearImpact,
53
+ PiecewiseLinearImpact,
54
+ RegistryImpactReference,
55
+ SigmoidImpact,
56
+ impact_registry_manifest,
57
+ impacts,
58
+ )
59
+
60
+ __all__ = [
61
+ "HORIZONS",
62
+ "PATHWAYS",
63
+ "RISK_FACTORS",
64
+ "BinaryOutcome",
65
+ "CensoredQuantileFitDiagnostics",
66
+ "CensoredQuantileFitResult",
67
+ "CallableImpact",
68
+ "CallableTransform",
69
+ "ClimateImpact",
70
+ "DiscreteDistribution",
71
+ "Distribution",
72
+ "EmpiricalDistribution",
73
+ "FitConstraints",
74
+ "FitDiagnostics",
75
+ "FitResult",
76
+ "FittedDistribution",
77
+ "GaussKronrodOptions",
78
+ "Geography",
79
+ "HistogramExposure",
80
+ "HurdleDistribution",
81
+ "HurdleQuantileFitDiagnostics",
82
+ "HurdleQuantileFitResult",
83
+ "ImpactDistribution",
84
+ "ImpactError",
85
+ "ImpactEvaluationRecord",
86
+ "ImpactEvaluationResult",
87
+ "ImpactExpression",
88
+ "ImpactFunction",
89
+ "ImpactRegistry",
90
+ "LinearImpact",
91
+ "Microscore",
92
+ "MicroscoreSuite",
93
+ "Pathway",
94
+ "PiecewiseLinearImpact",
95
+ "PointMassDistribution",
96
+ "QuantileFitDiagnostics",
97
+ "QuantileFitResult",
98
+ "RegistryImpactReference",
99
+ "RiskFactor",
100
+ "RiskResult",
101
+ "ScenarioMetadata",
102
+ "SigmoidImpact",
103
+ "TabulatedDistribution",
104
+ "TransformContext",
105
+ "compute_risk",
106
+ "compute_spanning_set",
107
+ "fit_all",
108
+ "fit_censored_quantiles",
109
+ "fit_distribution",
110
+ "fit_hurdle_quantiles",
111
+ "fit_quantiles",
112
+ "generate_microscores",
113
+ "impact_registry_manifest",
114
+ "impacts",
115
+ "lookup_continent",
116
+ "lookup_geography",
117
+ "lookup_ipcc_region",
118
+ "quality_metrics",
119
+ ]
Binary file
@@ -0,0 +1,333 @@
1
+ from typing import Dict, List, Optional, Sequence, Tuple
2
+
3
+ class NativeDistribution:
4
+ family: Optional[str]
5
+ shape: Optional[float]
6
+ location: Optional[float]
7
+ scale: Optional[float]
8
+ def pdf(self, x: float) -> float: ...
9
+ def cdf(self, x: float) -> float: ...
10
+ def ppf(self, probability: float) -> float: ...
11
+ def quantiles(self, probabilities: Sequence[float]) -> List[float]: ...
12
+ def sample(self, size: int, seed: Optional[int] = ...) -> List[float]: ...
13
+
14
+ class NativeFitResult:
15
+ distribution: NativeDistribution
16
+ ks_statistic: float
17
+ ks_pvalue: float
18
+ rmse: float
19
+ r_squared: float
20
+
21
+ class NativeQuantileFitResult:
22
+ distribution: NativeDistribution
23
+ rmse: float
24
+ normalized_rmse: float
25
+ weighted_r_squared: float
26
+ maximum_absolute_residual: float
27
+ point_count: int
28
+ converged: bool
29
+ iterations: int
30
+ evaluations: int
31
+
32
+ class NativeCensoredQuantileFitResult:
33
+ distribution: NativeDistribution
34
+ rmse: float
35
+ normalized_rmse: float
36
+ weighted_r_squared: float
37
+ maximum_absolute_residual: float
38
+ point_count: int
39
+ converged: bool
40
+ iterations: int
41
+ evaluations: int
42
+ negative_log_likelihood: float
43
+ residual_scale: float
44
+ residual_scale_floor: float
45
+ censor_location: float
46
+ censored_point_count: int
47
+ uncensored_point_count: int
48
+
49
+ class NativeHurdleQuantileFitResult:
50
+ distribution: NativeDistribution
51
+ base_distribution: NativeDistribution
52
+ atom_location: float
53
+ atom_probability: float
54
+ tail_rmse: float
55
+ tail_normalized_rmse: float
56
+ tail_weighted_r_squared: float
57
+ tail_maximum_absolute_residual: float
58
+ tail_point_count: int
59
+ converged: bool
60
+ iterations: int
61
+ evaluations: int
62
+ atom_probability_lower_bound: float
63
+ atom_probability_upper_bound: float
64
+ atom_point_count: int
65
+
66
+ class NativeMicroscore:
67
+ probability: float
68
+ exposure: float
69
+ impact: Optional[float]
70
+ probability_below: float
71
+ probability_above: float
72
+ impact_probability_below: Optional[float]
73
+ impact_probability_above: Optional[float]
74
+
75
+ class NativeBinaryOutcome:
76
+ factor: str
77
+ downside_probability: float
78
+ downside_impact: float
79
+ upside_probability: float
80
+ upside_impact: float
81
+ weight: float
82
+ def __init__(
83
+ self,
84
+ factor: str,
85
+ downside_probability: float,
86
+ downside_impact: float,
87
+ upside_probability: Optional[float] = ...,
88
+ upside_impact: float = ...,
89
+ weight: float = ...,
90
+ ) -> None: ...
91
+
92
+ class NativeMicroscoreSuite:
93
+ scores: List[NativeMicroscore]
94
+ def at(self, probability: float) -> NativeBinaryOutcome: ...
95
+ def exposure_statistics(self) -> Dict[str, float]: ...
96
+ def impact_statistics(self) -> Optional[Dict[str, float]]: ...
97
+
98
+ class NativeSpanningBranch:
99
+ choices: List[bool]
100
+ probability: float
101
+ impact: float
102
+ factor_impacts: List[Tuple[str, float]]
103
+
104
+ class NativeRiskAttribution:
105
+ factor: str
106
+ var_impact: float
107
+ cvar_impact: float
108
+
109
+ class NativeRiskLevel:
110
+ probability: float
111
+ var: float
112
+ cvar: float
113
+ attribution: List[NativeRiskAttribution]
114
+
115
+ class NativeRiskResult:
116
+ levels: List[NativeRiskLevel]
117
+ branch_count: int
118
+
119
+ def empirical_distribution(samples: Sequence[float]) -> NativeDistribution: ...
120
+ def point_mass_distribution(location: float) -> NativeDistribution: ...
121
+ def tabulated_distribution(
122
+ probabilities: Sequence[float],
123
+ values: Sequence[float],
124
+ interpolation: str = ...,
125
+ extrapolate: bool = ...,
126
+ ) -> NativeDistribution: ...
127
+ def return_period_distribution(
128
+ periods: Sequence[float],
129
+ values: Sequence[float],
130
+ tail: str,
131
+ interpolation: str = ...,
132
+ extrapolate: bool = ...,
133
+ ) -> NativeDistribution: ...
134
+ def fitted_distribution(
135
+ family: str, location: float, scale: float, shape: Optional[float] = ...
136
+ ) -> NativeDistribution: ...
137
+ def hurdle_distribution(
138
+ base: NativeDistribution,
139
+ atom_probability: float,
140
+ atom_location: float = ...,
141
+ ) -> NativeDistribution: ...
142
+ def fit(samples: Sequence[float], family: Optional[str] = ..., *, method: str = ...) -> NativeFitResult: ...
143
+ def fit_candidates(samples: Sequence[float]) -> List[NativeFitResult]: ...
144
+ def fit_quantiles(
145
+ probabilities: Sequence[float],
146
+ values: Sequence[float],
147
+ family: str,
148
+ weights: Optional[Sequence[float]] = ...,
149
+ ) -> NativeQuantileFitResult: ...
150
+ def fit_censored_quantiles(
151
+ probabilities: Sequence[float],
152
+ values: Sequence[float],
153
+ family: str,
154
+ censor_location: float = ...,
155
+ residual_scale_floor_ratio: float = ...,
156
+ weights: Optional[Sequence[float]] = ...,
157
+ ) -> NativeCensoredQuantileFitResult: ...
158
+ def fit_hurdle_quantiles(
159
+ probabilities: Sequence[float],
160
+ values: Sequence[float],
161
+ family: str,
162
+ atom_probability: float,
163
+ atom_location: float = ...,
164
+ weights: Optional[Sequence[float]] = ...,
165
+ ) -> NativeHurdleQuantileFitResult: ...
166
+ def diagnostic_metrics(
167
+ samples: Sequence[float], distribution: NativeDistribution
168
+ ) -> Dict[str, float]: ...
169
+ def evaluate_impact(
170
+ values: Sequence[float],
171
+ factor: str,
172
+ cell: Optional[int] = ...,
173
+ country: Optional[str] = ...,
174
+ continent: Optional[str] = ...,
175
+ building_type: Optional[str] = ...,
176
+ historic_mean: Optional[float] = ...,
177
+ overrides: Optional[Dict[str, float]] = ...,
178
+ ) -> List[float]: ...
179
+ def apply_impact(
180
+ distribution: NativeDistribution,
181
+ probabilities: Sequence[float],
182
+ factor: str,
183
+ cell: Optional[int] = ...,
184
+ country: Optional[str] = ...,
185
+ continent: Optional[str] = ...,
186
+ building_type: Optional[str] = ...,
187
+ historic_mean: Optional[float] = ...,
188
+ overrides: Optional[Dict[str, float]] = ...,
189
+ ) -> NativeDistribution: ...
190
+ def microscores(
191
+ exposure: NativeDistribution,
192
+ probabilities: Sequence[float],
193
+ impact: Optional[NativeDistribution] = ...,
194
+ cell: Optional[int] = ...,
195
+ factor: Optional[str] = ...,
196
+ pathway: Optional[str] = ...,
197
+ horizon: Optional[int] = ...,
198
+ country: Optional[str] = ...,
199
+ continent: Optional[str] = ...,
200
+ building_type: Optional[str] = ...,
201
+ ) -> NativeMicroscoreSuite: ...
202
+ def spanning_set(
203
+ outcomes: Sequence[NativeBinaryOutcome], max_branches: Optional[int] = ...
204
+ ) -> List[NativeSpanningBranch]: ...
205
+ def risk(
206
+ outcomes: Sequence[NativeBinaryOutcome],
207
+ levels: Sequence[float],
208
+ max_branches: Optional[int] = ...,
209
+ ) -> NativeRiskResult: ...
210
+ def lookup_ipcc_region(cell: object) -> Optional[str]: ...
211
+ def lookup_continent(cell: object) -> Optional[str]: ...
212
+ def lookup_geography(cell: object) -> Optional[Dict[str, object]]: ...
213
+ def pathways() -> List[Tuple[int, str]]: ...
214
+ def horizons() -> List[int]: ...
215
+ def risk_factors() -> List[Tuple[int, str]]: ...
216
+
217
+ class ImpactError(Exception):
218
+ code: str
219
+ path: str
220
+
221
+ class NativeImpactExpression:
222
+ definition_hash: str
223
+ model_kind: str
224
+ monotonicity: str
225
+ @staticmethod
226
+ def from_json(text: str) -> NativeImpactExpression: ...
227
+ def canonical_json(self) -> str: ...
228
+ def evaluate_value(self, value: float) -> float: ...
229
+ def evaluate_values(self, values: Sequence[float]) -> List[float]: ...
230
+ def expected_value(
231
+ self,
232
+ source: NativeImpactSource,
233
+ requested: str,
234
+ absolute_tolerance: Optional[float] = ...,
235
+ relative_tolerance: Optional[float] = ...,
236
+ max_evaluations: Optional[int] = ...,
237
+ ) -> NativeExpectation: ...
238
+ def transform_distribution(self, source: NativeImpactSource) -> NativeImpactDistribution: ...
239
+ def point_record(
240
+ self,
241
+ shape: Sequence[int],
242
+ values: Sequence[float],
243
+ snapshot_uri: Optional[str] = ...,
244
+ snapshot_revision: Optional[str] = ...,
245
+ snapshot_sha256: Optional[str] = ...,
246
+ snapshot_retention: Optional[str] = ...,
247
+ ) -> NativeImpactEvaluationRecord: ...
248
+ def expectation_record(
249
+ self,
250
+ source: NativeImpactSource,
251
+ expectation: NativeExpectation,
252
+ snapshot_uri: Optional[str] = ...,
253
+ snapshot_revision: Optional[str] = ...,
254
+ snapshot_sha256: Optional[str] = ...,
255
+ snapshot_retention: Optional[str] = ...,
256
+ ) -> NativeImpactEvaluationRecord: ...
257
+ def transform_record(
258
+ self,
259
+ source: NativeImpactSource,
260
+ snapshot_uri: Optional[str] = ...,
261
+ snapshot_revision: Optional[str] = ...,
262
+ snapshot_sha256: Optional[str] = ...,
263
+ snapshot_retention: Optional[str] = ...,
264
+ ) -> NativeImpactEvaluationRecord: ...
265
+
266
+ class NativeImpactSource:
267
+ original_mass_sum: Optional[float]
268
+ normalization_factor: Optional[float]
269
+ @staticmethod
270
+ def histogram(edges: Sequence[float], weights: Sequence[float]) -> NativeImpactSource: ...
271
+ @staticmethod
272
+ def discrete(
273
+ support: Sequence[float], probabilities: Sequence[float]
274
+ ) -> NativeImpactSource: ...
275
+ @staticmethod
276
+ def empirical(samples: Sequence[float]) -> NativeImpactSource: ...
277
+ @staticmethod
278
+ def curve(
279
+ curve_kind: str,
280
+ curve_type: str,
281
+ curve_shape: Optional[float] = ...,
282
+ curve_location: Optional[float] = ...,
283
+ curve_scale: Optional[float] = ...,
284
+ curve_atom_probability: Optional[float] = ...,
285
+ curve_atom_location: Optional[float] = ...,
286
+ curve_probabilities: Optional[Sequence[float]] = ...,
287
+ curve_values: Optional[Sequence[float]] = ...,
288
+ ) -> NativeImpactSource: ...
289
+
290
+ class NativeExpectation:
291
+ value: float
292
+ requested: str
293
+ method: str
294
+ method_version: str
295
+ absolute_tolerance: Optional[float]
296
+ relative_tolerance: Optional[float]
297
+ max_evaluations: Optional[int]
298
+ evaluations: int
299
+ error_estimate: float
300
+ exact_component: float
301
+ numerical_component: float
302
+ original_mass_sum: Optional[float]
303
+ normalization_factor: Optional[float]
304
+
305
+ class NativeImpactDistribution:
306
+ definition_hash: str
307
+ algorithm: str
308
+ def atoms(self) -> List[Tuple[float, float]]: ...
309
+ def quantile(self, probability: float) -> float: ...
310
+ def quantiles(self, probabilities: Sequence[float]) -> List[float]: ...
311
+ def tabulate(self, probabilities: Sequence[float], interpolation: str) -> List[float]: ...
312
+
313
+ class NativeImpactEvaluationRecord:
314
+ def canonical_json(self) -> str: ...
315
+
316
+ class NativeImpactReference:
317
+ reference_hash: str
318
+ @staticmethod
319
+ def from_json(text: str) -> NativeImpactReference: ...
320
+ def canonical_json(self) -> str: ...
321
+ def resolve(
322
+ self,
323
+ cell: Optional[str] = ...,
324
+ country: Optional[str] = ...,
325
+ continent: Optional[str] = ...,
326
+ building_type: Optional[str] = ...,
327
+ historic_mean: Optional[float] = ...,
328
+ ) -> NativeImpactExpression: ...
329
+
330
+ def impact_registry_identity() -> Tuple[str, str, str, str]: ...
331
+ def impact_registry_manifest_json() -> str: ...
332
+ def impact_engine() -> Tuple[str, str]: ...
333
+ def impact_array_digest(shape: Sequence[int], values: Sequence[float]) -> str: ...
@@ -0,0 +1,134 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from enum import Enum
5
+ from typing import Union
6
+
7
+ from crc_framework import _core
8
+
9
+
10
+ class RiskFactor(str, Enum):
11
+ DAILY_FREEZETHAW_CYCLES = "daily_freezethaw_cycles"
12
+ FROST_DAYS = "frost_days"
13
+ CYCLONE = "cyclone"
14
+ FWI = "fwi"
15
+ RX1DAY = "rx1day"
16
+ WIND_MAX_DAILY_MAX = "wind_max_daily_max"
17
+ CARBON_PRICE = "carbon_price"
18
+ HOT_DAYS = "hot_days"
19
+ CFLOOD = "cflood"
20
+ RFLOOD = "rflood"
21
+ INUNDATION = "inundation"
22
+ SPEI = "spei"
23
+ DC = "dc"
24
+ DMC = "dmc"
25
+ FFMC = "ffmc"
26
+ ISI = "isi"
27
+ BUI = "bui"
28
+ RX5DAY = "rx5day"
29
+ WIND_MAX_DAILY_MEAN = "wind_max_daily_mean"
30
+ COOLING_DEGREE_DAYS = "cooling_degree_days"
31
+ TG_MAX = "tg_max"
32
+ TG_MEAN = "tg_mean"
33
+ TG_MIN = "tg_min"
34
+ TX_MAX = "tx_max"
35
+ TX_MEAN = "tx_mean"
36
+ TX_MIN = "tx_min"
37
+ TN_MAX = "tn_max"
38
+ TN_MEAN = "tn_mean"
39
+ TN_MIN = "tn_min"
40
+ SDII = "sdii"
41
+ LIQUIDPRCPTOT = "liquidprcptot"
42
+ SOLIDPRCPTOT = "solidprcptot"
43
+ PRCPTOT = "prcptot"
44
+ PET = "pet"
45
+ WATER_BUDGET = "water_budget"
46
+ DTRMAX = "dtrmax"
47
+ DTRVAR = "dtrvar"
48
+ ETR = "etr"
49
+ CALM_DAYS = "calm_days"
50
+ CORN_HEAT_UNITS = "corn_heat_units"
51
+ WBGT = "wbgt"
52
+ WINDCHILL = "windchill"
53
+ HEAT_INDEX = "heat_index"
54
+ HEAT_WAVE_FREQUENCY = "heat_wave_frequency"
55
+ HEAT_WAVE_TOTAL_LENGTH = "heat_wave_total_length"
56
+ HEAT_WAVE_MAX_LENGTH = "heat_wave_max_length"
57
+ HEAT_WAVE_INDEX = "heat_wave_index"
58
+ HOT_SPELL_FREQUENCY = "hot_spell_frequency"
59
+ HOT_SPELL_MAX_LENGTH = "hot_spell_max_length"
60
+ MAXIMUM_CONSECUTIVE_FROST_DAYS = "maximum_consecutive_frost_days"
61
+ COLD_SPELL_DAYS = "cold_spell_days"
62
+ COLD_SPELL_FREQUENCY = "cold_spell_frequency"
63
+ MAXIMUM_CONSECUTIVE_WET_DAYS = "maximum_consecutive_wet_days"
64
+ MAXIMUM_CONSECUTIVE_DRY_DAYS = "maximum_consecutive_dry_days"
65
+ AT = "at"
66
+ SUMMER_DAYS = "summer_days"
67
+ TROPICAL_NIGHTS = "tropical_nights"
68
+ HUMIDEX = "humidex"
69
+ HEATING_DEGREE_DAYS = "heating_degree_days"
70
+ GROWING_DEGREE_DAYS = "growing_degree_days"
71
+ ICE_DAYS = "ice_days"
72
+ DRY_DAYS = "dry_days"
73
+ WET_DAYS = "wet_days"
74
+ DTR = "dtr"
75
+
76
+
77
+ class Pathway(str, Enum):
78
+ SV = "SV"
79
+ HOT_HOUSE = "Hot House"
80
+ PARIS = "Paris"
81
+ NDC = "NDC"
82
+ SSP126 = "ssp126"
83
+ SSP245 = "ssp245"
84
+ SSP370 = "ssp370"
85
+ SSP585 = "ssp585"
86
+ BELOW_2_DEGREES = "<2 degrees"
87
+ BETWEEN_2_AND_3_DEGREES = "2-3 degrees"
88
+ BETWEEN_3_AND_4_DEGREES = "3-4 degrees"
89
+ ABOVE_4_DEGREES = ">4 degrees"
90
+ HISTORIC = "historic"
91
+ SSP434 = "ssp434"
92
+ SSP119 = "ssp119"
93
+ SSP460 = "ssp460"
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class Dimension:
98
+ id: int
99
+ name: str
100
+
101
+
102
+ PATHWAYS = tuple(Dimension(id_, name) for id_, name in _core.pathways())
103
+ RISK_FACTORS = tuple(Dimension(id_, name) for id_, name in _core.risk_factors())
104
+ HORIZONS = tuple(_core.horizons())
105
+
106
+
107
+ def pathway_from_id(id_: int) -> Pathway:
108
+ try:
109
+ return Pathway(next(item.name for item in PATHWAYS if item.id == id_))
110
+ except StopIteration as error:
111
+ raise ValueError(f"unknown pathway id {id_}") from error
112
+
113
+
114
+ def pathway_id(pathway: Union[Pathway, str]) -> int:
115
+ value = str(pathway.value if isinstance(pathway, Pathway) else pathway)
116
+ try:
117
+ return next(item.id for item in PATHWAYS if item.name == value)
118
+ except StopIteration as error:
119
+ raise ValueError(f"unknown pathway {value}") from error
120
+
121
+
122
+ def risk_factor_from_id(id_: int) -> RiskFactor:
123
+ try:
124
+ return RiskFactor(next(item.name for item in RISK_FACTORS if item.id == id_))
125
+ except StopIteration as error:
126
+ raise ValueError(f"unknown risk factor id {id_}") from error
127
+
128
+
129
+ def risk_factor_id(factor: Union[RiskFactor, str]) -> int:
130
+ value = str(factor.value if isinstance(factor, RiskFactor) else factor)
131
+ try:
132
+ return next(item.id for item in RISK_FACTORS if item.name == value)
133
+ except StopIteration as error:
134
+ raise ValueError(f"unknown risk factor {value}") from error
@@ -0,0 +1,93 @@
1
+ """Versioned impact contract artifact: JSON Schemas, catalogs and conformance fixtures.
2
+
3
+ The artifact is generated by ``tools/impact_contracts/generate.py`` from an
4
+ independent reference implementation. Consumers pin
5
+ ``impact_contract_manifest_sha256()`` and call ``verify_impact_contracts()``
6
+ before relying on the files.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ from importlib import resources
14
+ from typing import Any, Dict, List
15
+
16
+ IMPACT_CONTRACT_ARTIFACT = "crc-impact-contracts"
17
+ IMPACT_CONTRACT_VERSION = "1.0.0"
18
+
19
+ _PACKAGE = "crc_framework.contracts"
20
+ _ROOT = "impact"
21
+
22
+
23
+ def _read_bytes(relative_path: str) -> bytes:
24
+ if relative_path.startswith("/") or ".." in relative_path.split("/"):
25
+ raise ValueError(f"invalid contract path {relative_path!r}")
26
+ node = resources.files(_PACKAGE).joinpath(_ROOT)
27
+ for part in relative_path.split("/"):
28
+ node = node.joinpath(part)
29
+ return node.read_bytes()
30
+
31
+
32
+ def read_impact_contract_file(relative_path: str) -> bytes:
33
+ """Return the exact bytes of an artifact file, for example ``schemas/...``."""
34
+ return _read_bytes(relative_path)
35
+
36
+
37
+ def load_impact_contract_file(relative_path: str) -> Any:
38
+ return json.loads(_read_bytes(relative_path).decode("utf-8"))
39
+
40
+
41
+ def impact_contract_manifest() -> Dict[str, Any]:
42
+ manifest: Dict[str, Any] = load_impact_contract_file("manifest.json")
43
+ return manifest
44
+
45
+
46
+ def impact_contract_manifest_sha256() -> str:
47
+ """Bare SHA-256 of ``manifest.json``; pinning it pins every listed file."""
48
+ return hashlib.sha256(_read_bytes("manifest.json")).hexdigest()
49
+
50
+
51
+ def load_impact_schema(contract: str) -> Dict[str, Any]:
52
+ """Load the JSON Schema for a contract such as ``impact_definition``."""
53
+ entry = impact_contract_manifest()["contracts"][contract]
54
+ schema: Dict[str, Any] = load_impact_contract_file(entry["schema"])
55
+ return schema
56
+
57
+
58
+ def load_impact_fixtures(contract: str) -> Dict[str, Any]:
59
+ """Load accepted and rejected conformance cases for a contract."""
60
+ entry = impact_contract_manifest()["contracts"][contract]
61
+ fixtures: Dict[str, Any] = load_impact_contract_file(entry["fixtures"])
62
+ return fixtures
63
+
64
+
65
+ def impact_contract_names() -> List[str]:
66
+ return sorted(impact_contract_manifest()["contracts"])
67
+
68
+
69
+ def verify_impact_contracts() -> None:
70
+ """Check the artifact identity and every file digest listed in the manifest."""
71
+ manifest = impact_contract_manifest()
72
+ if manifest.get("artifact") != IMPACT_CONTRACT_ARTIFACT:
73
+ raise ValueError(f"unexpected contract artifact {manifest.get('artifact')!r}")
74
+ if manifest.get("artifact_version") != IMPACT_CONTRACT_VERSION:
75
+ raise ValueError(f"unexpected contract version {manifest.get('artifact_version')!r}")
76
+ for entry in manifest["files"]:
77
+ content = _read_bytes(entry["path"])
78
+ if len(content) != entry["bytes"] or hashlib.sha256(content).hexdigest() != entry["sha256"]:
79
+ raise ValueError(f"impact contract file {entry['path']} does not match the manifest")
80
+
81
+
82
+ __all__ = [
83
+ "IMPACT_CONTRACT_ARTIFACT",
84
+ "IMPACT_CONTRACT_VERSION",
85
+ "impact_contract_manifest",
86
+ "impact_contract_manifest_sha256",
87
+ "impact_contract_names",
88
+ "load_impact_contract_file",
89
+ "load_impact_fixtures",
90
+ "load_impact_schema",
91
+ "read_impact_contract_file",
92
+ "verify_impact_contracts",
93
+ ]