Skip to content

Commit dcde9ef

Browse files
committed
Add yaml obs converter
The purpose of this converter class is to support conversion of observation configurations to a format supported by webviz. For now, only summary observations are of interest. RFTs are manually loaded through other workflows and other observations are not of interest as of now. Localization is not supported in webviz, so those attributes are left out.
1 parent 321a50d commit dcde9ef

4 files changed

Lines changed: 186 additions & 1 deletion

File tree

src/ert/observation_converters/dispatcher.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,21 @@
99
from .summary_to_bulk import (
1010
convert_summary_to_bulk,
1111
)
12+
from .summary_to_yaml import convert_summary_to_yaml
1213

1314

1415
class SupportedFormat(StrEnum):
1516
SUMMARY = "summary"
1617
BULK = "bulk"
18+
YAML = "yaml"
1719

1820

1921
ConverterFunction = Callable[[str], None]
2022

2123
_SUPPORTED_CONVERSIONS: dict[SupportedFormat, ConverterFunction] = {
2224
SupportedFormat.BULK: convert_summary_to_bulk,
2325
SupportedFormat.SUMMARY: convert_history_to_summary,
26+
SupportedFormat.YAML: convert_summary_to_yaml,
2427
}
2528

2629

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
from pathlib import Path
2+
from typing import Literal, TypedDict
3+
4+
from ruamel.yaml import YAML
5+
6+
from ert.cli.main import ErtCliError
7+
from ert.config import ErtConfig, Observation
8+
9+
10+
class YamlObservation(TypedDict):
11+
date: str
12+
value: float
13+
error: float
14+
15+
16+
class SummaryDict(TypedDict):
17+
key: str
18+
observations: list[YamlObservation]
19+
20+
21+
YamlDict = dict[Literal["smry"], list[SummaryDict]]
22+
23+
24+
class YamlConverter:
25+
target_file = "summary_observations.yaml"
26+
27+
def __init__(self, observations: list[Observation]) -> None:
28+
summary_observations = [
29+
o for o in observations if o.type == "summary_observation"
30+
]
31+
if not summary_observations:
32+
raise ErtCliError("No summary observations found.\nExiting ...")
33+
34+
self.summary_observations = summary_observations
35+
36+
def _summary_to_yaml_dict(self) -> YamlDict:
37+
summary_observations = [
38+
o for o in self.summary_observations if o.type == "summary_observation"
39+
]
40+
summary_keys: set[str] = {o.key for o in summary_observations}
41+
summary_list: list[SummaryDict] = []
42+
for key in summary_keys:
43+
observations_with_key = [o for o in summary_observations if o.key == key]
44+
obs_dicts: list[YamlObservation] = [
45+
{"date": o.date, "value": o.value, "error": o.error}
46+
for o in observations_with_key
47+
]
48+
summary_dict: SummaryDict = {"key": key, "observations": obs_dicts}
49+
summary_list.append(summary_dict)
50+
return {"smry": summary_list}
51+
52+
def export_yaml(self) -> None:
53+
yaml = YAML()
54+
yaml_dict = self._summary_to_yaml_dict()
55+
if Path(self.target_file).is_file():
56+
raise ErtCliError(
57+
f"A file with name '{self.target_file}' already exists. "
58+
f"Will not overwrite it and exit instead."
59+
)
60+
with Path(self.target_file).open("w", encoding="utf-8") as f:
61+
yaml.dump(yaml_dict, f)
62+
print(f"Successfully wrote summary observations to '{self.target_file}'.")
63+
64+
65+
def convert_summary_to_yaml(config: str) -> None:
66+
ert_config = ErtConfig.from_file(config)
67+
yaml_exporter = YamlConverter(
68+
observations=ert_config.observation_declarations,
69+
)
70+
yaml_exporter.export_yaml()

