geo-parameters 0.12.6__py3-none-any.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.
@@ -0,0 +1,11 @@
1
+ from .parameter_funcs import (
2
+ list_of_parameters,
3
+ dict_of_parameters,
4
+ create_parameter_dict,
5
+ get,
6
+ shortget,
7
+ )
8
+
9
+ from . import wave, wind, ocean, grid, atm
10
+
11
+ from .metaparameter import decode, is_same_class,is_gp, is_gp_instance, is_gp_class
geo_parameters/atm.py ADDED
@@ -0,0 +1,49 @@
1
+ from geo_parameters.metaparameter import MetaParameter
2
+ from typing import Optional, Union
3
+ from .relationships import _get_family_dict, _verify_param_type
4
+
5
+
6
+ class AtmosphereParameter(MetaParameter):
7
+ @classmethod
8
+ def my_family(
9
+ cls, param_type: Optional[str] = None
10
+ ) -> Union[dict[str, type["AtmosphereParameter"]], type["AtmosphereParameter"], None]:
11
+ """Returns the dictonary containing the parameters where cls is in.
12
+ Use .my_family('direction') to get the parameter isntead of a dict"""
13
+
14
+ _verify_param_type(param_type)
15
+ family_dict = _get_family_dict(cls)
16
+
17
+ if param_type is None: # Return entire family_dict
18
+ return_dict = {}
19
+ for key, value in family_dict.items():
20
+ # E.g. eval("XWind"), which can't be done outside of this module
21
+ return_dict[key] = eval(value)
22
+ return return_dict
23
+ else: # Retrun class for requested parameter type
24
+ return eval(family_dict.get(param_type, "None"))
25
+
26
+
27
+ class AirTemperature(AtmosphereParameter):
28
+ name = "t"
29
+ _long_name = "air temperature"
30
+ _standard_name = "air_temperature"
31
+ _unit = 'K'
32
+
33
+ class RelativeHumidity(AtmosphereParameter):
34
+ name = "r"
35
+ _long_name = "relative humidity"
36
+ _standard_name = "relative_humidity"
37
+ _unit = '%'
38
+
39
+ class SpecificHumidity(AtmosphereParameter):
40
+ name = "q"
41
+ _long_name = "specific humidity"
42
+ _standard_name = "specific_humidity"
43
+ _unit = '-'
44
+
45
+ class MeanSeaLevelPressure(AtmosphereParameter):
46
+ name = 'mslp'
47
+ _long_name = 'mean sea level pressure'
48
+ _standard_name = ['air_pressure_at_mean_sea_level', 'air_pressure_at_sea_level']
49
+ _unit = 'N/m**2'
geo_parameters/grid.py ADDED
@@ -0,0 +1,76 @@
1
+ from geo_parameters.metaparameter import MetaParameter
2
+ from typing import Optional, Union
3
+ from .relationships import _get_family_dict, _verify_param_type
4
+
5
+
6
+ class GridParameter(MetaParameter):
7
+ @classmethod
8
+ def my_family(
9
+ cls, param_type: Optional[str] = None
10
+ ) -> Union[dict[str, type["GridParameter"]], type["GridParameter"], None]:
11
+ """Returns the dictonary containing the parameters where cls is in.
12
+ Use .my_family('direction') to get the parameter isntead of a dict"""
13
+
14
+ _verify_param_type(param_type)
15
+ family_dict = _get_family_dict(cls)
16
+
17
+ if param_type is None: # Return entire family_dict
18
+ return_dict = {}
19
+ for key, value in family_dict.items():
20
+ # E.g. eval("Lon"), which can't be done outside of this module
21
+ return_dict[key] = eval(value)
22
+ return return_dict
23
+ else: # Retrun class for requested parameter type
24
+ return eval(family_dict.get(param_type, "None"))
25
+
26
+
27
+ class Lon(GridParameter):
28
+ name = "lon"
29
+ _long_name = "longitude"
30
+ _standard_name = "longitude"
31
+ _unit = "degrees_east"
32
+ _projection_type = 'lonlat'
33
+
34
+
35
+ class Lat(GridParameter):
36
+ name = "lat"
37
+ _long_name = "latitude"
38
+ _standard_name = "latitude"
39
+ _unit = "degrees_north"
40
+ _projection_type = 'lonlat'
41
+
42
+
43
+ class X(GridParameter):
44
+ name = "x"
45
+ _long_name = "easting"
46
+ _standard_name = "projection_x_coordinate"
47
+ _unit = 'm'
48
+ _projection_type = 'xy'
49
+
50
+ class Y(GridParameter):
51
+ name = "y"
52
+ _long_name = "northing"
53
+ _standard_name = "projection_y_coordinate"
54
+ _unit = 'm'
55
+ _projection_type = 'xy'
56
+
57
+ class RLon(GridParameter):
58
+ name = "x"
59
+ _long_name = "rotated longitude"
60
+ _standard_name = "grid_longitude"
61
+ _unit = 'degrees'
62
+ _projection_type = 'xy'
63
+
64
+ class RLat(GridParameter):
65
+ name = "y"
66
+ _long_name = "rotated latitude"
67
+ _standard_name = "grid_latitude"
68
+ _unit = 'degrees'
69
+ _projection_type = 'xy'
70
+
71
+ class Inds(GridParameter):
72
+ name = "inds"
73
+ _long_name = "index of points"
74
+ _standard_name = "index_of_geophysical_points"
75
+ _unit = "1"
76
+ _cf = False
@@ -0,0 +1,303 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import Union
3
+
4
+ #from .relationships import RELATIONSHIPS
5
+ from typing import Iterable
6
+
7
+ class ClassAccessor:
8
+ def __get__(self, instance, owner):
9
+ # owner is always the class (e.g. Test)
10
+ if instance is None:
11
+ # Accessed on the class: Test.cls
12
+ return owner
13
+ else:
14
+ # Accessed on an instance: Test().cls
15
+ # Return the instance's actual class (handles subclasses too)
16
+ return instance.__class__
17
+
18
+
19
+ class MetaParameter(ABC):
20
+ _cf = True
21
+ _projection_type = None
22
+ cls = ClassAccessor()
23
+
24
+
25
+ def __init__(self, name: str = ""):
26
+ self.name = name or self.name
27
+
28
+ @staticmethod
29
+ @abstractmethod
30
+ def _long_name() -> str:
31
+ pass
32
+
33
+ @staticmethod
34
+ @abstractmethod
35
+ def _standard_name() -> str:
36
+ pass
37
+
38
+ @staticmethod
39
+ @abstractmethod
40
+ def _unit() -> str:
41
+ pass
42
+
43
+ @classmethod
44
+ def cf(cls) -> bool:
45
+ return cls._cf
46
+
47
+ @classmethod
48
+ def long_name(cls) -> str:
49
+ return cls._long_name
50
+
51
+ @classmethod
52
+ def standard_name(cls, strict: bool = False, alias: bool = False) -> str:
53
+ names = cls._standard_name
54
+ if not isinstance(names, list):
55
+ names = [names]
56
+ if cls.cf() or not strict:
57
+ if alias:
58
+ return str(names[-1])
59
+ return str(names[0])
60
+
61
+ return ""
62
+
63
+ @classmethod
64
+ def standard_aliases(cls, strict=False) -> list[str]:
65
+ """Returns a list of all aliases, possible a list of only one name"""
66
+ if cls.cf() or not strict:
67
+ if isinstance(cls._standard_name, list):
68
+ return cls._standard_name
69
+ else:
70
+ return [cls._standard_name]
71
+
72
+ return [""]
73
+
74
+ @classmethod
75
+ def units(cls) -> str:
76
+ return cls._unit
77
+
78
+ @classmethod
79
+ def cf(cls) -> str:
80
+ return cls._cf
81
+
82
+ @classmethod
83
+ def projection_type(cls) -> str:
84
+ return cls._projection_type
85
+
86
+ @classmethod
87
+ def meta_dict(cls, alias: bool = False) -> dict:
88
+ return {
89
+ "short_name": cls.name,
90
+ "long_name": cls.long_name(),
91
+ "standard_name": cls.standard_name(alias=alias),
92
+ "units": str(cls.units()),
93
+ }
94
+
95
+ @classmethod
96
+ def find_me_in_ds(
97
+ cls, ds, return_first: bool = False
98
+ ) -> Union[list[str], str, None]:
99
+ """Takes an Xarray Dataset and returns list of all variable names that matches the parameter based on standard_name
100
+
101
+ If return_first = True, then returns first name as a sting"""
102
+ data_vars = list(ds.data_vars)
103
+ coords = list(ds.coords)
104
+
105
+ if not return_first:
106
+ vars = []
107
+
108
+ for var in data_vars:
109
+ if hasattr(ds.get(var), "standard_name"):
110
+ if ds.get(var).standard_name in cls.standard_aliases():
111
+ if return_first:
112
+ return var
113
+ else:
114
+ vars.append(var)
115
+
116
+ for var in coords:
117
+ if hasattr(ds.get(var), "standard_name"):
118
+ if ds.get(var).standard_name in cls.standard_aliases():
119
+ if return_first:
120
+ return var
121
+ else:
122
+ vars.append(var)
123
+
124
+ if return_first:
125
+ return None
126
+ else:
127
+ return vars
128
+
129
+ @classmethod
130
+ def i_am(cls) -> str:
131
+ """Finds what role this parameter has in a possible relationship to other parameters.
132
+ Roles are:
133
+ 'x', 'y', 'mag', 'dir', 'opposite_dir'
134
+ 'period', 'frequency', 'angular_frequency'
135
+ """
136
+ if cls.my_family() is None:
137
+ return None
138
+ for key, value in cls.my_family().items():
139
+ if cls.is_same(value):
140
+ return key
141
+ return None
142
+
143
+ @classmethod
144
+ def my_twin(cls):
145
+ if cls.i_am() == 'x':
146
+ return cls.my_family().get('y')
147
+ elif cls.i_am() == 'y':
148
+ return cls.my_family().get('x')
149
+ elif cls.i_am() == 'east':
150
+ return cls.my_family().get('north')
151
+ elif cls.i_am() == 'north':
152
+ return cls.my_family().get('east')
153
+ return None
154
+
155
+ @classmethod
156
+ def rot(cls):
157
+ if cls.i_am() == 'x':
158
+ return cls.my_family().get('east')
159
+ elif cls.i_am() == 'y':
160
+ return cls.my_family().get('north')
161
+ elif cls.i_am() == 'east':
162
+ return cls.my_family().get('x')
163
+ elif cls.i_am() == 'north':
164
+ return cls.my_family().get('y')
165
+ return None
166
+
167
+ @classmethod
168
+ def opposite_direction(cls):
169
+ if cls.i_am() == 'direction':
170
+ return cls.my_family().get('opposite_direction')
171
+ elif cls.i_am() == 'opposite_direction':
172
+ return cls.my_family().get('direction')
173
+ return None
174
+
175
+
176
+ @classmethod
177
+ def is_same(cls, gp) -> bool:
178
+ """Compares name of parameter and standard_name and returns true if they match
179
+
180
+ param = gp.wave.Hs
181
+ param.is_same(gp.wave.Hs) [True]
182
+ param.is_same(gp.wave.Hs()) [True]
183
+ param.is_same(gp.wave.Hs('other_name')) [True]
184
+ param.is_same(gp.wave.Hmax) [False]
185
+ """
186
+ try:
187
+ gp = gp()
188
+ except TypeError:
189
+ pass
190
+
191
+ type_match = type(cls()).__name__ == type(gp).__name__
192
+ try:
193
+ std_name_match = cls.standard_name() == gp.standard_name()
194
+ return type_match and std_name_match
195
+ except AttributeError:
196
+ return False
197
+
198
+ @classmethod
199
+ def is_in(cls, parameters: Iterable) -> bool:
200
+ """Checks if the parameter class is in (using .is_same()) in the list of provided parameters
201
+
202
+ Examples:
203
+ >> gp.wave.Hs.is_in([gp.wave.Hs, gp.wave.Tp]) -> True
204
+ >> gp.wave.Hs.is_in([gp.wave.Dirp, gp.wave.Tp]) -> False
205
+ >> gp.wave.Hs.is_in([]) -> False
206
+ >> gp.wave.Hs.is_in(['hs']) -> False
207
+ >> gp.wave.Hs.is_in([gp.wave.Hs(), 'hs']) -> True
208
+ """
209
+
210
+ for param in parameters:
211
+ if cls.is_same(param):
212
+ return True
213
+ return False
214
+
215
+ @classmethod
216
+ def find_me_in(
217
+ cls, parameters: Iterable, return_first: bool = False
218
+ ) -> Union[list, None]:
219
+ """Gets the parameters in list that matches the class (using .is_same())
220
+
221
+ Examples:
222
+ >> gp.wave.Hs.find_me_in([gp.wave.Hs, gp.wave.Tp]) -> gp.wave.Hs
223
+ >> gp.wave.Hs.find_me_in([gp.wave.Dirp, gp.wave.Tp]) -> None
224
+ >> gp.wave.Hs.find_me_in([]) -> None
225
+ >> gp.wave.Hs.find_me_in(['hs']) -> None
226
+ >> swh = gp.wave.Hs("swh")
227
+ >> gp.wave.Hs.find_me_in([swh, 'hs']) -> swh
228
+ """
229
+ matching_params = []
230
+ for param in parameters:
231
+ if cls.is_same(param):
232
+ if return_first:
233
+ return param
234
+ else:
235
+ matching_params.append(param)
236
+
237
+ if return_first:
238
+ return None
239
+ else:
240
+ return matching_params
241
+
242
+ @classmethod
243
+ def dir_type(cls) -> str:
244
+ for std_name in cls.standard_aliases():
245
+ if "to_direction" in std_name:
246
+ return "to"
247
+ if "from_direction" in std_name:
248
+ return "from"
249
+ return None
250
+
251
+
252
+ def is_same_class(param1, param2) -> bool:
253
+ """Checks if parameters (possibly initiated instances) are the same parameter class
254
+
255
+ gp.is_same_class(gp.wave.Hs, gp.wave.Hs) -> True
256
+ gp.is_same_class(gp.wave.Hs, gp.wave.Hs('swh')) -> True
257
+ gp.is_same_class(gp.wave.Hs, gp.wave.Tp) -> False"""
258
+ __, p1 = decode(param1, init=True)
259
+ __, p2 = decode(param2, init=True)
260
+
261
+ return p1.__class__.mro()[0].__name__ == p2.__class__.mro()[0].__name__
262
+
263
+
264
+ def decode(parameter, init: bool = False) -> tuple[str, MetaParameter]:
265
+ """Returns the name of the geo-parameter and the geo-parameter.
266
+ If a string is given, the string and None is returned, otherwise an error is thrown.
267
+
268
+ Examples:
269
+ >> gp.decode(gp.wave.Hs('hsig)) -> ('hsig', gp.wave.Hs('hsig'))
270
+ >> gp.decode('hsig') -> ('hsig', None)
271
+ >> gp.decode(gp.wave.Hs) -> ('hs', gp.wave.Hs)
272
+ >> gp.decode(gp.wave.Hs, init=True) -> ('hs', gp.wave.Hs())
273
+ >> gp.decode(<xr.DataArray>) -> *** TypeError: Can only decode types 'MetaParameter' and 'str', not 'DataArray'
274
+ """
275
+
276
+ if is_gp(parameter):
277
+ if init and is_gp_class(parameter):
278
+ parameter = parameter()
279
+ return parameter.name, parameter
280
+ elif isinstance(parameter, str):
281
+ return parameter, None
282
+ else:
283
+ raise TypeError(
284
+ f"Can only decode types 'MetaParameter' and 'str', not '{type(parameter).__name__}'"
285
+ )
286
+
287
+
288
+ def is_gp(parameter) -> bool:
289
+ """Checks if the given objects is an instance or class of a geo-parameter"""
290
+ return is_gp_instance(parameter) or is_gp_class(parameter)
291
+
292
+
293
+ def is_gp_instance(parameter) -> bool:
294
+ """Checks if the given object is an instance of a geo-parameter"""
295
+ return isinstance(parameter, MetaParameter)
296
+
297
+
298
+ def is_gp_class(parameter) -> bool:
299
+ """Checks if the given object is a geo-parameter class (i.e. a subclass of MetaParameter"""
300
+ try:
301
+ return issubclass(parameter, MetaParameter)
302
+ except TypeError:
303
+ return False
@@ -0,0 +1,4 @@
1
+ """This contains aliases from commonly used models to geo-parameters"""
2
+
3
+ from . import wave
4
+ WAM = {'Pdir': wave.DirpTo}
@@ -0,0 +1,141 @@
1
+ from geo_parameters.metaparameter import MetaParameter
2
+ from typing import Optional, Union
3
+ from .relationships import _get_family_dict, _verify_param_type
4
+
5
+ class OceanParameter(MetaParameter):
6
+ @classmethod
7
+ def my_family(
8
+ cls, param_type: Optional[str] = None
9
+ ) -> Union[dict[str, type["OceanParameter"]], type["OceanParameter"], None]:
10
+ """Returns the dictonary containing the parameters where cls is in.
11
+ Use .my_family('direction') to get the parameter isntead of a dict"""
12
+
13
+ _verify_param_type(param_type)
14
+ family_dict = _get_family_dict(cls)
15
+
16
+ if param_type is None: # Return entire family_dict
17
+ return_dict = {}
18
+ for key, value in family_dict.items():
19
+ # E.g. eval("WaterDepth"), which can't be done outside of this module
20
+ return_dict[key] = eval(value)
21
+ return return_dict
22
+ else: # Retrun class for requested parameter type
23
+ return eval(family_dict.get(param_type, "None"))
24
+
25
+
26
+ class WaterDepth(OceanParameter):
27
+ name = "depth"
28
+ _long_name = "water_depth"
29
+ _standard_name = "sea_floor_depth_below_sea_surface"
30
+ _unit = 'm'
31
+
32
+
33
+ class SeaLevel(OceanParameter):
34
+ name = "eta"
35
+ _long_name = "sea surface height"
36
+ _standard_name = [
37
+ "sea_surface_elevation",
38
+ "sea_surface_elevation_anomaly",
39
+ "sea_surface_height_above_geoid",
40
+ ]
41
+ _unit = 'm'
42
+
43
+
44
+ class XCurrent(OceanParameter):
45
+ name = "x_current"
46
+ _long_name = "current x-component"
47
+ _standard_name = [
48
+ "sea_water_x_velocity",
49
+ "x_sea_water_velocity",
50
+ ]
51
+ _unit = 'm/s'
52
+ _projection_type = 'xy'
53
+
54
+ class YCurrent(OceanParameter):
55
+ name = "y_current"
56
+ _long_name = "current y-component"
57
+ _standard_name = [
58
+ "sea_water_y_velocity",
59
+ "y_sea_water_velocity",
60
+ ]
61
+ _unit = 'm/s'
62
+ _projection_type = 'xy'
63
+
64
+
65
+ class EastCurrent(OceanParameter):
66
+ name = "u_current"
67
+ _long_name = "current east-component"
68
+ _standard_name = "eastward_sea_water_velocity"
69
+ _unit = 'm/s'
70
+ _projection_type = 'lonlat'
71
+
72
+
73
+ class NorthCurrent(OceanParameter):
74
+ name = "v_current"
75
+ _long_name = "current north-component"
76
+ _standard_name = "northward_sea_water_velocity"
77
+ _unit = 'm/s'
78
+ _projection_type = 'lonlat'
79
+
80
+
81
+ class Current(OceanParameter):
82
+ name = "current"
83
+ _long_name = "current speed"
84
+ _standard_name = "sea_water_speed"
85
+ _unit = 'm/s'
86
+
87
+
88
+ class CurrentDir(OceanParameter):
89
+ name = "current_dir"
90
+ _long_name = "current to-direction"
91
+ _standard_name = [
92
+ "sea_water_velocity_to_direction",
93
+ "sea_water_to_direction",
94
+ "direction_of_sea_water_velocity",
95
+ ]
96
+ _unit = 'deg'
97
+ _projection_type = 'lonlat'
98
+
99
+ class CurrentDirFrom(OceanParameter):
100
+ name = "current_dir"
101
+ _long_name = "current from-direction"
102
+ _standard_name = [
103
+ "sea_water_velocity_from_direction",
104
+ "sea_water_from_direction",
105
+ ]
106
+ _unit = 'deg'
107
+ _projection_type = 'lonlat'
108
+
109
+
110
+ class IceFraction(OceanParameter):
111
+ name = "ice_fraction"
112
+ _long_name = "sea ice fraction"
113
+ _standard_name = "sea_ice_area_fraction"
114
+ _unit = '%'
115
+
116
+
117
+ class IceThickness(OceanParameter):
118
+ name = "ice_thickness"
119
+ _long_name = "sea ice thickness"
120
+ _standard_name = "sea_ice_thickness"
121
+ _unit = 'm'
122
+
123
+
124
+ class SeaSurfaceTemperature(OceanParameter):
125
+ name = 'sst'
126
+ _long_name = 'sea surface temperature'
127
+ _standard_name = "sea_surface_temperature"
128
+ _unit = 'K'
129
+
130
+ class SeaSurfaceSalinity(OceanParameter):
131
+ name = 'sss'
132
+ _long_name = 'sea surface salinity'
133
+ _standard_name = "sea_surface_salinity"
134
+ _unit = 'g/kg'
135
+
136
+ class SeaSurfaceDensity(OceanParameter):
137
+ name = 'ssd'
138
+ _long_name = 'sea surface density'
139
+ _standard_name = "sea_surface_density"
140
+ _unit = 'kg/m**3'
141
+
@@ -0,0 +1,57 @@
1
+ from . import wave, ocean, wind
2
+ import inspect
3
+ from .metaparameter import MetaParameter
4
+ from .wind import WindParameter
5
+ from .wave import WaveParameter
6
+ from .ocean import OceanParameter
7
+ from .grid import GridParameter
8
+
9
+ BaseParameters = [
10
+ MetaParameter,
11
+ WindParameter,
12
+ WaveParameter,
13
+ OceanParameter,
14
+ GridParameter,
15
+ ]
16
+
17
+
18
+ def list_of_parameters() -> list:
19
+ """Get a list of all available geo-parameters"""
20
+ parameter_list = []
21
+ modules_to_inspect = [wave, ocean, wind]
22
+ for module in modules_to_inspect:
23
+ for __, obj in inspect.getmembers(module):
24
+ if inspect.isclass(obj):
25
+ if issubclass(obj, MetaParameter) and not obj in BaseParameters:
26
+ parameter_list.append(obj)
27
+ return parameter_list
28
+
29
+
30
+ def dict_of_parameters(short: bool = False, alias: bool = False) -> dict:
31
+ """Get a dict of all availabel geo-parameters.
32
+
33
+ Key is either standard_name (default), alias (alias=True) or non standard short name (short=True)
34
+ """
35
+ if short:
36
+ return {c.name: c for c in list_of_parameters()}
37
+ return {c.standard_name(alias=alias): c for c in list_of_parameters()}
38
+
39
+
40
+ def shortget(key: str):
41
+ """Find a geo-parameter based on a short string. Warning, these short strings follow no standard convention."""
42
+ return dict_of_parameters(short=True).get(key)
43
+
44
+
45
+ def get(key: str):
46
+ """Find a geo-parameter based on a string of the standard_name (or an alias)."""
47
+ return dict_of_parameters().get(key) or dict_of_parameters(alias=True).get(key)
48
+
49
+
50
+ def create_parameter_dict(parameter_strings: list[str]):
51
+ """Create a dict of geo-parameters based on a list of strings of standard_names"""
52
+ metaparameter_dict = {}
53
+ for param in parameter_strings:
54
+ val = get(param)
55
+ if val is not None:
56
+ metaparameter_dict[param] = val
57
+ return metaparameter_dict