Skip to content

Commit

Permalink
Merge pull request #662 from DHI/fix/pfs-copy
Browse files Browse the repository at this point in the history
Fix PfsDocument.copy
  • Loading branch information
ecomodeller authored Mar 11, 2024
2 parents 83a9359 + 221a632 commit 59ea9f7
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 12 deletions.
40 changes: 34 additions & 6 deletions mikeio/pfs/_pfsdocument.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
import re
import warnings
from collections import Counter
from collections.abc import Mapping, Sequence
from datetime import datetime
from pathlib import Path
from typing import Callable, Dict, List, Mapping, Sequence, TextIO, Tuple
from typing import Callable, Dict, List, TextIO, Tuple, overload

import yaml

Expand Down Expand Up @@ -84,10 +85,10 @@ def __init__(
self,
data: TextIO | PfsSection | Dict | str | Path,
*,
encoding: str = "cp1252",
names: Sequence[str] | None = None,
unique_keywords: bool = False,
) -> None:
encoding="cp1252",
names=None,
unique_keywords=False,
):

if isinstance(data, (str, Path)) or hasattr(data, "read"):
if names is not None:
Expand All @@ -103,6 +104,14 @@ def __init__(
if self._is_FM_engine:
self._add_all_FM_aliases()

@staticmethod
def from_text(text: str) -> PfsDocument:
"""Create a PfsDocument from a string"""
from io import StringIO

f = StringIO(text)
return PfsDocument(f)

@staticmethod
def _to_nonunique_key_dict(keys, vals):
key_count = Counter(keys)
Expand Down Expand Up @@ -164,6 +173,14 @@ def names(self) -> List[str]:
rkeys, _ = self._unravel_items(self.items)
return rkeys

def copy(self) -> PfsDocument:
"""Return a deep copy of the PfsDocument"""

lines = self.write()
text = "\n".join(lines)

return PfsDocument.from_text(text)

def _read_pfs_file(self, filename, encoding, unique_keywords=False):
try:
yml = self._pfs2yaml(filename, encoding)
Expand Down Expand Up @@ -356,7 +373,13 @@ def _parse_token(self, token: str, context: str = "") -> str:

return s

def write(self, filename=None):
@overload
def write(self) -> list[str]: ...

@overload
def write(self, filename: str) -> None: ...

def write(self, filename: str | None = None) -> list[str] | None:
"""Write object to a pfs file
Parameters
Expand All @@ -380,3 +403,8 @@ def write(self, filename=None):
f.write("\n\n")

self._write_with_func(f.write, level=0)
return None


# TODO remove this alias
Pfs = PfsDocument
7 changes: 1 addition & 6 deletions mikeio/pfs/_pfssection.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,12 +281,7 @@ def find_replace(self, old_value: Any, new_value: Any) -> None:

def copy(self) -> "PfsSection":
"""Return a copy of the PfsSection."""
# is all this necessary???
d = self.__dict__.copy()
for key, value in d.items():
if isinstance(value, PfsSection):
d[key] = value.to_dict().copy()
return self.__class__(d)
return PfsSection(self.to_dict())

def _to_txt_lines(self) -> List[str]:
lines: List[str] = []
Expand Down
10 changes: 10 additions & 0 deletions tests/test_pfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,16 @@ def test_basic():
assert data.POINT_1.y == 50


def test_pfsdocument_copy():

pfs = mikeio.PfsDocument("tests/testdata/pfs/simple.pfs")
pfs2 = pfs.copy()
data = pfs.targets[0]
data.z_min = -4000

assert pfs2.BoundaryExtractor.z_min == -3000


def test_ecolab():
pfs = mikeio.PfsDocument("tests/testdata/pfs/minimal.ecolab")
assert pfs.ECO_LAB_SETUP.MISC.DESCRIPTION == "Miscellaneous Description"
Expand Down

0 comments on commit 59ea9f7

Please sign in to comment.