Skip to content

Commit

Permalink
Add bits_per_value option when saving numpyfs grib data (#284)
Browse files Browse the repository at this point in the history
  • Loading branch information
sandorkertesz authored Jan 22, 2024
1 parent aff4b36 commit f21e226
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
5 changes: 4 additions & 1 deletion earthkit/data/writers/grib.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
class GribWriter(Writer):
DATA_FORMAT = "grib"

def write(self, f, values, metadata, check_nans=True):
def write(self, f, values, metadata, check_nans=True, bits_per_value=16):
r"""Write a GRIB field to a file object.
Parameters
Expand All @@ -28,6 +28,9 @@ def write(self, f, values, metadata, check_nans=True):
Replace nans in ``values`` with GRIB missing values when writing to``f``.
"""
handle = metadata._handle.clone()

handle.set_long("bitsPerValue", bits_per_value)

if check_nans:
import numpy as np

Expand Down
17 changes: 17 additions & 0 deletions tests/numpy_fs/test_numpy_fs_write.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import logging
import os
import sys

import numpy as np
import pytest
Expand All @@ -20,6 +21,10 @@
from earthkit.data.core.temporary import temp_file
from earthkit.data.testing import earthkit_examples_file

here = os.path.dirname(__file__)
sys.path.insert(0, here)
from numpy_fs_fixtures import load_numpy_fs # noqa: E402

LOG = logging.getLogger(__name__)


Expand Down Expand Up @@ -144,6 +149,18 @@ def test_numpy_fs_grib_write_generating_proc_id():
assert np.allclose(r_tmp.values[1], v2)


@pytest.mark.parametrize(
"_kwargs,expected_value", [({}, 16), ({"bits_per_value": 12}, 12)]
)
def test_numpy_fs_grib_write_bits_per_value(_kwargs, expected_value):
ds, _ = load_numpy_fs(1)

with temp_file() as tmp:
ds.save(tmp, **_kwargs)
ds1 = from_source("file", tmp)
assert ds1.metadata("bitsPerValue") == [expected_value] * len(ds)


if __name__ == "__main__":
from earthkit.data.testing import main

Expand Down

0 comments on commit f21e226

Please sign in to comment.