Skip to content

Limit JSON print to 10 significant figures #86

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Aug 2, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add a context manager for modifying the JSON encoder
  • Loading branch information
tbody-cfs committed Aug 2, 2024
commit b64ac22c9d0620691ffbc1ef2c27b684a87fecdc
50 changes: 36 additions & 14 deletions cfspopcon/file_io.py
Original file line number Diff line number Diff line change
@@ -2,7 +2,7 @@

import json
from pathlib import Path
from typing import Any, Literal
from typing import Any, Literal, Self

import numpy as np
import xarray as xr
@@ -91,6 +91,38 @@ def read_dataset_from_netcdf(filepath: Path) -> xr.Dataset:
return dataset


# These following lines are needed to modify the representation of floats
# in the JSON file. This is needed, because otherwise small errors in the
# floats lead to a large, meaningless diff of the reference JSON files.


class RoundingFloat(float):
"""A modified version of the 'float' built-in, with a modified __repr__.

This is needed because `iterencode` directly uses `float.__repr__` in `floatstr`.

From: https://stackoverflow.com/questions/54370322/how-to-limit-the-number-of-float-digits-jsonencoder-produces
"""

__repr__ = staticmethod(lambda x: f"{x:#.10g}") # type:ignore[assignment,unused-ignore]


class ModifyJSONFloatRepr:
"""A ContextManager to locally modify the representation of floats."""

def __enter__(self) -> Self:
"""Change the float representation to fixed precision on entry."""
self.c_make_encoder = json.encoder.c_make_encoder # type:ignore[attr-defined]
json.encoder.c_make_encoder = None # type:ignore[attr-defined]
json.encoder.float = RoundingFloat # type:ignore[attr-defined]
return self

def __exit__(self, *args: Any) -> None:
"""Change the float representation back to the default."""
json.encoder.c_make_encoder = self.c_make_encoder # type:ignore[attr-defined]
json.encoder.float = float # type:ignore[attr-defined]


def write_point_to_file(dataset: xr.Dataset, point_key: str, point_params: dict, output_dir: Path) -> None:
"""Write the analysis values at the named points to a json file."""
mask = build_mask_from_dict(dataset, point_params)
@@ -121,16 +153,6 @@ def write_point_to_file(dataset: xr.Dataset, point_key: str, point_params: dict,

output_dir.mkdir(parents=True, exist_ok=True)

class RoundingFloat(float):
"""A formatter to control how floats are written to JSON.

From: https://stackoverflow.com/questions/54370322/how-to-limit-the-number-of-float-digits-jsonencoder-produces
"""

__repr__ = staticmethod(lambda x: f"{x:#.10g}") # type:ignore[assignment,unused-ignore]

json.encoder.c_make_encoder = None # type:ignore[attr-defined]
json.encoder.float = RoundingFloat # type:ignore[attr-defined]

with open(output_dir / f"{point_key}.json", "w") as file:
json.dump(point.to_dict(), file, indent=4, sort_keys=True)
with ModifyJSONFloatRepr():
with open(output_dir / f"{point_key}.json", "w") as file:
json.dump(point.to_dict(), file, indent=4, sort_keys=True)
Loading