From b0f60c392f2f479e2f635e221f7dcbc76ad1c4ea Mon Sep 17 00:00:00 2001 From: Kristian Bendiksen Date: Fri, 18 Sep 2026 10:22:16 +0200 Subject: [PATCH] #14651 SIMEVENTS 1.1: datetime dates and Go-style durations Increase the time resolution of the SIMEVENTS format and replace whole-day integer offsets with Go-style duration literals. - All DATE values are now datetimes with second resolution. A date-only literal means midnight; a time-of-day requires the 'T' separator and fractional seconds are rounded to the nearest second. - DURATION values and offset terms are Go-style literals such as 5d, 12h30m, 1.5h, 3mon and -3d. Units (mon, d, h, m, s) are mandatory, must appear in strictly descending order without repeats, and a fraction is allowed only on the last component (never on mon or s). Unitless numbers and the legacy DAYS suffix are rejected with hints. - New Duration type keeps calendar months separate from the fixed timedelta part; adding months clamps to the end of shorter months, and str() renders the Go-style form. - Header version bumped to 1.1; 1.0 files are rejected with a migration hint. - Update tests, sample .events file, example script and docs/simulatorEvents.md. --- .../well_event_schedule_simulator_events.py | 14 +- .../simulator_events.events | 14 +- GrpcInterface/Python/rips/simulator_events.py | 446 ++++++++---- .../rips/tests/test_simulator_events.py | 663 ++++++++++++------ docs/simulatorEvents.md | 92 ++- 5 files changed, 841 insertions(+), 388 deletions(-) diff --git a/GrpcInterface/Python/rips/PythonExamples/experimental/well_event_schedule_simulator_events.py b/GrpcInterface/Python/rips/PythonExamples/experimental/well_event_schedule_simulator_events.py index c3adb9f00e..2eec598acc 100644 --- a/GrpcInterface/Python/rips/PythonExamples/experimental/well_event_schedule_simulator_events.py +++ b/GrpcInterface/Python/rips/PythonExamples/experimental/well_event_schedule_simulator_events.py @@ -5,7 +5,7 @@ Example: the well_event_schedule.py timeline expressed as a SIMEVENTS file. This is the SIMEVENTS counterpart to well_event_schedule.py: instead of calling the WellEventTimeline API methods one by one, the same events are -written as SIMEVENTS 1.0 text (see rips/simulator_events.py for the grammar) and +written as SIMEVENTS 1.1 text (see rips/simulator_events.py for the grammar) and applied in one go with rips.simulator_events.apply_simulator_events_document(). It demonstrates the full event coverage of the format: @@ -51,12 +51,12 @@ def build_simulator_events_text(well_name, with_filter): ) filter_ref = " FILTER=HIPORO" if with_filter else "" return f"""\ -SIMEVENTS 1.0 +SIMEVENTS 1.1 UNIT METRIC # Typed declarations DATE STARTUP = 2024-01-01 -DURATION RAMP = 31 DAYS +DURATION RAMP = 31d {filter_decl} WELL W1 = "{well_name}" @@ -75,7 +75,7 @@ WELL W1 STARTUP + RAMP PERFORATION MDSTART=2400 MDEND=2600 DIAMETER=0.1 SKIN=0.3 COMPLETION_NUMBER=2 # Time-of-day is preserved and emitted as the TIME field of DATES - 2024-05-15T14:45:30.500 PERFORATION MDSTART=2300 MDEND=2350 DIAMETER=0.1 SKIN=0.4 COMPLETION_NUMBER=3 + 2024-05-15T14:45:30 PERFORATION MDSTART=2300 MDEND=2350 DIAMETER=0.1 SKIN=0.4 COMPLETION_NUMBER=3 # Valve in the first perforation; state event for documentation 2024-03-01 VALVE MD=2100 TYPE=ICV STATE=OPEN CV=0.7 AREA=0.0001 @@ -117,7 +117,7 @@ END_RAW_TEXT # Recurring inserted dates become bare DATES keywords. The first series ends at # the last event; the second uses an explicit inclusive end date. INSERT_DATE STARTUP EVERY MONTH -INSERT_DATE 2024-07-01 EVERY 3 MONTHS UNTIL STARTUP + 365 +INSERT_DATE 2024-07-01 EVERY 3 MONTHS UNTIL STARTUP + 365d """ @@ -244,8 +244,8 @@ def main(): ] found = [kw for kw in expected_keywords if kw in schedule_text] print(f"\n Keywords found: {', '.join(found)}") - if "14:45:30.500" in schedule_text: - print(" DATES keyword preserves event time-of-day (14:45:30.500)") + if "14:45:30" in schedule_text: + print(" DATES keyword preserves event time-of-day (14:45:30)") else: print(" Warning: No schedule text was generated") diff --git a/GrpcInterface/Python/rips/example_input_files/simulator_events.events b/GrpcInterface/Python/rips/example_input_files/simulator_events.events index 8ab76f5f1b..26c40f50f4 100644 --- a/GrpcInterface/Python/rips/example_input_files/simulator_events.events +++ b/GrpcInterface/Python/rips/example_input_files/simulator_events.events @@ -1,15 +1,15 @@ -# Example SIMEVENTS well-event-timeline file (version 1.0). +# Example SIMEVENTS well-event-timeline file (version 1.1). # Parsed by rips.simulator_events; see that module's docstring for the grammar. # Validate with: python3 -m rips.simulator_events simulator_events.events -SIMEVENTS 1.0 +SIMEVENTS 1.1 UNIT METRIC -# Typed declarations: dates, whole-day durations, well-name aliases, and +# Typed declarations: dates, Go-style durations (e.g. 5d, 12h30m), well-name aliases, and # cell filter expressions. DATE A1_STARTUP = 2018-01-01 -DATE A2_STARTUP = 2018-03-01 + 9 -DURATION RAMP = 5 DAYS +DATE A2_STARTUP = 2018-03-01 + 9d +DURATION RAMP = 5d # A filter becomes a case-level combined data filter attached to the # perforations that reference it. An unqualified result name is searched in @@ -23,7 +23,7 @@ WELL A1 = "55_33-A-1" # dates may use an explicit inclusive end date or default to the last event. SCHEDULE INSERT_DATE A1_STARTUP EVERY MONTH -INSERT_DATE A2_STARTUP EVERY 30 DAYS UNTIL A2_STARTUP + 90 +INSERT_DATE A2_STARTUP EVERY 30 DAYS UNTIL A2_STARTUP + 90d # Raw schedule text is preserved verbatim. This block is inserted immediately # after the date declaration; lower priorities are emitted first when multiple @@ -45,6 +45,6 @@ WELL A1 WELL "55_33-A-2" # An inline quoted expression declares an anonymous filter for one event. - A2_STARTUP - 1 PERFORATION MDSTART=1692.79 MDEND=1706 DIAMETER=0.2413 SKIN=5 COMPLETION_NUMBER=1 FILTER="PORO > 0.2" + A2_STARTUP - 1d PERFORATION MDSTART=1692.79 MDEND=1706 DIAMETER=0.2413 SKIN=5 COMPLETION_NUMBER=1 FILTER="PORO > 0.2" A2_STARTUP WCONHIST STATUS=OPEN CMODE=ORAT VFP=2 A2_STARTUP WELTARG CMODE=BHP VALUE=50 diff --git a/GrpcInterface/Python/rips/simulator_events.py b/GrpcInterface/Python/rips/simulator_events.py index cea00f4d44..b825340fac 100644 --- a/GrpcInterface/Python/rips/simulator_events.py +++ b/GrpcInterface/Python/rips/simulator_events.py @@ -18,10 +18,10 @@ It is split into two independent layers: calls the ``WellEventTimeline`` API, performing all semantic mapping and validation. -File format grammar, version 1.0 (EBNF-ish):: +File format grammar, version 1.1 (EBNF-ish):: document = header , { statement } ; - header = "SIMEVENTS" , "1.0" ; (* first meaningful line *) + header = "SIMEVENTS" , "1.1" ; (* first meaningful line *) statement = unit_directive | declaration | insert_date_line | well_block_open | group_block_open | schedule_block_open | event_line | raw_text_event ; @@ -32,8 +32,8 @@ File format grammar, version 1.0 (EBNF-ish):: period = "DAY" | "DAYS" | "MONTH" | "MONTHS" | "YEAR" | "YEARS" ; declaration = date_decl | duration_decl | well_decl | filter_decl ; - date_decl = "DATE" , ident , "=" , date_expr ; (* DATE X = 2018-03-01 + 9 *) - duration_decl = "DURATION" , ident , "=" , duration_expr ; (* DURATION RAMP = 5 DAYS *) + date_decl = "DATE" , ident , "=" , date_expr ; (* DATE X = 2018-03-01 + 9d *) + duration_decl = "DURATION" , ident , "=" , duration_expr ; (* DURATION RAMP = 5d12h *) well_decl = "WELL" , ident , "=" , quoted_string ; (* WELL A1 = "55_33-A-1" *) filter_decl = "FILTER" , ident , "=" , '"' , filter_expr , '"' ; (* FILTER POROPERM = "PORO > 0.4 AND PERMX > 100.0" *) @@ -53,13 +53,19 @@ File format grammar, version 1.0 (EBNF-ish):: "AFTER_KEYWORD" | "END_OF_DATE" ) , [ "ANCHOR=" , ident ] , [ "PRIORITY=" , integer ] ; - date_expr = ( iso_date | iso_datetime | date_ident ) , { sign , term } ; - duration_expr = ( integer | dur_ident ) , { sign , term } , [ "DAYS" | "days" ] ; - term = signed_integer | dur_ident ; (* whole days, e.g. 2 or -2 *) + date_expr = ( iso_datetime | date_ident ) , { sign , term } ; + duration_expr = term , { sign , term } ; + term = duration_lit | dur_ident ; (* e.g. 2d, -12h30m, RAMP *) sign = "+" | "-" ; - iso_date = 4digit , "-" , 2digit , "-" , 2digit ; - iso_datetime = iso_date , "T" , 2digit , ":" , 2digit , ":" , 2digit , - [ "." , digits ] ; (* 2024-05-15T14:45:30.500 *) + duration_lit = [ sign ] , component , { component } ; + (* units strictly descending, each at most once *) + component = number , ( "mon" | "d" | "h" | "m" | "s" ) ; + number = digits | digits , "." , digits ; + (* a fraction is allowed only on the last + component and never on "mon" or "s" *) + iso_datetime = 4digit , "-" , 2digit , "-" , 2digit , + [ "T" , 2digit , ":" , 2digit , ":" , 2digit , [ "." , digits ] ] ; + (* 2024-05-15 or 2024-05-15T14:45:30 *) ident = letter_or_underscore , { word_char } ; attribute = ident , "=" , ( quoted_string | bareword ) ; comment = "#" , rest-of-line ; (* line or trailing *) @@ -69,22 +75,34 @@ Notes on the grammar: * The format is line-oriented; every non-blank line is dispatched on its first token: ``SIMEVENTS`` (once), ``UNIT``, ``DATE``, ``DURATION``, ``WELL``, ``GROUP``, ``SCHEDULE``, ``INSERT_DATE`` or an event date. Anything else is an - error. Keywords are - uppercase and case-sensitive (the ``DAYS`` suffix is also accepted as ``days``). + error. Keywords are uppercase and case-sensitive; duration units are + lowercase. * Comments start with ``#`` (outside of double quotes) and run to end of line. -* Variables are **typed**: ``DATE``, ``DURATION`` (whole days), ``WELL`` - (well-name alias) and ``FILTER`` (cell filter expression) declarations share - one namespace and must precede use. +* Variables are **typed**: ``DATE``, ``DURATION``, ``WELL`` (well-name alias) + and ``FILTER`` (cell filter expression) declarations share one namespace and + must precede use. Using a variable of the wrong type is an error that cites both the use and the declaration site. Redeclaring a name with the same type warns and the last value wins; redeclaring with a different type is an error. -* Date arithmetic is a chain of signed whole-day terms, each an integer or a - ``DURATION`` variable: ``START + RAMP - 2``. An operand may carry its own - sign, so ``START + -2`` is accepted and means the same as ``START - 2``. - Whitespace around ``+``/``-`` is optional but conventional. An event date - may carry a time-of-day - (``2024-05-15T14:45:30.500``), which the schedule generator preserves as - the optional TIME field of the DATES keyword. +* Every ``DATE`` value is a :class:`datetime.datetime` with second resolution. + A date-only literal means midnight; a time-of-day is written with a ``T`` + separator (``2024-05-15T14:45:30``). Fractional seconds are accepted and + rounded to the nearest second. The schedule generator emits a non-midnight + time as the optional TIME field of the DATES keyword. +* A ``DURATION`` is a Go-style literal: one or more ```` + components written without spaces, units in strictly descending order and + each used at most once — ``mon`` (calendar month), ``d``, ``h``, ``m`` + (minute), ``s``. Examples: ``5d``, ``12h30m``, ``1mon2d``, ``-3d``, ``1.5h``. + A fraction is allowed only on the last component, and never on ``mon`` or + ``s``; the result is rounded to whole seconds. Unitless numbers and the + legacy ``DAYS`` suffix are errors. Because ``mon`` is calendar-relative, a + :class:`Duration` keeps months separate from its fixed ``timedelta`` part. + Adding months clamps to the last day of a shorter month + (``2024-01-31 + 1mon`` is ``2024-02-29``). +* Date arithmetic is a chain of signed terms, each a duration literal or a + ``DURATION`` variable: ``START + RAMP - 2d``. An operand may carry its own + sign, so ``START + -2d`` is accepted and means the same as ``START - 2d``. + Whitespace around ``+``/``-`` is optional but conventional. * ``WELL `` opens an event block for a declared ``WELL`` alias; ``WELL ""`` opens a block for the literal well name and never consults variables. A ``WELL`` line containing ``=`` is always a declaration. A bare @@ -235,6 +253,89 @@ class FilterTerm: value: float +@dataclass(frozen=True, order=False) +class Duration: + """A signed calendar-aware duration: whole months plus a fixed time span. + + ``months`` is calendar-relative (``mon``); ``delta`` holds the ``d``, ``h``, + ``m`` and ``s`` components with second resolution. ``str()`` renders the + Go-style form used in the file format, e.g. ``1mon5d12h30m`` or ``-3d``. + """ + + months: int = 0 + delta: datetime.timedelta = datetime.timedelta(0) + + def __add__(self, other: "Duration") -> "Duration": + if not isinstance(other, Duration): + return NotImplemented + return Duration(self.months + other.months, self.delta + other.delta) + + def __sub__(self, other: "Duration") -> "Duration": + if not isinstance(other, Duration): + return NotImplemented + return Duration(self.months - other.months, self.delta - other.delta) + + def __neg__(self) -> "Duration": + return Duration(-self.months, -self.delta) + + def __bool__(self) -> bool: + return bool(self.months) or bool(self.delta) + + def __radd__(self, other: datetime.datetime) -> datetime.datetime: + if not isinstance(other, datetime.datetime): + return NotImplemented + return _add_months(other, self.months) + self.delta + + def __rsub__(self, other: datetime.datetime) -> datetime.datetime: + if not isinstance(other, datetime.datetime): + return NotImplemented + return other + (-self) + + def __str__(self) -> str: + negative = self.months < 0 or (self.months == 0 and self.delta < _ZERO_DELTA) + months = abs(self.months) + total_seconds = abs(int(self.delta.total_seconds())) + # A mixed-sign duration (e.g. 1mon - 1d) cannot be written as a single + # literal; render it as an explicit expression instead. + if ( + self.months + and self.delta + and (self.months < 0) != (self.delta < _ZERO_DELTA) + ): + return f"{Duration(self.months)} {'-' if self.delta < _ZERO_DELTA else '+'} {Duration(0, abs(self.delta))}" + days, rem = divmod(total_seconds, 86400) + hours, rem = divmod(rem, 3600) + minutes, seconds = divmod(rem, 60) + parts = [ + f"{value}{unit}" + for value, unit in ( + (months, "mon"), + (days, "d"), + (hours, "h"), + (minutes, "m"), + (seconds, "s"), + ) + if value + ] + if not parts: + return "0s" + return ("-" if negative else "") + "".join(parts) + + +_ZERO_DELTA = datetime.timedelta(0) + + +def _add_months(value: datetime.datetime, months: int) -> datetime.datetime: + """Shift a datetime by whole months, clamping to the end of shorter months.""" + if not months: + return value + month_index = value.year * 12 + value.month - 1 + months + year, zero_based_month = divmod(month_index, 12) + month = zero_based_month + 1 + day = min(value.day, calendar.monthrange(year, month)[1]) + return value.replace(year=year, month=month, day=day) + + @dataclass(frozen=True) class FilterExpr: """A parsed filter expression: comparison terms with one combine mode.""" @@ -262,13 +363,13 @@ class EventFilter: class SimulatorEventValue: """A typed variable: kind is ``DATE``, ``DURATION``, ``WELL`` or ``FILTER``. - A ``DATE`` value is a :class:`datetime.date`, or a :class:`datetime.datetime` - when declared with a time-of-day. A ``FILTER`` value is a - :class:`FilterExpr`. + A ``DATE`` value is a :class:`datetime.datetime` (midnight when declared + without a time-of-day), a ``DURATION`` value is a :class:`Duration`, a + ``WELL`` value is a string and a ``FILTER`` value is a :class:`FilterExpr`. """ kind: str - value: Union[datetime.date, datetime.datetime, int, str, FilterExpr] + value: Union[datetime.datetime, Duration, str, FilterExpr] loc: SourceLoc @@ -296,7 +397,7 @@ class SimulatorEvent: """One event line in an enclosing WELL, GROUP or SCHEDULE block.""" event_type: str - event_date: Union[datetime.date, datetime.datetime] + event_date: datetime.datetime attributes: Dict[str, AttrValue] loc: SourceLoc filter: Optional[EventFilter] = None @@ -331,10 +432,10 @@ class GroupBlock: class _ReportSpec: """One INSERT_DATE declaration, expanded after all event dates are known.""" - start: Union[datetime.date, datetime.datetime] + start: datetime.datetime interval: Optional[int] period: Optional[str] - end: Optional[Union[datetime.date, datetime.datetime]] + end: Optional[datetime.datetime] loc: SourceLoc @@ -348,19 +449,19 @@ class SimulatorEventsDocument: wells: List[WellBlock] = field(default_factory=list) groups: List[GroupBlock] = field(default_factory=list) schedule_events: List[SimulatorEvent] = field(default_factory=list) - report_dates: List[Union[datetime.date, datetime.datetime]] = field( - default_factory=list - ) + report_dates: List[datetime.datetime] = field(default_factory=list) warnings: List[ParseWarning] = field(default_factory=list) -def _iso_event_date(event_date: Union[datetime.date, datetime.datetime]) -> str: - """Format an event date for the timeline API, keeping ms time-of-day.""" - if isinstance(event_date, datetime.datetime): - if event_date.microsecond: - return event_date.isoformat(timespec="milliseconds") - return event_date.isoformat() - return event_date.isoformat() +def _iso_event_date(event_date: datetime.datetime) -> str: + """Format an event date for the timeline API. + + Midnight timestamps are written as a plain ``YYYY-MM-DD``; any other time + of day is written as ``YYYY-MM-DDTHH:MM:SS`` (second resolution). + """ + if event_date.time() == datetime.time.min: + return event_date.date().isoformat() + return event_date.isoformat(timespec="seconds") def _event_context(event: SimulatorEvent) -> str: @@ -414,17 +515,20 @@ _KEYWORDS = ( _IDENT = r"[A-Za-z_]\w*" _ISO_DATE = r"\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?)?" _DATE_BASE = rf"(?P{_ISO_DATE}|{_IDENT})" -# A term operand may carry its own sign, so "START + -2" subtracts two days. -_SIGNED_INT = r"[-+]?\d+" -_TERMS_BODY = rf"(?:\s*[-+]\s*(?:{_SIGNED_INT}|{_IDENT}))*" +# A duration literal is Go-style: e.g. 5d, 12h30m, -1mon2d, 1.5h. The regex is +# deliberately loose (any number/unit-letters run); _parse_duration_literal +# validates unit names, ordering and fractions and produces the diagnostics. +# Require unit letters between numbers to avoid ambiguous digit-run splits. +_DURATION_LIT = r"[-+]?\d+(?:\.\d+)?(?:[A-Za-z]+\d+(?:\.\d+)?)*[A-Za-z]*" +# A term operand may carry its own sign, so "START + -2d" subtracts two days. +_TERMS_BODY = rf"(?:\s*[-+]\s*(?:{_DURATION_LIT}|{_IDENT}))*" _TERMS = rf"(?P{_TERMS_BODY})" _HEADER_RE = re.compile(r"^SIMEVENTS\s+(?P\d+\.\d+)$") _UNIT_RE = re.compile(r"^UNIT\s+(?PMETRIC|FIELD|LAB)$") _DATE_DECL_RE = re.compile(rf"^DATE\s+(?P{_IDENT})\s*=\s*{_DATE_BASE}{_TERMS}$") _DURATION_DECL_RE = re.compile( - rf"^DURATION\s+(?P{_IDENT})\s*=\s*(?P\d+|{_IDENT}){_TERMS}" - r"(?:\s+(?:DAYS|days))?$" + rf"^DURATION\s+(?P{_IDENT})\s*=\s*(?P{_DURATION_LIT}|{_IDENT}){_TERMS}$" ) _WELL_DECL_RE = re.compile(rf'^WELL\s+(?P{_IDENT})\s*=\s*"(?P[^"]*)"$') _INSERT_DATE_RE = re.compile( @@ -453,7 +557,21 @@ _RESULT_TYPE_ALIASES = { _WELL_BLOCK_RE = re.compile(rf'^WELL\s+(?:"(?P[^"]*)"|(?P{_IDENT}))$') _GROUP_BLOCK_RE = re.compile(r'^GROUP\s+"(?P[^"]*)"$') _EVENT_RE = re.compile(rf"^{_DATE_BASE}{_TERMS}\s+(?P.+)$") -_TERM_RE = re.compile(rf"([-+])\s*({_SIGNED_INT}|{_IDENT})") +_TERM_RE = re.compile(rf"([-+])\s*({_DURATION_LIT}|{_IDENT})") +_DURATION_COMPONENT_RE = re.compile(r"(?P\d+(?:\.\d+)?)(?P[A-Za-z]*)") +_TIME_OF_DAY_RE = re.compile(r"\d{2}:\d{2}:\d{2}(?:\.\d+)?") +# Duration units in the order they must appear, with their length in seconds +# (None for the calendar-relative month). +_DURATION_UNITS: Tuple[Tuple[str, Optional[int]], ...] = ( + ("mon", None), + ("d", 86400), + ("h", 3600), + ("m", 60), + ("s", 1), +) +_DURATION_UNIT_ORDER = {unit: index for index, (unit, _) in enumerate(_DURATION_UNITS)} +_DURATION_UNIT_LIST = ", ".join(unit for unit, _ in _DURATION_UNITS) +_DURATION_NO_FRACTION_UNITS = {"mon", "s"} _ATTR_RE = re.compile(r'(?P[A-Za-z_]\w*)\s*=\s*(?:"(?P[^"]*)"|(?P\S+))') @@ -579,32 +697,18 @@ def parse_simulator_events(text: str) -> SimulatorEventsDocument: ) -def _as_datetime(value: Union[datetime.date, datetime.datetime]) -> datetime.datetime: - if isinstance(value, datetime.datetime): - return value - return datetime.datetime.combine(value, datetime.time.min) - - def _report_occurrence( - start: Union[datetime.date, datetime.datetime], + start: datetime.datetime, interval: int, period: str, occurrence: int, -) -> Union[datetime.date, datetime.datetime]: +) -> datetime.datetime: offset = interval * occurrence if period == "DAY": return start + datetime.timedelta(days=offset) - if period == "MONTH": - month_index = start.year * 12 + start.month - 1 + offset - year, zero_based_month = divmod(month_index, 12) - month = zero_based_month + 1 - else: - year = start.year + offset - month = start.month - - day = min(start.day, calendar.monthrange(year, month)[1]) - return start.replace(year=year, month=month, day=day) + return _add_months(start, offset) + return _add_months(start, 12 * offset) def _expand_report_specs( @@ -612,16 +716,13 @@ def _expand_report_specs( wells: List[WellBlock], groups: List[GroupBlock], schedule_events: List[SimulatorEvent], -) -> Tuple[ - List[Union[datetime.date, datetime.datetime]], - List[ParseIssue], -]: +) -> Tuple[List[datetime.datetime], List[ParseIssue]]: event_dates = [event.event_date for well in wells for event in well.events] event_dates.extend(event.event_date for group in groups for event in group.events) event_dates.extend(event.event_date for event in schedule_events) - last_event_date = max(event_dates, key=_as_datetime) if event_dates else None + last_event_date = max(event_dates) if event_dates else None - dates: List[Union[datetime.date, datetime.datetime]] = [] + dates: List[datetime.datetime] = [] issues: List[ParseIssue] = [] for spec in report_specs: if spec.period is None: @@ -643,7 +744,7 @@ def _expand_report_specs( ) ) continue - if _as_datetime(end) < _as_datetime(spec.start): + if end < spec.start: issues.append( ParseIssue( "INSERT_DATE end date must not precede its start date", spec.loc @@ -659,7 +760,7 @@ def _expand_report_specs( ) except (OverflowError, ValueError): break - if _as_datetime(value) > _as_datetime(end): + if value > end: break dates.append(value) occurrence += 1 @@ -718,7 +819,7 @@ def _restart_validation_issues( def _wellspec_validation_issues(wells: List[WellBlock]) -> List[ParseIssue]: """Reject multiple WELSPECS events for one well at the same timestamp.""" - seen: Dict[Tuple[str, Union[datetime.date, datetime.datetime]], SimulatorEvent] = {} + seen: Dict[Tuple[str, datetime.datetime], SimulatorEvent] = {} issues: List[ParseIssue] = [] for well in wells: for event in well.events: @@ -739,12 +840,21 @@ def _wellspec_validation_issues(wells: List[WellBlock]) -> List[ParseIssue]: return issues +_SUPPORTED_VERSION = "1.1" + + def _check_version(version: str, loc: SourceLoc) -> None: - if version == "1.0": + if version == _SUPPORTED_VERSION: return - raise SimulatorEventsParseError( - f"Unsupported SIMEVENTS version '{version}'; expected 1.0", loc + message = ( + f"Unsupported SIMEVENTS version '{version}'; expected {_SUPPORTED_VERSION}" ) + if version == "1.0": + message += ( + " (1.1 requires a unit on every duration, e.g. '5 DAYS' -> '5d', " + "and 'T' between date and time)" + ) + raise SimulatorEventsParseError(message, loc) def _parse_line( @@ -826,9 +936,13 @@ def _parse_line( if first == "DATE": match = _DATE_DECL_RE.match(line) if match is None: + hint = "" + if re.search(rf"\d{{4}}-\d{{2}}-\d{{2}}\s+{_TIME_OF_DAY_RE.pattern}", line): + hint = "; a time-of-day must be joined to the date with 'T'" raise SimulatorEventsParseError( f"Malformed DATE declaration: {line!r} " - "(expected DATE NAME = [+|- ...])", + "(expected DATE NAME = [+|- ...])" + f"{hint}", loc, ) value = _eval_date_expr( @@ -846,17 +960,21 @@ def _parse_line( if first == "DURATION": match = _DURATION_DECL_RE.match(line) if match is None: + hint = "" + if re.search(r"\b(?:DAYS|days)\b", line): + hint = "; the DAYS suffix is not supported, write e.g. 5d" raise SimulatorEventsParseError( f"Malformed DURATION declaration: {line!r} " - "(expected DURATION NAME = [+|- ...] [DAYS])", + "(expected DURATION NAME = [+|- ...], " + f"e.g. DURATION RAMP = 5d12h){hint}", loc, ) - days = _eval_duration_expr( + duration = _eval_duration_expr( match.group("base"), match.group("terms"), variables, loc ) _declare( match.group("name"), - SimulatorEventValue("DURATION", days, loc), + SimulatorEventValue("DURATION", duration, loc), variables, warnings, loc, @@ -986,56 +1104,142 @@ def _lookup_var( return value +def _parse_duration_literal(text: str, loc: SourceLoc) -> Duration: + """Parse a Go-style duration literal such as ``5d``, ``-12h30m`` or ``1.5h``. + + Units must be ``mon``, ``d``, ``h``, ``m`` or ``s``, appear in strictly + descending order and at most once each. A fraction is allowed only on the + last component and never on ``mon`` or ``s``. The fixed part is rounded to + whole seconds. + """ + body = text + negative = False + if body[:1] in "+-": + negative = body[0] == "-" + body = body[1:] + + def fail(reason: str) -> SimulatorEventsParseError: + return SimulatorEventsParseError(f"Invalid duration {text!r}: {reason}", loc) + + if not body or not body[0].isdigit(): + raise fail( + f"expected components with units {_DURATION_UNIT_LIST}" + ) + + components: List[Tuple[str, str]] = [] + pos = 0 + while pos < len(body): + match = _DURATION_COMPONENT_RE.match(body, pos) + if match is None: + raise fail(f"unexpected text {body[pos:]!r}") + components.append((match.group("number"), match.group("unit"))) + pos = match.end() + + months = 0 + seconds = 0.0 + previous_order = -1 + for index, (number, unit) in enumerate(components): + if not unit: + if len(components) == 1: + raise fail( + f"a unit is required ({_DURATION_UNIT_LIST}), e.g. {number}d" + ) + raise fail(f"missing unit after {number!r}") + if unit.upper() in ("DAY", "DAYS"): + raise fail(f"the DAYS suffix is not supported; write {number}d") + order = _DURATION_UNIT_ORDER.get(unit) + if order is None: + close = difflib.get_close_matches( + unit.lower(), list(_DURATION_UNIT_ORDER), n=1, cutoff=0.6 + ) + hint = f"; did you mean '{close[0]}'?" if close else "" + raise fail(f"unknown unit {unit!r} (expected {_DURATION_UNIT_LIST}){hint}") + if order == previous_order: + raise fail(f"unit '{unit}' given more than once") + if order < previous_order: + raise fail( + f"units must be in descending order ({_DURATION_UNIT_LIST}); " + f"'{unit}' cannot follow '{components[index - 1][1]}'" + ) + previous_order = order + + is_fraction = "." in number + if is_fraction: + if index != len(components) - 1: + raise fail("a fraction is only allowed on the last component") + if unit in _DURATION_NO_FRACTION_UNITS: + raise fail(f"a fraction is not allowed on '{unit}'") + + unit_seconds = dict(_DURATION_UNITS)[unit] + if unit_seconds is None: + months += int(number) + else: + seconds += float(number) * unit_seconds + + duration = Duration(months, datetime.timedelta(seconds=round(seconds))) + return -duration if negative else duration + + +def _eval_term( + term: str, variables: Dict[str, SimulatorEventValue], loc: SourceLoc +) -> Duration: + """Evaluate one term: a duration literal or a DURATION variable.""" + # Identifiers never start with a sign or a digit, so this stays unambiguous. + if term[0].isdigit() or term[0] in "+-": + return _parse_duration_literal(term, loc) + value = _lookup_var(term, "DURATION", variables, loc).value + assert isinstance(value, Duration) + return value + + def _eval_terms( terms: str, variables: Dict[str, SimulatorEventValue], loc: SourceLoc -) -> int: - """Evaluate a signed chain of whole-day terms to a net day count.""" - total = 0 +) -> Duration: + """Evaluate a signed chain of duration terms to a net :class:`Duration`.""" + total = Duration() for match in _TERM_RE.finditer(terms): sign, term = match.groups() - # An operand may be signed itself ("+ -2"); identifiers never start with - # a sign or a digit, so this stays unambiguous. - if term.lstrip("+-").isdigit(): - days = int(term) - else: - value = _lookup_var(term, "DURATION", variables, loc).value - assert isinstance(value, int) - days = value - total += days if sign == "+" else -days + value = _eval_term(term, variables, loc) + total = total + value if sign == "+" else total - value return total +def _parse_iso_datetime(base: str, loc: SourceLoc) -> datetime.datetime: + """Parse ``YYYY-MM-DD[THH:MM:SS[.fff]]`` to a second-resolution datetime.""" + try: + if "T" in base: + result = datetime.datetime.fromisoformat(base) + else: + result = datetime.datetime.combine( + datetime.date.fromisoformat(base), datetime.time.min + ) + except ValueError as exc: + raise SimulatorEventsParseError(f"Invalid date '{base}': {exc}", loc) + if result.microsecond: + result = result.replace(microsecond=0) + datetime.timedelta( + seconds=round(result.microsecond / 1_000_000) + ) + return result + + def _eval_date_expr( base: str, terms: str, variables: Dict[str, SimulatorEventValue], loc: SourceLoc -) -> Union[datetime.date, datetime.datetime]: - """Evaluate an ISO date(time) or DATE variable plus optional signed day terms.""" - result: Union[datetime.date, datetime.datetime] +) -> datetime.datetime: + """Evaluate an ISO datetime or DATE variable plus optional signed duration terms.""" if base[0].isdigit(): - try: - if "T" in base: - result = datetime.datetime.fromisoformat(base) - else: - result = datetime.date.fromisoformat(base) - except ValueError as exc: - raise SimulatorEventsParseError(f"Invalid date '{base}': {exc}", loc) + result = _parse_iso_datetime(base, loc) else: value = _lookup_var(base, "DATE", variables, loc).value - assert isinstance(value, datetime.date) + assert isinstance(value, datetime.datetime) result = value - return result + datetime.timedelta(days=_eval_terms(terms, variables, loc)) + return result + _eval_terms(terms, variables, loc) def _eval_duration_expr( base: str, terms: str, variables: Dict[str, SimulatorEventValue], loc: SourceLoc -) -> int: - """Evaluate an integer or DURATION variable plus optional signed day terms.""" - if base.isdigit(): - result = int(base) - else: - value = _lookup_var(base, "DURATION", variables, loc).value - assert isinstance(value, int) - result = value - return result + _eval_terms(terms, variables, loc) +) -> Duration: + """Evaluate a duration literal or DURATION variable plus optional signed terms.""" + return _eval_term(base, variables, loc) + _eval_terms(terms, variables, loc) def _parse_filter_expr(text: str, loc: SourceLoc) -> FilterExpr: @@ -1206,6 +1410,12 @@ def _parse_event_line( rest = match.group("rest").strip() parts = rest.split(None, 1) event_type = parts[0] + if _TIME_OF_DAY_RE.fullmatch(event_type): + raise SimulatorEventsParseError( + f"Malformed event line: {line!r} (a time-of-day must be joined to the " + f"date with 'T', e.g. {match.group('base')}T{event_type})", + loc, + ) attr_str = parts[1] if len(parts) > 1 else "" attributes = _parse_attributes(attr_str, loc) @@ -1422,12 +1632,8 @@ def coalesce_simulator_events_document( events: List[SimulatorEvent], *, inherit_history: bool = False ) -> List[SimulatorEvent]: merged: List[SimulatorEvent] = [] - by_key: Dict[ - Tuple[Union[datetime.date, datetime.datetime], str], SimulatorEvent - ] = {} - attribute_locs: Dict[ - Tuple[Union[datetime.date, datetime.datetime], str], Dict[str, SourceLoc] - ] = {} + by_key: Dict[Tuple[datetime.datetime, str], SimulatorEvent] = {} + attribute_locs: Dict[Tuple[datetime.datetime, str], Dict[str, SourceLoc]] = {} for event in events: event_type = event.event_type.upper() if event_type in _NON_COALESCING_EVENT_TYPES: @@ -1468,7 +1674,7 @@ def coalesce_simulator_events_document( if inherit_history: history: Dict[str, Dict[str, AttrValue]] = {} - for event in sorted(merged, key=lambda item: _as_datetime(item.event_date)): + for event in sorted(merged, key=lambda item: item.event_date): event_type = event.event_type.upper() if event_type in _NON_COALESCING_EVENT_TYPES: continue @@ -1634,7 +1840,7 @@ def apply_simulator_events_document( _validate_policy(on_unknown_event, "on_unknown_event") document = coalesce_simulator_events_document(document) report = ApplyReport() - report.report_dates = sorted({d.isoformat() for d in document.report_dates}) + report.report_dates = sorted({_iso_event_date(d) for d in document.report_dates}) report.warnings.extend( f"Line {warning.loc.line}: {warning.message}" for warning in document.warnings ) diff --git a/GrpcInterface/Python/rips/tests/test_simulator_events.py b/GrpcInterface/Python/rips/tests/test_simulator_events.py index 15af183049..10474c2a55 100644 --- a/GrpcInterface/Python/rips/tests/test_simulator_events.py +++ b/GrpcInterface/Python/rips/tests/test_simulator_events.py @@ -12,6 +12,8 @@ automatically when no instance is available. import datetime import os +import runpy +import subprocess import sys import pytest @@ -21,6 +23,7 @@ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) import rips # noqa: E402 import dataroot # noqa: E402 from rips.simulator_events import ( # noqa: E402 + Duration, ApplyReport, SimulatorEventsParseError, _cli, @@ -31,12 +34,12 @@ from rips.simulator_events import ( # noqa: E402 SAMPLE = """\ # A comment line -SIMEVENTS 1.0 +SIMEVENTS 1.1 UNIT METRIC DATE A1_STARTUP = 2018-01-01 -DATE A2_STARTUP = 2018-03-01 + 9 -DURATION RAMP = 5 DAYS +DATE A2_STARTUP = 2018-03-01 + 9d +DURATION RAMP = 5d WELL A1 = "55_33-A-1" @@ -239,22 +242,35 @@ class FakeTimeline: class TestParsing: def test_header_and_unit(self): doc = parse_simulator_events(SAMPLE) - assert doc.version == "1.0" + assert doc.version == "1.1" assert doc.unit_system == "METRIC" + @pytest.mark.parametrize("with_filter", [False, True]) + def test_schedule_example_parses(self, with_filter): + example = runpy.run_path( + os.path.join( + os.path.dirname(rips.__file__), + "PythonExamples", + "experimental", + "well_event_schedule_simulator_events.py", + ) + ) + text = example["build_simulator_events_text"]("W", with_filter) + doc = parse_simulator_events(text) + assert doc.wells[0].well_name == "W" + assert doc.report_dates[-1] == datetime.datetime(2024, 10, 1) + def test_date_declarations_with_day_offset(self): doc = parse_simulator_events(SAMPLE) assert doc.variables["A1_STARTUP"].kind == "DATE" - assert doc.variables["A1_STARTUP"].value == datetime.date(2018, 1, 1) + assert doc.variables["A1_STARTUP"].value == datetime.datetime(2018, 1, 1) # 2018-03-01 + 9 days - assert doc.variables["A2_STARTUP"].value == datetime.date(2018, 3, 10) + assert doc.variables["A2_STARTUP"].value == datetime.datetime(2018, 3, 10) def test_duration_and_well_declarations(self): doc = parse_simulator_events(SAMPLE) assert doc.variables["RAMP"].kind == "DURATION" - assert doc.variables["RAMP"].value == 5 - assert doc.variables["A1"].kind == "WELL" - assert doc.variables["A1"].value == "55_33-A-1" + assert doc.variables["RAMP"].value == Duration(delta=datetime.timedelta(days=5)) def test_well_blocks_and_event_dates(self): doc = parse_simulator_events(SAMPLE) @@ -266,7 +282,7 @@ class TestParsing: "WELTARG", ] # A1_STARTUP + RAMP -> 2018-01-06 - assert well1.events[1].event_date == datetime.date(2018, 1, 6) + assert well1.events[1].event_date == datetime.datetime(2018, 1, 6) def test_value_type_inference(self): doc = parse_simulator_events(SAMPLE) @@ -279,7 +295,7 @@ class TestParsing: def test_quoted_filter_value_is_single_attribute(self): text = ( - 'SIMEVENTS 1.0\nWELL "W"\n' + 'SIMEVENTS 1.1\nWELL "W"\n' ' 2018-01-01 PERFORATION MDSTART=1 MDEND=2 FILTER="SOIL > 0.8 AND PERMX > 200"\n' ) doc = parse_simulator_events(text) @@ -290,7 +306,7 @@ class TestParsing: def test_comment_attribute_is_preserved(self): text = ( - 'SIMEVENTS 1.0\nWELL "W"\n' + 'SIMEVENTS 1.1\nWELL "W"\n' ' 2018-01-01 WCONHIST STATUS=OPEN COMMENT="Startup target"\n' ) event = parse_simulator_events(text).wells[0].events[0] @@ -299,7 +315,7 @@ class TestParsing: def test_trailing_comment_ignored_but_not_inside_quotes(self): text = ( - 'SIMEVENTS 1.0\nWELL "W"\n' + 'SIMEVENTS 1.1\nWELL "W"\n' ' 2018-01-01 WCONHIST NOTE="a # b" CMODE=ORAT # trailing comment\n' ) doc = parse_simulator_events(text) @@ -308,90 +324,95 @@ class TestParsing: assert "CMODE" in attrs def test_iso_date_literal_event(self): - text = 'SIMEVENTS 1.0\nWELL "W"\n 2020-12-31 PERFORATION MDSTART=1 MDEND=2\n' + text = 'SIMEVENTS 1.1\nWELL "W"\n 2020-12-31 PERFORATION MDSTART=1 MDEND=2\n' doc = parse_simulator_events(text) - assert doc.wells[0].events[0].event_date == datetime.date(2020, 12, 31) + assert doc.wells[0].events[0].event_date == datetime.datetime(2020, 12, 31) def test_negative_offset(self): text = ( - "SIMEVENTS 1.0\nDATE START = 2018-01-10\n" - 'WELL "W"\n START - 5 PERFORATION MDSTART=1 MDEND=2\n' + "SIMEVENTS 1.1\nDATE START = 2018-01-10\n" + 'WELL "W"\n START - 5d PERFORATION MDSTART=1 MDEND=2\n' ) doc = parse_simulator_events(text) - assert doc.wells[0].events[0].event_date == datetime.date(2018, 1, 5) + assert doc.wells[0].events[0].event_date == datetime.datetime(2018, 1, 5) def test_minus_after_iso_date(self): text = ( - 'SIMEVENTS 1.0\nWELL "W"\n 2018-01-01 - 5 PERFORATION MDSTART=1 MDEND=2\n' + 'SIMEVENTS 1.1\nWELL "W"\n 2018-01-01 - 5d PERFORATION MDSTART=1 MDEND=2\n' ) doc = parse_simulator_events(text) - assert doc.wells[0].events[0].event_date == datetime.date(2017, 12, 27) + assert doc.wells[0].events[0].event_date == datetime.datetime(2017, 12, 27) def test_signed_operand_in_date_declaration(self): - """An operand may carry its own sign: '+ -2' subtracts (issue #14639).""" - text = "SIMEVENTS 1.0\nDATE STARTUP = 2026-08-28 + -2\n" + """An operand may carry its own sign: '+ -2d' subtracts (issue #14639).""" + text = "SIMEVENTS 1.1\nDATE STARTUP = 2026-08-28 + -2d\n" doc = parse_simulator_events(text) - assert doc.variables["STARTUP"].value == datetime.date(2026, 8, 26) + assert doc.variables["STARTUP"].value == datetime.datetime(2026, 8, 26) def test_signed_operand_sign_combinations(self): for expr, expected in ( - ("+ -2", datetime.date(2026, 8, 26)), - ("- -2", datetime.date(2026, 8, 30)), - ("+ +2", datetime.date(2026, 8, 30)), - ("+-2", datetime.date(2026, 8, 26)), + ("+ -2d", datetime.datetime(2026, 8, 26)), + ("- -2d", datetime.datetime(2026, 8, 30)), + ("+ +2d", datetime.datetime(2026, 8, 30)), + ("+-2d", datetime.datetime(2026, 8, 26)), # Unsigned operands keep their previous meaning. - ("+ 2", datetime.date(2026, 8, 30)), - ("- 2", datetime.date(2026, 8, 26)), + ("+ 2d", datetime.datetime(2026, 8, 30)), + ("- 2d", datetime.datetime(2026, 8, 26)), + ("-2d", datetime.datetime(2026, 8, 26)), ): - doc = parse_simulator_events(f"SIMEVENTS 1.0\nDATE S = 2026-08-28 {expr}\n") + doc = parse_simulator_events(f"SIMEVENTS 1.1\nDATE S = 2026-08-28 {expr}\n") assert doc.variables["S"].value == expected, expr def test_signed_operand_on_event_line_and_duration(self): text = ( - "SIMEVENTS 1.0\nDATE START = 2018-01-01\nDURATION RAMP = 5 + -2\n" - 'WELL "W"\n START + RAMP + -1 PERFORATION MDSTART=1 MDEND=2\n' + "SIMEVENTS 1.1\nDATE START = 2018-01-01\nDURATION RAMP = 5d + -2d\n" + 'WELL "W"\n START + RAMP + -1d PERFORATION MDSTART=1 MDEND=2\n' ) doc = parse_simulator_events(text) - assert doc.variables["RAMP"].value == 3 - assert doc.wells[0].events[0].event_date == datetime.date(2018, 1, 3) + assert doc.variables["RAMP"].value == Duration(delta=datetime.timedelta(days=3)) + assert doc.wells[0].events[0].event_date == datetime.datetime(2018, 1, 3) def test_signed_operand_in_insert_date_until(self): text = ( - "SIMEVENTS 1.0\nSCHEDULE\n" - "INSERT_DATE 2024-01-01 + -1 EVERY DAY UNTIL 2024-01-05 + -2\n" + "SIMEVENTS 1.1\nSCHEDULE\n" + "INSERT_DATE 2024-01-01 + -1d EVERY DAY UNTIL 2024-01-05 + -2d\n" ) doc = parse_simulator_events(text) assert doc.report_dates == [ - datetime.date(2023, 12, 31), - datetime.date(2024, 1, 1), - datetime.date(2024, 1, 2), - datetime.date(2024, 1, 3), + datetime.datetime(2023, 12, 31), + datetime.datetime(2024, 1, 1), + datetime.datetime(2024, 1, 2), + datetime.datetime(2024, 1, 3), ] - def test_signed_operand_does_not_accept_fractional_days(self): - """Fractional day offsets remain unsupported.""" - with pytest.raises( - SimulatorEventsParseError, match="Malformed DATE declaration" - ): - parse_simulator_events("SIMEVENTS 1.0\nDATE S = 2026-08-28 + -2.5\n") + def test_unitless_offset_is_rejected(self): + """Every duration needs a unit; bare day counts are no longer accepted.""" + with pytest.raises(SimulatorEventsParseError, match="a unit is required"): + parse_simulator_events("SIMEVENTS 1.1\nDATE S = 2026-08-28 + -2\n") + with pytest.raises(SimulatorEventsParseError, match="a unit is required"): + parse_simulator_events("SIMEVENTS 1.1\nDATE S = 2026-08-28 + 2.5\n") def test_offset_chain_with_duration_variable(self): text = ( - "SIMEVENTS 1.0\nDATE START = 2018-01-01\nDURATION RAMP = 5\n" - 'WELL "W"\n START + RAMP - 2 PERFORATION MDSTART=1 MDEND=2\n' + "SIMEVENTS 1.1\nDATE START = 2018-01-01\nDURATION RAMP = 5d\n" + 'WELL "W"\n START + RAMP - 2d PERFORATION MDSTART=1 MDEND=2\n' ) doc = parse_simulator_events(text) - assert doc.wells[0].events[0].event_date == datetime.date(2018, 1, 4) + assert doc.wells[0].events[0].event_date == datetime.datetime(2018, 1, 4) - def test_duration_declaration_days_suffix_optional(self): + def test_duration_declaration_days_suffix_rejected(self): for suffix in ("", " DAYS", " days"): - doc = parse_simulator_events(f"SIMEVENTS 1.0\nDURATION X = 5{suffix}\n") - assert doc.variables["X"].value == 5 + with pytest.raises(SimulatorEventsParseError): + parse_simulator_events(f"SIMEVENTS 1.1\nDURATION X = 5{suffix}\n") + with pytest.raises(SimulatorEventsParseError, match="DAYS suffix is not"): + parse_simulator_events("SIMEVENTS 1.1\nDURATION X = 5 DAYS\n") def test_duration_arithmetic_in_declaration(self): - text = "SIMEVENTS 1.0\nDURATION RAMP = 5\nDURATION X = RAMP + 2 DAYS\n" + text = "SIMEVENTS 1.1\nDURATION RAMP = 5d\nDURATION X = RAMP + 2d - 12h\n" doc = parse_simulator_events(text) - assert doc.variables["X"].value == 7 + assert doc.variables["X"].value == Duration( + delta=datetime.timedelta(days=6, hours=12) + ) def test_well_alias_resolution(self): doc = parse_simulator_events(SAMPLE) @@ -399,21 +420,25 @@ class TestParsing: assert doc.wells[0].well_name == "55_33-A-1" def test_quoted_well_block_ignores_alias(self): - text = 'SIMEVENTS 1.0\nWELL A1 = "55_33-A-1"\nWELL "A1"\n' + text = 'SIMEVENTS 1.1\nWELL A1 = "55_33-A-1"\nWELL "A1"\n' doc = parse_simulator_events(text) assert doc.wells[0].well_name == "A1" def test_unknown_well_alias_raises(self): with pytest.raises(SimulatorEventsParseError, match="Unknown variable 'NOPE'"): - parse_simulator_events("SIMEVENTS 1.0\nWELL NOPE\n") + parse_simulator_events("SIMEVENTS 1.1\nWELL NOPE\n") def test_empty_well_block_ok(self): - doc = parse_simulator_events('SIMEVENTS 1.0\nWELL "W"\n') + doc = parse_simulator_events('SIMEVENTS 1.1\nWELL "W"\n') assert doc.wells[0].well_name == "W" assert doc.wells[0].events == [] + def test_v1_0_file_rejected_with_migration_hint(self): + with pytest.raises(SimulatorEventsParseError, match="expected 1.1.*'5d'"): + parse_simulator_events("SIMEVENTS 1.0\nUNIT METRIC\n") + def test_v2_file_rejected_with_clear_message(self): - with pytest.raises(SimulatorEventsParseError, match="expected 1.0"): + with pytest.raises(SimulatorEventsParseError, match="expected 1.1"): parse_simulator_events("SIMEVENTS 2.0\nUNIT METRIC\n") def test_unsupported_version_rejected(self): @@ -431,18 +456,18 @@ class TestParsing: SimulatorEventsParseError, match="before any WELL or SCHEDULE block" ): parse_simulator_events( - "SIMEVENTS 1.0\n 2018-01-01 PERFORATION MDSTART=1 MDEND=2\n" + "SIMEVENTS 1.1\n 2018-01-01 PERFORATION MDSTART=1 MDEND=2\n" ) def test_unknown_variable_raises(self): with pytest.raises(SimulatorEventsParseError, match="Unknown variable 'NOPE'"): parse_simulator_events( - 'SIMEVENTS 1.0\nWELL "W"\n NOPE PERFORATION MDSTART=1 MDEND=2\n' + 'SIMEVENTS 1.1\nWELL "W"\n NOPE PERFORATION MDSTART=1 MDEND=2\n' ) def test_duration_where_date_expected_raises(self): text = ( - 'SIMEVENTS 1.0\nDURATION RAMP = 5\nWELL "W"\n RAMP WCONHIST STATUS=OPEN\n' + 'SIMEVENTS 1.1\nDURATION RAMP = 5d\nWELL "W"\n RAMP WCONHIST STATUS=OPEN\n' ) with pytest.raises( SimulatorEventsParseError, @@ -452,7 +477,7 @@ class TestParsing: def test_date_where_duration_expected_raises(self): text = ( - "SIMEVENTS 1.0\nDATE START = 2018-01-01\nDATE OTHER = 2018-02-01\n" + "SIMEVENTS 1.1\nDATE START = 2018-01-01\nDATE OTHER = 2018-02-01\n" 'WELL "W"\n START + OTHER WCONHIST STATUS=OPEN\n' ) with pytest.raises( @@ -461,12 +486,12 @@ class TestParsing: parse_simulator_events(text) def test_well_variable_in_date_context_raises(self): - text = 'SIMEVENTS 1.0\nWELL A1 = "X"\nWELL A1\n A1 WCONHIST STATUS=OPEN\n' + text = 'SIMEVENTS 1.1\nWELL A1 = "X"\nWELL A1\n A1 WCONHIST STATUS=OPEN\n' with pytest.raises(SimulatorEventsParseError, match="is a WELL .* but a DATE"): parse_simulator_events(text) def test_cross_type_redefinition_raises(self): - text = "SIMEVENTS 1.0\nDATE X = 2018-01-01\nDURATION X = 5\n" + text = "SIMEVENTS 1.1\nDATE X = 2018-01-01\nDURATION X = 5d\n" with pytest.raises( SimulatorEventsParseError, match="already declared as DATE .* redeclare as DURATION", @@ -475,36 +500,36 @@ class TestParsing: def test_forward_reference_raises(self): text = ( - 'SIMEVENTS 1.0\nWELL "W"\n START PERFORATION MDSTART=1 MDEND=2\n' + 'SIMEVENTS 1.1\nWELL "W"\n START PERFORATION MDSTART=1 MDEND=2\n' "DATE START = 2018-01-01\n" ) with pytest.raises(SimulatorEventsParseError, match="Unknown variable 'START'"): parse_simulator_events(text) def test_single_quoted_well_name_rejected(self): - text = "SIMEVENTS 1.0\n'W'\n" + text = "SIMEVENTS 1.1\n'W'\n" with pytest.raises(SimulatorEventsParseError, match="not supported"): parse_simulator_events(text) def test_set_line_rejected_with_hint(self): - text = "SIMEVENTS 1.0\nSET X = 2018-01-01\n" + text = "SIMEVENTS 1.1\nSET X = 2018-01-01\n" with pytest.raises(SimulatorEventsParseError, match="SET is not supported"): parse_simulator_events(text) def test_malformed_attribute_raises(self): - text = 'SIMEVENTS 1.0\nWELL "W"\n 2018-01-01 PERFORATION MDSTART=1 bogus MDEND=2\n' + text = 'SIMEVENTS 1.1\nWELL "W"\n 2018-01-01 PERFORATION MDSTART=1 bogus MDEND=2\n' with pytest.raises(SimulatorEventsParseError, match="Malformed attribute"): parse_simulator_events(text) def test_duplicate_date_declaration_warns(self): - text = 'SIMEVENTS 1.0\nDATE X = 2018-01-01\nDATE X = 2019-01-01\nWELL "W"\n' + text = 'SIMEVENTS 1.1\nDATE X = 2018-01-01\nDATE X = 2019-01-01\nWELL "W"\n' doc = parse_simulator_events(text) assert any("Duplicate" in w.message for w in doc.warnings) - assert doc.variables["X"].value == datetime.date(2019, 1, 1) + assert doc.variables["X"].value == datetime.datetime(2019, 1, 1) def test_schedule_block_parses(self): text = ( - 'SIMEVENTS 1.0\nWELL "W"\n' + 'SIMEVENTS 1.1\nWELL "W"\n' " 2024-01-01 WCONHIST STATUS=OPEN\n" "SCHEDULE\n" " 2024-01-01 RPTRST BASIC=2 FREQ=1\n" @@ -520,7 +545,7 @@ class TestParsing: def test_group_blocks_parse_and_switch_event_sink(self): text = ( - 'SIMEVENTS 1.0\nGROUP "OP"\n' + 'SIMEVENTS 1.1\nGROUP "OP"\n' " 2020-07-01 GEFAC FACTOR=1.0 TRANSFER=YES\n" " 2020-07-01 GCONPROD CMODE=LRAT LRAT=20000\n" 'GROUP "WI"\n' @@ -538,17 +563,17 @@ class TestParsing: assert [event.event_type for event in doc.schedule_events] == ["RPTRST"] def test_empty_group_block_ok(self): - doc = parse_simulator_events('SIMEVENTS 1.0\nGROUP "OP"\n') + doc = parse_simulator_events('SIMEVENTS 1.1\nGROUP "OP"\n') assert doc.groups[0].group_name == "OP" assert doc.groups[0].events == [] def test_malformed_group_line_rejected(self): with pytest.raises(SimulatorEventsParseError, match="Malformed GROUP line"): - parse_simulator_events("SIMEVENTS 1.0\nGROUP OP\n") + parse_simulator_events("SIMEVENTS 1.1\nGROUP OP\n") def test_duplicate_wellspec_for_well_and_date_is_rejected(self): text = ( - 'SIMEVENTS 1.0\nWELL "W"\n' + 'SIMEVENTS 1.1\nWELL "W"\n' " 2024-01-01 WELSPECS GROUP=A\n" 'WELL "W"\n' " 2024-01-01 WELSPECS PHASE=GAS\n" @@ -560,7 +585,7 @@ class TestParsing: def test_wellspec_same_date_for_different_wells_is_allowed(self): document = parse_simulator_events( - 'SIMEVENTS 1.0\nWELL "A"\n' + 'SIMEVENTS 1.1\nWELL "A"\n' " 2024-01-01 WELSPECS GROUP=GA\n" 'WELL "B"\n' " 2024-01-01 WELSPECS GROUP=GB\n" @@ -569,7 +594,7 @@ class TestParsing: def test_boolean_attributes_are_typed_unless_quoted(self): text = ( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" "SCHEDULE\n" ' 2024-01-01 RPTRST DEN=True ROCKC=FALSE LABEL="True"\n' ) @@ -582,7 +607,7 @@ class TestParsing: def test_single_restart_event_parses(self): document = parse_simulator_events( - "SIMEVENTS 1.0\nSCHEDULE\n 2024-02-01 RESTART\n" + "SIMEVENTS 1.1\nSCHEDULE\n 2024-02-01 RESTART\n" ) restart = document.schedule_events[0] assert restart.event_type == "RESTART" @@ -592,19 +617,19 @@ class TestParsing: "text,expected_error", [ ( - 'SIMEVENTS 1.0\nWELL "W"\n 2024-01-01 RESTART\n', + 'SIMEVENTS 1.1\nWELL "W"\n 2024-01-01 RESTART\n', "only valid in a SCHEDULE block", ), ( - 'SIMEVENTS 1.0\nGROUP "G"\n 2024-01-01 RESTART\n', + 'SIMEVENTS 1.1\nGROUP "G"\n 2024-01-01 RESTART\n', "only valid in a SCHEDULE block", ), ( - "SIMEVENTS 1.0\nSCHEDULE\n 2024-01-01 RESTART VALUE=1\n", + "SIMEVENTS 1.1\nSCHEDULE\n 2024-01-01 RESTART VALUE=1\n", "takes no attributes", ), ( - "SIMEVENTS 1.0\nSCHEDULE\n 2024-01-01 RESTART\n 2024-02-01 RESTART\n", + "SIMEVENTS 1.1\nSCHEDULE\n 2024-01-01 RESTART\n 2024-02-01 RESTART\n", "Only one RESTART event", ), ], @@ -617,11 +642,11 @@ class TestParsing: with pytest.raises( SimulatorEventsParseError, match="SCHEDULE takes no arguments" ): - parse_simulator_events("SIMEVENTS 1.0\nSCHEDULE NOW\n") + parse_simulator_events("SIMEVENTS 1.1\nSCHEDULE NOW\n") def test_raw_text_block_preserves_body_and_attributes(self): text = ( - "SIMEVENTS 1.0\nSCHEDULE\n" + "SIMEVENTS 1.1\nSCHEDULE\n" " 2024-01-01 RAW_TEXT PLACEMENT=BEFORE_KEYWORD " "ANCHOR=COMPDAT PRIORITY=-2\n" "# not a parser comment\n" @@ -661,13 +686,13 @@ class TestParsing: ], ) def test_invalid_raw_text_header_rejected(self, header, error): - text = f"SIMEVENTS 1.0\nSCHEDULE\n 2024-01-01 {header}\nx\nEND_RAW_TEXT\n" + text = f"SIMEVENTS 1.1\nSCHEDULE\n 2024-01-01 {header}\nx\nEND_RAW_TEXT\n" with pytest.raises(SimulatorEventsParseError, match=error): parse_simulator_events(text) def test_raw_text_outside_schedule_rejected(self): text = ( - 'SIMEVENTS 1.0\nWELL "W"\n' + 'SIMEVENTS 1.1\nWELL "W"\n' " 2024-01-01 RAW_TEXT PLACEMENT=AFTER_DATE\n" "x\nEND_RAW_TEXT\n" ) @@ -676,7 +701,7 @@ class TestParsing: def test_unterminated_raw_text_rejected(self): text = ( - "SIMEVENTS 1.0\nSCHEDULE\n" + "SIMEVENTS 1.1\nSCHEDULE\n" " 2024-01-01 RAW_TEXT PLACEMENT=AFTER_DATE\ntext\n" ) with pytest.raises(SimulatorEventsParseError, match="Unterminated RAW_TEXT"): @@ -684,92 +709,92 @@ class TestParsing: def test_report_lines_parse(self): text = ( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" "DATE START = 2024-01-01\n" "SCHEDULE\n" "INSERT_DATE 2024-06-01\n" - "INSERT_DATE START + 31\n" + "INSERT_DATE START + 31d\n" ) doc = parse_simulator_events(text) assert doc.report_dates == [ - datetime.date(2024, 6, 1), - datetime.date(2024, 2, 1), + datetime.datetime(2024, 6, 1), + datetime.datetime(2024, 2, 1), ] def test_report_keeps_duplicates_and_file_order(self): text = ( - "SIMEVENTS 1.0\nSCHEDULE\nINSERT_DATE 2024-06-01\nINSERT_DATE 2024-06-01\n" + "SIMEVENTS 1.1\nSCHEDULE\nINSERT_DATE 2024-06-01\nINSERT_DATE 2024-06-01\n" ) doc = parse_simulator_events(text) - assert doc.report_dates == [datetime.date(2024, 6, 1)] * 2 + assert doc.report_dates == [datetime.datetime(2024, 6, 1)] * 2 def test_insert_date_is_only_valid_in_schedule_block(self): with pytest.raises(SimulatorEventsParseError, match="only valid in a SCHEDULE"): - parse_simulator_events("SIMEVENTS 1.0\nINSERT_DATE 2024-06-01\n") + parse_simulator_events("SIMEVENTS 1.1\nINSERT_DATE 2024-06-01\n") def test_legacy_report_keyword_is_rejected(self): with pytest.raises(SimulatorEventsParseError, match="renamed to INSERT_DATE"): - parse_simulator_events("SIMEVENTS 1.0\nSCHEDULE\nREPORT 2024-06-01\n") + parse_simulator_events("SIMEVENTS 1.1\nSCHEDULE\nREPORT 2024-06-01\n") def test_report_with_undeclared_variable_raises(self): with pytest.raises(SimulatorEventsParseError, match="NOPE"): - parse_simulator_events("SIMEVENTS 1.0\nSCHEDULE\nINSERT_DATE NOPE + 1\n") + parse_simulator_events("SIMEVENTS 1.1\nSCHEDULE\nINSERT_DATE NOPE + 1d\n") def test_malformed_report_line_raises(self): with pytest.raises( SimulatorEventsParseError, match="Malformed INSERT_DATE line" ): - parse_simulator_events("SIMEVENTS 1.0\nSCHEDULE\nINSERT_DATE\n") + parse_simulator_events("SIMEVENTS 1.1\nSCHEDULE\nINSERT_DATE\n") def test_report_with_datetime_literal(self): - text = "SIMEVENTS 1.0\nSCHEDULE\nINSERT_DATE 2024-06-01T14:45:30.500\n" + text = "SIMEVENTS 1.1\nSCHEDULE\nINSERT_DATE 2024-06-01T14:45:30.700\n" doc = parse_simulator_events(text) - assert doc.report_dates == [datetime.datetime(2024, 6, 1, 14, 45, 30, 500000)] + assert doc.report_dates == [datetime.datetime(2024, 6, 1, 14, 45, 31)] def test_daily_report_recurrence_with_inclusive_until(self): text = ( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" "DATE START = 2024-01-01\n" "DATE END = 2024-01-05\n" "SCHEDULE\n" - "INSERT_DATE START + 1 EVERY 2 DAYS UNTIL END\n" + "INSERT_DATE START + 1d EVERY 2 DAYS UNTIL END\n" ) doc = parse_simulator_events(text) assert doc.report_dates == [ - datetime.date(2024, 1, 2), - datetime.date(2024, 1, 4), + datetime.datetime(2024, 1, 2), + datetime.datetime(2024, 1, 4), ] def test_monthly_report_recurrence_is_anchored_to_initial_day(self): text = ( - "SIMEVENTS 1.0\nSCHEDULE\n" + "SIMEVENTS 1.1\nSCHEDULE\n" "INSERT_DATE 2024-01-31 EVERY MONTH UNTIL 2024-04-30\n" ) doc = parse_simulator_events(text) assert doc.report_dates == [ - datetime.date(2024, 1, 31), - datetime.date(2024, 2, 29), - datetime.date(2024, 3, 31), - datetime.date(2024, 4, 30), + datetime.datetime(2024, 1, 31), + datetime.datetime(2024, 2, 29), + datetime.datetime(2024, 3, 31), + datetime.datetime(2024, 4, 30), ] def test_yearly_report_recurrence_clamps_leap_day(self): text = ( - "SIMEVENTS 1.0\nSCHEDULE\n" + "SIMEVENTS 1.1\nSCHEDULE\n" "INSERT_DATE 2024-02-29 EVERY YEAR UNTIL 2028-02-29\n" ) doc = parse_simulator_events(text) assert doc.report_dates == [ - datetime.date(2024, 2, 29), - datetime.date(2025, 2, 28), - datetime.date(2026, 2, 28), - datetime.date(2027, 2, 28), - datetime.date(2028, 2, 29), + datetime.datetime(2024, 2, 29), + datetime.datetime(2025, 2, 28), + datetime.datetime(2026, 2, 28), + datetime.datetime(2027, 2, 28), + datetime.datetime(2028, 2, 29), ] def test_report_recurrence_without_until_uses_last_event(self): text = ( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" "SCHEDULE\n" "INSERT_DATE 2024-01-01 EVERY MONTH\n" 'WELL "W"\n' @@ -777,22 +802,22 @@ class TestParsing: ) doc = parse_simulator_events(text) assert doc.report_dates == [ - datetime.date(2024, 1, 1), - datetime.date(2024, 2, 1), - datetime.date(2024, 3, 1), + datetime.datetime(2024, 1, 1), + datetime.datetime(2024, 2, 1), + datetime.datetime(2024, 3, 1), ] def test_recurring_report_preserves_datetime(self): text = ( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" "SCHEDULE\n" - "INSERT_DATE 2024-06-01T14:45:30.500 EVERY DAY " - "UNTIL 2024-06-02T14:45:30.500\n" + "INSERT_DATE 2024-06-01T14:45:30.700 EVERY DAY " + "UNTIL 2024-06-02T14:45:30.700\n" ) doc = parse_simulator_events(text) assert doc.report_dates == [ - datetime.datetime(2024, 6, 1, 14, 45, 30, 500000), - datetime.datetime(2024, 6, 2, 14, 45, 30, 500000), + datetime.datetime(2024, 6, 1, 14, 45, 31), + datetime.datetime(2024, 6, 2, 14, 45, 31), ] @pytest.mark.parametrize( @@ -808,40 +833,40 @@ class TestParsing: ) def test_invalid_report_recurrence_rejected(self, report_line, message): with pytest.raises(SimulatorEventsParseError, match=message): - parse_simulator_events(f"SIMEVENTS 1.0\nSCHEDULE\n{report_line}\n") + parse_simulator_events(f"SIMEVENTS 1.1\nSCHEDULE\n{report_line}\n") def test_event_dates_parse_without_prefix(self): text = ( - "SIMEVENTS 1.0\nDATE START = 2024-05-15\n" + "SIMEVENTS 1.1\nDATE START = 2024-05-15\n" 'WELL "W"\n' - " START + 1 PERFORATION MDSTART=1 MDEND=2\n" + " START + 1d PERFORATION MDSTART=1 MDEND=2\n" " 2024-05-17 WCONHIST STATUS=OPEN\n" ) doc = parse_simulator_events(text) assert [event.event_date for event in doc.wells[0].events] == [ - datetime.date(2024, 5, 16), - datetime.date(2024, 5, 17), + datetime.datetime(2024, 5, 16), + datetime.datetime(2024, 5, 17), ] def test_at_prefix_is_rejected(self): - text = 'SIMEVENTS 1.0\nWELL "W"\n @2024-05-17 WCONHIST STATUS=OPEN\n' + text = 'SIMEVENTS 1.1\nWELL "W"\n @2024-05-17 WCONHIST STATUS=OPEN\n' with pytest.raises(SimulatorEventsParseError, match="Unrecognized line"): parse_simulator_events(text) def test_datetime_literal_event(self): text = ( - 'SIMEVENTS 1.0\nWELL "W"\n' - " 2024-05-15T14:45:30.500 PERFORATION MDSTART=1 MDEND=2\n" + 'SIMEVENTS 1.1\nWELL "W"\n' + " 2024-05-15T14:45:30.700 PERFORATION MDSTART=1 MDEND=2\n" ) doc = parse_simulator_events(text) assert doc.wells[0].events[0].event_date == datetime.datetime( - 2024, 5, 15, 14, 45, 30, 500000 + 2024, 5, 15, 14, 45, 31 ) def test_datetime_with_day_offset(self): text = ( - 'SIMEVENTS 1.0\nWELL "W"\n' - " 2024-05-15T14:45:30 + 2 PERFORATION MDSTART=1 MDEND=2\n" + 'SIMEVENTS 1.1\nWELL "W"\n' + " 2024-05-15T14:45:30 + 2d PERFORATION MDSTART=1 MDEND=2\n" ) doc = parse_simulator_events(text) assert doc.wells[0].events[0].event_date == datetime.datetime( @@ -850,19 +875,201 @@ class TestParsing: def test_date_variable_with_time_of_day(self): text = ( - "SIMEVENTS 1.0\nDATE T0 = 2024-05-15T14:45:30.500\n" - 'WELL "W"\n T0 + 1 PERFORATION MDSTART=1 MDEND=2\n' + "SIMEVENTS 1.1\nDATE T0 = 2024-05-15T14:45:30.700\n" + 'WELL "W"\n T0 + 1d PERFORATION MDSTART=1 MDEND=2\n' ) doc = parse_simulator_events(text) assert doc.wells[0].events[0].event_date == datetime.datetime( - 2024, 5, 16, 14, 45, 30, 500000 + 2024, 5, 16, 14, 45, 31 ) + def test_fractional_seconds_round_to_nearest_second(self): + text = ( + 'SIMEVENTS 1.1\nWELL "W"\n' + " 2024-05-15T14:45:30.499 PERFORATION MDSTART=1 MDEND=2\n" + " 2024-05-15T14:45:59.900 WCONHIST STATUS=OPEN\n" + ) + doc = parse_simulator_events(text) + assert [event.event_date for event in doc.wells[0].events] == [ + datetime.datetime(2024, 5, 15, 14, 45, 30), + datetime.datetime(2024, 5, 15, 14, 46, 0), + ] + + def test_space_separated_datetime_is_rejected_with_hint(self): + text = 'SIMEVENTS 1.1\nWELL "W"\n 2018-01-01 11:20:33 WCONHIST STATUS=OPEN\n' + with pytest.raises( + SimulatorEventsParseError, match="joined to the date with 'T'" + ): + parse_simulator_events(text) + with pytest.raises( + SimulatorEventsParseError, match="joined to the date with 'T'" + ): + parse_simulator_events("SIMEVENTS 1.1\nDATE S = 2018-01-01 11:20:33\n") + + def test_date_only_literal_is_midnight_datetime(self): + doc = parse_simulator_events("SIMEVENTS 1.1\nDATE S = 2018-01-01\n") + value = doc.variables["S"].value + assert isinstance(value, datetime.datetime) + assert value == datetime.datetime(2018, 1, 1, 0, 0, 0) + + +class TestDurations: + """Go-style duration literals (issue #14651).""" + + @staticmethod + def _duration(text): + doc = parse_simulator_events(f"SIMEVENTS 1.1\nDURATION X = {text}\n") + return doc.variables["X"].value + + @pytest.mark.parametrize( + "literal, months, delta", + [ + ("5d", 0, datetime.timedelta(days=5)), + ("12h", 0, datetime.timedelta(hours=12)), + ("30m", 0, datetime.timedelta(minutes=30)), + ("45s", 0, datetime.timedelta(seconds=45)), + ("2mon", 2, datetime.timedelta(0)), + ("12h30m", 0, datetime.timedelta(hours=12, minutes=30)), + ( + "1mon2d3h4m5s", + 1, + datetime.timedelta(days=2, hours=3, minutes=4, seconds=5), + ), + ("1.5h", 0, datetime.timedelta(minutes=90)), + ("2.5d", 0, datetime.timedelta(days=2, hours=12)), + ("0.5m", 0, datetime.timedelta(seconds=30)), + ("1d1.5h", 0, datetime.timedelta(days=1, minutes=90)), + ("-3d", 0, datetime.timedelta(days=-3)), + ("+3d", 0, datetime.timedelta(days=3)), + ("-1mon12h", -1, datetime.timedelta(hours=-12)), + ("0d", 0, datetime.timedelta(0)), + ], + ) + def test_valid_literals(self, literal, months, delta): + assert self._duration(literal) == Duration(months, delta) + + @pytest.mark.parametrize( + "literal, message", + [ + ("5", "a unit is required"), + ("2.5", "a unit is required"), + ("5 DAYS", "DAYS suffix is not supported"), + ("5x", "unknown unit 'x'"), + ("5D", "unknown unit 'D'"), + ("5min", "unknown unit 'min'.*did you mean 'mon'"), + ("30m12h", "descending order"), + ("1d1d", "given more than once"), + ("1.5h30m", "fraction is only allowed on the last component"), + ("1.5s", "fraction is not allowed on 's'"), + ("1.5mon", "fraction is not allowed on 'mon'"), + ("d", "Unknown variable 'd'"), + ("1d 2h", "Malformed DURATION declaration"), + ("1d2", "missing unit after '2'"), + ], + ) + def test_invalid_literals(self, literal, message): + with pytest.raises(SimulatorEventsParseError, match=message): + self._duration(literal) + + def test_long_malformed_durations_rejected_promptly(self, tmp_path): + literal = "0." + "1" * 128 + "h!" + path = tmp_path / "malformed.events" + path.write_text( + "SIMEVENTS 1.1\n" + f"DURATION X = {literal}\n" + f"DATE S = 2024-01-01 + {literal}\n" + "SCHEDULE\n" + f"INSERT_DATE 2024-01-01 + {literal}\n", + encoding="utf-8", + ) + # Bound the runtime in a subprocess so a backtracking regression cannot + # hang the test runner. Use the same source package as this test. + result = subprocess.run( + [sys.executable, "-m", "rips.simulator_events", str(path)], + cwd=os.path.dirname(os.path.dirname(rips.__file__)), + capture_output=True, + text=True, + timeout=10, + ) + assert result.returncode == 1, result.stderr + assert "3 error(s) found" in result.stdout + + def test_fractional_component_rounds_to_whole_seconds(self): + # 0.0001h = 0.36s -> 0s; 0.001h = 3.6s -> 4s + assert self._duration("0.0001h") == Duration() + assert self._duration("0.001h") == Duration(delta=datetime.timedelta(seconds=4)) + + def test_go_style_str(self): + for literal, expected in ( + ("5d", "5d"), + ("12h30m", "12h30m"), + ("1.5h", "1h30m"), + ("36h", "1d12h"), + ("1mon2d3h4m5s", "1mon2d3h4m5s"), + ("-3d", "-3d"), + ("-1mon12h", "-1mon12h"), + ("0d", "0s"), + ): + assert str(self._duration(literal)) == expected, literal + # A mixed-sign result cannot be a single literal. + assert str(self._duration("1mon - 1d")) == "1mon - 1d" + + def test_arithmetic_combines_months_and_fixed_parts(self): + text = ( + "SIMEVENTS 1.1\nDURATION A = 1mon2d\nDURATION B = 12h\n" + "DURATION C = A + B - 1d + -6h\n" + ) + doc = parse_simulator_events(text) + assert doc.variables["C"].value == Duration( + 1, datetime.timedelta(days=1, hours=6) + ) + + def test_hour_offsets_on_event_dates(self): + text = ( + "SIMEVENTS 1.1\nDATE START = 2018-01-01T11:20:33 + 12h30m\n" + "DURATION RAMP = 5d\n" + 'WELL "W"\n' + " START + RAMP -3d PERFORATION MDSTART=1 MDEND=2\n" + " START + RAMP + -1d WCONHIST STATUS=OPEN\n" + ) + doc = parse_simulator_events(text) + assert doc.variables["START"].value == datetime.datetime(2018, 1, 1, 23, 50, 33) + assert [event.event_date for event in doc.wells[0].events] == [ + datetime.datetime(2018, 1, 3, 23, 50, 33), + datetime.datetime(2018, 1, 5, 23, 50, 33), + ] + + def test_month_offsets_clamp_to_end_of_month(self): + text = ( + "SIMEVENTS 1.1\n" + "DATE A = 2024-01-31 + 1mon\n" + "DATE B = 2024-03-31 - 1mon\n" + "DATE C = 2023-12-15T06:00:00 + 14mon\n" + "DATE D = 2024-01-31 + 1mon1d\n" + ) + doc = parse_simulator_events(text) + assert doc.variables["A"].value == datetime.datetime(2024, 2, 29) + assert doc.variables["B"].value == datetime.datetime(2024, 2, 29) + assert doc.variables["C"].value == datetime.datetime(2025, 2, 15, 6) + # Months are applied before the fixed part. + assert doc.variables["D"].value == datetime.datetime(2024, 3, 1) + + def test_duration_variable_in_insert_date(self): + text = ( + "SIMEVENTS 1.1\nDURATION STEP = 1mon\nSCHEDULE\n" + "INSERT_DATE 2024-01-31 + STEP EVERY DAY UNTIL 2024-01-31 + STEP + 1d\n" + ) + doc = parse_simulator_events(text) + assert doc.report_dates == [ + datetime.datetime(2024, 2, 29), + datetime.datetime(2024, 3, 1), + ] + class TestFilterParsing: def _perf_with_filter(self, decls, filter_value): text = ( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" + decls + 'WELL "W"\n' + f" 2018-01-01 PERFORATION MDSTART=1 MDEND=2 FILTER={filter_value}\n" @@ -870,7 +1077,7 @@ class TestFilterParsing: return parse_simulator_events(text) def test_filter_declaration_single_term(self): - doc = parse_simulator_events('SIMEVENTS 1.0\nFILTER F = "poro > 0.4"\n') + doc = parse_simulator_events('SIMEVENTS 1.1\nFILTER F = "poro > 0.4"\n') value = doc.variables["F"] assert value.kind == "FILTER" expr = value.value @@ -884,7 +1091,7 @@ class TestFilterParsing: def test_filter_declaration_two_terms_and(self): doc = parse_simulator_events( - 'SIMEVENTS 1.0\nFILTER F = "poro>0.4 AND permx > 100.0"\n' + 'SIMEVENTS 1.1\nFILTER F = "poro>0.4 AND permx > 100.0"\n' ) expr = doc.variables["F"].value assert expr.combine_mode == "AND" @@ -892,7 +1099,7 @@ class TestFilterParsing: def test_filter_declaration_or_mode(self): doc = parse_simulator_events( - 'SIMEVENTS 1.0\nFILTER F = "PORO < 0.1 OR PERMX <= 10"\n' + 'SIMEVENTS 1.1\nFILTER F = "PORO < 0.1 OR PERMX <= 10"\n' ) expr = doc.variables["F"].value assert expr.combine_mode == "OR" @@ -900,19 +1107,19 @@ class TestFilterParsing: def test_filter_all_operators(self): doc = parse_simulator_events( - 'SIMEVENTS 1.0\nFILTER F = "A > 1 AND B >= 2 AND C < 3 AND D <= 4"\n' + 'SIMEVENTS 1.1\nFILTER F = "A > 1 AND B >= 2 AND C < 3 AND D <= 4"\n' ) expr = doc.variables["F"].value assert [t.op for t in expr.terms] == [">", ">=", "<", "<="] assert [t.value for t in expr.terms] == [1.0, 2.0, 3.0, 4.0] def test_filter_scientific_notation_value(self): - doc = parse_simulator_events('SIMEVENTS 1.0\nFILTER F = "PERMX < 1.5e4"\n') + doc = parse_simulator_events('SIMEVENTS 1.1\nFILTER F = "PERMX < 1.5e4"\n') assert doc.variables["F"].value.terms[0].value == 15000.0 def test_filter_qualified_result_type(self): doc = parse_simulator_events( - 'SIMEVENTS 1.0\nFILTER F = "DYNAMIC_NATIVE.MY_PROPERTY > 1"\n' + 'SIMEVENTS 1.1\nFILTER F = "DYNAMIC_NATIVE.MY_PROPERTY > 1"\n' ) term = doc.variables["F"].value.terms[0] assert term.result_type == "DYNAMIC_NATIVE" @@ -926,7 +1133,7 @@ class TestFilterParsing: ("static_native", "STATIC_NATIVE"), ): doc = parse_simulator_events( - f'SIMEVENTS 1.0\nFILTER F = "{qualifier}.my_property > 1"\n' + f'SIMEVENTS 1.1\nFILTER F = "{qualifier}.my_property > 1"\n' ) term = doc.variables["F"].value.terms[0] assert term.result_type == expected @@ -951,7 +1158,7 @@ class TestFilterParsing: def test_filter_on_non_perforation_event_is_plain_attribute(self): text = ( - 'SIMEVENTS 1.0\nWELL "W"\n' + 'SIMEVENTS 1.1\nWELL "W"\n' ' 2018-01-01 WCONHIST STATUS=OPEN FILTER="PERMX > 200"\n' ) doc = parse_simulator_events(text) @@ -962,41 +1169,41 @@ class TestFilterParsing: def test_mixed_and_or_raises(self): with pytest.raises(SimulatorEventsParseError, match="mixes AND and OR"): parse_simulator_events( - 'SIMEVENTS 1.0\nFILTER F = "A > 1 AND B > 2 OR C > 3"\n' + 'SIMEVENTS 1.1\nFILTER F = "A > 1 AND B > 2 OR C > 3"\n' ) def test_lowercase_connector_raises(self): with pytest.raises(SimulatorEventsParseError, match="uppercase AND / OR"): - parse_simulator_events('SIMEVENTS 1.0\nFILTER F = "poro>0.4 and permx>1"\n') + parse_simulator_events('SIMEVENTS 1.1\nFILTER F = "poro>0.4 and permx>1"\n') def test_equality_operator_raises(self): with pytest.raises(SimulatorEventsParseError, match="only >, >=, < and <="): - parse_simulator_events('SIMEVENTS 1.0\nFILTER F = "poro = 0.4"\n') + parse_simulator_events('SIMEVENTS 1.1\nFILTER F = "poro = 0.4"\n') def test_function_style_result_name_raises(self): with pytest.raises(SimulatorEventsParseError, match="Malformed filter term"): - parse_simulator_events('SIMEVENTS 1.0\nFILTER F = "SOIL(0) > 0.8"\n') + parse_simulator_events('SIMEVENTS 1.1\nFILTER F = "SOIL(0) > 0.8"\n') def test_non_numeric_value_raises(self): with pytest.raises(SimulatorEventsParseError, match="Malformed filter term"): - parse_simulator_events('SIMEVENTS 1.0\nFILTER F = "poro > high"\n') + parse_simulator_events('SIMEVENTS 1.1\nFILTER F = "poro > high"\n') def test_empty_filter_expression_raises(self): with pytest.raises(SimulatorEventsParseError, match="Empty filter expression"): - parse_simulator_events('SIMEVENTS 1.0\nFILTER F = ""\n') + parse_simulator_events('SIMEVENTS 1.1\nFILTER F = ""\n') def test_unknown_qualifier_raises_with_hint(self): with pytest.raises( SimulatorEventsParseError, match="Unknown result type 'DYNAMIK'.*did you mean", ): - parse_simulator_events('SIMEVENTS 1.0\nFILTER F = "DYNAMIK.PORO > 1"\n') + parse_simulator_events('SIMEVENTS 1.1\nFILTER F = "DYNAMIK.PORO > 1"\n') def test_malformed_filter_declaration_raises(self): with pytest.raises( SimulatorEventsParseError, match="Malformed FILTER declaration" ): - parse_simulator_events("SIMEVENTS 1.0\nFILTER F = poro>0.4\n") + parse_simulator_events("SIMEVENTS 1.1\nFILTER F = poro>0.4\n") def test_undeclared_filter_reference_raises_with_hint(self): with pytest.raises(SimulatorEventsParseError, match="did you mean 'poroperm'"): @@ -1010,7 +1217,7 @@ class TestFilterParsing: def test_filter_variable_in_date_context_raises(self): text = ( - 'SIMEVENTS 1.0\nFILTER F = "poro>1"\nWELL "W"\n' + 'SIMEVENTS 1.1\nFILTER F = "poro>1"\nWELL "W"\n' " F PERFORATION MDSTART=1 MDEND=2\n" ) with pytest.raises( @@ -1025,7 +1232,7 @@ class TestFilterParsing: self._perf_with_filter("", "123") def test_duplicate_filter_declaration_warns(self): - text = 'SIMEVENTS 1.0\nFILTER F = "poro>1"\nFILTER F = "permx>2"\n' + text = 'SIMEVENTS 1.1\nFILTER F = "poro>1"\nFILTER F = "permx>2"\n' doc = parse_simulator_events(text) assert any("Duplicate FILTER" in w.message for w in doc.warnings) assert doc.variables["F"].value.terms[0].result_name == "PERMX" @@ -1034,7 +1241,7 @@ class TestFilterParsing: class TestDiagnostics: def test_all_errors_reported_in_one_pass(self): text = ( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" "DATE A1_STARTUP = 2018-01-01\n" "SET X = 2018-01-01\n" # line 3 'WELL "W"\n' @@ -1047,7 +1254,7 @@ class TestDiagnostics: def test_malformed_well_block_suppresses_cascading_errors(self): text = ( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" "WELL 55_33-A-2\n" # malformed: unquoted special characters " 2018-01-01 PERFORATION MDSTART=1 MDEND=2\n" " 2018-01-01 WCONHIST STATUS=OPEN\n" @@ -1059,7 +1266,7 @@ class TestDiagnostics: def test_unknown_variable_hint(self): text = ( - "SIMEVENTS 1.0\nDATE A1_STARTUP = 2018-01-01\n" + "SIMEVENTS 1.1\nDATE A1_STARTUP = 2018-01-01\n" 'WELL "W"\n A1_STRTUP PERFORATION MDSTART=1 MDEND=2\n' ) with pytest.raises( @@ -1069,7 +1276,7 @@ class TestDiagnostics: def test_misspelled_keyword_hint(self): with pytest.raises(SimulatorEventsParseError, match="did you mean 'DURATION'"): - parse_simulator_events("SIMEVENTS 1.0\nDURATON X = 5\n") + parse_simulator_events("SIMEVENTS 1.1\nDURATON X = 5\n") class TestValidatorCli: @@ -1088,7 +1295,7 @@ class TestValidatorCli: def test_invalid_file_exits_nonzero_with_errors(self, tmp_path, capsys): path = self._write( tmp_path, - 'SIMEVENTS 1.0\nSET X = 2018-01-01\nWELL "W"\n NOPE WCONHIST A=1\n', + 'SIMEVENTS 1.1\nSET X = 2018-01-01\nWELL "W"\n NOPE WCONHIST A=1\n', ) assert _cli([path]) == 1 out = capsys.readouterr().out @@ -1195,7 +1402,7 @@ class TestApplying: def test_same_owner_type_and_date_events_are_merged(self): text = ( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" 'WELL "55_33-A-1"\n' " 2018-01-01 WCONHIST STATUS=OPEN ORAT=100\n" 'WELL "55_33-A-1"\n' @@ -1227,7 +1434,7 @@ class TestApplying: def test_well_keyword_history_is_inherited_chronologically(self): text = ( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" 'WELL "55_33-A-1"\n' " 2024-01-20 WCONHIST WRAT=0.03\n" ' 2024-01-15 WCONHIST STATUS=OPEN CMODE=RESV GRAT=4756545.5 COMMENT="Startup"\n' @@ -1244,13 +1451,13 @@ class TestApplying: event for event in first_well_events if event.event_type.upper() == "WCONHIST" - and event.event_date.isoformat() == "2024-01-15" + and event.event_date == datetime.datetime(2024, 1, 15) ) january_20 = next( event for event in first_well_events if event.event_type.upper() == "WCONHIST" - and event.event_date.isoformat() == "2024-01-20" + and event.event_date == datetime.datetime(2024, 1, 20) ) assert january_15.attributes["GRAT"].value == 550678.44 @@ -1290,7 +1497,7 @@ class TestApplying: def test_same_date_perforations_are_not_merged(self): text = ( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" 'WELL "55_33-A-1"\n' " 2018-01-01 PERFORATION MDSTART=1000 MDEND=1100 COMPLETION_NUMBER=1\n" " 2018-01-01 PERFORATION MDSTART=1200 MDEND=1300 COMPLETION_NUMBER=2\n" @@ -1312,7 +1519,7 @@ class TestApplying: def test_group_and_schedule_events_merge_only_within_owner(self): text = ( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" 'GROUP "OP"\n' " 2018-01-01 GCONPROD CONTROL_MODE=ORAT\n" 'GROUP "OP"\n' @@ -1362,7 +1569,7 @@ class TestApplying: def test_comment_is_applied_to_timeline_event_not_keyword_data(self): text = ( - 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n' + 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n' ' 2018-01-01 WCONHIST STATUS=OPEN COMMENT="Startup target"\n' ) timeline, report = self._apply(text) @@ -1374,7 +1581,7 @@ class TestApplying: def test_perforation_comment_is_applied(self): text = ( - 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n' + 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n' " 2018-01-01 PERFORATION MDSTART=1 MDEND=2 COMMENT=Interval\n" ) timeline, report = self._apply(text) @@ -1396,7 +1603,7 @@ class TestApplying: # DSHIFT is not part of the format; it forwards unchanged like any # other attribute instead of being stripped. text = ( - 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n' + 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n' " 2018-01-01 WCONHIST STATUS=OPEN CMODE=ORAT DSHIFT=10\n" ) timeline, report = self._apply(text) @@ -1407,7 +1614,7 @@ class TestApplying: def test_report_dates_on_apply_report(self): text = ( - 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n' + 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n' " 2018-01-01 WCONHIST STATUS=OPEN\n" "SCHEDULE\n" "INSERT_DATE 2018-07-01\n" @@ -1422,7 +1629,7 @@ class TestApplying: def test_radius_on_perforation_is_unknown_attribute_error(self): text = ( - 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n' + 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n' " 2018-01-01 PERFORATION MDSTART=1 MDEND=2 RADIUS=0.1\n" ) timeline, report = self._apply(text) @@ -1435,7 +1642,7 @@ class TestApplying: # PERFID is not part of the format; it is rejected like any other # unknown completion attribute. text = ( - 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n' + 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n' " 2018-01-01 PERFORATION MDSTART=1 MDEND=2 PERFID=Valysar\n" ) timeline, report = self._apply(text) @@ -1446,7 +1653,7 @@ class TestApplying: def test_filter_on_keyword_event_warns_and_applies(self): text = ( - 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n' + 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n' ' 2018-01-01 WCONHIST STATUS=OPEN FILTER="PERMX > 200"\n' ) timeline, report = self._apply(text) @@ -1467,7 +1674,7 @@ class TestApplying: self._apply(SAMPLE, names=("55_33-A-1",), on_unknown_well="error") def test_unknown_event_type_warns_with_hint(self): - text = 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n 2018-01-01 WCONHST STATUS=OPEN\n' + text = 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n 2018-01-01 WCONHST STATUS=OPEN\n' _, report = self._apply(text) assert report.events_skipped == 1 assert any( @@ -1475,21 +1682,21 @@ class TestApplying: ) def test_perforation_missing_required_attr_is_error(self): - text = 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n 2018-01-01 PERFORATION MDSTART=1\n' + text = 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n 2018-01-01 PERFORATION MDSTART=1\n' _, report = self._apply(text) assert report.events_skipped == 1 assert any("MDEND" in e for e in report.errors) assert 'Line 3 [WELL "55_33-A-1", date 2018-01-01]' in report.errors[0] def test_perforation_unknown_attr_is_error(self): - text = 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n 2018-01-01 PERFORATION MDSTART=1 MDEND=2 ZZZ=3\n' + text = 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n 2018-01-01 PERFORATION MDSTART=1 MDEND=2 ZZZ=3\n' _, report = self._apply(text) assert report.events_skipped == 1 assert any("ZZZ" in e for e in report.errors) def test_wellspec_partial_updates_are_cumulative_by_date(self): text = ( - 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n' + 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n' " 2019-01-01 WELSPECS CROSSFLOW=False PHASE=gas\n" " 2018-01-01 WELSPECS GROUP=my_group REFDEPTH=1002 PHASE=water\n" ) @@ -1522,7 +1729,7 @@ class TestApplying: ], ) def test_invalid_wellspec_is_reported_and_skipped(self, attributes, expected_error): - text = f'SIMEVENTS 1.0\nWELL "55_33-A-1"\n 2018-01-01 WELSPECS {attributes}\n' + text = f'SIMEVENTS 1.1\nWELL "55_33-A-1"\n 2018-01-01 WELSPECS {attributes}\n' timeline, report = self._apply(text) assert report.events_applied == 0 @@ -1532,7 +1739,7 @@ class TestApplying: def test_segment_mapping_creates_custom_interval_and_sets_pressure_drop(self): text = ( - 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n' + 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n' " 2024-01-01 SEGMENT MDSTART=0 MDEND=2500 INNER_DIAMETER=0.15 " "ROUGHNESS=1.0e-5 PRESSURE_COMPONENTS=HFA\n" ) @@ -1558,7 +1765,7 @@ class TestApplying: def test_segment_rejects_invalid_pressure_components(self): text = ( - 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n' + 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n' " 2024-01-01 SEGMENT MDSTART=0 MDEND=2500 " "PRESSURE_COMPONENTS=INVALID\n" ) @@ -1571,7 +1778,7 @@ class TestApplying: def test_tubing_is_reported_as_renamed_event(self): text = ( - 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n' + 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n' " 2024-01-01 TUBING MDSTART=0 MDEND=2500\n" ) timeline, report = self._apply(text) @@ -1581,7 +1788,7 @@ class TestApplying: assert any("did you mean 'SEGMENT'" in warning for warning in report.warnings) def test_wellspec_is_reported_as_renamed_event(self): - text = 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n 2024-01-01 WELLSPEC GROUP=FIELD\n' + text = 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n 2024-01-01 WELLSPEC GROUP=FIELD\n' timeline, report = self._apply(text) assert report.events_skipped == 1 @@ -1590,7 +1797,7 @@ class TestApplying: def test_valve_mapping(self): text = ( - 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n' + 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n' " 2024-03-01 VALVE MD=2100 TYPE=ICV STATE=OPEN CV=0.7 AREA=0.0001\n" ) timeline, report = self._apply(text) @@ -1603,20 +1810,20 @@ class TestApplying: assert call["area"] == pytest.approx(0.0001) def test_valve_missing_type_is_error(self): - text = 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n 2024-03-01 VALVE MD=2100\n' + text = 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n 2024-03-01 VALVE MD=2100\n' _, report = self._apply(text) assert report.events_skipped == 1 assert any("TYPE" in e for e in report.errors) def test_state_mapping(self): - text = 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n 2024-02-15 STATE STATE=SHUT\n' + text = 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n 2024-02-15 STATE STATE=SHUT\n' timeline, report = self._apply(text) assert report.events_applied == 1 assert timeline.state_calls[0]["well_state"] == "SHUT" def test_generic_well_keyword_pass_through(self): text = ( - 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n' + 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n' " 2024-06-01 WRFTPLT OUTPUT_RFT=YES OUTPUT_PLT=NO OUTPUT_SEGMENT=NO\n" ) timeline, report = self._apply(text) @@ -1629,7 +1836,7 @@ class TestApplying: def test_typo_of_builtin_is_not_passed_through(self): text = ( - 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n' + 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n' " 2024-01-01 PERFORATIN MDSTART=1 MDEND=2\n" ) timeline, report = self._apply(text) @@ -1639,7 +1846,7 @@ class TestApplying: def test_schedule_events_applied_without_well(self): text = ( - "SIMEVENTS 1.0\nSCHEDULE\n" + "SIMEVENTS 1.1\nSCHEDULE\n" " 2024-01-01 RPTRST BASIC=2 FREQ=1\n" " 2024-01-01 TUNING TSINIT=1 TSMAXZ=30\n" ) @@ -1651,7 +1858,7 @@ class TestApplying: assert "WELL" not in rptrst["keyword_data"] def test_restart_event_creates_non_emitting_timeline_marker(self): - text = "SIMEVENTS 1.0\nSCHEDULE\n 2024-02-01 RESTART\n" + text = "SIMEVENTS 1.1\nSCHEDULE\n 2024-02-01 RESTART\n" timeline, report = self._apply(text) assert report.events_applied == 1 @@ -1666,7 +1873,7 @@ class TestApplying: def test_raw_text_event_is_applied_without_coalescing(self): text = ( - "SIMEVENTS 1.0\nSCHEDULE\n" + "SIMEVENTS 1.1\nSCHEDULE\n" " 2024-01-01 RAW_TEXT PLACEMENT=AFTER_DATE PRIORITY=2\n" "first\nEND_RAW_TEXT\n" " 2024-01-01 RAW_TEXT PLACEMENT=AFTER_DATE PRIORITY=1\n" @@ -1689,7 +1896,7 @@ class TestApplying: def test_group_events_inject_group_name(self): text = ( - 'SIMEVENTS 1.0\nGROUP "OP"\n' + 'SIMEVENTS 1.1\nGROUP "OP"\n' " 2020-07-01 GEFAC EFFICIENCY_FACTOR=1.0 USE_GEFAC_IN_NETWORK=YES\n" " 2020-07-01 GCONPROD CONTROL_MODE=LRAT LIQUID_TARGET=20000 WATER_TARGET=20000 OIL_TARGET=20000\n" 'GROUP "WI"\n' @@ -1712,7 +1919,7 @@ class TestApplying: def test_member_event_expands_to_unique_grouptree_events(self): text = ( - 'SIMEVENTS 1.0\nGROUP "PRODUCERS"\n' + 'SIMEVENTS 1.1\nGROUP "PRODUCERS"\n' ' 2024-01-01 MEMBER MEMBERS="WELL_A, WELL_B,WELL_A" ' 'COMMENT="Group membership"\n' ) @@ -1746,7 +1953,7 @@ class TestApplying: ], ) def test_invalid_member_event_is_skipped(self, block, event, expected_error): - text = f"SIMEVENTS 1.0\n{block}\n 2024-01-01 {event}\n" + text = f"SIMEVENTS 1.1\n{block}\n 2024-01-01 {event}\n" timeline, report = self._apply(text) assert report.events_applied == 0 @@ -1757,19 +1964,19 @@ class TestApplying: assert f"[{expected_scope}, date 2024-01-01]" in report.errors[0] def test_completion_event_in_schedule_block_is_error(self): - text = "SIMEVENTS 1.0\nSCHEDULE\n 2024-01-01 PERFORATION MDSTART=1 MDEND=2\n" + text = "SIMEVENTS 1.1\nSCHEDULE\n 2024-01-01 PERFORATION MDSTART=1 MDEND=2\n" timeline, report = self._apply(text) assert report.events_skipped == 1 assert timeline.schedule_keyword_calls == [] assert any("needs a WELL block" in e for e in report.errors) - def test_datetime_event_date_keeps_milliseconds(self): + def test_datetime_event_date_rounds_to_seconds(self): text = ( - 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n' - " 2024-05-15T14:45:30.500 PERFORATION MDSTART=1 MDEND=2\n" + 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n' + " 2024-05-15T14:45:30.700 PERFORATION MDSTART=1 MDEND=2\n" ) timeline, _ = self._apply(text) - assert timeline.perf_calls[0]["event_date"] == "2024-05-15T14:45:30.500" + assert timeline.perf_calls[0]["event_date"] == "2024-05-15T14:45:31" def test_invalid_policy_value_raises(self): doc = parse_simulator_events(SAMPLE) @@ -1801,7 +2008,7 @@ class TestFilterApplying: f" 2018-01-{index:02d} PERFORATION MDSTART=1 MDEND=2 FILTER={value}\n" for index, value in enumerate(filter_values, start=1) ) - return "SIMEVENTS 1.0\n" + decls + 'WELL "55_33-A-1"\n' + events + return "SIMEVENTS 1.1\n" + decls + 'WELL "55_33-A-1"\n' + events def test_declared_filter_creates_combined_filter_and_attaches(self): text = self._perf_text( @@ -1885,7 +2092,7 @@ class TestFilterApplying: self._apply(text, cases=[]) def test_no_filter_without_case_is_fine(self): - text = 'SIMEVENTS 1.0\nWELL "55_33-A-1"\n 2018-01-01 PERFORATION MDSTART=1 MDEND=2\n' + text = 'SIMEVENTS 1.1\nWELL "55_33-A-1"\n 2018-01-01 PERFORATION MDSTART=1 MDEND=2\n' _, _, report = self._apply(text, cases=[]) assert report.events_applied == 1 @@ -1912,7 +2119,7 @@ class TestFilterApplying: def test_declared_but_unused_filter_creates_nothing(self): text = ( - 'SIMEVENTS 1.0\nFILTER unused = "poro>0.4"\nWELL "55_33-A-1"\n' + 'SIMEVENTS 1.1\nFILTER unused = "poro>0.4"\nWELL "55_33-A-1"\n' " 2018-01-01 PERFORATION MDSTART=1 MDEND=2\n" ) _, project, report = self._apply(text) @@ -1948,7 +2155,7 @@ class TestSimulatorEventsIntegration: project, _case, timeline = project_with_case_and_wells well = project.well_paths()[0] document = parse_simulator_events( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" f'WELL "{well.name}"\n' " 2024-01-01 WCONHIST STATUS=OPEN INVALID_FIELD=1.0\n" ) @@ -1971,7 +2178,7 @@ class TestSimulatorEventsIntegration: project, _case, timeline = project_with_case_and_wells well = project.well_paths()[0] document = parse_simulator_events( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" f'WELL "{well.name}"\n' " 2018-06-08 WTRACER TRACER=T1 CONCENTRATION=1.0 COMMENTS=typo\n" ) @@ -1998,7 +2205,7 @@ class TestSimulatorEventsIntegration: project, _case, timeline = project_with_case_and_wells well = project.well_paths()[0] document = parse_simulator_events( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" f'WELL "{well.name}"\n' ' 2018-06-08 WTRACER TRACER=T1 CONCENTRATION=1.0 COMMENT="Tracer start"\n' ) @@ -2014,7 +2221,7 @@ class TestSimulatorEventsIntegration: project, _case, timeline = project_with_case_and_wells well = project.well_paths()[0] document = parse_simulator_events( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" f'WELL "{well.name}"\n' " 2024-01-01 NOT_A_KEYWORD VALUE=1\n" " 2024-01-02 WCONHIST STATUS=OPEN\n" @@ -2039,7 +2246,7 @@ class TestSimulatorEventsIntegration: settings.update() document = parse_simulator_events( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" f'WELL "{well.name}"\n' " 2024-01-01 WCONHIST STATUS=OPEN CMODE=ORAT ORAT=100\n" " 2024-01-01 WELTARG CMODE=ORAT VALUE=200\n" @@ -2063,7 +2270,7 @@ class TestSimulatorEventsIntegration: project, case, timeline = project_with_case_and_wells well = project.well_paths()[0] document = parse_simulator_events( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" f'WELL "{well.name}"\n' " 2024-01-01 WCONHIST STATUS=OPEN\n" "SCHEDULE\n" @@ -2090,7 +2297,7 @@ class TestSimulatorEventsIntegration: project, case, timeline = project_with_case_and_wells well = project.well_paths()[0] document = parse_simulator_events( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" f'WELL "{well.name}"\n' " 2024-01-01 WCONHIST STATUS=OPEN\n" "SCHEDULE\n" @@ -2129,7 +2336,7 @@ class TestSimulatorEventsIntegration: def test_raw_text_only_schedule_is_generated(self, project_with_case_and_wells): project, case, timeline = project_with_case_and_wells document = parse_simulator_events( - "SIMEVENTS 1.0\nSCHEDULE\n" + "SIMEVENTS 1.1\nSCHEDULE\n" " 2024-01-01 RAW_TEXT PLACEMENT=AFTER_DATE\n" "-- raw-only\nEND_RAW_TEXT\n" ) @@ -2149,7 +2356,7 @@ class TestSimulatorEventsIntegration: ): project, case, timeline = project_with_case_and_wells document = parse_simulator_events( - "SIMEVENTS 1.0\nSCHEDULE\n" + "SIMEVENTS 1.1\nSCHEDULE\n" " 2024-01-01 RAW_TEXT PLACEMENT=BEFORE_KEYWORD ANCHOR=COMPDAT\n" "text\nEND_RAW_TEXT\n" ) @@ -2164,7 +2371,7 @@ class TestSimulatorEventsIntegration: project, case, timeline = project_with_case_and_wells well = project.well_paths()[0] document = parse_simulator_events( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" f'WELL "{well.name}"\n' ' 2024-01-01 WCONHIST STATUS=OPEN COMMENT="Startup target"\n' ) @@ -2180,7 +2387,7 @@ class TestSimulatorEventsIntegration: project, case, timeline = project_with_case_and_wells well = project.well_paths()[0] document = parse_simulator_events( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" f'WELL "{well.name}"\n' " 2020-07-01 WCONHIST STATUS=OPEN CMODE=ORAT\n" 'GROUP "OP"\n' @@ -2209,7 +2416,7 @@ class TestSimulatorEventsIntegration: project, case, timeline = project_with_case_and_wells well = project.well_paths()[0] document = parse_simulator_events( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" f'WELL "{well.name}"\n' " 2024-01-01 WCONHIST STATUS=OPEN\n" 'GROUP "PRODUCERS"\n' @@ -2232,7 +2439,7 @@ class TestSimulatorEventsIntegration: project, case, timeline = project_with_case_and_wells well = next(wp for wp in project.well_paths() if "A" in wp.name) document = parse_simulator_events( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" f'WELL "{well.name}"\n' " 2018-01-01 WELSPECS GROUP=my_group REFDEPTH=1002 PHASE=water\n" " 2019-01-01 WELSPECS CROSSFLOW=False REFDEPTH=1000 PHASE=oil\n" @@ -2279,7 +2486,7 @@ class TestSimulatorEventsIntegration: project, case, timeline = project_with_case_and_wells well = project.well_paths()[0] document = parse_simulator_events( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" f'WELL "{well.name}"\n' " 2024-01-01 WCONHIST STATUS=OPEN CMODE=ORAT ORAT=100\n" " 2024-02-01 WCONHIST STATUS=OPEN CMODE=ORAT ORAT=200\n" @@ -2311,7 +2518,7 @@ class TestSimulatorEventsIntegration: def test_report_only_document_generates_schedule(self, project_with_case_and_wells): project, case, timeline = project_with_case_and_wells document = parse_simulator_events( - "SIMEVENTS 1.0\nSCHEDULE\nINSERT_DATE 2024-02-01\nINSERT_DATE 2024-06-01\n" + "SIMEVENTS 1.1\nSCHEDULE\nINSERT_DATE 2024-02-01\nINSERT_DATE 2024-06-01\n" ) report = apply_simulator_events_document(document, timeline, project) @@ -2329,7 +2536,7 @@ class TestSimulatorEventsIntegration: def test_end_is_first_keyword_after_date(self, project_with_case_and_wells): project, case, timeline = project_with_case_and_wells document = parse_simulator_events( - "SIMEVENTS 1.0\nSCHEDULE\n" + "SIMEVENTS 1.1\nSCHEDULE\n" "2024-01-01 RPTRST BASIC=2 FREQ=1\n" "2024-01-01 END\n" ) @@ -2353,10 +2560,10 @@ class TestSimulatorEventsIntegration: # Reference the real well name; MD range is valid for well path A. text = ( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" "UNIT METRIC\n" "DATE START = 2024-01-01\n" - "DURATION RAMP = 5 DAYS\n" + "DURATION RAMP = 5d\n" f'WELL "{well.name}"\n' " START PERFORATION MDSTART=2000 MDEND=2200 DIAMETER=0.1 SKIN=0.5 COMPLETION_NUMBER=1\n" " START + RAMP WCONHIST STATUS=OPEN CMODE=ORAT VFP=1\n" @@ -2400,14 +2607,14 @@ class TestSimulatorEventsIntegration: well = next(wp for wp in project.well_paths() if "A" in wp.name) text = ( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" "UNIT METRIC\n" "DATE STARTUP = 2024-01-01\n" - "DURATION RAMP = 31 DAYS\n" + "DURATION RAMP = 31d\n" f'WELL "{well.name}"\n' " STARTUP SEGMENT MDSTART=0 MDEND=2500 INNER_DIAMETER=0.15 ROUGHNESS=1.0e-5 PRESSURE_COMPONENTS=HFA\n" " STARTUP + RAMP PERFORATION MDSTART=2000 MDEND=2200 DIAMETER=0.1 SKIN=0.5 COMPLETION_NUMBER=1\n" - " 2024-05-15T14:45:30.500 PERFORATION MDSTART=2300 MDEND=2350 DIAMETER=0.1 SKIN=0.4 COMPLETION_NUMBER=2\n" + " 2024-05-15T14:45:30.700 PERFORATION MDSTART=2300 MDEND=2350 DIAMETER=0.1 SKIN=0.4 COMPLETION_NUMBER=2\n" " 2024-03-01 VALVE MD=2100 TYPE=ICV STATE=OPEN CV=0.7 AREA=0.0001\n" " 2024-02-15 STATE STATE=OPEN\n" " 2024-01-15 WCONHIST STATUS=OPEN CMODE=RESV ORAT=3999.99 VFP=1\n" @@ -2447,14 +2654,14 @@ class TestSimulatorEventsIntegration: ): assert keyword in schedule, f"{keyword} missing from schedule" # The datetime perforation must surface as a DATES entry with TIME. - assert "14:45:30.500" in schedule + assert "14:45:31" in schedule def test_apply_unknown_well_warns_and_applies_nothing( self, project_with_case_and_wells ): project, _case, timeline = project_with_case_and_wells text = ( - 'SIMEVENTS 1.0\nWELL "NO_SUCH_WELL"\n' + 'SIMEVENTS 1.1\nWELL "NO_SUCH_WELL"\n' " 2024-01-01 PERFORATION MDSTART=1 MDEND=2\n" ) document = parse_simulator_events(text) @@ -2470,7 +2677,7 @@ class TestSimulatorEventsIntegration: well = next(wp for wp in project.well_paths() if "A" in wp.name) text = ( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" 'FILTER hiperm = "PERMX > 50.0"\n' f'WELL "{well.name}"\n' " 2024-01-01 PERFORATION MDSTART=2000 MDEND=2200 DIAMETER=0.1 FILTER=hiperm\n" @@ -2507,7 +2714,7 @@ class TestSimulatorEventsIntegration: well = next(wp for wp in project.well_paths() if "A" in wp.name) text = ( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" f'WELL "{well.name}"\n' ' 2024-01-01 PERFORATION MDSTART=2000 MDEND=2200 FILTER="static.PERMX >= 50"\n' ) @@ -2530,7 +2737,7 @@ class TestSimulatorEventsIntegration: well = next(wp for wp in project.well_paths() if "A" in wp.name) text = ( - "SIMEVENTS 1.0\n" + "SIMEVENTS 1.1\n" f'WELL "{well.name}"\n' ' 2024-01-01 PERFORATION MDSTART=2000 MDEND=2200 FILTER="NO_SUCH_RESULT > 1"\n' ) diff --git a/docs/simulatorEvents.md b/docs/simulatorEvents.md index 0595d0cc6f..3bcab6b211 100644 --- a/docs/simulatorEvents.md +++ b/docs/simulatorEvents.md @@ -1,4 +1,4 @@ -# SIMEVENTS File Format — Version 1.0 +# SIMEVENTS File Format — Version 1.1 ## Overview @@ -22,13 +22,13 @@ Runnable examples: `rips/PythonExamples/experimental/import_simulator_events.py` ## Quick example ``` -SIMEVENTS 1.0 +SIMEVENTS 1.1 UNIT METRIC # Typed declarations DATE STARTUP = 2024-01-01 -DATE PHASE2 = 2024-03-01 + 9 -DURATION RAMP = 31 DAYS +DATE PHASE2 = 2024-03-01 + 9d +DURATION RAMP = 31d FILTER POROPERM = "PORO > 0.4 AND PERMX > 100.0" WELL A1 = "55_33-A-1" # alias declaration (has '=') @@ -36,14 +36,14 @@ WELL A1 = "55_33-A-1" # alias declaration (has '=') WELL A1 # opens an event block via the alias @STARTUP SEGMENT MDSTART=0 MDEND=2500 INNER_DIAMETER=0.15 ROUGHNESS=1.0e-5 PRESSURE_COMPONENTS=HFA @STARTUP + RAMP PERFORATION MDSTART=2000 MDEND=2200 RADIUS=0.05 SKIN=0.5 COMPLETION_NUMBER=1 FILTER=POROPERM - @2024-05-15T14:45:30.500 PERFORATION MDSTART=2300 MDEND=2350 RADIUS=0.05 + @2024-05-15T14:45:30 PERFORATION MDSTART=2300 MDEND=2350 RADIUS=0.05 @2024-03-01 VALVE MD=2100 TYPE=ICV STATE=OPEN CV=0.7 AREA=0.0001 @STARTUP + RAMP WCONHIST STATUS=OPEN CMODE=ORAT VFP=1 @2024-05-01 WELTARG CMODE=ORAT VALUE=5000.0 @2024-06-01 WRFTPLT OUTPUT_RFT=YES OUTPUT_PLT=NO OUTPUT_SEGMENT=NO WELL "55_33-A-2" # quoted form: literal well name - @PHASE2 - 1 PERFORATION MDSTART=1692.79 MDEND=1706 RADIUS=0.12065 SKIN=5 + @PHASE2 - 1d PERFORATION MDSTART=1692.79 MDEND=1706 RADIUS=0.12065 SKIN=5 SCHEDULE # schedule-level keywords, not tied to a well @STARTUP RPTRST BASIC=2 FREQ=1 @@ -55,15 +55,15 @@ SCHEDULE # schedule-level keywords, not tied to a well ``` document = header , { statement } ; -header = "SIMEVENTS" , "1.0" ; (* first meaningful line *) +header = "SIMEVENTS" , "1.1" ; (* first meaningful line *) statement = unit_directive | declaration | report_line | well_block_open | group_block_open | schedule_block_open | event_line ; unit_directive = "UNIT" , ( "METRIC" | "FIELD" | "LAB" ) ; report_line = "REPORT" , date_expr ; declaration = date_decl | duration_decl | well_decl | filter_decl ; -date_decl = "DATE" , ident , "=" , date_expr ; (* DATE X = 2018-03-01 + 9 *) -duration_decl = "DURATION" , ident , "=" , duration_expr ; (* DURATION RAMP = 5 DAYS *) +date_decl = "DATE" , ident , "=" , date_expr ; (* DATE X = 2018-03-01 + 9d *) +duration_decl = "DURATION" , ident , "=" , duration_expr ; (* DURATION RAMP = 5d12h *) well_decl = "WELL" , ident , "=" , quoted_string ; (* WELL A1 = "55_33-A-1" *) filter_decl = "FILTER" , ident , "=" , '"' , filter_expr , '"' ; (* FILTER F = "PORO > 0.4 AND PERMX > 100.0" *) @@ -82,13 +82,19 @@ segment_attribute = "MDSTART" | "MDEND" | "INNER_DIAMETER" | "ROUGHNESS" | "PRESSURE_COMPONENTS" | "COMMENT" ; (* accepted attribute names when event_type is "SEGMENT" *) -date_expr = ( iso_date | iso_datetime | date_ident ) , { sign , term } ; -duration_expr = ( integer | dur_ident ) , { sign , term } , [ "DAYS" | "days" ] ; -term = integer | dur_ident ; (* whole days *) +date_expr = ( iso_datetime | date_ident ) , { sign , term } ; +duration_expr = term , { sign , term } ; +term = duration_lit | dur_ident ; (* e.g. 2d, -12h30m, RAMP *) sign = "+" | "-" ; -iso_date = 4digit , "-" , 2digit , "-" , 2digit ; -iso_datetime = iso_date , "T" , 2digit , ":" , 2digit , ":" , 2digit , - [ "." , digits ] ; (* 2024-05-15T14:45:30.500 *) +duration_lit = [ sign ] , component , { component } ; + (* units strictly descending, each at most once *) +component = number , ( "mon" | "d" | "h" | "m" | "s" ) ; +number = digits | digits , "." , digits ; + (* a fraction only on the last component, + never on "mon" or "s" *) +iso_datetime = 4digit , "-" , 2digit , "-" , 2digit , + [ "T" , 2digit , ":" , 2digit , ":" , 2digit , [ "." , digits ] ] ; + (* 2024-05-15 or 2024-05-15T14:45:30 *) ident = letter_or_underscore , { word_char } ; attribute = ident , "=" , ( quoted_string | bareword ) ; comment = "#" , rest-of-line ; (* line or trailing *) @@ -96,14 +102,14 @@ comment = "#" , rest-of-line ; (* line or trailing *) ## Line types -The format is line-oriented. Every non-blank line is dispatched on its first token; anything else is an error. Keywords are uppercase and case-sensitive (the `DAYS` suffix is also accepted as `days`). +The format is line-oriented. Every non-blank line is dispatched on its first token; anything else is an error. Keywords are uppercase and case-sensitive; duration units (`mon`, `d`, `h`, `m`, `s`) are lowercase. | First token | Meaning | |---|---| | `SIMEVENTS` | Header with version; must be the first meaningful line, exactly once | | `UNIT` | Unit system: `METRIC`, `FIELD` or `LAB` (default `METRIC`) | | `DATE` | Declare a typed date variable | -| `DURATION` | Declare a typed whole-day duration variable | +| `DURATION` | Declare a typed duration variable (Go-style literal, e.g. `5d`, `12h30m`) | | `FILTER` | Declare a typed cell-filter expression | | `REPORT` | Add a date that must appear in generated schedule output | | `WELL` | With `=`: declare a well-name alias. Without `=`: open a well event block | @@ -114,11 +120,11 @@ The format is line-oriented. Every non-blank line is dispatched on its first tok ## Typed declarations -Variables are typed — `DATE`, `DURATION` (whole days), `WELL` (well-name alias) and `FILTER` (cell filter expression) — and share one namespace. They must be declared before use (single-pass, no forward references). +Variables are typed — `DATE`, `DURATION`, `WELL` (well-name alias) and `FILTER` (cell filter expression) — and share one namespace. They must be declared before use (single-pass, no forward references). ``` DATE STARTUP = 2024-01-01 -DURATION RAMP = 31 DAYS # DAYS suffix optional +DURATION RAMP = 31d # Go-style duration literal DATE PHASE2 = STARTUP + RAMP # date arithmetic with variables WELL A1 = "55_33-A-1" FILTER POROPERM = "PORO > 0.4 AND PERMX > 100.0" @@ -134,16 +140,49 @@ Redeclaring a name with the same type warns and the last value wins; redeclaring ## Date expressions -A date expression is an ISO date, an ISO datetime, or a `DATE` variable, followed by a chain of signed whole-day terms. Each term is a non-negative integer or a `DURATION` variable: +A date expression is an ISO datetime or a `DATE` variable, followed by a chain of signed terms. Each term is a [duration literal](#duration-literals) or a `DURATION` variable: ``` @2024-01-01 -@STARTUP + 5 -@STARTUP + RAMP - 2 -@2024-05-15T14:45:30.500 # time-of-day, millisecond precision +@STARTUP + 5d +@STARTUP + RAMP - 2d +@STARTUP + 12h30m +@2024-05-15T14:45:30 # time-of-day, second precision +@2024-01-31 + 1mon # calendar month: 2024-02-29 ``` -Whitespace around `+`/`-` is optional but conventional. A time-of-day is preserved through the applier and emitted as the optional TIME field of the generated DATES keyword. +Every date is a datetime with **second** resolution. A date-only literal (`2024-01-01`) means midnight; a time-of-day is written with the `T` separator (`YYYY-MM-DDTHH:MM:SS`). Fractional seconds are accepted and rounded to the nearest second. An operand may carry its own sign (`START + -2d` equals `START - 2d`); whitespace around `+`/`-` is optional but conventional. A non-midnight time-of-day is preserved through the applier and emitted as the optional TIME field of the generated DATES keyword. + +## Duration literals + +A duration literal is written Go-style: one or more `` components with no spaces, using the units below in strictly descending order, each at most once. + +| Unit | Meaning | +|---|---| +| `mon` | calendar month | +| `d` | day (24 h) | +| `h` | hour | +| `m` | minute | +| `s` | second | + +``` +DURATION RAMP = 5d +DURATION SHIFT = 12h30m +DURATION QUARTER = 3mon +DURATION BACK = -3d +DURATION HALF = 1.5h # fraction allowed on the last component only +DURATION TOTAL = RAMP + SHIFT - 6h # duration arithmetic with variables +``` + +Rules: + +* A unit is mandatory: `5` and the pre-1.1 `5 DAYS` are errors (write `5d`). +* Units must be in the order `mon`, `d`, `h`, `m`, `s` and may not repeat: `12h30m` is valid, `30m12h` and `1h1h` are not. +* A fraction is allowed only on the **last** component, and never on `mon` or `s`: `1.5h` and `1d1.5h` are valid, `1.5h30m`, `1.5s` and `1.5mon` are not. The result is rounded to whole seconds. +* `mon` is calendar-relative and is applied before the fixed part of a duration. Adding months clamps to the last day of a shorter month: `2024-01-31 + 1mon` is `2024-02-29` and `2024-01-31 + 1mon1d` is `2024-03-01`. +* A leading `-` negates the whole literal (`-1mon12h` is minus one month and minus twelve hours). + +In Python a `DURATION` value is a `rips.simulator_events.Duration` with `months` and `delta` (`datetime.timedelta`) fields; `str()` renders the Go-style form, e.g. `1mon5d12h30m`. ## WELL blocks @@ -264,7 +303,7 @@ The validator CLI prints these and exits non-zero: ``` $ python3 -m rips.simulator_events simulator_events.events -simulator_events.events: OK (SIMEVENTS 1.0, units METRIC) +simulator_events.events: OK (SIMEVENTS 1.1, units METRIC) 4 variable(s), 2 well block(s), 8 well event(s), 0 schedule event(s) ``` @@ -303,4 +342,5 @@ The returned `ApplyReport` carries `events_applied`, `events_skipped`, `warnings ## Version history -- **1.0** — current: typed `DATE`/`DURATION`/`WELL`/`FILTER` declarations, `WELL`/`SCHEDULE` blocks, signed day-offset chains, ISO datetimes, built-in completion events (including `SEGMENT` custom intervals and pressure components) plus generic keyword pass-through, perforation data filters, multi-error diagnostics, validator CLI. +- **1.1** — current: all dates are datetimes with second resolution (`T` separator required for a time-of-day; fractional seconds rounded); `DURATION` values and offset terms are Go-style literals (`5d`, `12h30m`, `1.5h`, `3mon`, `-3d`) with mandatory units, strict descending unit order, and calendar-aware months. Unitless numbers and the `DAYS` suffix are rejected; `1.0` files are rejected with a migration hint. +- **1.0** — typed `DATE`/`DURATION`/`WELL`/`FILTER` declarations, `WELL`/`SCHEDULE` blocks, signed day-offset chains, ISO datetimes, built-in completion events (including `SEGMENT` custom intervals and pressure components) plus generic keyword pass-through, perforation data filters, multi-error diagnostics, validator CLI.