tests/ert/unit_tests/cli/test_summary_to_bulk.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def _make_summary_obs(
112112
key += f":{well}" if well else ""
113113
return SummaryObservation(
114114
name="foo",
115-
key=f"{key}:{well}",
115+
key=key,
116116
value=0.5,
117117
error=0.02,
118118
date=date,
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
from pathlib import Path
2+
from textwrap import dedent
3+
from unittest.mock import MagicMock
4+
5+
import pytest
6+
7+
from ert.cli.main import ErtCliError
8+
from ert.config._observations import GeneralObservation
9+
from ert.observation_converters import convert_observations
10+
from ert.observation_converters.summary_to_yaml import YamlConverter
11+
from tests.ert.unit_tests.cli.test_summary_to_bulk import _make_summary_obs
12+
13+
14+
@pytest.mark.usefixtures("snake_oil_case")
15+
def test_that_happy_path_on_snake_oil_produces_yaml_and_stdout(capsys):
16+
args = MagicMock(format="yaml", config="snake_oil.ert")
17+
convert_observations(args)
18+
19+
expected_yaml_content = dedent("""\
20+
smry:
21+
- key: WOPR:OP1
22+
observations:
23+
- date: '2010-03-31T00:00:00'
24+
value: 0.1
25+
error: 0.05
26+
- date: '2010-12-26T00:00:00'
27+
value: 0.7
28+
error: 0.07
29+
- date: '2011-12-21T00:00:00'
30+
value: 0.5
31+
error: 0.05
32+
- date: '2012-12-15T00:00:00'
33+
value: 0.3
34+
error: 0.075
35+
- date: '2013-12-10T00:00:00'
36+
value: 0.2
37+
error: 0.035
38+
- date: '2015-03-15T00:00:00'
39+
value: 0.015
40+
error: 0.01
41+
""")
42+
yaml_content = Path("summary_observations.yaml").read_text(encoding="utf-8")
43+
assert yaml_content == expected_yaml_content
44+
45+
expected_stdout = (
46+
f"Successfully wrote summary observations to '{YamlConverter.target_file}'."
47+
)
48+
stdout = capsys.readouterr().out
49+
assert expected_stdout in stdout
50+
51+
52+
def test_that_empty_observations_raises_ert_cli_error():
53+
with pytest.raises(ErtCliError, match="No summary observations found"):
54+
YamlConverter([])
55+
56+
57+
def test_that_no_summary_observations_raises_ert_cli_error():
58+
gen_obs = GeneralObservation(
59+
name="foo", data="foo", value=1.0, error=1.0, restart=5, index=5
60+
)
61+
with pytest.raises(ErtCliError, match="No summary observations found"):
62+
YamlConverter([gen_obs])
63+
64+
65+
def test_that_observations_with_same_summary_key_are_gathered_in_yaml_dict(use_tmpdir):
66+
k1, k2 = "foo", "bar"
67+
observations = 2 * [
68+
_make_summary_obs(key=k1, well=None),
69+
_make_summary_obs(key=k2, well=None),
70+
]
71+
72+
converter = YamlConverter(observations=observations)
73+
summary_dicts = converter._summary_to_yaml_dict()
74+
75+
keys = [entry["key"] for entry in summary_dicts["smry"]]
76+
assert len(keys) == 2
77+
assert set(keys) == {k1, k2}
78+
79+
observations = [s_d["observations"] for s_d in summary_dicts["smry"]]
80+
assert all(len(o) == 2 for o in observations)
81+
82+
83+
def test_that_observations_with_different_summary_keys_are_separated_in_yaml_dict():
84+
k1, k2 = "foo", "bar"
85+
observations = [
86+
_make_summary_obs(key=k1, well=None),
87+
_make_summary_obs(key=k2, well=None),
88+
]
89+
90+
converter = YamlConverter(observations=observations)
91+
result = converter._summary_to_yaml_dict()
92+
93+
keys = [entry["key"] for entry in result["smry"]]
94+
assert len(keys) == 2
95+
assert set(keys) == {k1, k2}
96+
97+
98+
def test_that_dumping_to_yaml_is_skipped_when_file_already_exists(use_tmpdir):
99+
observations = [_make_summary_obs()]
100+
101+
Path("summary_observations.yaml").write_text("existing", encoding="utf-8")
102+
assert Path("summary_observations.yaml").is_file()
103+
104+
converter = YamlConverter(observations=observations)
105+
with pytest.raises(
106+
ErtCliError,
107+
match=(
108+
r"A file with name 'summary_observations.yaml' already exists. "
109+
"Will not overwrite it and exit instead."
110+
),
111+
):
112+
converter.export_yaml()

0 commit comments

Comments
 (0)