pymetrix-eviews 0.1.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1479 @@
1
+ """Phase 1: data work, and the translator. Each statement becomes ``Op``s (``ir.py``) with a status and a reason, or is
2
+ left out with one; estimation and tests (``estimation.py``) and models (``models.py``) are phase 2's handlers.
3
+
4
+ The translator walks the program in order, as EViews runs it, keeping what the program's text tells: the pages
5
+ (each a Dataset variable, the current one, their frequencies, series and samples) and the program's own variables
6
+ (scalars, ``!`` numbers, ``%`` strings, groups, samples, matrices), with their values where they are known before
7
+ the program runs, so ``{%s}`` and ``{!i}`` in a line can be put in. A value known only when the program runs (set
8
+ in a loop, a subroutine or from the data) is used by name, and a name made from it is made as the program runs
9
+ (phase 3, ``control.py``, which walks loops, ``if`` blocks and subroutines).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import builtins
15
+ import math
16
+ import re
17
+ from dataclasses import dataclass, field, replace
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from pymetrix.extension import EViewsBinary, EViewsBrackets, EViewsCall, EViewsCoefficient, EViewsExpressionError, EViewsName
22
+ from pymetrix.extension import EViewsNegative, EViewsNumber, parse_eviews_expression, render_eviews_expression
23
+ from pymetrix.extension import walk_eviews_expression
24
+
25
+ from ..bundle import _py_name
26
+ from .estimation import ESTIMATORS, LEFT_ESTIMATORS, Estimation
27
+ from .control import PLACEHOLDER, ProgramValues, dynamic_ops
28
+ from .ir import Arg, Code, Op, Py, SampleSpec, Spread, Step, Text, Var, quote
29
+ from .left import (GAP_FUNCTIONS, PROGRAM_FUNCTIONS, PHASE2_COMMANDS, PHASE3_WORDS, PHASE4_COMMANDS, PHASE4_METHODS,
30
+ STATISTICS, left_reason)
31
+ from .models import Models
32
+ from .parse import Statement, _statement
33
+ from .report import ERROR, LEFT, NOTE, TRANSLATED
34
+
35
+ __all__ = ["Outcome", "Translator", "is_closer", "is_opener"]
36
+
37
+ _UNKNOWN = object()
38
+ _NAN = 'float("nan")'
39
+ DEFAULT_SEED = 0 # before any rndseed, the k-th random draw of the program is seeded DEFAULT_SEED*1000 + k: 1, 2, ...
40
+ _OPENERS = {"for": "next", "while": "wend", "if": "endif", "subroutine": "endsub"}
41
+ _CLOSERS = {"next", "wend", "endif", "endsub"}
42
+ _HARMLESS = frozenset({*PHASE4_COMMANDS, "wfsave", "pagesave", "wfclose"}) # left out without making series
43
+ _SCRIPT_NAMES = {"Dataset", "Matrix", "Sample", "pymetrix", "pymetrix_eviews", "eviews_dates"}
44
+ # the core reader's refusals of what EViews reads but pymetrix's expressions do not: left out, not errors
45
+ _NOT_TRANSLATED = ("is read with g a series' name", "inside d, dlog, @pch or a moving window", "no seed is given")
46
+
47
+
48
+ class _Out(Exception):
49
+ """A statement that does not translate: its status (left out or error) and the reason."""
50
+
51
+ def __init__(self, status: str, reason: str) -> None:
52
+ super().__init__(reason)
53
+ self.status, self.reason = status, reason
54
+
55
+
56
+ def _left(reason: str) -> _Out:
57
+ return _Out(LEFT, reason)
58
+
59
+
60
+ def _error(reason: str) -> _Out:
61
+ return _Out(ERROR, reason)
62
+
63
+
64
+ @dataclass
65
+ class _Page:
66
+ var: str
67
+ eviews: str
68
+ freq: str | None # Y, Q, M, W, D; None undated or unknown
69
+ series: set[str] | None # pymetrix names; None when not known
70
+ sample: Any = None # None (all), a SampleSpec, or a Var (a named sample)
71
+ first: str | None = None
72
+ last: str | None = None
73
+
74
+
75
+ @dataclass
76
+ class _Py:
77
+ name: str
78
+ kind: str # scalar, control, string, group, sample, matrix
79
+ value: Any = _UNKNOWN
80
+ shape: tuple[int, int] | None = None
81
+ members: list[str] = field(default_factory=list)
82
+ page: str = ""
83
+
84
+
85
+ @dataclass
86
+ class Outcome:
87
+ """One statement translated: its status, reason and ops; a block's also its body (``children``), its else branch
88
+ (``orelse``, after ``else_outcome``) and its end (``closer``); ``file`` the included program it is in."""
89
+
90
+ statement: Statement
91
+ status: str
92
+ reason: str = ""
93
+ ops: list[Op] = field(default_factory=list)
94
+ file: str = ""
95
+ kind: str = ""
96
+ children: list[Any] = field(default_factory=list)
97
+ orelse: list[Any] = field(default_factory=list)
98
+ else_outcome: Any = None
99
+ closer: Any = None
100
+
101
+
102
+ def _public_names() -> set[str]:
103
+ import pymetrix
104
+
105
+ return {n for n in getattr(pymetrix, "__all__", ())} | {"data"} | {n for n in dir(builtins) if not n.startswith("_")}
106
+
107
+
108
+ def _number_text(value: float) -> str:
109
+ return str(int(value)) if float(value).is_integer() and abs(value) < 1e15 else repr(float(value))
110
+
111
+
112
+ _FREQ = {"a": "Y", "y": "Y", "q": "Q", "m": "M", "w": "W", "d": "D", "d7": "D", "7": "D"}
113
+ _FREQ_GAP = {"s": "semi-annual pages: pandas has no half-year period (a gap)",
114
+ "d5": "business-day pages are not translated (a gap)", "5": "business-day pages are not translated (a gap)",
115
+ "u": "undated pages are not made here: read the data with Dataset.read, or use a dated page",
116
+ "h": "intraday pages are not translated (a gap)", "min": "intraday pages are not translated (a gap)",
117
+ "sec": "intraday pages are not translated (a gap)", "bm": "bimonthly pages are not translated (a gap)",
118
+ "f": "fortnightly pages are not translated (a gap)", "t": "ten-day pages are not translated (a gap)"}
119
+
120
+
121
+ def _period(token: str, freq: str | None) -> str | None:
122
+ """An EViews date as a pymetrix period of frequency ``freq`` (Y, Q or M): 1990q1, 1990:1, 1990m3, 1990."""
123
+ token = token.strip().strip('"').lower()
124
+ m = re.fullmatch(r"(\d{4})(?:([qm:])(\d{1,2}))?", token)
125
+ if m is None or freq not in ("Y", "Q", "M"):
126
+ return None
127
+ year, kind, sub = m.group(1), m.group(2), int(m.group(3) or 1)
128
+ if freq == "Y":
129
+ return year if kind is None else None
130
+ if freq == "Q" and kind in ("q", ":") and 1 <= sub <= 4:
131
+ return f"{year}Q{sub}"
132
+ if freq == "M" and kind in ("m", ":") and 1 <= sub <= 12:
133
+ return f"{year}-{sub:02d}"
134
+ return None # a year alone in a quarterly or monthly page: the caller decides its first or last period
135
+
136
+
137
+ def _shifted(period: str, freq: str, n: int) -> str:
138
+ import pandas as pd
139
+
140
+ return str(pd.Period(period, freq=freq) + n)
141
+
142
+
143
+ class Translator(Estimation, Models, ProgramValues):
144
+ """Translates a program's statements in order (see the module's docstring); estimation and tests
145
+ (``estimation.py``) and models (``models.py``) are phase 2's, the program's own values (``control.py``) phase 3's."""
146
+
147
+ def __init__(self, bundle: str | None = None, read_options: dict[str, Any] | None = None) -> None:
148
+ self.bundle = bundle
149
+ self.read_options = dict(read_options or {})
150
+ self.pages: dict[str, _Page] = {} # by EViews name, lower case
151
+ self.current: _Page | None = None
152
+ self.py: dict[str, _Py] = {} # by EViews name: "s", "!i", "%x"
153
+ self.taken: dict[str, str] = {} # Python name -> what holds it
154
+ self.types: dict[str, str] = {} # other objects' types, by EViews name: model, graph, table, equation, ...
155
+ self.opened: str | None = None
156
+ self.uses_bundle = False
157
+ self.public = _public_names()
158
+ self.workfile_frequency: str | None = None
159
+ self.lost = False # a line that may have set values was left out
160
+ self.unset: dict[str, int] = {} # variables a left-out line sets, by EViews name -> that line
161
+ self.fits: dict[str, Any] = {} # estimated objects, by EViews name (estimation.Fit)
162
+ self.systems: dict[str, dict[str, Any]] = {} # systems being collected
163
+ self.models: dict[str, Any] = {} # models (models._Model)
164
+ self.last_fit: Any = None # the estimation that last filled c
165
+ self.building: list[tuple[str, int]] = [] # (model, line) of each line that builds a model
166
+ self.refusals: dict[int, list[str]] = {} # the model reader's problems, by the program's line
167
+ self._declared: dict[str, int] = {} # scalars -> the line that made them
168
+ self._fit_line: dict[str, int] = {} # estimated objects -> the line that estimated them last
169
+ self.line = 0 # the line being translated
170
+ self.runtime = 0 # > 0 inside a loop, an if block or a subroutine: values are known when the program runs
171
+ self.dynamic: dict[int, str] = {} # placeholder number -> the Python variable whose value it stands for
172
+ self.sample_unknown: set[str] = set() # pages whose sample depends on the branch an if block takes
173
+ self._made_names = False # the statement being translated makes a name from a value known when it runs
174
+ self._dated_note = False # the sample being read has dates known when the program runs
175
+ self.rndseed: int | None = None # the last rndseed's value (None before one)
176
+ self.draws = 0 # random draws translated since it (or since the start)
177
+ self.expression_notes: list[str] = [] # what the statement's expressions say (random draws, the sample)
178
+
179
+ # -- names ------------------------------------------------------------------------------------------------------
180
+
181
+ def _name(self, eviews: str, what: str) -> tuple[str, str]:
182
+ """A Python variable for an EViews object, and a note when its name changed."""
183
+ base = _py_name(eviews.lstrip("!%"))
184
+ note = f"{eviews} is called {base} ({eviews.lstrip('!%').lower()} is a Python word)" if base != eviews.lstrip("!%").lower() else ""
185
+ if base in self.public or base in _SCRIPT_NAMES:
186
+ note = f"{eviews} is called {base}_v ({base} is a Python or pymetrix name)"
187
+ base = f"{base}_v"
188
+ name, i = base, 2
189
+ while name in self.taken and self.taken[name] != what:
190
+ name, i = f"{base}_{i}", i + 1
191
+ if name != base:
192
+ note = f"{eviews} is called {name} ({base} is taken)"
193
+ self.taken[name] = what
194
+ return name, note
195
+
196
+ def _page_named(self, name: str) -> _Page:
197
+ page = self.pages.get(name.lower())
198
+ if page is None:
199
+ raise _error(f"no page {name!r}" + (f"; the pages: {', '.join(p.eviews for p in self.pages.values())}" if self.pages else ""))
200
+ return page
201
+
202
+ def _page(self) -> _Page:
203
+ if self.current is None and self.runtime:
204
+ raise _left("no page is open where this line is translated: a subroutine works on the page selected when it is "
205
+ "called (translate the program that opens the workfile and calls it)")
206
+ if self.current is None:
207
+ raise _error("no workfile is open yet: wfopen or wfcreate comes first")
208
+ return self.current
209
+
210
+ # -- the program's values ----------------------------------------------------------------------------------------
211
+
212
+ def _known(self, key: str) -> Any:
213
+ v = self.py.get(key.lower())
214
+ return _UNKNOWN if v is None else v.value
215
+
216
+ def _value_text(self, key: str, braces: bool, notes: list[str]) -> str:
217
+ """A program variable's value as text, for ``{key}`` (or ``%key`` in a command); a value known only when the
218
+ program runs is a placeholder, made into a name made as it runs (``control.dynamic_ops``)."""
219
+ low = key.lower()
220
+ value = self._known(key)
221
+ v = self.py.get(low)
222
+ if v is None:
223
+ v = self.runtime_variable(low) if low[:1] in "!%" else None
224
+ if value is _UNKNOWN and v is not None and v.kind in ("scalar", "control", "string"):
225
+ self._made_names = True
226
+ return self.placeholder(low)
227
+ if value is _UNKNOWN:
228
+ kind = (f"set by line {self.unset[low]}, which is left out" if low in self.unset else
229
+ "a line left out may set it" if self.lost else "never set")
230
+ raise _left(f"{'{' + key + '}' if braces else key} has no value ({kind})")
231
+ text = _number_text(value) if isinstance(value, (int, float)) else str(value)
232
+ shown = "{" + key + "}" if braces else key
233
+ if f"{shown} is {text!r}" not in notes and not self.runtime:
234
+ notes.append(f"{shown} is {text!r}")
235
+ return text
236
+
237
+ def _braces(self, text: str, notes: list[str] | None = None) -> tuple[str, list[str]]:
238
+ """``{%s}``, ``{!i}`` and ``{s}`` in ``text`` put in."""
239
+ notes = [] if notes is None else notes
240
+ if "{" in text:
241
+ text = re.sub(r"\{\s*([!%]?\w+)\s*\}", lambda m: self._value_text(m.group(1), True, notes), text)
242
+ if "{" in text:
243
+ raise _left("a name made from an expression in braces ({!i+1}) is not translated: give a variable its value "
244
+ "first (!j = !i + 1), then use {!j}")
245
+ return text, notes
246
+
247
+ def _substitute(self, st: Statement) -> tuple[Statement, list[str]]:
248
+ """``{%s}``, ``{!i}`` and ``{s}`` put in with their values, and ``%s`` in a command's arguments; a value known
249
+ only when the program runs makes the name as it runs."""
250
+ notes: list[str] = []
251
+ text = st.text
252
+ if "{" in text:
253
+ text, _ = self._braces(text, notes)
254
+ if st.kind != "assign" and st.word not in ("string",) and "%" in text:
255
+ pieces = re.split(r'("[^"]*")', text)
256
+ text = "".join(p if p.startswith('"') else re.sub(r"%(\w+)", lambda m: self._value_text("%" + m.group(1), False, notes), p)
257
+ for p in pieces)
258
+ if text == st.text:
259
+ return st, []
260
+ lead = len(st.text) - len(st.text.lstrip())
261
+ new = _statement(text, st.at, st.line, st.last_line)
262
+ return replace(new, rest_at=st.rest_at if new.rest == st.rest else st.at + lead), notes
263
+
264
+ # -- expressions ------------------------------------------------------------------------------------------------
265
+
266
+ def _scan(self, text: str) -> None:
267
+ """Functions pymetrix's expressions have no equivalent of (the audit), and statistics: left out by name."""
268
+ if re.search(r"\w\.@?\w", re.sub(r'"[^"]*"|\d+\.\d*', "", text)):
269
+ raise _left("an object's data member (eq.@coefs(2), g.@count) in a series expression is not translated: give a "
270
+ "scalar its value first (scalar b = eq.@coefs(2)), then use the scalar")
271
+ for m in re.finditer(r'"[^"]*"|(?<![\w@!%])(@?[A-Za-z_]\w*)', text):
272
+ if m.group(1) is None:
273
+ continue
274
+ name = m.group(1).lower()
275
+ if name in STATISTICS:
276
+ raise _left(f"{name} is the sample's {STATISTICS[name].replace('std', 'standard deviation').replace('count', 'number of observations')}, "
277
+ f"a number: give a scalar its value first (scalar m = {name}(x)), then use the scalar")
278
+ if name in PROGRAM_FUNCTIONS:
279
+ raise _left(f"{name} is part of EViews's programming language (strings, objects, matrices): it makes a "
280
+ "program's value, not a series; give a string or a scalar its value first (%w = @word(%s, 1))")
281
+ if name in GAP_FUNCTIONS:
282
+ raise _left(f"{name} ({GAP_FUNCTIONS[name]}) has no equivalent in pymetrix's expressions: a gap "
283
+ "(docs/known-gaps.md)")
284
+ if name.startswith("@") and name in ("@uiprompt", "@uidialog", "@uiedit", "@uilist", "@uiradio"):
285
+ raise _left(left_reason("interactive prompts", "the dialog asks for the program's arguments"))
286
+
287
+ def _scalars(self) -> dict[str, str]:
288
+ """Names as the expression parser sees them (``!i`` as ``_i``) -> Python variables, for the numbers."""
289
+ out = {}
290
+ for key, v in self.py.items():
291
+ if v.kind in ("scalar", "control"):
292
+ out["_" + key[1:] if key.startswith("!") else key] = v.name
293
+ return out
294
+
295
+ def _tree(self, text: str, at: int, comparison: bool = False, coefs: bool = False) -> Any:
296
+ self._scan(text)
297
+ if re.search(r'%\w', re.sub(r'"[^"]*"', "", text)):
298
+ raise _left("a string variable in a series expression: put it in a name with braces ({%s}), or compare it "
299
+ "in an if block")
300
+ work = re.sub(r"!(?=[A-Za-z_])", "_", text)
301
+ vectors = {"c"} | {k for k, v in self.types.items() if v == "coef"}
302
+ try:
303
+ tree = parse_eviews_expression(work, at, vectors, comparison)
304
+ except EViewsExpressionError as exc:
305
+ group = re.search(r"([A-Za-z_]\w*)\(\.\.\.\) is neither", exc.message)
306
+ if group and (PLACEHOLDER.fullmatch(group.group(1).lower()) or self.py.get(group.group(1).lower(), _Py("", "")).kind == "group"):
307
+ raise _left("a group's i-th series (g(i)) in an expression is not translated: name the series "
308
+ "(%s = {%g}.@seriesname(!i), then {%s})") from None
309
+ if "is not read here" in exc.message:
310
+ raise _left(exc.message.split(";")[0] + ": not in pymetrix's expressions, nor in the audit (docs/known-gaps.md)") from None
311
+ raise _error(exc.message or "this does not read as an EViews expression") from None
312
+ if not coefs:
313
+ for node in walk_eviews_expression(tree):
314
+ if isinstance(node, EViewsCoefficient):
315
+ raise _left(f"{node.vector}({node.index}) is an estimated coefficient: in a series expression it is not "
316
+ f"translated; give a scalar its value first (scalar b = {node.vector}({node.index})), then use the scalar")
317
+ return tree
318
+
319
+ def _names_in(self, rendered: str, page: _Page | None, scalars: dict[str, str], allowed: frozenset[str] = frozenset()) -> Text:
320
+ """The rendered pymetrix text with the program's numbers as variables (in brackets) and series renamed as
321
+ the bundle reader names them; a name that is neither, where the page's series are known, is an error."""
322
+ parts: list[Any] = []
323
+ pos = 0
324
+ for m in re.finditer(r"(?<![\w.])([A-Za-z_]\w*)(?!\w)(\s*\()?", rendered):
325
+ if m.group(2):
326
+ continue
327
+ name = m.group(1)
328
+ if name in ("and", "or", "not", "na") or re.match(r"\s*=(?!=)", rendered[m.end():]): # na; by=, seed=
329
+ continue
330
+ if name in scalars:
331
+ parts += [rendered[pos:m.start()] + "(", Var(scalars[name]), ")"]
332
+ pos = m.end()
333
+ continue
334
+ if name in allowed:
335
+ continue
336
+ series = _py_name(name)
337
+ if page is not None and not _has_series(page, series):
338
+ if series == "resid":
339
+ raise _left("resid, EViews's series of the last residuals, is not translated: eq.makeresids r makes them "
340
+ "a series of the page")
341
+ raise _error(f"{name} is not a series of page {page.eviews}, nor a scalar of the program")
342
+ if series != name:
343
+ parts.append(rendered[pos:m.start()] + series)
344
+ pos = m.end()
345
+ parts.append(rendered[pos:])
346
+ merged: list[Any] = []
347
+ for p in parts:
348
+ if isinstance(p, str) and merged and isinstance(merged[-1], str):
349
+ merged[-1] += p
350
+ elif p != "":
351
+ merged.append(p)
352
+ return Text(tuple(merged))
353
+
354
+ def expression(self, text: str, at: int, page: _Page, coefs: bool = False) -> Text:
355
+ """A series expression as pymetrix's text, with the program's numbers in it by name; with ``coefs``, an
356
+ estimated equation's right-hand side, its coefficients ``c(i)`` as ``c_i``."""
357
+ tree = self._tree(text, at, comparison=True, coefs=coefs) # EViews: series d = x > 3, 1 where it holds
358
+ scalars = self._scalars()
359
+ try:
360
+ seeds: list[int] = []
361
+ rendered = render_eviews_expression(tree, tuple(n for n in scalars), frequency="A" if page.freq == "Y" else page.freq,
362
+ data=True, seeds=lambda: self._seed(seeds))
363
+ except EViewsExpressionError as exc:
364
+ if any(w in exc.message for w in _NOT_TRANSLATED): # EViews reads it; pymetrix's expressions do not
365
+ raise _left(exc.message) from None
366
+ raise _error(exc.message) from None
367
+ except Exception as exc: # the frequency of @pchy and the like
368
+ raise _error(str(exc)) from None
369
+ self._data_notes(tree, page, seeds)
370
+ allowed = frozenset(f"{n.vector}_{n.index}" for n in walk_eviews_expression(tree) if isinstance(n, EViewsCoefficient)) if coefs else frozenset()
371
+ return self._names_in(rendered, page, scalars, allowed)
372
+
373
+ def _seed(self, seeds: list[int]) -> int:
374
+ """The next random draw's seed: ``rndseed``'s value times 1,000 plus the draw's number since it (1, 2, ...),
375
+ or, before any ``rndseed``, the draw's number from the program's start (``DEFAULT_SEED``*1000 + k)."""
376
+ self.draws += 1
377
+ seed = (self.rndseed if self.rndseed is not None else DEFAULT_SEED) * 1000 + self.draws
378
+ seeds.append(seed)
379
+ return seed
380
+
381
+ def _data_notes(self, tree: Any, page: _Page, seeds: list[int]) -> None:
382
+ """What the report says of an expression's random draws, and of statistics EViews takes over the sample."""
383
+ fns = {n.fn for n in walk_eviews_expression(tree) if isinstance(n, EViewsCall)}
384
+ if seeds:
385
+ given = (f"seeded from rndseed {self.rndseed} (rndseed*1000 + the draw's number after it)" if self.rndseed is not None
386
+ else "seeded by their order in the program, no rndseed before them")
387
+ note = (f"random draws, to check: pymetrix's own generator, {given}: seed{'s' if len(seeds) > 1 else ''} "
388
+ f"{', '.join(map(str, seeds))}; EViews's numbers differ")
389
+ if self.runtime:
390
+ note += "; inside a loop or subroutine every pass draws the same numbers (the seed is in the text)"
391
+ self.expression_notes.append(note)
392
+ stats = sorted(fns & {"@cumsum", "@sumsby", "@meansby", "@minsby", "@maxsby"})
393
+ if stats and (page.sample is not None or self.runtime or page.var in self.sample_unknown):
394
+ self.expression_notes.append(f"{', '.join(stats)} over all the page's rows in pymetrix, over the current sample in "
395
+ "EViews: the same when the sample has every row")
396
+
397
+ def _cmd_rndseed(self, st: Statement) -> tuple[list[Op], str]:
398
+ text = st.rest.strip()
399
+ m = re.fullmatch(r"(\d+)|([!]?[A-Za-z_]\w*)", text)
400
+ if m is None:
401
+ raise _error("rndseed takes a whole number: rndseed 12345")
402
+ if m.group(1):
403
+ value: Any = int(m.group(1))
404
+ else:
405
+ value = self._known(m.group(2))
406
+ if value is _UNKNOWN or not float(value).is_integer() or value < 0:
407
+ raise _left(f"rndseed {text}: the seed is known only when the program runs, so the draws after it are "
408
+ "seeded by their order in the program; give the number")
409
+ value = int(value)
410
+ self.rndseed, self.draws = value, 0
411
+ note = (f"the seed of the random draws after it: rndseed*1000 + the draw's number ({value * 1000 + 1}, ...); "
412
+ "pymetrix's generator, not EViews's, so the numbers differ")
413
+ if st.options:
414
+ note += f"; ({st.options}) chooses EViews's generator: pymetrix's is set by set_random_generator"
415
+ return [], note
416
+
417
+ def condition(self, text: str, at: int, page: _Page) -> Text:
418
+ """A sample's condition (``if x > 0 and y < 3``) as a row condition on the page's columns (``Sample(where=)``)."""
419
+ pieces: list[tuple[str, int, str]] = [] # (text, offset, the connector before it)
420
+ depth, start, connector, i = 0, 0, "", 0
421
+ quoted = False
422
+ while i < len(text):
423
+ ch = text[i]
424
+ if ch == '"':
425
+ quoted = not quoted
426
+ elif not quoted and ch == "(":
427
+ depth += 1
428
+ elif not quoted and ch == ")":
429
+ depth -= 1
430
+ elif not quoted and depth == 0:
431
+ m = re.match(r"(?i)(?<![\w])(and|or)(?![\w])", text[i:]) if (i == 0 or not (text[i - 1].isalnum() or text[i - 1] == "_")) else None
432
+ if m:
433
+ pieces.append((text[start:i], start, connector))
434
+ connector = m.group(1).lower()
435
+ i += len(m.group(1))
436
+ start = i
437
+ continue
438
+ i += 1
439
+ pieces.append((text[start:], start, connector))
440
+ scalars = self._scalars()
441
+ out: list[Any] = []
442
+ for piece, offset, conn in pieces:
443
+ if not piece.strip():
444
+ raise _error("a condition is missing on one side of and/or")
445
+ negated = re.match(r"\s*not\s+", piece, re.I)
446
+ body = piece[negated.end():] if negated else piece
447
+ tree = self._tree(body, at + offset + (negated.end() if negated else 0), comparison=True)
448
+ for node in walk_eviews_expression(tree):
449
+ if isinstance(node, EViewsName) and node.lag:
450
+ raise _left("a lag in a sample's condition: a sample selects rows by the data's columns; make the lagged "
451
+ "series first (series x_1 = x(-1)) and use it")
452
+ if isinstance(node, EViewsCall) and node.fn not in ("log", "@log", "exp", "@exp", "abs", "@abs", "sqr", "@sqrt"):
453
+ raise _left(f"{node.fn} in a sample's condition: a sample's condition uses columns, numbers, comparisons "
454
+ "and log, exp, abs and sqrt; make the series first and use it")
455
+ try:
456
+ rendered = render_eviews_expression(tree, tuple(scalars))
457
+ except EViewsExpressionError as exc:
458
+ raise _error(exc.message) from None
459
+ rendered = rendered.replace("^", "**")
460
+ if conn:
461
+ out.append(f" {conn} ")
462
+ if negated:
463
+ out.append("not ")
464
+ out += list(self._names_in(rendered, page, scalars).parts)
465
+ merged: list[Any] = []
466
+ for p in out:
467
+ if isinstance(p, str) and merged and isinstance(merged[-1], str):
468
+ merged[-1] += p
469
+ else:
470
+ merged.append(p)
471
+ return Text(tuple(merged))
472
+
473
+ def _number(self, node: Any) -> tuple[str, Any]:
474
+ """A scalar expression's tree as Python, and its value when known before the program runs."""
475
+ if isinstance(node, EViewsNumber):
476
+ text = "0" + node.text if node.text.startswith(".") else node.text
477
+ return text, float(text)
478
+ if isinstance(node, EViewsName):
479
+ key = "!" + node.name[1:] if node.name.startswith("_") and ("!" + node.name[1:]) in self.py else node.name
480
+ v = self.py.get(key)
481
+ if v is None and node.name.startswith("_") and self.runtime:
482
+ key = "!" + node.name[1:]
483
+ v = self.runtime_variable(key)
484
+ if v is None or v.kind not in ("scalar", "control"):
485
+ if key in self.py:
486
+ raise _error(f"{node.name} is a {self.py[key].kind}, not a number")
487
+ if key in self.unset or self.lost:
488
+ raise self._missing(key)
489
+ raise _error(f"{node.name.lstrip('_')} is not a scalar of the program: a scalar's value needs numbers "
490
+ "(a series' value at a date is @elem, not read yet; a statistic is @mean(x) and the like)")
491
+ if node.lag:
492
+ raise _error(f"{node.name} is a scalar: it has no lags or leads")
493
+ return v.name, v.value
494
+ if isinstance(node, EViewsBrackets):
495
+ code, value = self._number(node.x)
496
+ return f"({code})", value
497
+ if isinstance(node, EViewsNegative):
498
+ code, value = self._number(node.x)
499
+ return f"-{code}", (-value if value is not _UNKNOWN else _UNKNOWN)
500
+ if isinstance(node, EViewsBinary):
501
+ (lc, lv), (rc, rv) = self._number(node.left), self._number(node.right)
502
+ op = {"^": "**", "=": "==", "<>": "!="}.get(node.op, node.op)
503
+ code = f"{lc} {op} {rc}"
504
+ value = _UNKNOWN
505
+ if lv is not _UNKNOWN and rv is not _UNKNOWN:
506
+ try:
507
+ value = float(eval(f"{lv!r} {op} {rv!r}", {"__builtins__": {}})) # noqa: S307 - two numbers and an operator
508
+ except (ZeroDivisionError, OverflowError):
509
+ value = math.nan
510
+ if op in ("<", ">", "<=", ">=", "==", "!="):
511
+ code = f"float({code})"
512
+ return code, value
513
+ if isinstance(node, EViewsCall):
514
+ fns = {"log": math.log, "@log": math.log, "exp": math.exp, "@exp": math.exp, "abs": abs, "@abs": abs,
515
+ "sqr": math.sqrt, "@sqrt": math.sqrt}
516
+ if node.fn in fns and len(node.args) == 1:
517
+ _, value = self._number(node.args[0])
518
+ if value is not _UNKNOWN:
519
+ try:
520
+ result = float(fns[node.fn](value))
521
+ except (ValueError, OverflowError):
522
+ result = math.nan
523
+ return _number_text(result) if math.isfinite(result) else _NAN, result
524
+ raise _left(f"{node.fn} of a value known only when the program runs: compute it in Python (math.{fns[node.fn].__name__})")
525
+ raise _left(f"{node.fn} in a scalar's expression is not translated")
526
+ raise _error("this does not read as a number")
527
+
528
+ def number(self, text: str, at: int) -> tuple[str, Any, bool]:
529
+ """A scalar expression: Python, its value where known, and whether a function was worked out."""
530
+ tree = self._tree(text, at)
531
+ code, value = self._number(tree)
532
+ worked = any(isinstance(n, EViewsCall) for n in walk_eviews_expression(tree))
533
+ if worked and value is not _UNKNOWN:
534
+ code = _number_text(value) if isinstance(value, float) and math.isfinite(value) else _NAN
535
+ return code, value, worked
536
+
537
+ def string(self, text: str) -> tuple[str, Any]:
538
+ """A string expression (literals and ``%`` variables joined by ``+``): Python, and its value when known."""
539
+ tokens = re.findall(r'\s*("[^"]*"|%\w+|[A-Za-z_]\w*|\+|\S+)', text)
540
+ if not tokens:
541
+ raise _error("a string assignment needs a value")
542
+ codes, values = [], []
543
+ expect_value = True
544
+ for tok in tokens:
545
+ tok = tok.strip()
546
+ if expect_value:
547
+ if tok.startswith('"'):
548
+ codes.append(quote(tok[1:-1]))
549
+ values.append(tok[1:-1])
550
+ elif tok.startswith("%") or tok.lower() in self.py and self.py[tok.lower()].kind == "string" or tok.lower() in self.unset:
551
+ v = self.py.get(tok.lower()) or self.runtime_variable(tok.lower())
552
+ if v is None:
553
+ raise self._missing(tok)
554
+ codes.append(v.name)
555
+ values.append(v.value)
556
+ elif tok.startswith("@"):
557
+ raise _left(f"{tok} does not read here")
558
+ elif self.lost:
559
+ raise self._missing(tok)
560
+ else:
561
+ raise _error(f"{tok} is not a string or a string variable")
562
+ elif tok != "+":
563
+ if '""' in text:
564
+ raise _left('a quote inside a string ("" in EViews) is not translated')
565
+ raise _error(f"expected + between strings, not {tok!r}")
566
+ expect_value = not expect_value
567
+ if expect_value:
568
+ raise _error("the string ends with +")
569
+ value = "".join(values) if all(v is not _UNKNOWN for v in values) else _UNKNOWN
570
+ return " + ".join(codes), value
571
+
572
+ # -- statements -------------------------------------------------------------------------------------------------
573
+
574
+ def statement(self, st: Statement) -> Outcome:
575
+ self.line = st.line
576
+ self._made_names = False
577
+ self.expression_notes = []
578
+ original = st
579
+ try:
580
+ if "$" in re.sub(r'"[^"]*"', "", st.text):
581
+ from .control import _DOLLAR
582
+
583
+ raise _left(_DOLLAR)
584
+ st, notes = self._substitute(st)
585
+ ops, note = self._dispatch(st)
586
+ notes = [*notes, *([note] if note else []), *(n for n in self.expression_notes if n not in notes and n != note)]
587
+ if self._made_names or any(PLACEHOLDER.search(repr(op)) for op in ops):
588
+ ops = dynamic_ops(ops, self.dynamic)
589
+ if _makes_names(ops):
590
+ notes.append("a name made from a value known when the program runs: an f-string in the script")
591
+ return Outcome(original, NOTE if notes else TRANSLATED, "; ".join(notes), ops)
592
+ except _Out as out:
593
+ self._unset(st)
594
+ if not (st.kind == "command" and st.word in _HARMLESS or st.kind == "method" and st.word in PHASE4_METHODS
595
+ or self.types.get(st.obj.lower()) in ("graph", "table", "spool", "text")):
596
+ self.forget()
597
+ return Outcome(original, out.status, out.reason)
598
+
599
+ def inside_block(self, st: Statement) -> None:
600
+ """A line inside a loop, an if block or a subroutine: not translated, but what it sets is no longer known."""
601
+ self._unset(st)
602
+
603
+ def _unset(self, st: Statement) -> None:
604
+ """A variable that a line left out would set: later lines that use it are left out too, saying why."""
605
+ key = ""
606
+ if st.kind == "assign" and st.lhs[:1] in "!%":
607
+ key = st.lhs.lower()
608
+ elif st.kind == "command" and st.word in ("scalar", "string"):
609
+ key = _first_word(st.rest).split("=")[0].lower()
610
+ if key:
611
+ self.unset[key] = st.line
612
+ self.py.pop(key, None)
613
+
614
+ def _missing(self, name: str) -> _Out:
615
+ """A name the program has not set: left out when a line left out sets it (or may), else an error."""
616
+ key = name.lower()
617
+ if key in self.unset:
618
+ return _left(f"{name} is set by line {self.unset[key]}, which is left out")
619
+ if self.lost:
620
+ return _left(f"{name} is not set by a line translated so far (a line left out may set it)")
621
+ return _error(f"{name} is not set before this line")
622
+
623
+ def _made_series(self, page: _Page, series: str) -> None:
624
+ """A series the line makes: added to the page's known series, or, for a name made as the program runs, which
625
+ series the pages have is no longer known."""
626
+ if PLACEHOLDER.search(series):
627
+ self._unchecked()
628
+ elif page.series is not None:
629
+ page.series.add(series)
630
+
631
+ def _unchecked(self) -> None:
632
+ """After a name made as the program runs: which series each page has is no longer known."""
633
+ for page in self.pages.values():
634
+ page.series = None
635
+
636
+ def forget(self) -> None:
637
+ """After a line left out that may have made series (a loop, a subroutine, a fetch, an add-in), which series
638
+ each page has is no longer known: names are no longer checked."""
639
+ self.lost = True
640
+ for page in self.pages.values():
641
+ page.series = None
642
+
643
+ def _dispatch(self, st: Statement) -> tuple[list[Op], str]:
644
+ if st.kind == "assign":
645
+ return self._assign(st)
646
+ if st.kind == "method":
647
+ return self._method(st)
648
+ word = st.word
649
+ if word in PHASE3_WORDS:
650
+ raise _error(f"{PHASE3_WORDS[word]} out of place")
651
+ handler = getattr(self, f"_cmd_{word}", None)
652
+ if handler is not None:
653
+ return handler(st)
654
+ if word in PHASE2_COMMANDS:
655
+ if word in ("sspace",):
656
+ self.types[_first_word(st.rest).split(".")[0].lower()] = word
657
+ raise _left(left_reason("state-space objects are read by read_eviews_sspace, not translated line by line",
658
+ PHASE2_COMMANDS[word]))
659
+ if word in PHASE4_COMMANDS:
660
+ why, eq = PHASE4_COMMANDS[word]
661
+ if word in ("graph", "table", "spool", "text"):
662
+ self.types[_first_word(st.rest).split(".")[0].lower()] = word
663
+ raise _left(left_reason(why, eq))
664
+ if word.startswith("{") or not word:
665
+ raise _error("this does not read as an EViews statement")
666
+ raise _left(f"{word} is not an EViews command this translator knows: an add-in or a user-defined command, "
667
+ "another program's code, is not translated")
668
+
669
+ # workfiles and pages
670
+
671
+ def _cmd_wfopen(self, st: Statement) -> tuple[list[Op], str]:
672
+ args = _arguments(st.rest)
673
+ if not args:
674
+ raise _error("wfopen names a workfile")
675
+ named = Path(args[0].strip('"').replace("\\", "/")).stem.lower()
676
+ if self.bundle is None:
677
+ raise _error("wfopen needs the workfile's data: give translate_program the bundle the export program wrote "
678
+ "(bundle=\".../<workfile>.evbundle\"), or a CSV or Excel file saved from the workfile in EViews")
679
+ if self.opened is not None and self.opened != named:
680
+ raise _error(f"a second workfile ({named}) after {self.opened}: one bundle or data file stands for one workfile")
681
+ first = self.opened is None
682
+ self.opened = named
683
+ if not first:
684
+ raise _left(f"{named} is open already (line before): nothing more to read")
685
+ if str(self.bundle).lower().endswith(".evbundle"):
686
+ return self._open_bundle(named)
687
+ return self._open_file(named)
688
+
689
+ def _open_bundle(self, named: str) -> tuple[list[Op], str]:
690
+ from pymetrix.errors import PyMetrixError
691
+
692
+ from ..bundle import _open, bundle_pages, eviews_sample
693
+
694
+ try:
695
+ manifest = _open(self.bundle).manifest
696
+ infos = bundle_pages(self.bundle)
697
+ except PyMetrixError as exc:
698
+ raise _error(str(exc)) from None
699
+ self.uses_bundle = True
700
+ ops: list[Op] = []
701
+ notes: list[str] = []
702
+ wf = manifest.get("workfile", {}).get("name", "")
703
+ if wf and wf.lower() != named:
704
+ notes.append(f"the bundle is of workfile {wf}, the program opens {named}")
705
+ active = str(manifest.get("workfile", {}).get("active_page", "")).lower()
706
+ for p, info in zip(manifest["pages"], infos):
707
+ if info["refused"]:
708
+ notes.append(f"page {p['name']} is not read: {info['refused']}")
709
+ continue
710
+ var, note = self._name(p["name"], "page")
711
+ if note:
712
+ notes.append(note)
713
+ code = str(p.get("frequency") or "").upper()
714
+ freq = {"A": "Y", "Y": "Y", "Q": "Q", "M": "M", "W": "W", "D7": "D", "D": "D"}.get(code) if p["structure"] == "dated" else None
715
+ rng = p.get("range") or [None, None]
716
+ page = _Page(var, p["name"], freq, {_py_name(s["name"]) for s in p["series"]},
717
+ first=_period(str(rng[0]), freq) if rng[0] and freq else None,
718
+ last=_period(str(rng[-1]), freq) if rng[-1] and freq else None)
719
+ self.pages[p["name"].lower()] = page
720
+ ops.append(Step("pymetrix:dataset.read", None, var, "Dataset.read", (Arg("source", str(self.bundle), "pos"),
721
+ Arg("kw", {"page": p["name"]}, "varkw"))))
722
+ saved = str(p.get("sample") or "").strip()
723
+ if saved and saved.lower() != "@all":
724
+ sample = eviews_sample(saved, code if code in ("Q", "M", "A") else None)
725
+ if sample is None:
726
+ notes.append(f"page {p['name']}'s saved sample ({saved}) does not translate: all its rows are used")
727
+ elif not sample.everything:
728
+ spec = SampleSpec(sample.start, sample.end)
729
+ page.sample = spec
730
+ ops.append(self._with_sample(page, spec))
731
+ notes.append(f"page {p['name']} opens with its saved sample, {saved}")
732
+ for s in p.get("scalars", []):
733
+ key = s["name"].lower()
734
+ name, _ = self._name(key, f"scalar {key}")
735
+ value = math.nan if s.get("value") is None else float(s["value"])
736
+ self.py[key] = _Py(name, "scalar", value)
737
+ ops.append(Code(f"{name} = {_number_text(value) if math.isfinite(value) else _NAN} "
738
+ f"# the workfile's scalar {s['name']}", (name,)))
739
+ for s in p.get("strings", []):
740
+ key = s["name"].lower()
741
+ name, _ = self._name(key, f"string {key}")
742
+ self.py[key] = _Py(name, "string", str(s.get("value", "")))
743
+ ops.append(Code(f"{name} = {quote(str(s.get('value', '')))} # the workfile's string {s['name']}", (name,)))
744
+ if any(p.get(k) for k in ("groups", "samples", "arrays", "equations", "models")):
745
+ notes.append(f"page {p['name']}'s groups, samples, matrices, equations and models: eviews_objects({var})")
746
+ if not ops:
747
+ raise _error("the bundle has no page that reads")
748
+ self.current = self.pages.get(active) or next(iter(self.pages.values()))
749
+ return ops, "; ".join(notes)
750
+
751
+ def _open_file(self, named: str) -> tuple[list[Op], str]:
752
+ from pymetrix import Dataset
753
+ from pymetrix.errors import PyMetrixError
754
+
755
+ try:
756
+ data = Dataset.read(str(self.bundle), **self.read_options)
757
+ except (PyMetrixError, OSError, ValueError) as exc:
758
+ raise _error(f"{self.bundle} does not read: {exc}") from None
759
+ var, note = self._name(named, "page")
760
+ t = data.time_axis
761
+ freq = None
762
+ if t is not None:
763
+ code = str(t.freq).upper()
764
+ freq = "Y" if code.startswith(("Y", "A")) else code[:1] if code[:1] in ("Q", "M", "W", "D") else None
765
+ periods = data.frame.index.get_level_values(t.name) if t is not None else None
766
+ page = _Page(var, named, freq, set(data.names), first=str(periods.min()) if periods is not None and len(periods) else None,
767
+ last=str(periods.max()) if periods is not None and len(periods) else None)
768
+ self.pages[named] = page
769
+ self.current = page
770
+ step = Step("pymetrix:dataset.read", None, var, "Dataset.read",
771
+ (Arg("source", str(self.bundle), "pos"), *([Arg("kw", dict(self.read_options), "varkw")] if self.read_options else [])))
772
+ notes = [f"the workfile {named} is read from {Path(str(self.bundle)).name}"] + ([note] if note else [])
773
+ return [step], "; ".join(notes)
774
+
775
+ def _new_page(self, st: Statement, name: str, freq_text: str, start: str, end: str) -> tuple[list[Op], str]:
776
+ f = freq_text.lower()
777
+ if f in _FREQ_GAP:
778
+ raise _left(_FREQ_GAP[f])
779
+ freq = _FREQ.get(f)
780
+ if freq is None:
781
+ raise _error(f"{freq_text!r} is not a frequency read here: a, q, m, w or d")
782
+ if freq not in ("Y", "Q", "M"):
783
+ raise _left("weekly and daily pages are not translated yet: their dates are written differently "
784
+ "(Dataset.empty(\"W\" or \"D\", start, end))")
785
+ first, last = _period(start, freq), _period(end, freq)
786
+ if first is None or last is None:
787
+ raise _error(f"{start} to {end} are not dates of frequency {freq_text}: 1990q1, 1990:1, 1990m3 or 1990")
788
+ var, note = self._name(name, "page")
789
+ page = _Page(var, name, freq, set(), first=first, last=last)
790
+ self.pages[name.lower()] = page
791
+ self.current = page
792
+ return [Step("pymetrix:dataset.empty", None, var, "Dataset.empty",
793
+ (Arg("freq", freq, "pos"), Arg("start", first, "pos"), Arg("end", last, "pos")))], note
794
+
795
+ def _cmd_wfcreate(self, st: Statement) -> tuple[list[Op], str]:
796
+ options = _option_map(st.options)
797
+ args = _arguments(st.rest)
798
+ name = options.get("page") or options.get("wf")
799
+ if len(args) == 4:
800
+ name = name or args[0]
801
+ args = args[1:]
802
+ if len(args) == 2 and args[0].lower() == "u":
803
+ raise _left(_FREQ_GAP["u"])
804
+ if len(args) != 3:
805
+ raise _error("wfcreate takes a frequency and the first and last dates: wfcreate q 1990q1 2030q4")
806
+ self.workfile_frequency = args[0]
807
+ return self._new_page(st, name or "untitled", *args)
808
+
809
+ def _cmd_pagecreate(self, st: Statement) -> tuple[list[Op], str]:
810
+ options = _option_map(st.options)
811
+ args = _arguments(st.rest)
812
+ if len(args) == 2 and args[0].lower() == "u":
813
+ raise _left(_FREQ_GAP["u"])
814
+ if len(args) != 3:
815
+ raise _error("pagecreate takes a frequency and the first and last dates: pagecreate(page=a) a 1990 2030")
816
+ name = options.get("page")
817
+ note = ""
818
+ if not name:
819
+ name = f"untitled{len(self.pages) + 1:02d}"
820
+ note = f"the new page has no name (page=): it is called {name}"
821
+ ops, n = self._new_page(st, name, *args)
822
+ return ops, "; ".join(x for x in (note, n) if x)
823
+
824
+ def _list_names(self, member: str) -> bool:
825
+ """Whether a group's member is a string variable's value (its words are the series' names)."""
826
+ ph = PLACEHOLDER.fullmatch(member.lower())
827
+ if ph is None:
828
+ return False
829
+ name = self.dynamic[int(ph.group(1))]
830
+ return any(v.name == name and v.kind == "string" for v in self.py.values())
831
+
832
+ def _cmd_pageselect(self, st: Statement) -> tuple[list[Op], str]:
833
+ args = _arguments(st.rest)
834
+ if len(args) != 1:
835
+ raise _error("pageselect names one page")
836
+ self.current = self._page_named(args[0])
837
+ return [], f"later lines use {self.current.var} (no step)"
838
+
839
+ def _save(self, st: Statement) -> tuple[list[Op], str]:
840
+ raise _left("the project is saved by the user: save the project (File → Save)")
841
+
842
+ _cmd_wfsave = _cmd_pagesave = _save
843
+
844
+ def _cmd_wfclose(self, st: Statement) -> tuple[list[Op], str]:
845
+ raise _left("closing the workfile: nothing to do (the session keeps its objects; save the project with File → Save)")
846
+
847
+ def _cmd_read(self, st: Statement) -> tuple[list[Op], str]:
848
+ raise _left(left_reason(f"{st.word} adds a file's series to the page; its options are not translated",
849
+ "Dataset.read(path, time=..., freq=...), then add its series to the page"))
850
+
851
+ _cmd_import = _cmd_read
852
+
853
+ def _database(self, st: Statement) -> tuple[list[Op], str]:
854
+ raise _left("EViews databases are not read: export the database's series to the bundle (fetch them into the "
855
+ "workfile, then run the export program)")
856
+
857
+ _cmd_fetch = _cmd_store = _cmd_dbopen = _cmd_dbclose = _cmd_dbcreate = _cmd_db = _database
858
+
859
+ def _page_op(self, st: Statement) -> tuple[list[Op], str]:
860
+ raise _left(left_reason(f"{st.word}: page operations are not translated", "a Dataset per page; xs, keep, to_freq"))
861
+
862
+ _cmd_pagestruct = _cmd_pagedelete = _cmd_pagerename = _cmd_pagecopy = _cmd_pageappend = _cmd_pagecontract = _page_op
863
+ _cmd_pagestack = _cmd_pageunstack = _cmd_wfstruct = _page_op
864
+
865
+ def _cmd_copy(self, st: Statement) -> tuple[list[Op], str]:
866
+ raise _left(left_reason("copying between pages is not translated", "Dataset.to_freq(freq, how=...) (Convert frequency)"))
867
+
868
+ # samples
869
+
870
+ def _sample_spec(self, text: str, at: int, page: _Page) -> Any:
871
+ """An EViews sample (``1990q1 2007q4``, ``@all``, ``@first 2000q4 if x > 0``, a named sample) as a
872
+ ``SampleSpec``, a ``Var`` or None (all rows)."""
873
+ body, cond = text, None
874
+ m = re.search(r"(?i)(?:^|\s)if\s", text)
875
+ if m:
876
+ body, cond = text[:m.start()], text[m.end():]
877
+ cond_at = at + m.end()
878
+ tokens = re.sub(r"\s*([+-])\s*", r"\1", body).split()
879
+ where = self.condition(cond, cond_at, page) if cond is not None else None
880
+ if len(tokens) == 1 and tokens[0].lower() not in ("@all",) and tokens[0].lower() in self.py:
881
+ v = self.py[tokens[0].lower()]
882
+ if v.kind != "sample":
883
+ raise _error(f"{tokens[0]} is a {v.kind}, not a sample")
884
+ if where is not None:
885
+ raise _left("a named sample with a condition: write the sample out")
886
+ return Var(v.name)
887
+ if not tokens or [t.lower() for t in tokens] == ["@all"]:
888
+ return SampleSpec(where=where) if where is not None else None
889
+ if len(tokens) != 2:
890
+ raise _left("a sample of several pairs of dates is not translated: one pair, with a condition, is "
891
+ "(Sample(...) | Sample(...) combines them)")
892
+ ends = []
893
+ for i, tok in enumerate(tokens):
894
+ ends.append(self._end(tok, page, i == 0))
895
+ if ends == [None, None] and where is None:
896
+ return None
897
+ if any(isinstance(e, str) and PLACEHOLDER.search(e) for e in ends):
898
+ self._dated_note = True
899
+ return SampleSpec(ends[0], ends[1], where)
900
+
901
+ def _end(self, token: str, page: _Page, first: bool) -> Any:
902
+ t = token.lower()
903
+ if PLACEHOLDER.search(t):
904
+ if not PLACEHOLDER.fullmatch(t):
905
+ raise _left(f"{token}: a date with a variable's value in it, and more, is not translated; a variable "
906
+ "holding the whole date is")
907
+ if page.freq not in ("Y", "Q"):
908
+ raise _left("a date known only when the program runs is translated for annual and quarterly pages, "
909
+ "whose EViews dates (1990, 1990q1) Sample reads as they are")
910
+ return t
911
+ m = re.fullmatch(r"(@first|@last|[^+\-]+)((?:[+-](?:\d+|!\w+))*)", t)
912
+ if m is None:
913
+ raise _error(f"{token} is not a date")
914
+ base, n = m.group(1), 0
915
+ for sign, amount in re.findall(r"([+-])(\d+|!\w+)", m.group(2)):
916
+ if amount.startswith("!"):
917
+ value = self._known(amount)
918
+ if value is _UNKNOWN or not float(value).is_integer():
919
+ raise self._missing(amount) if value is _UNKNOWN else _error(f"{amount} is not a whole number")
920
+ amount = str(int(value))
921
+ n += int(amount) if sign == "+" else -int(amount)
922
+ if page.freq not in ("Y", "Q", "M"):
923
+ raise _left("samples by date are translated for annual, quarterly and monthly pages")
924
+ if base in ("@first", "@last"):
925
+ if not n:
926
+ return None
927
+ known = page.first if base == "@first" else page.last
928
+ if known is None:
929
+ raise _left(f"{token}: the page's {base[1:]} period is not known here: write the date")
930
+ return _shifted(known, page.freq, n)
931
+ period = _period(base, page.freq)
932
+ if period is None:
933
+ if re.fullmatch(r"\d{4}", base) and page.freq in ("Q", "M"): # a year: its first or last period
934
+ period = _shifted(f"{base}Q1" if page.freq == "Q" else f"{base}-01", page.freq, 0 if first else (3 if page.freq == "Q" else 11))
935
+ else:
936
+ raise _error(f"{token} is not a date of page {page.eviews} ({page.freq})")
937
+ return _shifted(period, page.freq, n) if n else period
938
+
939
+ def _with_sample(self, page: _Page, spec: Any) -> Step:
940
+ return Step("pymetrix:dataset.with_sample", page.var, page.var, f"{page.var}.with_sample", (Arg("sample", spec, "pos"),))
941
+
942
+ def _cmd_smpl(self, st: Statement) -> tuple[list[Op], str]:
943
+ page = self._page()
944
+ self._dated_note = False
945
+ spec = self._sample_spec(st.rest, st.rest_at, page)
946
+ page.sample = spec
947
+ self.sample_unknown.discard(page.var)
948
+ note = ("the dates are known when the program runs: Sample reads them as EViews writes them (1990q1, 1990)"
949
+ if self._dated_note else "")
950
+ return [self._with_sample(page, spec)], note
951
+
952
+ def _cmd_sample(self, st: Statement) -> tuple[list[Op], str]:
953
+ name = _first_word(st.rest)
954
+ if not name:
955
+ raise _error("sample names the sample: sample s 1990q1 2007q4")
956
+ page = self._page()
957
+ rest = st.rest[len(name):]
958
+ spec = self._sample_spec(rest, st.rest_at + len(name), page) if rest.strip() else None
959
+ var, note = self._name(name, f"sample {name.lower()}")
960
+ self.py[name.lower()] = _Py(var, "sample", page=page.var)
961
+ if isinstance(spec, Var):
962
+ return [Code(f"{var} = {spec.name}", (var,))], note
963
+ spec = spec if spec is not None else SampleSpec()
964
+ return [Code(f"{var} = {spec.code()}", (var,))], note
965
+
966
+ # series
967
+
968
+ def _assign_series(self, name: str, rhs: str, at: int, declare: bool = False) -> tuple[list[Op], str]:
969
+ page = self._page()
970
+ if "\\" in name or not re.fullmatch(r"[A-Za-z_]\w*", name):
971
+ raise _left(f"{name}: assigning to anything but a series name (a page\\series, an element) is not translated")
972
+ series = _py_name(name)
973
+ if series == "within":
974
+ raise _left("a series named within: with_series takes within= for the sample; rename the series "
975
+ "(or add it with data.add_series)")
976
+ notes = [f"{name} is called {series}"] if series != name.lower() else []
977
+ if rhs.strip().lower() == "na":
978
+ value: Any = None
979
+ else:
980
+ value = self.expression(rhs, at, page)
981
+ args: list[Arg] = [Arg("exprs", {series: value}, "varkw")]
982
+ own = value is not None and _uses(str(value), series)
983
+ within = page.sample
984
+ if self.runtime or page.var in self.sample_unknown:
985
+ # inside a block or a subroutine, the sample is the one the page has when the line runs
986
+ within = Py(f"{page.var}.sample or Sample()") if own else Py(f"{page.var}.sample")
987
+ if own:
988
+ notes.append("it uses its own values: worked out period by period within the sample, as EViews does")
989
+ elif own and within is None:
990
+ within = SampleSpec()
991
+ notes.append("it uses its own values, so it is worked out period by period, as EViews does")
992
+ elif own:
993
+ notes.append("it uses its own values: worked out period by period within the sample, as EViews does")
994
+ if within is not None:
995
+ args.append(Arg("within", within))
996
+ self._made_series(page, series)
997
+ return [Step("pymetrix:dataset.with_series", page.var, page.var, f"{page.var}.with_series", tuple(args))], "; ".join(notes)
998
+
999
+ def _cmd_series(self, st: Statement) -> tuple[list[Op], str]:
1000
+ m = re.fullmatch(r"\s*([^\s=]+)\s*(?:=(.*))?", st.rest, re.S)
1001
+ if m is None:
1002
+ raise _error(f"{st.word} names a series: series y = x")
1003
+ name, rhs = m.group(1), m.group(2)
1004
+ if rhs is None:
1005
+ if st.word == "genr":
1006
+ raise _error("genr assigns a formula: genr y = x")
1007
+ return self._assign_series(name, "na", st.rest_at, declare=True)
1008
+ return self._assign_series(name, rhs, st.rest_at + m.start(2))
1009
+
1010
+ _cmd_genr = _cmd_series
1011
+
1012
+ def _cmd_frml(self, st: Statement) -> tuple[list[Op], str]:
1013
+ m = re.fullmatch(r"\s*([A-Za-z_]\w*)\s*=(.*)", st.rest, re.S)
1014
+ if m is None:
1015
+ raise _error("frml names a series and its formula: frml y = x")
1016
+ page = self._page()
1017
+ series = _py_name(m.group(1))
1018
+ value = self.expression(m.group(2), st.rest_at + m.start(2), page)
1019
+ self._made_series(page, series)
1020
+ return [Step("pymetrix:dataset.derive", page.var, page.var, f"{page.var}.derive", (Arg("recipes", {series: value}, "varkw"),))], \
1021
+ "a derived series: it follows its inputs (Keep updated), over all rows, as a formula series ignores the sample"
1022
+
1023
+ def _cmd_alpha(self, st: Statement) -> tuple[list[Op], str]:
1024
+ raise _left("alpha (text) series are not translated: a text column comes with the data (a gap for assigning text)")
1025
+
1026
+ def _cmd_group(self, st: Statement) -> tuple[list[Op], str]:
1027
+ words = _arguments(st.rest)
1028
+ if not words:
1029
+ raise _error("group names the group: group g a b c")
1030
+ page = self._page()
1031
+ return self._group(words[0], words[1:], page, "")
1032
+
1033
+ def _group(self, name: str, members: list[str], page: _Page, note: str) -> tuple[list[Op], str]:
1034
+ for m in members:
1035
+ if not re.fullmatch(r"[A-Za-z_][\w*?]*|[*?][\w*?]*", m):
1036
+ raise _left(f"{m}: a group of expressions is not translated: a Selection holds series; make the series first")
1037
+ series: list[Any] = []
1038
+ for m in members:
1039
+ ph = PLACEHOLDER.fullmatch(m.lower())
1040
+ if ph and self._list_names(m): # a string of names, as EViews puts it in: its words
1041
+ series.append(Spread(self.dynamic[int(ph.group(1))]))
1042
+ else:
1043
+ series.append(_py_name(m) if "*" not in m and "?" not in m else m.lower())
1044
+ if any(isinstance(m, Spread) for m in series):
1045
+ note = "; ".join(x for x in (note, "the group's series are the words of a string known when the program runs") if x)
1046
+ if page.series is not None:
1047
+ missing = [m for m in series if isinstance(m, str) and "*" not in m and "?" not in m and not _has_series(page, m)]
1048
+ if missing:
1049
+ raise _error(f"{', '.join(missing)} {'is' if len(missing) == 1 else 'are'} not series of page {page.eviews}")
1050
+ key = name.lower()
1051
+ var, n = self._name(name, f"group {key}")
1052
+ self.py[key] = _Py(var, "group", members=series, page=page.var)
1053
+ notes = "; ".join(x for x in (note, n) if x)
1054
+ return [Step("pymetrix:dataset.series", page.var, var, f"{page.var}.series", (Arg("patterns", tuple(series), "star"),))], notes
1055
+
1056
+ def _cmd_rename(self, st: Statement) -> tuple[list[Op], str]:
1057
+ args = _arguments(st.rest)
1058
+ if len(args) != 2 or any(ch in "".join(args) for ch in "*?"):
1059
+ raise _left("rename of several names or a pattern is not translated: data.rename(old=\"new\") for each")
1060
+ old, new = args
1061
+ page = self._page()
1062
+ if old.lower() in self.py:
1063
+ raise _left(f"{old} is a {self.py[old.lower()].kind}: renaming the program's variables is not translated")
1064
+ o, n = _py_name(old), _py_name(new)
1065
+ if not _has_series(page, o):
1066
+ raise _error(f"{old} is not a series of page {page.eviews}")
1067
+ if page.series is not None:
1068
+ page.series.discard(o)
1069
+ self._made_series(page, n)
1070
+ return [Step("pymetrix:dataset.rename", page.var, page.var, f"{page.var}.rename", (Arg("names", {o: n}, "varkw"),))], ""
1071
+
1072
+ def _cmd_delete(self, st: Statement) -> tuple[list[Op], str]:
1073
+ args = _arguments(st.rest)
1074
+ if not args or any(ch in "".join(args) for ch in "*?\\"):
1075
+ raise _left("delete with a pattern or a page is not translated: data.drop(\"a\", \"b\") with the names")
1076
+ page = self._page()
1077
+ series, gone = [], []
1078
+ for a in args:
1079
+ key = a.lower()
1080
+ if key in self.py:
1081
+ gone.append(self.py.pop(key).name)
1082
+ elif key in self.types:
1083
+ del self.types[key]
1084
+ gone.append(key)
1085
+ else:
1086
+ s = _py_name(a)
1087
+ if not _has_series(page, s):
1088
+ raise _error(f"{a} is not a series of page {page.eviews}, nor an object of the program")
1089
+ series.append(s)
1090
+ ops: list[Op] = []
1091
+ if series:
1092
+ if page.series is not None:
1093
+ page.series -= set(series)
1094
+ ops.append(Step("pymetrix:dataset.drop", page.var, page.var, f"{page.var}.drop", (Arg("names", tuple(series), "star"),)))
1095
+ note = f"{', '.join(gone)}: not series, so nothing to remove in the script" if gone else ""
1096
+ return ops, note
1097
+
1098
+ # scalars, strings, matrices
1099
+
1100
+ def _scalar(self, name: str, rhs: str | None, at: int, kind: str) -> tuple[list[Op], str]:
1101
+ key = name.lower()
1102
+ old = self.py.get(key)
1103
+ if old is not None and old.kind not in ("scalar", "control"):
1104
+ raise _error(f"{name} is a {old.kind}, not a number")
1105
+ var, note = (old.name, "") if old is not None else self._name(name, f"{kind} {key}")
1106
+ if rhs is None:
1107
+ if old is None:
1108
+ self._declared[key] = self.line
1109
+ self.py[key] = _Py(var, kind, math.nan)
1110
+ return [Code(f"{var} = {_NAN}", (var,))], "; ".join(x for x in (note, "a new scalar has no value: NA (verify)") if x)
1111
+ if _program_text(rhs):
1112
+ code, value, kind_, notes = self.program_value(rhs, at)
1113
+ if kind_ == "str":
1114
+ raise _error(f"{name} is a number: {rhs.strip()} is a string")
1115
+ if kind_ == "bool":
1116
+ code = f"float({code})"
1117
+ if old is None:
1118
+ self._declared[key] = self.line
1119
+ self.py[key] = _Py(var, kind, value if not self.runtime else _UNKNOWN)
1120
+ return [Code(f"{var} = {code}", (var,))], "; ".join(x for x in (note, *notes) if x)
1121
+ stat = re.fullmatch(r"\s*(@\w+)\s*\((.*)\)\s*", rhs, re.S)
1122
+ if stat and stat.group(1).lower() in STATISTICS and _balanced(stat.group(2)):
1123
+ page = self._page()
1124
+ fn = STATISTICS[stat.group(1).lower()]
1125
+ inner = self.expression(stat.group(2), at + stat.start(2), page)
1126
+ self.py[key] = _Py(var, kind, _UNKNOWN)
1127
+ code = f"{var} = float({page.var}.eval({inner.code()})[{page.var}.sample_mask()].{fn}())"
1128
+ why = (f"{stat.group(1).lower()} over the page's sample, missing values skipped"
1129
+ + (" (the standard deviation with n - 1, as EViews's @stdev)" if fn == "std" else ""))
1130
+ return [Code(code, (var,))], "; ".join(x for x in (note, why) if x)
1131
+ rhs, members, member_notes = self.members_in(rhs)
1132
+ for placeholder, member in members.items():
1133
+ self.py[placeholder] = _Py(member, "scalar", _UNKNOWN)
1134
+ try:
1135
+ code, value, worked = self.number(rhs, at)
1136
+ finally:
1137
+ for placeholder in members:
1138
+ self.py.pop(placeholder, None)
1139
+ if members:
1140
+ code = f"float({code})"
1141
+ if old is None:
1142
+ self._declared[key] = self.line
1143
+ self.py[key] = _Py(var, kind, value if not self.runtime else _UNKNOWN)
1144
+ why = f"worked out: {rhs.strip()}" if worked else ""
1145
+ return [Code(f"{var} = {code}", (var,))], "; ".join(x for x in (note, why, *member_notes) if x)
1146
+
1147
+ def _cmd_scalar(self, st: Statement) -> tuple[list[Op], str]:
1148
+ m = re.fullmatch(r"\s*([A-Za-z_]\w*)\s*(?:=(.*))?", st.rest, re.S)
1149
+ if m is None:
1150
+ raise _error("scalar names the scalar: scalar s = 0.3")
1151
+ return self._scalar(m.group(1), m.group(2), st.rest_at + (m.start(2) if m.group(2) is not None else 0), "scalar")
1152
+
1153
+ def _string(self, key: str, name: str, rhs: str | None) -> tuple[list[Op], str]:
1154
+ old = self.py.get(key)
1155
+ if old is not None and old.kind != "string":
1156
+ raise _error(f"{name} is a {old.kind}, not a string")
1157
+ var, note = (old.name, "") if old is not None else self._name(name, f"string {key}")
1158
+ if rhs is None:
1159
+ self.py[key] = _Py(var, "string", "")
1160
+ return [Code(f'{var} = ""', (var,))], note
1161
+ notes: list[str] = []
1162
+ if _program_text(rhs, string=True):
1163
+ code, value, kind, notes = self.program_value(rhs)
1164
+ if kind == "num":
1165
+ raise _left(f"{name} is a string: {rhs.strip()} is a number (@str(...) makes it text)")
1166
+ else:
1167
+ code, value = self.string(rhs)
1168
+ self.py[key] = _Py(var, "string", value if not self.runtime else _UNKNOWN)
1169
+ return [Code(f"{var} = {code}", (var,))], "; ".join(x for x in (note, *notes) if x)
1170
+
1171
+ def _cmd_string(self, st: Statement) -> tuple[list[Op], str]:
1172
+ m = re.fullmatch(r"\s*([A-Za-z_]\w*)\s*(?:=(.*))?", st.rest, re.S)
1173
+ if m is None:
1174
+ raise _error("string names the string: string s = \"abc\"")
1175
+ return self._string(m.group(1).lower(), m.group(1), m.group(2))
1176
+
1177
+ def _matrix(self, st: Statement, kind: str) -> tuple[list[Op], str]:
1178
+ size = [s.strip() for s in (st.options or "").split(",") if s.strip()]
1179
+ m = re.fullmatch(r"\s*([A-Za-z_]\w*)\s*(?:=(.*))?", st.rest, re.S)
1180
+ if m is None:
1181
+ raise _error(f"{kind} names the object: {kind}(3) v")
1182
+ if m.group(2) is not None:
1183
+ raise _left(f"{kind} filled from an expression is not translated: Matrix arithmetic (Model → Matrix)")
1184
+ try:
1185
+ dims = [int(self._static_int(s)) for s in size]
1186
+ except ValueError:
1187
+ raise _left(f"{kind}'s size is known only when the program runs: not translated (Matrix.zeros(rows, cols) with "
1188
+ "the numbers)") from None
1189
+ if kind == "matrix":
1190
+ rows, cols = (dims + [1, 1])[:2] if dims else (1, 1)
1191
+ elif kind == "sym":
1192
+ rows = cols = dims[0] if dims else 1
1193
+ else:
1194
+ rows, cols = (dims[0] if dims else 1), 1
1195
+ if kind == "coef":
1196
+ self.types[m.group(1).lower()] = "coef"
1197
+ return [], f"a coefficient vector: an expression specification's {m.group(1).lower()}(i) are its parameters {m.group(1).lower()}_i (no step)"
1198
+ key = m.group(1).lower()
1199
+ var, note = self._name(m.group(1), f"matrix {key}")
1200
+ self.py[key] = _Py(var, "matrix", shape=(rows, cols))
1201
+ extra = "; a sym is a full matrix here: keep it symmetric" if kind == "sym" else ""
1202
+ return [Code(f"{var} = Matrix.zeros({rows}, {cols})", (var,))], (note + extra).strip("; ")
1203
+
1204
+ def _static_int(self, text: str) -> float:
1205
+ if re.fullmatch(r"\d+", text):
1206
+ return float(text)
1207
+ if text.startswith("!") and self._known(text) is not _UNKNOWN:
1208
+ return float(self._known(text))
1209
+ raise ValueError(text)
1210
+
1211
+ def _cmd_matrix(self, st: Statement) -> tuple[list[Op], str]:
1212
+ return self._matrix(st, st.word)
1213
+
1214
+ _cmd_vector = _cmd_sym = _cmd_coef = _cmd_rowvector = _cmd_matrix
1215
+
1216
+ # assignments
1217
+
1218
+ def _assign(self, st: Statement) -> tuple[list[Op], str]:
1219
+ lhs = st.lhs
1220
+ if lhs.startswith("!"):
1221
+ return self._scalar(lhs, st.rest, st.rest_at, "control")
1222
+ if lhs.startswith("%"):
1223
+ return self._string(lhs.lower(), lhs, st.rest)
1224
+ if "(" in lhs:
1225
+ name = lhs.split("(")[0].lower()
1226
+ if self.types.get(name) in ("table",):
1227
+ why, eq = PHASE4_COMMANDS["table"]
1228
+ raise _left(left_reason(why, eq))
1229
+ if self.py.get(name) and self.py[name].kind == "matrix":
1230
+ raise _left("assigning one element of a matrix is not translated: Matrix.set (Model → Matrix)")
1231
+ raise _left(f"{lhs}: assigning to a lag or an element is not translated")
1232
+ key = lhs.lower()
1233
+ v = self.py.get(key)
1234
+ if v is not None:
1235
+ if v.kind in ("scalar", "control"):
1236
+ return self._scalar(lhs, st.rest, st.rest_at, v.kind)
1237
+ if v.kind == "string":
1238
+ return self._string(key, lhs, st.rest)
1239
+ raise _left(f"{lhs} is a {v.kind}: assigning to it is not translated")
1240
+ if '"' in st.rest: # a string object, as EViews makes one from a string's value
1241
+ return self._string(key, lhs, st.rest)
1242
+ if key in self.types:
1243
+ raise _left(f"{lhs} is a {self.types[key]}: assigning to it is not translated")
1244
+ return self._assign_series(lhs, st.rest, st.rest_at)
1245
+
1246
+ # methods
1247
+
1248
+ def _method(self, st: Statement) -> tuple[list[Op], str]:
1249
+ obj, method = st.obj, st.word
1250
+ key = obj.lower()
1251
+ kind = self.py[key].kind if key in self.py else self.types.get(key, "")
1252
+ if kind == "group" and method in ("add", "drop"):
1253
+ g = self.py[key]
1254
+ words = _arguments(st.rest)
1255
+ members = list(g.members)
1256
+ for w in words:
1257
+ s = _py_name(w)
1258
+ if method == "add" and s not in members:
1259
+ members.append(s)
1260
+ elif method == "drop" and s in members:
1261
+ members.remove(s)
1262
+ page = next((p for p in self.pages.values() if p.var == g.page), self._page())
1263
+ del self.taken[g.name]
1264
+ return self._group(obj, members, page, f"the group made again with {'more' if method == 'add' else 'fewer'} series")
1265
+ if kind == "sample" and method == "set":
1266
+ page = self._page()
1267
+ spec = self._sample_spec(st.rest, st.rest_at, page)
1268
+ v = self.py[key]
1269
+ return [Code(f"{v.name} = {(spec or SampleSpec()).code() if not isinstance(spec, Var) else spec.name}", (v.name,))], ""
1270
+ if kind == "matrix" and method == "fill":
1271
+ return self._fill(self.py[key], st)
1272
+ if method == "fill" and not kind:
1273
+ return self._series_fill(st)
1274
+ if method in ("label", "displayname", "setattr") and not kind:
1275
+ return self._label(st)
1276
+ if key in self.models:
1277
+ return self._model_method(st, key)
1278
+ if key in self.systems:
1279
+ return self._system_method(st, key)
1280
+ if kind == "group" and method == "coint":
1281
+ return self._coint(st, self.py[key])
1282
+ if method == "uroot" and not kind:
1283
+ return self._uroot(st)
1284
+ if kind in ("equation", "var") or (not kind and (method in ESTIMATORS or method in LEFT_ESTIMATORS)):
1285
+ return self._fit_method(st, key)
1286
+ if kind in ("graph", "table", "spool", "text") or (method in PHASE4_METHODS and kind not in PHASE2_COMMANDS):
1287
+ why, eq = PHASE4_METHODS.get(method, PHASE4_COMMANDS.get(kind, ("not translated", "")))
1288
+ raise _left(left_reason(why, eq))
1289
+ if method in _OBJECT_METHODS and not kind:
1290
+ if self.lost:
1291
+ raise _left(f"{obj} is not made by a line translated so far (a subroutine, an add-in or a line left out may make "
1292
+ "it)")
1293
+ raise _error(f"{obj} is not an object of the program: {obj}.{method} needs a model, an equation or a system")
1294
+ raise _left(f"{obj}.{method} is not translated" + (f" (a {kind})" if kind else ""))
1295
+
1296
+ def _label(self, st: Statement) -> tuple[list[Op], str]:
1297
+ page = self._page()
1298
+ series = _py_name(st.obj)
1299
+ if not _has_series(page, series):
1300
+ raise _error(f"{st.obj} is not a series of page {page.eviews}")
1301
+ text = st.rest.strip()
1302
+ if text.startswith('"') and text.endswith('"') and len(text) > 1:
1303
+ text = text[1:-1]
1304
+ option = (st.options or "").strip().lower()
1305
+ if st.word == "displayname":
1306
+ info, note = {"label": text}, ""
1307
+ elif st.word == "setattr":
1308
+ field_ = {"units": "units", "source": "source", "description": "description", "unit": "units"}.get(option)
1309
+ if field_ is None:
1310
+ raise _left(f"the attribute {option!r} is not a field of a series' description: Variable.extra")
1311
+ info, note = {field_: text}, ""
1312
+ else:
1313
+ fields = {"d": "description", "u": "units", "s": "source"}
1314
+ if option == "c":
1315
+ info, note = {"label": "", "description": "", "units": "", "source": ""}, "the series' description cleared"
1316
+ elif option in fields:
1317
+ info, note = {fields[option]: text}, ""
1318
+ elif option == "r":
1319
+ raise _left("remarks have no field in a series' description: Variable.extra[\"remarks\"]")
1320
+ elif not option:
1321
+ info, note = {"description": text}, "label with no option read as the description (verify)"
1322
+ else:
1323
+ raise _left(f"label({option}) is not translated: d, u, s and c are")
1324
+ return [Step("pymetrix:dataset.with_info", page.var, page.var, f"{page.var}.with_info",
1325
+ (Arg("name", series, "pos"), Arg("info", info, "varkw")))], note
1326
+
1327
+ def _series_fill(self, st: Statement) -> tuple[list[Op], str]:
1328
+ page = self._page()
1329
+ series = _py_name(st.obj)
1330
+ if not _has_series(page, series):
1331
+ raise _error(f"{st.obj} is not a series of page {page.eviews}")
1332
+ options = _option_map(st.options)
1333
+ flags = [o.strip().lower() for o in (st.options or "").split(",") if o.strip() and "=" not in o]
1334
+ if flags or set(options) - {"o"}:
1335
+ raise _left(f"fill({st.options}) is not translated: values from a date (o=) are")
1336
+ start = options.get("o")
1337
+ note = ""
1338
+ if start is None:
1339
+ if page.first is None:
1340
+ raise _left("fill from the page's first period, which is not known here: give o=")
1341
+ first, note = page.first, "filled from the page's first period (verify: EViews's default)"
1342
+ else:
1343
+ first = self._end(start, page, True)
1344
+ if first is None:
1345
+ raise _error(f"o={start} is not a date")
1346
+ if PLACEHOLDER.search(str(first)):
1347
+ raise _left("fill from a date known only when the program runs is not translated: write the date")
1348
+ values: dict[str, Any] = {}
1349
+ for i, tok in enumerate(t.strip() for t in st.rest.split(",")):
1350
+ try:
1351
+ number = float(tok)
1352
+ except ValueError:
1353
+ if tok.lower() != "na":
1354
+ raise _left("fill with expressions is not translated: numbers are") from None
1355
+ number = math.nan
1356
+ values[_shifted(first, page.freq or "Q", i)] = None if math.isnan(number) else number
1357
+ return [Step("pymetrix:dataset.edit", page.var, page.var, f"{page.var}.edit", (Arg("values", {series: values}, "pos"),))], \
1358
+ "; ".join(x for x in (note, "the values are marked edited") if x)
1359
+
1360
+ def _fill(self, v: _Py, st: Statement) -> tuple[list[Op], str]:
1361
+ options = (st.options or "").replace(" ", "").lower()
1362
+ by_row = options in ("b=r", "byrow")
1363
+ if options and not by_row and options not in ("b=c",):
1364
+ raise _left(f"fill({st.options}) is not translated: by column and by row (b=r) are")
1365
+ values = []
1366
+ for tok in st.rest.split(","):
1367
+ tok = tok.strip()
1368
+ try:
1369
+ values.append(float(tok))
1370
+ except ValueError:
1371
+ if tok.lower() == "na":
1372
+ values.append(math.nan)
1373
+ else:
1374
+ raise _left("fill with expressions is not translated: numbers are") from None
1375
+ rows, cols = v.shape or (len(values), 1)
1376
+ if len(values) != rows * cols:
1377
+ raise _left(f"fill with {len(values)} values for a {rows} by {cols} matrix (EViews fills part, or repeats): "
1378
+ "not translated")
1379
+ grid = [[values[r * cols + c] if by_row else values[c * rows + r] for c in range(cols)] for r in range(rows)]
1380
+ text = "[" + ", ".join("[" + ", ".join(_number_text(x) if math.isfinite(x) else _NAN for x in row) + "]"
1381
+ for row in grid) + "]"
1382
+ return [Code(f"{v.name} = Matrix({text})", (v.name,))], "" if by_row else "filled by column, as EViews does"
1383
+
1384
+
1385
+ # methods of models, equations and systems: on a name the program has not made, the object comes from a line left out
1386
+ _OBJECT_METHODS = frozenset({"solve", "solveopt", "addassign", "addinit", "scenario", "override", "exclude", "append", "merge",
1387
+ "makegroup", "wald", "auto", "hettest", "archtest", "reset", "chow", "hist", "rls", "testdrop",
1388
+ "testadd", "forecast", "fit", "makeresids", "ec", "sur", "3sls", "fiml", "makemodel", "results", "spec",
1389
+ "output"})
1390
+
1391
+
1392
+ def _has_series(page: _Page, name: str) -> bool:
1393
+ """Whether the page may have the series: its series known and the name among them, or a name made as the program
1394
+ runs (not checked)."""
1395
+ return page.series is None or PLACEHOLDER.search(name) is not None or name in page.series
1396
+
1397
+
1398
+ def _makes_names(ops: list[Any]) -> bool:
1399
+ """Whether ops make an object or a series whose name is made as the program runs."""
1400
+ from .ir import Cmd, Text
1401
+
1402
+ for op in ops:
1403
+ if isinstance(op, Step) and (isinstance(op.output, Text) and op.output.names
1404
+ or any(a.how == "varkw" and any(isinstance(k, Text) for k in a.value) for a in op.args)):
1405
+ return True
1406
+ if isinstance(op, Code) and any(isinstance(n, Text) for n in op.names):
1407
+ return True
1408
+ if isinstance(op, Cmd) and op.fields:
1409
+ return True
1410
+ return False
1411
+
1412
+
1413
+ _PROGRAM_WORDS = re.compile(r"(?i)@(?:lower|upper|trim|ltrim|rtrim|len|length|replace|left|right|mid|instr|str|val|wcount|word|wfind"
1414
+ r"|wfindnc|wlookup|isobject|obssmpl|dateval|dateadd|datestr|datediff|uiprompt)\b|\.@(?:count|seriesname|members)\b")
1415
+
1416
+
1417
+ def _program_text(text: str, string: bool = False) -> bool:
1418
+ """Whether a scalar's or a string's right-hand side is a program expression (strings, the programming language's
1419
+ functions, a group's members, a comparison of strings) rather than phase 1's numbers and joined strings."""
1420
+ bare = re.sub(r'"[^"]*"', '""', text)
1421
+ if _PROGRAM_WORDS.search(bare) or PLACEHOLDER.search(bare.lower()):
1422
+ return True
1423
+ if string:
1424
+ return bool(re.search(r"[-*/^=<>(]|@", bare))
1425
+ return bool(re.search(r'%\w|""', bare))
1426
+
1427
+
1428
+ def _top_level(text: str, ch: str) -> list[int]:
1429
+ """Where ``ch`` is outside brackets (an ``=`` not part of ``<=``, ``>=`` or ``<>``)."""
1430
+ out, depth = [], 0
1431
+ for i, c in enumerate(text):
1432
+ depth += (c == "(") - (c == ")")
1433
+ if c == ch and depth == 0 and text[i - 1:i] not in ("<", ">") and text[i + 1:i + 2] not in (">",):
1434
+ out.append(i)
1435
+ return out
1436
+
1437
+
1438
+ def _uses(expr: str, name: str) -> bool:
1439
+ return re.search(rf"(?<![\w.]){re.escape(name)}(?!\w)(?!\s*\()", expr) is not None
1440
+
1441
+
1442
+ def _balanced(text: str) -> bool:
1443
+ depth = 0
1444
+ for ch in text:
1445
+ depth += ch == "("
1446
+ depth -= ch == ")"
1447
+ if depth < 0:
1448
+ return False
1449
+ return depth == 0
1450
+
1451
+
1452
+ def _first_word(text: str) -> str:
1453
+ m = re.match(r"\s*([^\s(]+)", text)
1454
+ return m.group(1) if m else ""
1455
+
1456
+
1457
+ def _arguments(text: str) -> list[str]:
1458
+ """Words separated by spaces, a quoted text one word."""
1459
+ return [a for a in re.findall(r'"[^"]*"|\S+', text)]
1460
+
1461
+
1462
+ def _option_map(options: str | None) -> dict[str, str]:
1463
+ out = {}
1464
+ for part in (options or "").split(","):
1465
+ if "=" in part:
1466
+ k, _, v = part.partition("=")
1467
+ out[k.strip().lower()] = v.strip().strip('"')
1468
+ return out
1469
+
1470
+
1471
+ def is_opener(st: Statement) -> str:
1472
+ """The block a statement opens (``for``, ``if``, ``while``, ``subroutine``), or ''."""
1473
+ return st.word if st.kind == "command" and st.word in _OPENERS else ""
1474
+
1475
+
1476
+ def is_closer(st: Statement) -> bool:
1477
+ return st.kind == "command" and st.word in _CLOSERS
1478
+
1479
+