Skip to content

Commit

Permalink
eclsum -> summary
Browse files Browse the repository at this point in the history
  • Loading branch information
Yngve S. Kristiansen committed Nov 15, 2023
1 parent 1888da7 commit 8790e7e
Show file tree
Hide file tree
Showing 5 changed files with 77 additions and 77 deletions.
2 changes: 1 addition & 1 deletion res2df/csv2res.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def get_parser() -> argparse.ArgumentParser:

summary_parser = subparsers.add_parser(
"summary",
help="Write EclSum UNSMRY files",
help="Write summary UNSMRY files",
description=("Write Eclipse UNSMRY files from CSV files."),
)
summary.fill_reverse_parser(summary_parser)
Expand Down
12 changes: 6 additions & 6 deletions res2df/resdatafiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def __init__(self, eclbase):
# Set class variables to None
self._egridfile = None # Should be ResdataFile
self._initfile = None # Should be ResdataFile
self._eclsum = None # Should be Summary
self._summary = None # Should be Summary

self._egrid = None # Should be Grid

Expand Down Expand Up @@ -138,23 +138,23 @@ def get_egridfile(self) -> ResdataFile:

return self._egridfile

def get_eclsum(self, include_restart: bool = True) -> Summary:
def get_summary(self, include_restart: bool = True) -> Summary:
"""Find and return the summary file and
return as Summary object
Args:
include_restart: Sent to libecl for whether restart files
should be traversed.
"""
if not self._eclsum:
if not self._summary:
smryfilename = self._eclbase + ".UNSMRY"
if not Path(smryfilename).is_file():
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), smryfilename
)
logger.info("Opening UNSMRY file: %s", smryfilename)
self._eclsum = Summary(smryfilename, include_restart=include_restart)
return self._eclsum
self._summary = Summary(smryfilename, include_restart=include_restart)
return self._summary

def get_initfile(self) -> ResdataFile:
"""Find and return the INIT file as an ResdataFile object"""
Expand Down Expand Up @@ -207,7 +207,7 @@ def close(self) -> None:
self._egridfile = None
self._initfile = None
# This is necessary for garbage collection to close the Summary file:
self._eclsum = None
self._summary = None
self._rstfile = None
self._rftfile = None

