Skip to content

Commit 64c8c7b

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 eeebf63 commit 64c8c7b

6 files changed

Lines changed: 350 additions & 42 deletions

File tree

src/ert/__main__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -496,7 +496,7 @@ def get_ert_parser(parser: ArgumentParser | None = None) -> ArgumentParser:
496496
"observation format to summary, but this can be "
497497
"configured using the --format flag to specify "
498498
"which format to convert to."
499-
"Valid formats are: bulk, summary"
499+
"Valid formats are: bulk, summary, yaml"
500500
)
501501
convert_obs_parser = subparsers.add_parser(
502502
"convert_observations",

src/ert/observation_converters/dispatcher.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,19 @@
1111
from .summary_to_bulk import (
1212
convert_summary_to_bulk,
1313
)
14+
from .summary_to_yaml import convert_summary_to_yaml
1415

1516

1617
class SupportedFormat(StrEnum):
1718
SUMMARY = "summary"
1819
BULK = "bulk"
20+
YAML = "yaml"
1921

2022

2123
_SUPPORTED_CONVERSIONS: dict[SupportedFormat, Callable[..., None]] = {
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: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import warnings
2+
from pathlib import Path
3+
from typing import Literal, TypedDict
4+
5+
from natsort import natsorted
6+
from ruamel.yaml import YAML
7+
8+
from ert.cli.main import ErtCliError
9+
from ert.config import ErtConfig, Observation
10+
from ert.plugins import ErtRuntimePlugins
11+
12+
13+
class YamlObservation(TypedDict):
14+
date: str
15+
value: float
16+
error: float
17+
18+
19+
class SummaryDict(TypedDict):
20+
key: str
21+
observations: list[YamlObservation]
22+
23+
24+
YamlDict = dict[Literal["smry"], list[SummaryDict]]
25+
26+
27+
class YamlConverter:
28+
TARGET_FILE = "summary_observations.yaml"
29+
30+
def __init__(self, observations: list[Observation]) -> None:
31+
summary_observations = [
32+
o for o in observations if o.type == "summary_observation"
33+
]
34+
if not summary_observations:
35+
raise ErtCliError("No summary observations in configuration.\nExiting ...")
36+
37+
self.summary_observations = summary_observations
38+
39+
def _summary_to_yaml_dict(self) -> YamlDict:
40+
summary_keys: set[str] = {o.key for o in self.summary_observations}
41+
summary_list: list[SummaryDict] = []
42+
for key in natsorted(summary_keys):
43+
observations_with_key = [
44+
o for o in self.summary_observations if o.key == key
45+
]
46+
chronological_observations = sorted(
47+
observations_with_key, key=lambda o: o.date
48+
)
49+
# Round dates without HH/MM/SS to just date
50+
for o in chronological_observations:
51+
if o.date.endswith("T00:00:00"):
52+
o.date = o.date.split("T")[0]
53+
obs_dicts: list[YamlObservation] = [
54+
{
55+
"date": o.date,
56+
"value": o.value,
57+
"error": o.error,
58+
}
59+
for o in chronological_observations
60+
]
61+
summary_dict: SummaryDict = {"key": key, "observations": obs_dicts}
62+
summary_list.append(summary_dict)
63+
return {"smry": summary_list}
64+
65+
def export_yaml(self) -> None:
66+
yaml = YAML()
67+
yaml_dict = self._summary_to_yaml_dict()
68+
try:
69+
with Path(self.TARGET_FILE).open("x", encoding="utf-8") as f:
70+
yaml.dump(yaml_dict, f)
71+
except FileExistsError as error:
72+
raise ErtCliError(
73+
f"A file with name '{self.TARGET_FILE}' already exists. "
74+
"Will not overwrite it and exit instead."
75+
) from error
76+
print(f"Successfully wrote summary observations to '{self.TARGET_FILE}'.")
77+
78+
79+
def convert_summary_to_yaml(config: str, site_plugins: ErtRuntimePlugins) -> None:
80+
with warnings.catch_warnings():
81+
warnings.filterwarnings(action="ignore")
82+
ert_config = ErtConfig.with_plugins(site_plugins).from_file(config)
83+
84+
observations = ert_config.observation_declarations
85+
86+
yaml_exporter = YamlConverter(
87+
observations=observations,
88+
)
89+
yaml_exporter.export_yaml()
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
from pathlib import Path
2+
from unittest.mock import MagicMock
3+
4+
from ert.observation_converters import convert_observations
5+
from ert.plugins import get_site_plugins
6+
7+
8+
def test_that_convert_observations_does_not_fail_when_config_has_hooked_workflows(
9+
use_tmpdir,
10+
):
11+
"""This reproduces the case where ErtConfig.from_file() is called without
12+
plugins while hooked workflows reference plugin-provided jobs.
13+
"""
14+
site_plugins = get_site_plugins()
15+
16+
arbitrary_existing_job = next(iter(site_plugins.installed_workflow_jobs))
17+
18+
workflow_file = Path("my_hook_workflow")
19+
workflow_file.write_text(f"{arbitrary_existing_job}\n", encoding="utf-8")
20+
21+
obs_config = "foo.txt"
22+
summary_obs = (
23+
"SUMMARY_OBSERVATION { KEY = FOPR; VALUE = 10; ERROR = 5; DATE = 2000-01-01; };"
24+
)
25+
Path(obs_config).write_text(
26+
summary_obs,
27+
encoding="utf-8",
28+
)
29+
30+
ert_config = "config.ert"
31+
minimal_workflow_config = f"""\
32+
NUM_REALIZATIONS 10
33+
ECLBASE foo
34+
OBS_CONFIG {obs_config}
35+
LOAD_WORKFLOW {workflow_file} MY_HOOK
36+
HOOK_WORKFLOW MY_HOOK PRE_SIMULATION
37+
"""
38+
Path(ert_config).write_text(
39+
minimal_workflow_config,
40+
encoding="utf-8",
41+
)
42+
43+
for format_ in ["summary", "bulk", "yaml"]:
44+
args = MagicMock(format=format_, config=ert_config)
45+
convert_observations(args, site_plugins)

tests/ert/unit_tests/cli/test_summary_to_bulk.py

Lines changed: 2 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
BulkConfigConverter,
1818
_breakthrough_to_string,
1919
)
20-
from ert.plugins import ErtRuntimePlugins, get_site_plugins
20+
from ert.plugins import ErtRuntimePlugins
2121

2222

2323
@pytest.mark.usefixtures("snake_oil_case")
@@ -113,7 +113,7 @@ def _make_summary_obs(
113113
key += f":{well}" if well else ""
114114
return SummaryObservation(
115115
name="foo",
116-
key=f"{key}:{well}",
116+
key=key,
117117
value=0.5,
118118
error=0.02,
119119
date=date,
@@ -397,42 +397,3 @@ def test_that_no_summary_observations_raises_ert_cli_error():
397397
args = MagicMock(format="bulk", config="snake_oil.ert")
398398
with pytest.raises(ErtCliError, match="No summary observations found"):
399399
convert_observations(args, ErtRuntimePlugins())
400-
401-
402-
def test_that_convert_observations_does_not_fail_when_config_has_hooked_workflows(
403-
use_tmpdir,
404-
):
405-
"""This reproduces the case where ErtConfig.from_file() is called without
406-
plugins while hooked workflows reference plugin-provided jobs.
407-
"""
408-
site_plugins = get_site_plugins()
409-
410-
arbitrary_existing_job = next(iter(site_plugins.installed_workflow_jobs))
411-
412-
workflow_file = Path("my_hook_workflow")
413-
workflow_file.write_text(f"{arbitrary_existing_job}\n", encoding="utf-8")
414-
415-
obs_config = "foo"
416-
summary_obs = (
417-
"SUMMARY_OBSERVATION { KEY = FOPR; VALUE = 10; ERROR = 5; DATE = 2000-01-01; };"
418-
)
419-
Path(obs_config).write_text(
420-
summary_obs,
421-
encoding="utf-8",
422-
)
423-
424-
ert_config = "config.ert"
425-
minimal_workflow_config = f"""\
426-
NUM_REALIZATIONS 10
427-
ECLBASE foo
428-
OBS_CONFIG {obs_config}
429-
LOAD_WORKFLOW {workflow_file} MY_HOOK
430-
HOOK_WORKFLOW MY_HOOK PRE_SIMULATION
431-
"""
432-
Path(ert_config).write_text(
433-
minimal_workflow_config,
434-
encoding="utf-8",
435-
)
436-
437-
args = MagicMock(format="bulk", config=ert_config)
438-
convert_observations(args, site_plugins)

0 commit comments

Comments
 (0)