Processor Utilities
Internal utilities for data processor implementation.
Overview
The processor utilities modules provide base classes and helper functions for implementing data processors in the ClimateData interface architecture:
- Abstract base class — DataProcessor base class and registry
- Processor utilities — Helper functions for common operations
Data Processor Base Class
Bases: ABC
Abstract base class for data processing.
All data processors should inherit from this class and implement the required methods.
Notes
- Processors should only store parameters needed for processing, not the data itself.
- Processors should not throw exceptions; instead, they should return the data and a warning message if needed.
- All processors should update the context with information about how they modified the data.
Methods:
| Name | Description |
|---|---|
execute |
Process the data and return the result. |
update_context |
Update the context with additional parameters. |
set_data_accessor |
Set the data accessor for the processor. |
execute(result, context)
abstractmethod
Process raw data into the required format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
Dataset, DataArray, or iterable of these
|
Data to be processed. |
required |
context
|
dict
|
Parameters for processing the data. |
required |
Returns:
| Type | Description |
|---|---|
Dataset, DataArray, or iterable of these
|
Processed data. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the data cannot be processed. |
Source code in climakitae/new_core/processors/abc_data_processor.py
update_context(context)
abstractmethod
Update the context with additional parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
dict
|
Parameters for processing the data. |
required |
Returns:
| Type | Description |
|---|---|
None
|
|
Source code in climakitae/new_core/processors/abc_data_processor.py
set_data_accessor(catalog)
abstractmethod
Set the data accessor for the processor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
catalog
|
DataCatalog
|
Data catalog for accessing datasets. |
required |
Returns:
| Type | Description |
|---|---|
None
|
|
Source code in climakitae/new_core/processors/abc_data_processor.py
Processor Registry
Decorator to register a processor class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to register the processor under. If not provided, a key will be generated from the class name. |
UNSET
|
priority
|
int
|
Optional priority for the processor. Lower values indicate higher priority. |
UNSET
|
Returns:
| Type | Description |
|---|---|
callable
|
The decorator function that registers the processor class. |
Examples:
@register_processor("my_processor", priority=10) class MyProcessor(DataProcessor): ...
Source code in climakitae/new_core/processors/abc_data_processor.py
Processor Utilities
Utility functions for processing data arrays in climakitae.
is_station_identifier(value)
Check if a string looks like a station identifier.
This function uses heuristics to determine if a string appears to be a weather station identifier based on common patterns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
String to check |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the value looks like a station code or station name |
Notes
Recognizes two patterns: 1. 4-character codes starting with 'K' (common US airport weather stations) Examples: KSAC (Sacramento), KBFL (Bakersfield), KSFO (San Francisco) 2. Strings with parentheses containing a code with 'K' Examples: "Sacramento (KSAC)", "San Francisco International (KSFO)"
Examples:
>>> is_station_identifier("KSAC")
True
>>> is_station_identifier("Sacramento (KSAC)")
True
>>> is_station_identifier("CA")
False
>>> is_station_identifier("Kern County")
False
Source code in climakitae/new_core/processors/processor_utils.py
find_station_match(station_identifier, stations_df)
Find matching station(s) in the stations DataFrame.
This function centralizes the station matching logic used by both the Clip processor and the clip parameter validator. It tries multiple matching strategies in order of specificity: 1. Exact match on station ID column 2. Exact match on station name column 3. Partial match on station name column
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
station_identifier
|
str
|
Station identifier to search for (e.g., "KSAC", "Sacramento (KSAC)", "Sacramento") |
required |
stations_df
|
DataFrame
|
DataFrame containing station data with columns: ID, station, city, state, LAT_Y, LON_X |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing matching station(s). May have 0, 1, or multiple rows: - Empty (len=0): No matches found - Single row (len=1): Exact match found - Multiple rows (len>1): Multiple stations match the identifier |
Notes
The caller is responsible for: - Checking if stations_df is None or empty before calling - Handling the different match scenarios (no match, single match, multiple matches) - Providing appropriate error messages or warnings based on context
Examples:
>>> # For validation (clip_param_validator.py)
>>> match = find_station_match("KSAC", stations_df)
>>> if len(match) == 0:
... # Handle no match - provide suggestions
>>> elif len(match) > 1:
... # Handle multiple matches - ask user to be more specific
>>> else:
... # Valid single match
... return True
>>> # For coordinate extraction (clip.py)
>>> match = find_station_match("KSAC", stations_df)
>>> if len(match) == 0:
... # Raise ValueError with suggestions
>>> elif len(match) > 1:
... # Raise ValueError asking for more specific identifier
>>> else:
... # Extract coordinates and metadata
... lat = float(match.iloc[0]["LAT_Y"])
... lon = float(match.iloc[0]["LON_X"])
Source code in climakitae/new_core/processors/processor_utils.py
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 | |
extend_time_domain(result)
Extend the time domain of the input data to cover 1980-2100.
This method ensures that all SSP scenarios have historical data included in the time series, allowing for proper warming level calculations. This is handled by concatenating historical data with SSP data and updating the attributes to that of the SSP data. Historical data is expected to be available in the input dictionary with keys formatted the same as SSP keys but with "historical" instead of r"ssp.{3}" (e.g., "ssp245" becomes "historical").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
Dict[str, Union[Dataset | DataArray]]
|
A dictionary containing time-series data with keys representing different scenarios. |
required |
Returns:
| Type | Description |
|---|---|
Union[Dataset, DataArray]
|
The extended time-series data. |
Notes
- By construction, this function will drop reanalysis data.
Source code in climakitae/new_core/processors/processor_utils.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 | |
get_station_coordinates(station_identifier, catalog, stations_df=None)
Get lat/lon coordinates and metadata for a station identifier.
This function provides a centralized way to extract station coordinates from the catalog. It's used by both the Clip processor and the BiasAdjustModelToStation processor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
station_identifier
|
str
|
Station code (e.g., "KSAC") or full station name (e.g., "Sacramento (KSAC)") |
required |
catalog
|
DataCatalog
|
Data catalog instance for accessing station metadata |
required |
stations_df
|
DataFrame
|
Pre-loaded stations DataFrame. If None, will be loaded from catalog. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[float, float, dict]
|
Latitude, longitude, and station metadata dictionary containing: - station_id: Station ID code - station_name: Full station name - city: City name - state: State abbreviation - elevation: Elevation value (if available) |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If catalog is not set or station data is not available |
ValueError
|
If station is not found or multiple matches exist |
Examples:
>>> lat, lon, metadata = get_station_coordinates("KSAC", catalog)
>>> print(f"Sacramento station at ({lat}, {lon})")
>>> print(f"Elevation: {metadata['elevation']}")
Source code in climakitae/new_core/processors/processor_utils.py
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 | |
convert_stations_to_points(station_identifiers, catalog, stations_df=None)
Convert a list of station identifiers to lat/lon coordinates.
This function provides batch conversion of station identifiers to coordinates, used by processors that need to work with multiple stations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
station_identifiers
|
list[str]
|
List of station codes or names |
required |
catalog
|
DataCatalog
|
Data catalog instance for accessing station metadata |
required |
stations_df
|
DataFrame
|
Pre-loaded stations DataFrame. If None, will be loaded from catalog. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[list[tuple[float, float]], list[dict]]
|
List of (lat, lon) tuples and list of metadata dictionaries |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any station is not found or if there are validation errors |
Examples:
>>> stations = ["KSAC", "KSFO", "KLAX"]
>>> points, metadata = convert_stations_to_points(stations, catalog)
>>> for (lat, lon), meta in zip(points, metadata):
... print(f"{meta['station_name']}: ({lat}, {lon})")
Source code in climakitae/new_core/processors/processor_utils.py
resolve_hdp_stations(station_identifiers, hdp_df)
Resolve and validate HDP station identifiers against the HDP catalog.
Validates that every requested station exists in the catalog. Stations may span multiple HDP networks in a single call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
station_identifiers
|
list[str]
|
HDP |
required |
hdp_df
|
DataFrame
|
The HDP catalog dataframe (e.g. |
required |
Returns:
| Type | Description |
|---|---|
tuple[list[str], list[str]]
|
The validated |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any station is not found. |
Examples:
>>> station_ids, network_ids = resolve_hdp_stations(
... ["ASOSAWOS_69007093217"], DataCatalog().hdp.df
... )
Source code in climakitae/new_core/processors/processor_utils.py
resolve_airport_code_to_hdp_station_id(identifier, stations_df, hdp_df=None)
Translate a legacy airport code/name into its HDP ASOSAWOS station_id.
HDP's numeric station_id suffix for the ASOSAWOS network is the same
USAF/WBAN identifier used by the legacy HadISD station lookup table
(catalog["stations"]), so that table still doubles as an airport-code
lookup for ASOS stations, e.g. "KSAC" or "Sacramento (KSAC)" resolves to
"ASOSAWOS_72483023232".
Some legacy stations (those with a placeholder WBAN of 99999) are not in
HDP's ASOSAWOS network but are in OtherISD under the same numeric id.
When hdp_df is provided and the ASOSAWOS id isn't in it, the OtherISD
id is returned instead if it exists.
Only strings that look like a legacy airport code/name (per
is_station_identifier) are translated; anything else (an already-formed
HDP station_id) is returned unchanged, so this is safe to apply
unconditionally to HDP identifiers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identifier
|
str
|
Station identifier as provided by the user. |
required |
stations_df
|
DataFrame
|
The legacy HadISD station lookup table ( |
required |
hdp_df
|
DataFrame
|
The HDP catalog dataframe (e.g. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The HDP |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the identifier ambiguously matches more than one legacy station. |
Examples:
>>> resolve_airport_code_to_hdp_station_id("KSAC", stations_df)
'ASOSAWOS_72483023232'
>>> resolve_airport_code_to_hdp_station_id("ASOSAWOS_69007093217", stations_df)
'ASOSAWOS_69007093217'
Source code in climakitae/new_core/processors/processor_utils.py
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 | |
Implementation Guide
To create a new processor, follow this template:
from climakitae.new_core.processors.abc_data_processor import DataProcessor, register_processor
@register_processor(key="my_processor", priority=50)
class MyProcessor(DataProcessor):
"""Process climate data in a specific way.
Parameters
----------
config : dict
Configuration dictionary with processor-specific parameters
"""
def __init__(self, config=None):
self.config = config or {}
# Validation
def execute(self, data, context):
"""Execute the processing step.
Parameters
----------
data : xr.Dataset or xr.DataArray
Input climate data
context : dict
Shared processing context
Returns
-------
xr.Dataset or xr.DataArray
Processed data with same lazy evaluation properties
"""
# Processing logic
return processed_data
def update_context(self, context):
"""Update shared processing context with metadata.
Parameters
----------
context : dict
Shared context to update with processor metadata
"""
# Store processor-specific metadata
pass
def set_data_accessor(self, catalog):
"""Configure data accessor if needed.
Parameters
----------
catalog : DataCatalog
Data catalog instance for this processor
"""
pass