Skip to content

Instantly share code, notes, and snippets.

@derrickturk
Created May 2, 2023 19:42
Show Gist options
  • Save derrickturk/2c7fb8445e1803c63c7d11c10d97972c to your computer and use it in GitHub Desktop.
Save derrickturk/2c7fb8445e1803c63c7d11c10d97972c to your computer and use it in GitHub Desktop.
View SMT Kingdom .GRD data (WIP)
# Copyright (c) 2023 Derrick W. Turk / terminus, LLC
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sys
import struct
import numpy as np
import numpy.typing as npt
import matplotlib.pyplot as plt # type: ignore
from typing import NamedTuple
_EPS = 1e-3
_KINGDOM_MISSING = struct.unpack('<f', b'\x0C\x13\x9A\xF9')
class KingdomGrid(NamedTuple):
title: str
colorbar_path: str
rows: int
cols: int
color_index: int
zmin: float
zmax: float
xmin: float
ymin: float
xmax: float
ymax: float
xinc: float
yinc: float
data: npt.NDArray[np.float32]
def plot(self) -> None:
plt.imshow(self.data,
extent=(self.xmin, self.xmax, self.ymin, self.ymax),
origin='upper')
plt.title(f'{self.title}')
plt.colorbar()
plt.show()
def read_grid(buf: bytes) -> KingdomGrid:
title, = struct.unpack_from('<256s', buf, 0x10)
cols, rows, color_index, zmin, zmax, colorbar_path = struct.unpack_from(
'<3I2f256s', buf, 0x230)
xmin, ymin, xmax, ymax, xinc, yinc = struct.unpack_from(
'<6d', buf, 0x354)
arr = np.frombuffer(buf, dtype=np.dtype('<f'), offset=0x7a4)
if np.abs(xmin + xinc * (cols - 1) - xmax) > _EPS:
raise ValueError(f'have x = {xmin} to {xmax} but increment {xinc}')
if np.abs(ymin + yinc * (rows - 1) - ymax) > _EPS:
raise ValueError(f'have y = {ymin} to {ymax} but increment {yinc}')
sz = arr.shape[0]
if sz != rows * cols:
raise ValueError(f'expected {rows} x {cols} grid, found {sz} elements')
data = arr.reshape((cols, rows)).transpose().copy()
data[data == _KINGDOM_MISSING] = np.nan
return KingdomGrid(
_asciz_string(title),
_asciz_string(colorbar_path),
rows,
cols,
color_index,
zmin,
zmax,
xmin,
ymin,
xmax,
ymax,
xinc,
yinc,
data,
)
def _asciz_string(buf: bytes) -> str:
return buf[:buf.index(b'\x00')].decode('ascii')
def main(argv: list[str]) -> int:
if len(argv) <= 1:
print(f'Usage: {argv[0] if argv else "view_grid.py"} .grd-files...',
file=sys.stderr)
return 2
had_err = False
for grid in argv[1:]:
try:
with open(grid, 'rb') as f:
g = read_grid(f.read())
print(f'{g.title} ({g.rows} x {g.cols})')
g.plot()
except Exception as e:
print(f'Error reading {grid}: {e}', file=sys.stderr)
had_err = True
return 1 if had_err else 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment