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,462 @@
1
+ """Phase 2: models. ``model m``, ``m.append``, ``m.merge eq``, ``@identity``, ``@add`` and ``@innov`` are collected into
2
+ one text, which the core reader reads (``read_eviews(text, data=..., params=...)``) before the model is first used;
3
+ its refusals are passed into the report at their lines. ``m.solve``, ``m.solveopt``, ``m.addassign``, ``m.addinit``,
4
+ ``m.scenario``, ``m.override`` and ``m.exclude`` become ``Model.solve`` with a solver and a ``Scenario``, the add
5
+ factors ``Model.add_factors``, and the solution's endogenous series are added to the page under the scenario's
6
+ alias (``y_0``), as EViews writes them.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ import re
13
+ from dataclasses import dataclass, field
14
+ from typing import Any
15
+
16
+ from .estimation import _commas, _options, _value
17
+ from .ir import Arg, Attr, Cmd, New, Op, RefTo, SampleSpec, Step, Var
18
+
19
+ __all__ = ["Models"]
20
+
21
+
22
+ @dataclass
23
+ class _Scenario:
24
+ name: str
25
+ alias: str
26
+ overrides: list[str] = field(default_factory=list)
27
+ excludes: list[str] = field(default_factory=list)
28
+
29
+
30
+ @dataclass
31
+ class _Model:
32
+ var: str
33
+ eviews: str
34
+ page: Any
35
+ lines: list[tuple[int, str]] = field(default_factory=list) # (program line, the line of the model's text)
36
+ scalars: dict[str, int] = field(default_factory=dict) # the program's scalars it uses -> the line declaring them
37
+ merged: dict[str, int] = field(default_factory=dict) # equation -> line
38
+ dirty: bool = True
39
+ read: bool = False
40
+ refused: str = ""
41
+ endogenous: list[str] = field(default_factory=list)
42
+ equations: list[str] = field(default_factory=list) # names of its equations, for add factors
43
+ identities: set[str] = field(default_factory=set)
44
+ solver: Any = None
45
+ solver_note: str = ""
46
+ scenarios: dict[str, _Scenario] = field(default_factory=dict)
47
+ active: str = "baseline"
48
+ factors: str = "" # the variable holding its add factors (addinit), if any
49
+ solving: str = "" # the variable holding the Model read (m_model = m.model), which solves
50
+ assigned: bool = False
51
+ building: list[Any] = field(default_factory=list) # the outcomes of the lines that build it (set by the translator)
52
+ given: bool = False # given to the translation (objects=), not built by the program
53
+
54
+
55
+ class Models:
56
+ """The phase 2 handlers for models, mixed into the ``Translator`` (``data.py``)."""
57
+
58
+ def _cmd_model(self, st: Any) -> tuple[list[Op], str]:
59
+ from .data import _error
60
+
61
+ m = re.fullmatch(r"\s*([A-Za-z_]\w*)\s*", st.rest)
62
+ if m is None:
63
+ raise _error("model names the model: model m")
64
+ key = m.group(1).lower()
65
+ var, note = self._name(m.group(1), f"model {key}")
66
+ page = self.current # a model's text needs no page; solving it does
67
+ model = _Model(var, m.group(1), page)
68
+ model.scenarios["baseline"] = _Scenario("baseline", "_0")
69
+ self.models[key] = model
70
+ self.types[key] = "model"
71
+ model.lines.append((st.line, f"model {key}"))
72
+ self.building.append((key, st.line))
73
+ return [], "; ".join(x for x in ("the model's text is collected and read (read_eviews) before its first use", note) if x)
74
+
75
+ def _model_method(self, st: Any, key: str) -> tuple[list[Op], str]:
76
+ from .data import _error, _left
77
+
78
+ model = self.models[key]
79
+ word = st.word
80
+ if model.given and word in ("append", "merge"):
81
+ raise _left(f"{model.eviews} is given to the translation (objects=): its equations are not changed here")
82
+ if model.refused and word not in ("append", "merge"):
83
+ raise _left(f"the model {model.eviews} is not read: {model.refused}")
84
+ if word == "append":
85
+ text = st.rest.strip()
86
+ if not text:
87
+ raise _error("append takes a line of the model: m.append y = c(1) + x")
88
+ self._model_scalars(model, text)
89
+ model.lines.append((st.line, f"{key}.append {text}"))
90
+ model.dirty = True
91
+ self.building.append((key, st.line))
92
+ return [], "collected into the model's text"
93
+ if word == "merge":
94
+ name = st.rest.strip().lower()
95
+ fit = self.fits.get(name)
96
+ if fit is None:
97
+ raise _left(f"{st.rest.strip()} is not an equation estimated by a line translated so far")
98
+ if fit.kind != "equation" or fit.method != "ls" or fit.method == "ardl":
99
+ raise _left(f"{name} is estimated by {fit.method}: the model reader re-reads least-squares equations only; "
100
+ "add the fitted equation to a Model in pymetrix (Model([...]))")
101
+ if any(t in fit.spec.lower() for t in ("ar(", "ma(")):
102
+ raise _left(f"{name} has ARMA terms: the model reader does not read them")
103
+ if model.page is None:
104
+ model.page = fit.page
105
+ if fit.page is not model.page:
106
+ raise _left(f"{name} is estimated on another page")
107
+ sample = fit.sample
108
+ if isinstance(sample, Var) or (isinstance(sample, SampleSpec) and sample.where is not None):
109
+ raise _left(f"{name} is estimated over a named sample or a sample with a condition: the model reader takes two dates")
110
+ if isinstance(sample, SampleSpec) and (sample.start or sample.end):
111
+ model.lines.append((st.line, f"smpl {_eviews_period(sample.start) or '@first'} {_eviews_period(sample.end) or '@last'}"))
112
+ else:
113
+ model.lines.append((st.line, "smpl @all"))
114
+ model.lines.append((st.line, f"equation {name}.ls {' '.join(fit.spec.split())}"))
115
+ model.lines.append((st.line, f"{key}.merge {name}"))
116
+ model.merged[name] = st.line
117
+ model.dirty = True
118
+ self.building.append((key, st.line))
119
+ return [], (f"collected: the model reader fits {name} again by least squares, on its sample, as line "
120
+ f"{self._fit_line.get(name, '?')} does")
121
+ if word == "solveopt":
122
+ note = self._solver(model, st.options)
123
+ return [], "; ".join(x for x in ("the solver for the model's later solves (no step)", note) if x)
124
+ if word == "solve":
125
+ return self._solve(st, model)
126
+ if word == "addassign":
127
+ return self._addassign(st, model)
128
+ if word == "addinit":
129
+ return self._addinit(st, model)
130
+ if word == "scenario":
131
+ return self._scenario(st, model)
132
+ if word in ("override", "exclude"):
133
+ names = [w.lower() for w in st.rest.split()]
134
+ if not names:
135
+ raise _error(f"{word} names the variables: m.{word} x")
136
+ if st.options:
137
+ raise _left(f"{word}({st.options}) is not translated")
138
+ scen = model.scenarios[model.active]
139
+ if scen.name == "baseline" and word == "override":
140
+ raise _left("an override in the baseline scenario is not translated: EViews ignores overrides there (verify)")
141
+ kept = scen.overrides if word == "override" else scen.excludes
142
+ for n in names:
143
+ if n not in kept:
144
+ kept.append(n)
145
+ return [], f"{', '.join(names)} {'take their values from the alias series' if word == 'override' else 'held at their data values'} in the scenario {scen.name} (no step)"
146
+ if word == "makegroup":
147
+ return self._makegroup(st, model)
148
+ raise _left(f"{model.eviews}.{word} is not translated: append, merge, solve, solveopt, addassign, addinit, scenario, "
149
+ "override and exclude are")
150
+
151
+ def _makegroup(self, st: Any, model: _Model) -> tuple[list[Op], str]:
152
+ """``m.makegroup(a,n) g @endog``: a group (a ``Selection`` of the page) of the model's endogenous or exogenous
153
+ variables."""
154
+ from .data import _Py, _left
155
+
156
+ named, flags = _options(st.options)
157
+ unknown = [f for f in flags if f.lower() not in ("a", "n")] + sorted(named)
158
+ if unknown:
159
+ raise _left(f"makegroup({st.options}) is not translated: the options a and n are")
160
+ words = st.rest.split()
161
+ if len(words) != 2 or words[1].lower() not in ("@endog", "@exog"):
162
+ raise _left("makegroup is translated for one group of all the endogenous or all the exogenous variables: "
163
+ "m.makegroup g @endog")
164
+ page = self._page()
165
+ ops = self._ensure_read(model)
166
+ which = "endogenous" if words[1].lower() == "@endog" else "exogenous"
167
+ var, note = self._name(words[0], f"group {words[0].lower()}")
168
+ self.py[words[0].lower()] = _Py(var, "group", members=list(model.endogenous) if which == "endogenous" else [], page=page.var)
169
+ ops.append(Step("pymetrix:dataset.series", page.var, var, f"{page.var}.series",
170
+ (Arg("patterns", Attr(model.solving, which), "star"),)))
171
+ notes = [f"the model's {which} variables, by their names in the data (the baseline's series)"]
172
+ if flags:
173
+ notes.append(f"makegroup's options {', '.join(flags)}: the group holds the baseline's names (verify what a and n do)")
174
+ return ops, "; ".join(x for x in (note, *notes) if x)
175
+
176
+ def _model_scalars(self, model: _Model, text: str) -> None:
177
+ for name in re.findall(r"(?<![\w.@!%])([A-Za-z_]\w*)(?!\w)(?!\s*\()", text):
178
+ key = name.lower()
179
+ v = self.py.get(key)
180
+ if v is not None and v.kind == "scalar" and key not in model.scalars:
181
+ model.scalars[key] = 0
182
+
183
+ # -- reading ----------------------------------------------------------------------------------------------------
184
+
185
+ def _text(self, model: _Model, check: bool) -> tuple[str, list[int]]:
186
+ """The model's text, and the program's line of each of its lines. ``check``: the scalars with a value for the
187
+ checking only (their values are given with params= when read)."""
188
+ lines: list[str] = []
189
+ where: list[int] = []
190
+ first = model.lines[0][0]
191
+ for key in model.scalars:
192
+ v = self.py[key]
193
+ value = v.value
194
+ if check and not (isinstance(value, float) and math.isnan(value)):
195
+ lines.append(f"scalar {key} = 1")
196
+ else:
197
+ lines.append(f"scalar {key}")
198
+ where.append(self._declared.get(key, first))
199
+ for line, text in model.lines:
200
+ lines.append(text)
201
+ where.append(line)
202
+ return "\n".join(lines) + "\n", where
203
+
204
+ def _ensure_read(self, model: _Model) -> list[Op]:
205
+ """The step reading the model, when its text changed since it was last read; refused with the reader's problems."""
206
+ from pymetrix.models import ModelSource
207
+
208
+ from .data import _left
209
+
210
+ if model.refused:
211
+ raise _left(f"the model {model.eviews} is not read: {model.refused}")
212
+ if not model.dirty:
213
+ return []
214
+ text, where = self._text(model, True)
215
+ check = ModelSource(text, "eviews").check()
216
+ errors = [d for d in check.diagnostics if d.severity == "error"]
217
+ if errors:
218
+ parts = []
219
+ for d in errors:
220
+ line = where[d.line - 1] if 0 < d.line <= len(where) else where[0]
221
+ self.refusals.setdefault(line, []).append(f"the model reader: {d.message}")
222
+ parts.append(f"line {line}: {d.message}")
223
+ model.refused = "; ".join(parts)
224
+ raise _left(f"the model {model.eviews} is not read: {model.refused}")
225
+ model.endogenous = [s.name for s in check.symbols if s.role == "endogenous"]
226
+ model.dirty = False
227
+ model.read = True
228
+ text, _ = self._text(model, False)
229
+ args: list[Arg] = [Arg("source", text, "pos")]
230
+ if model.scalars:
231
+ args.append(Arg("params", {k: Var(self.py[k].name) for k in model.scalars}))
232
+ if model.merged:
233
+ args.append(Arg("data", RefTo(model.page.var)))
234
+ from pymetrix.commands import RunCode
235
+
236
+ if not model.solving:
237
+ model.solving, _ = self._name(f"{model.var}_model", f"model {model.var}_model")
238
+ return [Step("pymetrix:read_eviews", None, model.var, "read_eviews", tuple(args)),
239
+ Cmd(RunCode(code=f"{model.solving} = {model.var}.model", source="script"), (model.var,))]
240
+
241
+ def finish_models(self) -> list[tuple[int, list[Op], str]]:
242
+ """At the end of the program: each model built but never used is read at its last building line; the reader's
243
+ problems are kept for their lines (``refusals``)."""
244
+ from .data import _Out
245
+
246
+ out = []
247
+ for key, model in self.models.items():
248
+ if model.dirty and not model.refused:
249
+ last = max(line for k, line in self.building if k == key)
250
+ try:
251
+ ops = self._ensure_read(model)
252
+ except _Out:
253
+ continue
254
+ out.append((last, ops, "the model is read here, after its last line: nothing later uses it"))
255
+ return out
256
+
257
+ # -- solving ----------------------------------------------------------------------------------------------------
258
+
259
+ def _solver(self, model: _Model, options: str | None) -> str:
260
+ from .data import _left
261
+
262
+ named, flags = _options(options)
263
+ if flags:
264
+ raise _left(f"solveopt's options {', '.join(flags)} are not translated")
265
+ notes: list[str] = []
266
+ kind = named.pop("o", "")
267
+ args: list[Arg] = []
268
+ if kind == "g":
269
+ cls = "GaussSeidel"
270
+ elif kind in ("n", ""):
271
+ cls = "Newton"
272
+ elif kind == "b":
273
+ cls = "Newton"
274
+ notes.append("o=b (Broyden): pymetrix's Newton; the solution is the same where both converge, the iterations differ")
275
+ else:
276
+ raise _left(f"solveopt(o={kind}) is not translated: g, n and b are")
277
+ if "m" in named:
278
+ args.append(Arg("max_iter", _value(named.pop("m"), "m")))
279
+ if "c" in named:
280
+ args.append(Arg("tol", _value(named.pop("c"), "c", float)))
281
+ args.append(Arg("convergence", "step"))
282
+ notes.append("c= is EViews's convergence on the relative change of the variables: pymetrix's convergence='step' (verify)")
283
+ for key in ("s", "d"):
284
+ if key in named:
285
+ value = named.pop(key).lower()
286
+ if (key, value) not in (("s", "d"), ("d", "d")):
287
+ raise _left(f"solveopt({key}={value}) is not translated: deterministic (s=d), dynamic (d=d) solutions are")
288
+ unmapped = sorted(named)
289
+ if unmapped:
290
+ notes.append(f"not mapped: {', '.join(f'{k}={named[k]}' for k in unmapped)}; check what they do in EViews's "
291
+ "documentation of solveopt (g= rounding digits, z= the zero threshold, verify) before comparing solutions")
292
+ model.solver = New(cls, tuple(args)) if (cls != "Newton" or args) else None
293
+ model.solver_note = "; ".join(notes)
294
+ return model.solver_note
295
+
296
+ def _solve(self, st: Any, model: _Model) -> tuple[list[Op], str]:
297
+ from pymetrix.commands import AddToDataset
298
+
299
+ from .data import _left
300
+
301
+ notes: list[str] = []
302
+ if st.options:
303
+ note = self._solver(model, st.options)
304
+ if note:
305
+ notes.append(note)
306
+ elif model.solver_note:
307
+ notes.append(model.solver_note)
308
+ if st.rest.strip():
309
+ raise _left("solve with arguments is not translated")
310
+ page = model.page = model.page or self._page()
311
+ if self._page() is not page:
312
+ raise _left(f"the model {model.eviews} works on page {page.eviews}; select it first")
313
+ span = self._span(page, "solve")
314
+ ops = self._ensure_read(model)
315
+ scen = model.scenarios[model.active]
316
+ data: Any = RefTo(page.var)
317
+ if scen.overrides:
318
+ missing = [f"{v}{scen.alias}" for v in scen.overrides if page.series is not None and f"{v}{scen.alias}" not in page.series]
319
+ if missing:
320
+ raise _left(f"the override series {', '.join(missing)} are not in the page")
321
+ name, _ = self._name(f"{page.var}{scen.alias}", f"data {page.var}{scen.alias}")
322
+ ops.append(Step("pymetrix:dataset.with_series", page.var, name, f"{page.var}.with_series",
323
+ (Arg("exprs", {v: f"{v}{scen.alias}" for v in scen.overrides}, "varkw"),)))
324
+ data = RefTo(name)
325
+ notes.append(f"the overridden series take the alias series' values ({', '.join(f'{v}{scen.alias}' for v in scen.overrides)}) "
326
+ "in every period the solution reads, as EViews (verify)")
327
+ innovs = [m.group(1).lower() for _, text in model.lines for m in re.finditer(r"@innov\s+([A-Za-z_]\w*)", text, re.I)]
328
+ zero = {f"{v}_innov": "0" for v in innovs if page.series is None or f"{v}_innov" not in page.series}
329
+ if zero:
330
+ base = data.name
331
+ name, _ = self._name(f"{page.var}_solve", f"data {page.var}_solve")
332
+ ops.append(Step("pymetrix:dataset.with_series", base, name, f"{base}.with_series", (Arg("exprs", zero, "varkw"),)))
333
+ data = RefTo(name)
334
+ notes.append(f"a deterministic solve: the innovations ({', '.join(zero)}) are zero")
335
+ sargs: list[Arg] = []
336
+ if model.factors:
337
+ sargs.append(Arg("adjust", RefTo(model.factors)))
338
+ if scen.excludes:
339
+ sargs.append(Arg("fix", {v: None for v in scen.excludes}))
340
+ if sargs or scen.name != "baseline":
341
+ sargs.append(Arg("name", scen.name))
342
+ args = [Arg("data", data, "pos"), Arg("span", span, "pos")]
343
+ if sargs:
344
+ args.append(Arg("scenario", New("Scenario", tuple(sargs))))
345
+ if model.solver is not None:
346
+ args.append(Arg("solver", model.solver))
347
+ elif not model.solver_note:
348
+ notes.append("pymetrix's Newton: EViews's default solver differs by version (verify); the solution is the same "
349
+ "where both converge")
350
+ out, _ = self._name(f"{model.var}{scen.alias}", f"solution {model.var}{scen.alias}")
351
+ ops.append(Step("pymetrix:model.solve", model.solving, out, f"{model.solving}.solve", tuple(args)))
352
+ for v in model.endogenous:
353
+ series = f"{v}{scen.alias}"
354
+ ops.append(Cmd(AddToDataset(source=out, item=f"column:{v}", data=page.var, series_name=series, replace=True), (out,)))
355
+ if page.series is not None:
356
+ page.series.add(series)
357
+ notes.append(f"solved over {span[0]} to {span[1]}; the endogenous series are added to the page as {scen.alias} "
358
+ "(outside the span they hold the data's values; verify what EViews keeps there)")
359
+ if model.factors:
360
+ notes.append("with the add factors of addinit")
361
+ return ops, "; ".join(notes)
362
+
363
+ def _equations_named(self, model: _Model, words: list[str]) -> str:
364
+ from .data import _left
365
+
366
+ if [w.lower() for w in words] in (["@all"], ["@stochastic"], ["@stoch"]):
367
+ return "all"
368
+ raise _left("add factors for some of the equations are not translated: @all is (Scenario(adjust={...}) takes the ones wanted)")
369
+
370
+ def _addassign(self, st: Any, model: _Model) -> tuple[list[Op], str]:
371
+ from .data import _left
372
+
373
+ named, flags = _options(st.options)
374
+ if named or flags:
375
+ raise _left(f"addassign({st.options}) is not translated: EViews's default add factor (on the equation) is")
376
+ self._equations_named(model, st.rest.split())
377
+ if model.merged:
378
+ raise _left("add factors on a model with merged estimated equations are not translated: the core reader adds them "
379
+ "to the model's text equations only")
380
+ model.assigned = True
381
+ return [], ("add factors for every equation: pymetrix keeps them as a Scenario's adjust=, set by addinit "
382
+ "(no series named _a are made; no step)")
383
+
384
+ def _addinit(self, st: Any, model: _Model) -> tuple[list[Op], str]:
385
+ from .data import _left
386
+
387
+ named, flags = _options(st.options)
388
+ if not model.assigned:
389
+ raise _left("addinit before addassign: the model has no add factors")
390
+ v = named.pop("v", "n").lower()
391
+ if v != "n" or named or flags:
392
+ raise _left(f"addinit({st.options}) is not translated: v=n (the add factors that make the equations hold at the "
393
+ "data) is")
394
+ self._equations_named(model, st.rest.split())
395
+ page = model.page = model.page or self._page()
396
+ span = self._span(page, "addinit")
397
+ ops = self._ensure_read(model)
398
+ out, _ = self._name(f"{model.var}_addfactors", f"add factors {model.var}")
399
+ ops.append(Step("pymetrix:model.add_factors", model.solving, out, f"{model.solving}.add_factors",
400
+ (Arg("data", RefTo(page.var), "pos"), Arg("span", span))))
401
+ model.factors = out
402
+ note = (f"the add factors that make each equation hold at the data over {span[0]} to {span[1]}; later solves use them "
403
+ "(Scenario(adjust=...)) in every scenario (verify which scenarios use add factors in EViews)")
404
+ if "v" not in (st.options or ""):
405
+ note += "; v=n, EViews's default (verify)"
406
+ return ops, note
407
+
408
+ def _scenario(self, st: Any, model: _Model) -> tuple[list[Op], str]:
409
+ from .data import _error, _left
410
+
411
+ name_m = re.fullmatch(r'\s*"([^"]+)"\s*', st.rest)
412
+ if name_m is None:
413
+ raise _error('scenario names the scenario in quotes: m.scenario "s1"')
414
+ name = name_m.group(1)
415
+ parts = _commas(st.options)
416
+ create = False
417
+ alias = None
418
+ for p in parts:
419
+ low = p.lower()
420
+ if low == "n":
421
+ create = True
422
+ elif low.startswith("a="):
423
+ alias = p[2:].strip()
424
+ if not alias.startswith("_"):
425
+ alias = "_" + alias
426
+ else:
427
+ raise _left(f"scenario({p}) is not translated: n (a new scenario) and a= (its alias) are")
428
+ key = name.lower()
429
+ if key in ("baseline",) and create:
430
+ raise _left("a new scenario named Baseline is not translated")
431
+ if create:
432
+ if key in model.scenarios:
433
+ raise _error(f"the scenario {name} exists already")
434
+ n = len(model.scenarios)
435
+ model.scenarios[key] = _Scenario(name, alias or f"_{n}")
436
+ note = f"a new scenario {name}, alias {model.scenarios[key].alias}" + ("" if alias else " (EViews's default alias, verify)")
437
+ else:
438
+ if key in ("baseline", "actuals"):
439
+ key = "baseline"
440
+ if key not in model.scenarios:
441
+ raise _error(f"no scenario {name}: m.scenario(n) \"{name}\" makes one")
442
+ if alias:
443
+ model.scenarios[key].alias = alias
444
+ note = f"the scenario {name} is used by later solves"
445
+ model.active = key
446
+ if key == "baseline" and name.lower() == "actuals":
447
+ raise _left("solving into the actual series (the Actuals scenario) is not translated: the page's series would be "
448
+ "replaced; solve a scenario and use its alias series")
449
+ return [], note + " (no step)"
450
+
451
+
452
+ def _eviews_period(period: str | None) -> str | None:
453
+ if period is None:
454
+ return None
455
+ m = re.fullmatch(r"(\d{4})Q(\d)", period)
456
+ if m:
457
+ return f"{m.group(1)}q{m.group(2)}"
458
+ m = re.fullmatch(r"(\d{4})-(\d{2})", period)
459
+ if m:
460
+ return f"{m.group(1)}m{int(m.group(2))}"
461
+ return period
462
+
@@ -0,0 +1,124 @@
1
+ """An EViews program split into statements, each with its lines, its command and its parts.
2
+
3
+ The splitting is the core EViews reader's (``eviews_blank_comments`` and ``eviews_statements`` in
4
+ ``pymetrix.extension``): comments become spaces, so every offset stays, and a line ending in `` _`` continues on the
5
+ next. A statement is then read into its command word, its options in brackets (``ls(cov=white)``), an object and
6
+ method (``x.label(d)``), or an assignment (``y = ...``, ``!i = 1``, ``%s = "a"``).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from dataclasses import dataclass
13
+
14
+ from pymetrix.extension import eviews_blank_comments, eviews_statements
15
+
16
+ __all__ = ["Program", "Statement", "parse_program"]
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Statement:
21
+ """One statement: ``text`` as written (comments blanked, continued lines joined), from offset ``at``, on lines
22
+ ``line`` to ``last_line`` (from 1). ``kind`` is ``"command"`` (``smpl 1990q1 2000q4``), ``"method"``
23
+ (``x.label(d) GDP``, with ``obj`` and ``method``) or ``"assign"`` (``y = x``, with ``lhs``). ``word`` is the
24
+ command or method in lower case, ``options`` the text in brackets right after it, and ``rest`` (from offset
25
+ ``rest_at``) what follows: the arguments, or an assignment's right-hand side."""
26
+
27
+ text: str
28
+ at: int
29
+ line: int
30
+ last_line: int
31
+ kind: str
32
+ word: str = ""
33
+ options: str | None = None
34
+ obj: str = ""
35
+ lhs: str = ""
36
+ rest: str = ""
37
+ rest_at: int = 0
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class Program:
42
+ """A program read: its ``source``, its lines, the statements, and each line's comment (``'`` to the end of the
43
+ line), by line number."""
44
+
45
+ source: str
46
+ lines: tuple[str, ...]
47
+ statements: tuple[Statement, ...]
48
+ comments: dict[int, str]
49
+
50
+
51
+ _WORD = re.compile(r"\s*([A-Za-z_@][\w@]*|[!%]\w+|\{[^}]*\}\w*)")
52
+ _ASSIGN = re.compile(r"\s*([!%]?[A-Za-z_{][\w{}%!]*(?:\([^()=]*\))?)\s*=(?!=)")
53
+
54
+
55
+ def _options(text: str, pos: int) -> tuple[str | None, int]:
56
+ """Options in brackets starting at ``pos`` (no space before them): the text inside and the position after."""
57
+ if pos >= len(text) or text[pos] != "(":
58
+ return None, pos
59
+ depth = 0
60
+ for i in range(pos, len(text)):
61
+ if text[i] == "(":
62
+ depth += 1
63
+ elif text[i] == ")":
64
+ depth -= 1
65
+ if depth == 0:
66
+ return text[pos + 1:i], i + 1
67
+ return text[pos + 1:], len(text)
68
+
69
+
70
+ def _statement(text: str, at: int, line: int, last_line: int) -> Statement:
71
+ lead = len(text) - len(text.lstrip())
72
+ body = text.strip()
73
+ base = at + lead
74
+ m = _ASSIGN.match(body)
75
+ word = _WORD.match(body)
76
+ first = word.group(1).lower() if word else ""
77
+ if m and not (first in _NOT_ASSIGNMENT and word is not None and word.end() < m.end(1)):
78
+ rest_at = m.end()
79
+ rest = body[rest_at:]
80
+ return Statement(text, at, line, last_line, "assign", lhs=m.group(1).strip(), rest=rest.strip(),
81
+ rest_at=base + rest_at + (len(rest) - len(rest.lstrip())))
82
+ if word is None:
83
+ return Statement(text, at, line, last_line, "command", rest=body, rest_at=base)
84
+ name = word.group(1)
85
+ pos = word.end()
86
+ if pos < len(body) and body[pos] == "." and not name.startswith(("!", "%")):
87
+ method = re.match(r"\.(@?\w+)", body[pos:])
88
+ if method:
89
+ options, after = _options(body, pos + method.end())
90
+ rest = body[after:]
91
+ return Statement(text, at, line, last_line, "method", word=method.group(1).lower(), options=options, obj=name,
92
+ rest=rest.strip(), rest_at=base + after + (len(rest) - len(rest.lstrip())))
93
+ options, after = _options(body, pos)
94
+ rest = body[after:]
95
+ return Statement(text, at, line, last_line, "command", word=name.lower(), options=options, rest=rest.strip(),
96
+ rest_at=base + after + (len(rest) - len(rest.lstrip())))
97
+
98
+
99
+ # commands whose arguments may hold an equals sign: never read as assignments
100
+ _NOT_ASSIGNMENT = frozenset({"for", "if", "while", "smpl", "sample", "call", "subroutine", "series", "genr", "frml", "scalar",
101
+ "string", "alpha", "vector", "matrix", "sym", "coef", "equation", "model", "group", "wfcreate",
102
+ "pagecreate", "wfopen", "copy", "freeze", "graph", "table", "statusline", "include"})
103
+
104
+
105
+ def parse_program(source: str) -> Program:
106
+ """``source`` split into statements; see the module's docstring."""
107
+ source = source.replace("\r\n", "\n").replace("\r", "\n")
108
+ clean = eviews_blank_comments(source)
109
+ lines = tuple(source.split("\n"))
110
+ comments: dict[int, str] = {}
111
+ for number, (raw, blanked) in enumerate(zip(lines, clean.split("\n")), start=1):
112
+ cut = len(blanked.rstrip())
113
+ tail = raw[cut:].strip()
114
+ if tail.startswith("'"):
115
+ comments[number] = tail[1:].strip()
116
+ clean_lines = clean.split("\n")
117
+ statements = []
118
+ for text, at in eviews_statements(clean):
119
+ line = source.count("\n", 0, at) + 1
120
+ last = line
121
+ while last < len(clean_lines) and re.search(r"(^|\s)_\s*$", clean_lines[last - 1]):
122
+ last += 1
123
+ statements.append(_statement(text, at, line, last))
124
+ return Program(source, lines, tuple(statements), comments)