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
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 | |
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
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 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 | |
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 StationBiasCorrection 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
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 1094 1095 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 | |
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
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