Skip to content

Commit 3c4b504

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 6ce6ad2 commit 3c4b504

6 files changed

Lines changed: 442 additions & 2 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,18 +11,21 @@
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
ConverterFunction = Callable[[str, ErtRuntimePlugins], None]
2224

2325
_SUPPORTED_CONVERSIONS: dict[SupportedFormat, ConverterFunction] = {
2426
SupportedFormat.BULK: convert_summary_to_bulk,
2527
SupportedFormat.SUMMARY: convert_history_to_summary,
28+
SupportedFormat.YAML: convert_summary_to_yaml,
2629
}
2730

2831

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
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 ConfigValidationError, 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+
try:
83+
ert_config = ErtConfig.with_plugins(site_plugins).from_file(config)
84+
except ConfigValidationError as e:
85+
raise ErtCliError(
86+
f"Failed to internalize the ert config '{config}' with error:\n {e}"
87+
) from e
88+
89+
observations = ert_config.observation_declarations
90+
91+
yaml_exporter = YamlConverter(
92+
observations=observations,
93+
)
94+
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: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -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,

0 commit comments

Comments
 (0)