Skip to content

Commit

Permalink
#308: Add formatting for xyz file
Browse files Browse the repository at this point in the history
  • Loading branch information
priscavdsluis committed Nov 14, 2022
1 parent 4c0c353 commit de5de22
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
18 changes: 15 additions & 3 deletions hydrolib/core/io/dflowfm/xyz/serializer.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from pathlib import Path
from typing import Dict
from typing import Dict, Generator

from hydrolib.core.basemodel import SerializerConfig

Expand All @@ -16,9 +16,21 @@ def serialize(path: Path, data: Dict, config: SerializerConfig) -> None:
config (SerializerConfig): The serialization configuration.
"""
path.parent.mkdir(parents=True, exist_ok=True)

space = 1 * " "
format_float = lambda x: f"{x:{config.float_format}}"

with path.open("w") as f:
for point in data["points"]:
geometry: str = space.join([format_float(p) for p in XYZSerializer._get_point_values(point)])
if point.comment:
f.write(f"{point.x} {point.y} {point.z} # {point.comment}\n")
f.write(f"{geometry} # {point.comment}\n")
else:
f.write(f"{point.x} {point.y} {point.z}\n")
f.write(f"{geometry}\n")

@staticmethod
def _get_point_values(point) -> Generator[float, None, None]:
yield point.x
yield point.y
yield point.z

2 changes: 2 additions & 0 deletions tests/data/reference/xyz/test.xyz
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
1.23 2.34 3.45
4.57 5.68 6.79 # Some comment
23 changes: 23 additions & 0 deletions tests/io/dflowfm/test_xyz.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from tests.utils import test_output_dir, test_reference_dir, assert_files_equal
from hydrolib.core.io.dflowfm.xyz.models import XYZPoint
from hydrolib.core.io.dflowfm.xyz.serializer import XYZSerializer
from hydrolib.core.basemodel import SerializerConfig

class TestXYZSerializer:
def test_serialize(self):
output_file = test_output_dir / "test.xyz"
reference_file = test_reference_dir / "xyz" / "test.xyz"

data = {
"points" : [
XYZPoint(x=1.232, y=2.343, z= 3.454),
XYZPoint(x=4.565, y=5.676, z= 6.787, comment="Some comment")]
}

config = SerializerConfig(float_format=".2f")

XYZSerializer.serialize(output_file, data, config)

assert_files_equal(output_file, reference_file)


0 comments on commit de5de22

Please sign in to comment.