File: tables.py

package info (click to toggle)
eccodes-python 2%3A2.44.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,048 kB
  • sloc: python: 7,750; ansic: 280; sh: 94; makefile: 81; cpp: 30
file content (267 lines) | stat: -rw-r--r-- 7,897 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# Copyright 2022- ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction.

import csv
import ctypes
import os
import re
import sys
from collections import ChainMap, UserDict
from dataclasses import dataclass
from pathlib import Path
from typing import Iterator, List, Tuple, Union

import eccodes
import gribapi


class Code(int):
    def __new__(cls, code: int):
        return int.__new__(cls, code)

    def __repr__(self) -> str:
        return "'%s'" % str(int(self)).zfill(6)

    @property
    def F(self) -> int:
        return int(self) // 100000

    @property
    def X(self) -> int:
        return int(self) // 1000 % 100

    @property
    def Y(self) -> int:
        return int(self) % 1000

    @property
    def FX(self) -> Tuple[int, int]:
        return self.F, self.X


CodeLike = Union[Code, int]


@dataclass
class Descriptor:
    code: Code = 0
    name: str = ""


@dataclass
class Element(Descriptor):
    units: str = ""
    scale: int = 0
    reference: int = 0
    width: int = 0


@dataclass(unsafe_hash=True)
class Version:
    master: int = 0
    local: int = 0
    centre: int = 0
    subcentre: int = 0


class _Singleton(type(UserDict)):
    cache = {}

    def __call__(cls, *args):
        try:
            obj = cls.cache[cls, args]
        except KeyError:
            obj = super().__call__(*args)
            cls.cache[cls, args] = obj
        return obj


class Table(UserDict, metaclass=_Singleton):
    def __init__(self, version: Version, local: bool) -> None:
        base_path = Path("bufr", "tables", "0")
        if local:
            dashed_version_number = "%d-%d" % (version.master, version.local)
            path = base_path.joinpath(
                "local",
                dashed_version_number,
                str(version.centre),
                str(version.subcentre),
            )
            if not gribapi.grib_full_defs_path(str(path / "element.table")):
                path = base_path.joinpath(
                    "local",
                    str(version.local),
                    str(version.centre),
                    str(version.subcentre),
                )
        else:
            path = base_path.joinpath("wmo", str(version.master))
        self.version = version
        self.path = path
        self.data = {}


class ElementTable(Table):
    def __init__(self, version: Version, local: bool) -> None:
        super().__init__(version, local)
        self.path /= "element.table"
        try:
            text = codes_read_file(self.path)
        except RuntimeError as e:
            if local:
                return  # ignore non-existing local tables
            else:
                raise e
        reader = csv.reader(text.splitlines(), delimiter="|")
        next(reader)  # skip header row
        for r in reader:
            c = Code(int(r[0]))
            e = Element(c, r[1], r[4], int(r[5]), int(r[6]), int(r[7]))
            self.data[c] = e

    def __getitem__(self, code: CodeLike) -> Element:
        try:
            return self.data[code]
        except KeyError:
            message = "No such element in tables version %s (%s): %s"
            raise KeyError(message % (self.version, self.path, code))


class SequenceTable(Table):
    def __init__(self, version: Version, local: bool) -> None:
        super().__init__(version, local)
        self.path /= "sequence.def"
        try:
            text = codes_read_file(self.path)
        except RuntimeError as e:
            if local:
                return  # ignore non-existing local tables
            else:
                raise e
        tokens = re.split("]\n?", text)
        tokens = tokens[:-1]  # strip the last, empty token
        for token in tokens:
            pair = token.split("= [")
            code = int(pair[0].strip().strip('"'))
            sequence = [Code(c) for c in pair[1].split(",")]
            self.data[code] = sequence

    def __getitem__(self, code: CodeLike) -> List[Code]:
        try:
            return self.data[code]
        except KeyError:
            message = "No such element in tables version %s (%s): %s"
            raise KeyError(message % (self.version, self.path, code))


class CombinedTable(Table):
    def __init__(self, table_class, version):
        self.master = table_class(version, False)
        self.local = table_class(version, True)
        self.version = version
        self.data = ChainMap(self.local.data, self.master.data)  # [1]

    # [1] Note that the individual mappings in the ChainMap are searched from first to last.


class Tables:
    def __init__(self, version):
        self.sequences = CombinedTable(SequenceTable, version)
        self.elements = CombinedTable(ElementTable, version)
        self.version = version

    def expand_codes(
        self, code_s: Union[CodeLike, List[CodeLike]], recursive=True
    ) -> Iterator[Code]:
        if isinstance(code_s, int):
            codes = [code_s]
        else:
            codes = code_s
        for c in map(Code, codes):
            if c.F == 3:
                sequence_codes = self.sequences[c]
                if recursive:
                    yield from self.expand_codes(sequence_codes)
                else:
                    yield from sequence_codes
            else:
                yield c

    def expand_descriptors(
        self, codes_s: Union[CodeLike, List[CodeLike]], recursive=True
    ) -> Iterator[Descriptor]:
        previous_code = Code(0)
        for code in self.expand_codes(codes_s, recursive):
            name = None
            if code.F == 0:
                try:
                    name = self.elements[code].name
                except KeyError as error:
                    if previous_code.FX == (2, 6):  # Operator: Signify data width
                        # TODO: raise warning
                        name = ""
                    else:
                        raise error
                previous_code = code
            yield Descriptor(code, name)


libcname = "msvcrt" if sys.platform.startswith("win") else None

libc = ctypes.CDLL(
    libcname, winmode=0
)  # automatically finds and loads the C standard library

fseek = libc.fseek
fseek.argtypes = [ctypes.c_void_p, ctypes.c_long, ctypes.c_int]
fseek.restype = ctypes.c_int
SEEK_SET, SEEK_END = 0, 2

ftell = libc.ftell
ftell.argtypes = [ctypes.c_void_p]
ftell.restype = ctypes.c_long

fread = libc.fread
fread.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_size_t, ctypes.c_void_p]
fread.restype = ctypes.c_size_t

fclose = libc.fclose
fclose.argtypes = [ctypes.c_void_p]
fclose.restype = ctypes.c_int

libeccodes = ctypes.CDLL(eccodes.codes_get_library_path())

codes_fopen = libeccodes.codes_fopen
codes_fopen.restype = ctypes.c_void_p


def codes_has_file(path: Union[str, os.PathLike]) -> bool:
    stream = libeccodes.codes_fopen(str(path).encode(), b"r")
    if stream:
        libc.fclose(stream)
        has = True
    else:
        has = False
    return has


def codes_read_file(path: Union[str, os.PathLike]) -> str:
    full_path = gribapi.grib_full_defs_path(str(path))
    stream = libeccodes.codes_fopen(full_path.encode(), b"r")
    if not stream:
        raise RuntimeError(f"Tables path does not exist: {path}")
    try:
        fseek(stream, 0, SEEK_END)
        buffer_size = ftell(stream)
        buffer = ctypes.create_string_buffer(buffer_size)
        fseek(stream, 0, SEEK_SET)
        read_size = fread(buffer, ctypes.sizeof(ctypes.c_char), buffer_size, stream)
        string = buffer.raw[:read_size].decode()
    finally:
        fclose(stream)
    return string