Expand Down
82 changes: 41 additions & 41 deletions res2df/summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def _ensure_date_or_none(some_date: Optional[Union[str, dt.date]]) -> Optional[d


def _crop_datelist(
eclsumsdates: List[dt.datetime],
summarysdates: List[dt.datetime],
freq: Union[dt.date, dt.datetime, str],
start_date: Optional[dt.date] = None,
end_date: Optional[dt.date] = None,
Expand All @@ -94,7 +94,7 @@ def _crop_datelist(
only cropped or returned as is.
Args:
eclsumsdates: list of datetimes, typically coming from Summary.dates
summarysdates: list of datetimes, typically coming from Summary.dates
freq: Either a date or datetime, or a frequency string
"raw", "first" or "last".
start_date: Dates prior to this date will be cropped.
Expand All @@ -105,7 +105,7 @@ def _crop_datelist(
"""
datetimes: Union[List[dt.date], List[dt.datetime]] = [] # type: ignore
if freq == FREQ_RAW:
datetimes = eclsumsdates
datetimes = summarysdates
datetimes.sort()
if start_date:
# Convert to datetime (at 00:00:00)
Expand All @@ -117,9 +117,9 @@ def _crop_datelist(
datetimes = [x for x in datetimes if x < end_date]
datetimes = datetimes + [end_date]
elif freq == FREQ_FIRST:
datetimes = [min(eclsumsdates).date()]
datetimes = [min(summarysdates).date()]
elif freq == FREQ_LAST:
datetimes = [max(eclsumsdates).date()]
datetimes = [max(summarysdates).date()]
elif isinstance(freq, (dt.date, dt.datetime)):
datetimes = [freq]
return datetimes
Expand Down Expand Up @@ -193,7 +193,7 @@ def _fallback_date_range(start: dt.date, end: dt.date, freq: str) -> List[dt.dat


def resample_smry_dates(
eclsumsdates: List[dt.datetime],
summarysdates: List[dt.datetime],
freq: str = FREQ_RAW,
normalize: bool = True,
start_date: Optional[Union[str, dt.date]] = None,
Expand All @@ -206,7 +206,7 @@ def resample_smry_dates(
can be returned, on the same date range. Incoming dates can also be cropped.
Args:
eclsumsdates: list of datetimes, typically coming from Summary.dates
summarysdates: list of datetimes, typically coming from Summary.dates
freq: string denoting requested frequency for
the returned list of datetime. 'raw' will
return the input datetimes (no resampling).
Expand All @@ -233,7 +233,7 @@ def resample_smry_dates(
if freq in [FREQ_RAW, FREQ_FIRST, FREQ_LAST] or isinstance(
freq, (dt.date, dt.datetime)
):
return _crop_datelist(eclsumsdates, freq, start_date, end_date)
return _crop_datelist(summarysdates, freq, start_date, end_date)

# In case freq is an ISO-date(time)-string, interpret as such:
try:
Expand All @@ -244,8 +244,8 @@ def resample_smry_dates(
pass

# These are datetime.datetime, not datetime.date
start_smry = min(eclsumsdates)
end_smry = max(eclsumsdates)
start_smry = min(summarysdates)
end_smry = max(summarysdates)

# Normalize start and end date according to frequency by extending the time range.
# [1997-11-05, 2020-03-02] and monthly frequecy
Expand Down Expand Up @@ -355,26 +355,26 @@ def df(
column_keys = [column_keys]

if isinstance(resdatafiles, Summary):
eclsum = resdatafiles
summary = resdatafiles
else:
try:
eclsum = resdatafiles.get_eclsum(include_restart=include_restart)
summary = resdatafiles.get_summary(include_restart=include_restart)
except OSError:
logger.warning("Error reading summary instance, returning empty dataframe")
return pd.DataFrame()

time_index_arg: Optional[Union[List[dt.date], List[dt.datetime]]]
if isinstance(time_index, str) and time_index == "raw":
time_index_arg = resample_smry_dates(
eclsum.dates,
summary.dates,
"raw",
False,
start_date,
end_date,
)
elif isinstance(time_index, str):
time_index_arg = resample_smry_dates(
eclsum.dates,
summary.dates,
time_index,
True,
start_date,
Expand Down Expand Up @@ -402,8 +402,8 @@ def df(
time_index_str or "raw",
)

# dframe = eclsum.pandas_frame(time_index_arg, column_keys)
dframe = _libecl_eclsum_pandas_frame(eclsum, time_index_arg, column_keys)
# dframe = summary.pandas_frame(time_index_arg, column_keys)
dframe = _libecl_summary_pandas_frame(summary, time_index_arg, column_keys)

logger.info(
"Dataframe with smry data ready, %d columns and %d rows",
Expand All @@ -415,7 +415,7 @@ def df(
dframe = _merge_params(dframe, paramfile, resdatafiles)

# Add metadata as an attribute the dataframe, using experimental Pandas features:
meta = smry_meta(eclsum)
meta = smry_meta(summary)
# Slice meta to dataframe columns:
dframe.attrs["meta"] = {
column_key: meta[column_key] for column_key in dframe if column_key in meta
Expand Down Expand Up @@ -592,20 +592,20 @@ def smry_meta(resdatafiles: ResdataFiles) -> Dict[str, Dict[str, Any]]:
* wgname (str or None)
"""
if isinstance(resdatafiles, Summary):
eclsum = resdatafiles
summary = resdatafiles
else:
eclsum = resdatafiles.get_eclsum()
summary = resdatafiles.get_summary()

meta: Dict[str, Dict[str, Any]] = {}
for col in eclsum.keys():
for col in summary.keys():
meta[col] = {}
meta[col]["unit"] = eclsum.unit(col)
meta[col]["is_total"] = eclsum.is_total(col)
meta[col]["is_rate"] = eclsum.is_rate(col)
meta[col]["is_historical"] = eclsum.smspec_node(col).is_historical()
meta[col]["keyword"] = eclsum.smspec_node(col).keyword
meta[col]["wgname"] = eclsum.smspec_node(col).wgname
num = eclsum.smspec_node(col).get_num()
meta[col]["unit"] = summary.unit(col)
meta[col]["is_total"] = summary.is_total(col)
meta[col]["is_rate"] = summary.is_rate(col)
meta[col]["is_historical"] = summary.smspec_node(col).is_historical()
meta[col]["keyword"] = summary.smspec_node(col).keyword
meta[col]["wgname"] = summary.smspec_node(col).wgname
num = summary.smspec_node(col).get_num()
if num is not None:
meta[col]["get_num"] = num
return meta
Expand Down Expand Up @@ -679,7 +679,7 @@ def _fix_dframe_for_libecl(dframe: pd.DataFrame) -> pd.DataFrame:
return dframe


def df2ressum(
def df2summary(
dframe: pd.DataFrame,
casename: str = "SYNTHETIC",
) -> Summary:
Expand All @@ -701,12 +701,12 @@ def df2ressum(
raise ValueError(f"Do not use dots in casename {casename}")

dframe = _fix_dframe_for_libecl(dframe)
return _libecl_eclsum_from_pandas(casename, dframe)
return _libecl_summary_from_pandas(casename, dframe)
# return Summary.from_pandas(casename, dframe)


def _libecl_eclsum_pandas_frame(
eclsum: Summary,
def _libecl_summary_pandas_frame(
summary: Summary,
time_index: Optional[Union[List[dt.date], List[dt.datetime]]] = None,
column_keys: Optional[List[str]] = None,
) -> pd.DataFrame:
Expand All @@ -717,24 +717,24 @@ def _libecl_eclsum_pandas_frame(
https://github.com/equinor/ecl/issues/802
"""
if column_keys is None:
keywords = SummaryKeyWordVector(eclsum, add_keywords=True)
keywords = SummaryKeyWordVector(summary, add_keywords=True)
else:
keywords = SummaryKeyWordVector(eclsum)
keywords = SummaryKeyWordVector(summary)
for key in column_keys:
keywords.add_keywords(key)

# pylint: disable=protected-access
if time_index is None:
time_index = eclsum.dates # Changed from libecl
time_index = summary.dates # Changed from libecl
data = np.zeros([len(time_index), len(keywords)])
Summary._init_pandas_frame(
eclsum, keywords, data.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
summary, keywords, data.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
)
else:
time_points = eclsum._make_time_vector(time_index)
time_points = summary._make_time_vector(time_index)
data = np.zeros([len(time_points), len(keywords)])
Summary._init_pandas_frame_interp(
eclsum,
summary,
keywords,
time_points,
data.ctypes.data_as(ctypes.POINTER(ctypes.c_double)),
Expand All @@ -754,7 +754,7 @@ def _libecl_eclsum_pandas_frame(
return frame


def _libecl_eclsum_from_pandas(
def _libecl_summary_from_pandas(
case: str,
frame: pd.DataFrame,
dims: Optional[List[int]] = None,
Expand Down Expand Up @@ -882,7 +882,7 @@ def fill_parser(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:


def fill_reverse_parser(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
"""Fill a parser for the operation: dataframe -> eclsum files"""
"""Fill a parser for the operation: dataframe -> summary files"""

parser.add_argument(
"-o",
Expand Down Expand Up @@ -938,10 +938,10 @@ def summary_reverse_main(args) -> None:

# Summary.fwrite() can only write to current directory:
cwd = os.getcwd()
eclsum = df2ressum(summary_df, eclbase)
summary = df2summary(summary_df, eclbase)
try:
os.chdir(outputdir)
Summary.fwrite(eclsum)
Summary.fwrite(summary)
finally:
os.chdir(cwd)

Expand Down
2 changes: 1 addition & 1 deletion tests/test_eclfiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def test_filedescriptors():
assert len(list(fd_dir.glob("*"))) == pre_fd_count
assert resdatafiles._rstfile is None

resdatafiles.get_eclsum()
resdatafiles.get_summary()
assert len(list(fd_dir.glob("*"))) == pre_fd_count + 1
resdatafiles.close()
assert len(list(fd_dir.glob("*"))) == pre_fd_count
Expand Down
Loading

0 comments on commit 8790e7e

Please sign in to comment.