Skip to content

Commit

Permalink
Rename in common.py
Browse files Browse the repository at this point in the history
  • Loading branch information
Yngve S. Kristiansen committed Nov 14, 2023
1 parent 0606b7c commit 4e3bb3a
Show file tree
Hide file tree
Showing 7 changed files with 55 additions and 55 deletions.
48 changes: 24 additions & 24 deletions res2df/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@
.splitlines()
)
]
ECLMONTH2NUM = {
RESDATAMONTH2NUM = {
"JAN": 1,
"FEB": 2,
"MAR": 3,
Expand All @@ -109,7 +109,7 @@
"NOV": 11,
"DEC": 12,
}
NUM2ECLMONTH = {num: month for month, num in ECLMONTH2NUM.items()}
NUM2RESDATAMONTH = {num: month for month, num in RESDATAMONTH2NUM.items()}

logger: logging.Logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -165,29 +165,29 @@ def write_inc_stdout_file(string: str, outputfilename: str) -> None:
print(f"Wrote to {outputfilename}")


def parse_ecl_month(eclmonth: str) -> int:
"""Translate Eclipse month strings to integer months"""
return ECLMONTH2NUM[eclmonth]
def parse_resdata_month(rdmonth: str) -> int:
"""Translate resdata month strings to integer months"""
return RESDATAMONTH2NUM[rdmonth]


def datetime_to_eclipsedate(
def datetime_to_resdate(
timestamp: Union[str, datetime.datetime, datetime.date]
) -> str:
"""Convert a Python timestamp or date to the Eclipse DATE format"""
"""Convert a Python timestamp or date to the res DATE format"""
if isinstance(timestamp, str):
if list(map(len, timestamp.split(" ")[0].split("-"))) != [4, 2, 2]:
# Need this as dateutil.parser.isoparse() is not in Python 3.6.
raise ValueError("Use ISO-format for dates")
timestamp = dateutil.parser.parse(timestamp) # noqa (py36 flake8 bug)
if not isinstance(timestamp, (datetime.datetime, datetime.date)):
raise TypeError("Require string or datetime")
string = f"{timestamp.day} '{NUM2ECLMONTH[timestamp.month]}' {timestamp.year}"
string = f"{timestamp.day} '{NUM2RESDATAMONTH[timestamp.month]}' {timestamp.year}"
if isinstance(timestamp, datetime.datetime):
string += " " + timestamp.strftime("%H:%M:%S")
return string.replace("00:00:00", "").strip()


def ecl_keyworddata_to_df(
def res_keyworddata_to_df(
deck,
keyword: str,
renamer: Optional[Dict[str, Union[str, List[str]]]] = None,
Expand Down Expand Up @@ -353,7 +353,7 @@ def parse_opmio_date_rec(record: "opm.io.DeckRecord") -> datetime.date:
day = record[0].get_int(0)
month = record[1].get_str(0)
year = record[2].get_int(0)
return datetime.date(year=year, month=parse_ecl_month(month), day=day)
return datetime.date(year=year, month=parse_resdata_month(month), day=day)


def parse_opmio_tstep_rec(record: "opm.io.DeckRecord") -> List[Union[float, int]]:
Expand Down Expand Up @@ -412,7 +412,7 @@ def comment_formatter(multiline: Optional[str], prefix: str = "-- ") -> str:
Args:
multiline: String that can contain newlines
prefix: Comment characters to prepend every line with
Default is the Eclipse comment syntax '-- '
Default is the comment syntax '-- '
Returns:
string, with newlines preserved, and where each line
Expand Down Expand Up @@ -521,7 +521,7 @@ def df2res(
This function hands over the actual text generation pr. keyword
to functions named df2res_<keywordname> in the calling module.
These functions may again use generic_ecltable() from this module
These functions may again use generic_restable() from this module
for the actual string construction.
Args:
Expand All @@ -539,7 +539,7 @@ def df2res(
to file.
Returns:
string that can be used as an include file for Eclipse.
string that can be used as an include file for resdata.
"""
from_module = inspect.stack()[1]
calling_module = inspect.getmodule(from_module[0])
Expand Down Expand Up @@ -624,15 +624,15 @@ def df2res(
return string


def generic_ecltable(
def generic_restable(
dframe: pd.DataFrame,
keyword: str,
comment: Optional[str] = None,
renamer: Optional[Dict[str, str]] = None,
drop_trailing_columns: bool = True,
) -> str:
"""Construct a typical Eclipse table for data following
a keyword. Each row (record in Eclipse terms) ends with a slash.
"""Construct a typical resdata table for data following
a keyword. Each row ends with a slash.
This function will *not* add a final slash after all rows, as
this is keyword dependent. Some keywords require it, some keywords
Expand All @@ -647,7 +647,7 @@ def generic_ecltable(
dataframe columns, the renamer is only applied to the column header comment.
Trailing columns that are all defaulted (that is either np.nan, None)
or consisting of only "1*" will be dropped, as Eclipse will always
or consisting of only "1*" will be dropped, as resdata will always
interpret that as "1*".
"""

Expand All @@ -656,7 +656,7 @@ def generic_ecltable(
if comment is not None and comment:
string += "\n".join(["-- " + line for line in comment.splitlines()]) + "\n"

# Empty tables are ok with Eclipse (at least sometimes)
# Empty tables are ok with resdata (at least sometimes)
if dframe.empty:
return string

Expand Down Expand Up @@ -684,14 +684,14 @@ def generic_ecltable(
return string
relevant_columns = keyword_col_headers[0 : rightmost_column + 1] # noqa
for colname in relevant_columns:
# Add those that are missing, as Eclipse defaults
# Add those that are missing, as resdata defaults
if colname not in dframe:
dframe[colname] = "1*"

# Reorder and slice columns:
dframe = dframe[relevant_columns]

# NaN or Nones are assumed to be defaulted, which in Eclipse terminology is
# NaN or Nones are assumed to be defaulted, which in resdata terminology is
# the string "1*":
dframe.fillna(value="1*", inplace=True)

Expand Down Expand Up @@ -742,12 +742,12 @@ def generic_ecltable(
[" " + line.strip().replace(" /", " /") for line in tablestring.splitlines()]
# The replace() in there is needed for py36/pandas==1.1.5 only.
)
# Eclipse comment for the header line:
# resdata comment for the header line:
tablestring = "--" + tablestring[1:]
return string + tablestring + "\n"


def runlength_eclcompress(string: str, sep: str = " ") -> str:
def runlength_rescompress(string: str, sep: str = " ") -> str:
"""Compress a string of space-separated elements so that
2 2 2 2 2 3 3 4
Expand All @@ -756,7 +756,7 @@ def runlength_eclcompress(string: str, sep: str = " ") -> str:
5*2 2*3 4
which is the format supported by Eclipse. The input
which is the format supported by resdata. The input
string must be splittable with split(). Any newlines
will be replaced by a space prior to split().
Expand Down Expand Up @@ -954,7 +954,7 @@ def get_wells_matching_template(template: str, wells: list):
non-empty character. Any wildcards in the beginning of the template
must be preceded with a \\.
Well name templates starting with ? might be allowed in Eclipse
Well name templates starting with ? might be allowed in resdata
in some contexts, but not in all and will not be permitted here to
avoid confusion.
Expand Down
12 changes: 6 additions & 6 deletions res2df/equil.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def rsvd_fromdeck(
"""
if "EQLDIMS" not in deck:
deck = inferdims.inject_xxxdims_ntxxx("EQLDIMS", "NTEQUL", deck, ntequl)
return common.ecl_keyworddata_to_df(
return common.res_keyworddata_to_df(
deck, "RSVD", renamer=RENAMERS["RSVD"], recordcountername="EQLNUM"
)

Expand All @@ -158,7 +158,7 @@ def rvvd_fromdeck(
"""
if "EQLDIMS" not in deck:
deck = inferdims.inject_xxxdims_ntxxx("EQLDIMS", "NTEQUL", deck, ntequl)
return common.ecl_keyworddata_to_df(
return common.res_keyworddata_to_df(
deck, "RVVD", renamer=RENAMERS["RVVD"], recordcountername="EQLNUM"
)

Expand All @@ -175,7 +175,7 @@ def pbvd_fromdeck(
"""
if "EQLDIMS" not in deck:
deck = inferdims.inject_xxxdims_ntxxx("EQLDIMS", "NTEQUL", deck, ntequl)
return common.ecl_keyworddata_to_df(
return common.res_keyworddata_to_df(
deck, "PBVD", renamer=RENAMERS["PBVD"], recordcountername="EQLNUM"
)

Expand All @@ -192,7 +192,7 @@ def pdvd_fromdeck(
"""
if "EQLDIMS" not in deck:
deck = inferdims.inject_xxxdims_ntxxx("EQLDIMS", "NTEQUL", deck, ntequl)
return common.ecl_keyworddata_to_df(
return common.res_keyworddata_to_df(
deck, "PDVD", renamer=RENAMERS["PDVD"], recordcountername="EQLNUM"
)

Expand Down Expand Up @@ -264,7 +264,7 @@ def equil_fromdeck(
raise ValueError(f"Could not determine phase configuration, got '{phases}'")
columnrenamer = RENAMERS[phases_from_deck(deck)]

dataframe = common.ecl_keyworddata_to_df(
dataframe = common.res_keyworddata_to_df(
deck, "EQUIL", renamer=columnrenamer, recordcountername="EQLNUM"
)

Expand Down Expand Up @@ -418,7 +418,7 @@ def df2res_equil(dframe: pd.DataFrame, comment: Optional[str] = None) -> str:

phases = phases_from_columns(subset.columns)

return common.generic_ecltable(
return common.generic_restable(
subset,
"EQUIL",
renamer=RENAMERS[phases], # type: ignore
Expand Down
4 changes: 2 additions & 2 deletions res2df/fipreports.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import pandas as pd

from res2df import ResdataFiles, getLogger_res2csv
from res2df.common import parse_ecl_month, write_dframe_stdout_file
from res2df.common import parse_resdata_month, write_dframe_stdout_file

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -152,7 +152,7 @@ def df(prtfile: Union[str, ResdataFiles], fipname: str = "FIPNUM") -> pd.DataFra
if matcheddate is not None:
newdate = datetime.date(
year=int(matcheddate.group(3)),
month=parse_ecl_month(matcheddate.group(2).upper()),
month=parse_resdata_month(matcheddate.group(2).upper()),
day=int(matcheddate.group(1)),
)
if newdate != date:
Expand Down
2 changes: 1 addition & 1 deletion res2df/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -737,7 +737,7 @@ def df2res(
)
logger.warning("Data will be dumped, but may error in simulator")
strvector = " ".join([str(x) for x in vector])
strvector = common.runlength_eclcompress(strvector)
strvector = common.runlength_rescompress(strvector)

string += keyword + "\n"
indent = " " * 5
Expand Down
14 changes: 7 additions & 7 deletions res2df/pvt.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def pvtw_fromdeck(
"""
if "TABDIMS" not in deck:
deck = inferdims.inject_xxxdims_ntxxx("TABDIMS", "NTPVT", deck, ntpvt)
return common.ecl_keyworddata_to_df(
return common.res_keyworddata_to_df(
deck, "PVTW", renamer=RENAMERS["PVTW"], recordcountername="PVTNUM"
)

Expand All @@ -98,7 +98,7 @@ def density_fromdeck(
"""
if "TABDIMS" not in deck:
deck = inferdims.inject_xxxdims_ntxxx("TABDIMS", "NTPVT", deck, ntpvt)
return common.ecl_keyworddata_to_df(
return common.res_keyworddata_to_df(
deck, "DENSITY", renamer=RENAMERS["DENSITY"], recordcountername="PVTNUM"
)

Expand All @@ -115,7 +115,7 @@ def rock_fromdeck(
"""
if "TABDIMS" not in deck:
deck = inferdims.inject_xxxdims_ntxxx("TABDIMS", "NTPVT", deck, ntpvt)
return common.ecl_keyworddata_to_df(
return common.res_keyworddata_to_df(
deck, "ROCK", renamer=RENAMERS["ROCK"], recordcountername="PVTNUM"
)

Expand All @@ -132,7 +132,7 @@ def pvto_fromdeck(
"""
if "TABDIMS" not in deck:
deck = inferdims.inject_xxxdims_ntxxx("TABDIMS", "NTPVT", deck, ntpvt)
pvto_df = common.ecl_keyworddata_to_df(
pvto_df = common.res_keyworddata_to_df(
deck, "PVTO", renamer=RENAMERS["PVTO"], emptyrecordcountername="PVTNUM"
)
return pvto_df
Expand All @@ -150,7 +150,7 @@ def pvdo_fromdeck(
"""
if "TABDIMS" not in deck:
deck = inferdims.inject_xxxdims_ntxxx("TABDIMS", "NTPVT", deck, ntpvt)
pvdg_df = common.ecl_keyworddata_to_df(
pvdg_df = common.res_keyworddata_to_df(
deck, "PVDO", renamer=RENAMERS["PVDO"], recordcountername="PVTNUM"
)
return pvdg_df
Expand All @@ -168,7 +168,7 @@ def pvdg_fromdeck(
"""
if "TABDIMS" not in deck:
deck = inferdims.inject_xxxdims_ntxxx("TABDIMS", "NTPVT", deck, ntpvt)
pvdg_df = common.ecl_keyworddata_to_df(
pvdg_df = common.res_keyworddata_to_df(
deck, "PVDG", renamer=RENAMERS["PVDG"], recordcountername="PVTNUM"
)
return pvdg_df
Expand All @@ -186,7 +186,7 @@ def pvtg_fromdeck(
"""
if "TABDIMS" not in deck:
deck = inferdims.inject_xxxdims_ntxxx("TABDIMS", "NTPVT", deck, ntpvt)
pvtg_df = common.ecl_keyworddata_to_df(
pvtg_df = common.res_keyworddata_to_df(
deck, "PVTG", renamer=RENAMERS["PVTG"], emptyrecordcountername="PVTNUM"
)
return pvtg_df
Expand Down
2 changes: 1 addition & 1 deletion res2df/satfunc.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def df(
for keyword in wanted_keywords:
frames.append(
interpolate_defaults(
common.ecl_keyworddata_to_df(
common.res_keyworddata_to_df(
deck, keyword, renamer=RENAMERS[keyword], recordcountername="SATNUM"
).assign(KEYWORD=keyword)
)
Expand Down
28 changes: 14 additions & 14 deletions tests/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,24 +250,24 @@ def test_df2res():
),
],
)
def test_datetime_to_eclipsedate(somedate, expected):
def test_datetime_to_resdate(somedate, expected):
"""Test conversion of datetime to Eclipse date or datetime syntax"""
assert common.datetime_to_eclipsedate(somedate) == expected
assert common.datetime_to_resdate(somedate) == expected


def test_eclcompress():
"""Test that we can compress string using Eclipse style
run-length encoding"""
assert common.runlength_eclcompress("") == ""
assert common.runlength_eclcompress(" ") == ""
assert common.runlength_eclcompress("1 2") == "1 2"
assert common.runlength_eclcompress("1 2", sep=" ") == "1 2"
assert common.runlength_eclcompress("1 2", sep=" ") == "1 2"
assert common.runlength_eclcompress("1") == "1"
assert common.runlength_eclcompress("1 1") == "2*1"
assert common.runlength_eclcompress("1 1 1") == "3*1"
assert common.runlength_eclcompress("1 1 1") == "3*1"
assert common.runlength_eclcompress("1 \n 1 1 2") == "3*1 2"
assert common.runlength_rescompress("") == ""
assert common.runlength_rescompress(" ") == ""
assert common.runlength_rescompress("1 2") == "1 2"
assert common.runlength_rescompress("1 2", sep=" ") == "1 2"
assert common.runlength_rescompress("1 2", sep=" ") == "1 2"
assert common.runlength_rescompress("1") == "1"
assert common.runlength_rescompress("1 1") == "2*1"
assert common.runlength_rescompress("1 1 1") == "3*1"
assert common.runlength_rescompress("1 1 1") == "3*1"
assert common.runlength_rescompress("1 \n 1 1 2") == "3*1 2"


@pytest.mark.parametrize(
Expand Down Expand Up @@ -446,10 +446,10 @@ def test_well_matching_template(template, wells, output):
),
],
)
def test_generic_ecltable(
def test_generic_restable(
dframe, keyword, comment, renamer, drop_trailing_columns, expected
):
stringtable = common.generic_ecltable(
stringtable = common.generic_restable(
dframe,
keyword,
comment=comment,
Expand Down

0 comments on commit 4e3bb3a

Please sign in to comment.