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.
- pymetrix_eviews/__init__.py +83 -0
- pymetrix_eviews/_version.py +1 -0
- pymetrix_eviews/app.py +374 -0
- pymetrix_eviews/bundle-1.schema.json +104 -0
- pymetrix_eviews/bundle.py +889 -0
- pymetrix_eviews/dates.py +196 -0
- pymetrix_eviews/export/pymetrix_export.prg +476 -0
- pymetrix_eviews/panel.py +326 -0
- pymetrix_eviews/program/__init__.py +292 -0
- pymetrix_eviews/program/control.py +1368 -0
- pymetrix_eviews/program/data.py +1479 -0
- pymetrix_eviews/program/estimation.py +1133 -0
- pymetrix_eviews/program/ir.py +395 -0
- pymetrix_eviews/program/left.py +89 -0
- pymetrix_eviews/program/models.py +462 -0
- pymetrix_eviews/program/parse.py +124 -0
- pymetrix_eviews/program/report.py +155 -0
- pymetrix_eviews/program/script.py +258 -0
- pymetrix_eviews/program/steps.py +234 -0
- pymetrix_eviews-0.1.0a1.dist-info/METADATA +248 -0
- pymetrix_eviews-0.1.0a1.dist-info/RECORD +24 -0
- pymetrix_eviews-0.1.0a1.dist-info/WHEEL +4 -0
- pymetrix_eviews-0.1.0a1.dist-info/entry_points.txt +8 -0
- pymetrix_eviews-0.1.0a1.dist-info/licenses/LICENSE +28 -0
pymetrix_eviews/panel.py
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
"""The EViews translation panel (``AppPanel("EViews translation", create_panel, area="bottom")``, View → EViews
|
|
2
|
+
translation): the report of a program translated with File → Translate EViews program….
|
|
3
|
+
|
|
4
|
+
- a table, a row per line: its number (and file, for an included program), its status in words and in colour, the
|
|
5
|
+
EViews text, the Python and the reason;
|
|
6
|
+
- the program and the script side by side; selecting a row scrolls both to that line;
|
|
7
|
+
- a filter for each status, with its count;
|
|
8
|
+
- Copy (the selected rows, or the whole report, as text) and Copy script;
|
|
9
|
+
- Run as steps: the translation's steps run one at a time through ``AppInterface.run``, so each is recorded and can be
|
|
10
|
+
undone; the run stops at the first step that fails, and that row is marked.
|
|
11
|
+
|
|
12
|
+
The panel uses only ``AppInterface``: the session (its History's translate steps are the translations listed), its
|
|
13
|
+
runner, the status bar and the translate dialog. When a new translation is made, the panel shows itself (its dock).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
__all__ = ["COLOURS", "create_panel", "panel_class"]
|
|
21
|
+
|
|
22
|
+
# a status's colour, behind its text (never the colour alone): translucent, so it reads on light and dark themes
|
|
23
|
+
COLOURS = {"translated": (46, 160, 67, 55), "translated with a note": (31, 111, 235, 60), "left out": (191, 135, 0, 75),
|
|
24
|
+
"error": (207, 34, 46, 85), "failed": (207, 34, 46, 150)}
|
|
25
|
+
COLUMNS = ("line", "status", "EViews", "Python", "reason")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
_CLASS: Any = None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def create_panel(app: Any) -> Any:
|
|
32
|
+
"""The panel's widget (``AppPanel.create``): ``app`` is pymetrix's ``AppInterface``."""
|
|
33
|
+
return panel_class()(app)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def panel_class() -> Any:
|
|
37
|
+
"""The panel's Qt class, made on first use (Qt is not imported with the plugin)."""
|
|
38
|
+
global _CLASS
|
|
39
|
+
if _CLASS is None:
|
|
40
|
+
_CLASS = _panel_class()
|
|
41
|
+
return _CLASS
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _panel_class() -> Any:
|
|
45
|
+
from PySide6 import QtCore, QtGui, QtWidgets
|
|
46
|
+
|
|
47
|
+
from .program import STATUSES
|
|
48
|
+
|
|
49
|
+
class TranslationPanel(QtWidgets.QWidget):
|
|
50
|
+
def __init__(self, app: Any) -> None:
|
|
51
|
+
super().__init__()
|
|
52
|
+
self.app = app
|
|
53
|
+
self.setObjectName("eviews-translation-panel")
|
|
54
|
+
self.items: list[tuple[Any, Any]] = [] # (the translate step, its translation)
|
|
55
|
+
self.current: Any = None
|
|
56
|
+
self.failed: tuple[str, int, str] | None = None # (file, line, message) of the step that failed
|
|
57
|
+
self._known = 0
|
|
58
|
+
self._running = False # Run as steps under way: the History changes at each step, the report does not
|
|
59
|
+
layout = QtWidgets.QVBoxLayout(self)
|
|
60
|
+
layout.setContentsMargins(4, 4, 4, 4)
|
|
61
|
+
top = QtWidgets.QHBoxLayout()
|
|
62
|
+
self.program = QtWidgets.QComboBox()
|
|
63
|
+
self.program.setObjectName("eviews-program")
|
|
64
|
+
self.program.setToolTip("The programs translated in this session (File → Translate EViews program…)")
|
|
65
|
+
self.program.currentIndexChanged.connect(self._chosen)
|
|
66
|
+
top.addWidget(self.program, 1)
|
|
67
|
+
self.translate_button = QtWidgets.QPushButton("Translate…")
|
|
68
|
+
self.translate_button.setToolTip("Translate an EViews program (File → Translate EViews program…)")
|
|
69
|
+
self.translate_button.clicked.connect(self.translate)
|
|
70
|
+
self.copy_button = QtWidgets.QPushButton("Copy")
|
|
71
|
+
self.copy_button.setToolTip("Copy the selected rows, or the whole report when none is selected, as text")
|
|
72
|
+
self.copy_button.clicked.connect(self.copy)
|
|
73
|
+
self.copy_script_button = QtWidgets.QPushButton("Copy script")
|
|
74
|
+
self.copy_script_button.setToolTip("Copy the readable script")
|
|
75
|
+
self.copy_script_button.clicked.connect(self.copy_script)
|
|
76
|
+
self.run_button = QtWidgets.QPushButton("Run as steps")
|
|
77
|
+
self.run_button.setToolTip("Run the program's work in this session, one recorded step at a time (each can be "
|
|
78
|
+
"undone); stops at the first step that fails and marks its row")
|
|
79
|
+
self.run_button.clicked.connect(self.run_steps)
|
|
80
|
+
for b in (self.translate_button, self.copy_button, self.copy_script_button, self.run_button):
|
|
81
|
+
top.addWidget(b)
|
|
82
|
+
layout.addLayout(top)
|
|
83
|
+
filters = QtWidgets.QHBoxLayout()
|
|
84
|
+
self.filters: dict[str, Any] = {}
|
|
85
|
+
for status in STATUSES:
|
|
86
|
+
box = QtWidgets.QCheckBox(status)
|
|
87
|
+
box.setChecked(True)
|
|
88
|
+
box.setToolTip(f"Show the lines {status}")
|
|
89
|
+
box.toggled.connect(self._filter)
|
|
90
|
+
self.filters[status] = box
|
|
91
|
+
filters.addWidget(box)
|
|
92
|
+
filters.addStretch(1)
|
|
93
|
+
layout.addLayout(filters)
|
|
94
|
+
self.message = QtWidgets.QLabel("No program translated yet: File → Translate EViews program….")
|
|
95
|
+
self.message.setWordWrap(True)
|
|
96
|
+
self.message.setObjectName("eviews-translation-message")
|
|
97
|
+
layout.addWidget(self.message)
|
|
98
|
+
split = QtWidgets.QSplitter(QtCore.Qt.Orientation.Vertical)
|
|
99
|
+
self.table = QtWidgets.QTableWidget(0, len(COLUMNS))
|
|
100
|
+
self.table.setObjectName("eviews-report")
|
|
101
|
+
self.table.setHorizontalHeaderLabels(list(COLUMNS))
|
|
102
|
+
self.table.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers)
|
|
103
|
+
self.table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows)
|
|
104
|
+
self.table.verticalHeader().setVisible(False)
|
|
105
|
+
self.table.horizontalHeader().setStretchLastSection(True)
|
|
106
|
+
self.table.itemSelectionChanged.connect(self._selected)
|
|
107
|
+
split.addWidget(self.table)
|
|
108
|
+
texts = QtWidgets.QSplitter(QtCore.Qt.Orientation.Horizontal)
|
|
109
|
+
fixed = QtGui.QFontDatabase.systemFont(QtGui.QFontDatabase.SystemFont.FixedFont)
|
|
110
|
+
self.source = QtWidgets.QPlainTextEdit()
|
|
111
|
+
self.script = QtWidgets.QPlainTextEdit()
|
|
112
|
+
for name, edit in (("eviews-source", self.source), ("eviews-script", self.script)):
|
|
113
|
+
edit.setObjectName(name)
|
|
114
|
+
edit.setReadOnly(True)
|
|
115
|
+
edit.setFont(fixed)
|
|
116
|
+
edit.setLineWrapMode(QtWidgets.QPlainTextEdit.LineWrapMode.NoWrap)
|
|
117
|
+
texts.addWidget(edit)
|
|
118
|
+
self.source.setToolTip("The EViews program (an included program's text when its row is selected)")
|
|
119
|
+
self.script.setToolTip("The readable script: each EViews line as a comment above what it became")
|
|
120
|
+
split.addWidget(texts)
|
|
121
|
+
layout.addWidget(split, 1)
|
|
122
|
+
self.shown_file = ""
|
|
123
|
+
self.refresh()
|
|
124
|
+
app.on_history_changed(self.refresh)
|
|
125
|
+
|
|
126
|
+
# -- the translations --------------------------------------------------------------------------------------
|
|
127
|
+
|
|
128
|
+
def refresh(self) -> None:
|
|
129
|
+
"""The session's translations again (after a step, an undo or another project)."""
|
|
130
|
+
from .app import translations
|
|
131
|
+
|
|
132
|
+
if self._running:
|
|
133
|
+
return
|
|
134
|
+
items = translations(self.app.session)
|
|
135
|
+
if [id(t) for _, t in items] == [id(t) for _, t in self.items] and self.items:
|
|
136
|
+
return # the same translations: a step of another kind, nothing to show again
|
|
137
|
+
before = self.program.currentIndex()
|
|
138
|
+
newer = len(items) > self._known
|
|
139
|
+
self.items = items
|
|
140
|
+
self.program.blockSignals(True)
|
|
141
|
+
self.program.clear()
|
|
142
|
+
for cmd, t in items:
|
|
143
|
+
counts = t.report.counts()
|
|
144
|
+
self.program.addItem(f"{t.program or cmd.path} — {sum(counts.values())} lines, {counts['left out']} left out, "
|
|
145
|
+
f"{counts['error']} errors")
|
|
146
|
+
self.program.blockSignals(False)
|
|
147
|
+
if items:
|
|
148
|
+
index = len(items) - 1 if newer or before < 0 or before >= len(items) else before
|
|
149
|
+
self.program.setCurrentIndex(index)
|
|
150
|
+
self._show(items[index][1], reset=newer or self.current is not items[index][1])
|
|
151
|
+
if newer and self._known:
|
|
152
|
+
self._reveal()
|
|
153
|
+
else:
|
|
154
|
+
self._show(None, reset=True)
|
|
155
|
+
self._known = len(items)
|
|
156
|
+
|
|
157
|
+
def _reveal(self) -> None:
|
|
158
|
+
"""A new translation: show the panel's own dock, if it is hidden."""
|
|
159
|
+
dock = self.parentWidget()
|
|
160
|
+
while dock is not None and not isinstance(dock, QtWidgets.QDockWidget):
|
|
161
|
+
dock = dock.parentWidget()
|
|
162
|
+
if dock is not None:
|
|
163
|
+
dock.setVisible(True)
|
|
164
|
+
dock.raise_()
|
|
165
|
+
|
|
166
|
+
def _chosen(self, index: int) -> None:
|
|
167
|
+
if 0 <= index < len(self.items):
|
|
168
|
+
self._show(self.items[index][1], reset=True)
|
|
169
|
+
|
|
170
|
+
def _show(self, t: Any, reset: bool) -> None:
|
|
171
|
+
if reset:
|
|
172
|
+
self.failed = None
|
|
173
|
+
self.current = t
|
|
174
|
+
enabled = t is not None
|
|
175
|
+
for b in (self.copy_button, self.copy_script_button, self.run_button):
|
|
176
|
+
b.setEnabled(enabled)
|
|
177
|
+
self.message.setVisible(not enabled)
|
|
178
|
+
if t is None:
|
|
179
|
+
self.table.setRowCount(0)
|
|
180
|
+
self.source.setPlainText("")
|
|
181
|
+
self.script.setPlainText("")
|
|
182
|
+
for status, box in self.filters.items():
|
|
183
|
+
box.setText(f"{status} (0)")
|
|
184
|
+
return
|
|
185
|
+
counts = t.report.counts()
|
|
186
|
+
for status, box in self.filters.items():
|
|
187
|
+
box.setText(f"{status} ({counts[status]})")
|
|
188
|
+
self.script.setPlainText(t.script)
|
|
189
|
+
self.shown_file = t.program
|
|
190
|
+
self.source.setPlainText(t.sources.get(t.program, ""))
|
|
191
|
+
self.table.setRowCount(len(t.report))
|
|
192
|
+
for i, row in enumerate(t.report):
|
|
193
|
+
where = f"{row.line}" if row.file == t.program else f"{row.file}:{row.line}"
|
|
194
|
+
cells = (where, row.status, row.eviews.strip(), row.python, row.reason)
|
|
195
|
+
for j, text in enumerate(cells):
|
|
196
|
+
item = QtWidgets.QTableWidgetItem(text)
|
|
197
|
+
if j in (2, 3, 4):
|
|
198
|
+
item.setToolTip(text)
|
|
199
|
+
self.table.setItem(i, j, item)
|
|
200
|
+
self._colour(i, row.status)
|
|
201
|
+
if self.failed is not None:
|
|
202
|
+
self._mark_failed()
|
|
203
|
+
self._filter()
|
|
204
|
+
|
|
205
|
+
def _colour(self, i: int, status: str) -> None:
|
|
206
|
+
item = self.table.item(i, 1)
|
|
207
|
+
item.setBackground(QtGui.QBrush(QtGui.QColor(*COLOURS[status])))
|
|
208
|
+
|
|
209
|
+
def _filter(self, *_: Any) -> None:
|
|
210
|
+
if self.current is None:
|
|
211
|
+
return
|
|
212
|
+
shown = {s for s, box in self.filters.items() if box.isChecked()}
|
|
213
|
+
for i, row in enumerate(self.current.report):
|
|
214
|
+
failed = self.failed is not None and (row.file, row.line) == self.failed[:2]
|
|
215
|
+
self.table.setRowHidden(i, row.status not in shown and not failed)
|
|
216
|
+
|
|
217
|
+
def row_of(self, line: int, file: str | None = None) -> int:
|
|
218
|
+
"""The table's row of a program's line (an included program's, with ``file``), or -1."""
|
|
219
|
+
if self.current is None:
|
|
220
|
+
return -1
|
|
221
|
+
file = self.current.program if file is None else file
|
|
222
|
+
for i, row in enumerate(self.current.report):
|
|
223
|
+
if row.line == line and row.file == file:
|
|
224
|
+
return i
|
|
225
|
+
return -1
|
|
226
|
+
|
|
227
|
+
# -- following the selected row ----------------------------------------------------------------------------
|
|
228
|
+
|
|
229
|
+
def _selected(self) -> None:
|
|
230
|
+
rows = sorted({i.row() for i in self.table.selectedItems()})
|
|
231
|
+
if not rows or self.current is None:
|
|
232
|
+
return
|
|
233
|
+
row = self.current.report[rows[0]]
|
|
234
|
+
if row.file != self.shown_file:
|
|
235
|
+
self.shown_file = row.file
|
|
236
|
+
self.source.setPlainText(self.current.sources.get(row.file, ""))
|
|
237
|
+
self._go(self.source, row.line)
|
|
238
|
+
at = self.current.script_line(row.line, row.file)
|
|
239
|
+
if at is not None:
|
|
240
|
+
self._go(self.script, at)
|
|
241
|
+
|
|
242
|
+
@staticmethod
|
|
243
|
+
def _go(edit: Any, line: int) -> None:
|
|
244
|
+
"""Put line ``line`` (from 1) of ``edit`` at the top of its view, selected."""
|
|
245
|
+
block = edit.document().findBlockByLineNumber(max(0, line - 1))
|
|
246
|
+
cursor = QtGui.QTextCursor(block)
|
|
247
|
+
cursor.select(QtGui.QTextCursor.SelectionType.LineUnderCursor)
|
|
248
|
+
edit.setTextCursor(cursor)
|
|
249
|
+
bar = edit.verticalScrollBar()
|
|
250
|
+
bar.setValue(min(bar.maximum(), max(0, line - 1)))
|
|
251
|
+
|
|
252
|
+
def source_line(self) -> int:
|
|
253
|
+
"""The line (from 1) of the program at the top of the program's view, selected."""
|
|
254
|
+
return self.source.textCursor().blockNumber() + 1
|
|
255
|
+
|
|
256
|
+
def script_at(self) -> int:
|
|
257
|
+
return self.script.textCursor().blockNumber() + 1
|
|
258
|
+
|
|
259
|
+
# -- actions -----------------------------------------------------------------------------------------------
|
|
260
|
+
|
|
261
|
+
def translate(self) -> None:
|
|
262
|
+
from .app import TranslateEViewsProgram
|
|
263
|
+
|
|
264
|
+
self.app.open_dialog(TranslateEViewsProgram, None)
|
|
265
|
+
|
|
266
|
+
def selected_rows(self) -> list[Any]:
|
|
267
|
+
if self.current is None:
|
|
268
|
+
return []
|
|
269
|
+
rows = sorted({i.row() for i in self.table.selectedItems()})
|
|
270
|
+
return [self.current.report[i] for i in rows]
|
|
271
|
+
|
|
272
|
+
def copy(self) -> str:
|
|
273
|
+
"""The selected rows, or the whole report, onto the clipboard as text."""
|
|
274
|
+
if self.current is None:
|
|
275
|
+
return ""
|
|
276
|
+
rows = self.selected_rows()
|
|
277
|
+
text = self.current.report.to_text(rows or None)
|
|
278
|
+
QtWidgets.QApplication.clipboard().setText(text)
|
|
279
|
+
self.app.status(f"Copied {len(rows) if rows else 'every'} row{'s' if len(rows) != 1 else ''} of the translation")
|
|
280
|
+
return text
|
|
281
|
+
|
|
282
|
+
def copy_script(self) -> str:
|
|
283
|
+
if self.current is None:
|
|
284
|
+
return ""
|
|
285
|
+
QtWidgets.QApplication.clipboard().setText(self.current.script)
|
|
286
|
+
self.app.status("Copied the translated script")
|
|
287
|
+
return self.current.script
|
|
288
|
+
|
|
289
|
+
def run_steps(self) -> bool:
|
|
290
|
+
"""The translation's steps, one at a time through the app's runner (each recorded and undoable); at the
|
|
291
|
+
first that fails, its row is marked and selected. True when every step ran."""
|
|
292
|
+
t = self.current
|
|
293
|
+
if t is None:
|
|
294
|
+
return False
|
|
295
|
+
self.failed = None
|
|
296
|
+
self._show(t, reset=False)
|
|
297
|
+
self._running = True
|
|
298
|
+
try:
|
|
299
|
+
t.run(self.app.session, run=self.app.run)
|
|
300
|
+
except Exception as exc: # noqa: BLE001 - the failing step is shown on its row, not raised into the app
|
|
301
|
+
self._running = False
|
|
302
|
+
line, file = getattr(exc, "line", 0), getattr(exc, "file", "") or t.program
|
|
303
|
+
self.failed = (file, line, str(exc))
|
|
304
|
+
self._mark_failed()
|
|
305
|
+
self.app.status(f"Run as steps stopped: {exc}")
|
|
306
|
+
return False
|
|
307
|
+
self._running = False
|
|
308
|
+
self.app.status(f"Ran {t.program or 'the program'} as steps: see History")
|
|
309
|
+
return True
|
|
310
|
+
|
|
311
|
+
def _mark_failed(self) -> None:
|
|
312
|
+
file, line, message = self.failed
|
|
313
|
+
i = self.row_of(line, file)
|
|
314
|
+
if i < 0:
|
|
315
|
+
return
|
|
316
|
+
self.table.setRowHidden(i, False)
|
|
317
|
+
item = self.table.item(i, 1)
|
|
318
|
+
item.setText("failed")
|
|
319
|
+
item.setToolTip(message)
|
|
320
|
+
item.setBackground(QtGui.QBrush(QtGui.QColor(*COLOURS["failed"])))
|
|
321
|
+
self.table.item(i, 4).setText(f"failed when run: {message}")
|
|
322
|
+
self.table.selectRow(i)
|
|
323
|
+
self.table.scrollToItem(item)
|
|
324
|
+
|
|
325
|
+
return TranslationPanel
|
|
326
|
+
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"""EViews programs (``.prg``) translated into pymetrix: a readable script, a report with a row per line, and the same
|
|
2
|
+
work as recorded steps (design note, docs/design/eviews-plugin.md, section 2).
|
|
3
|
+
|
|
4
|
+
from pymetrix_eviews import translate_program
|
|
5
|
+
|
|
6
|
+
t = translate_program("C:/work/macro.prg", bundle="C:/work/macro-export/macro.evbundle")
|
|
7
|
+
print(t.script) # Python that uses pymetrix's public API, each EViews line above what it became
|
|
8
|
+
t.report.summary() # a Table: line, status, EViews, Python, reason
|
|
9
|
+
out = t.run(session) # steps mode: each data statement a recorded step in the session
|
|
10
|
+
|
|
11
|
+
Phase 1 is data work: workfiles and pages, samples, series, formulas, groups, labels, renaming and deleting, scalars,
|
|
12
|
+
strings and matrices. Phase 2 is estimation, tests and models: equations by the common methods, VARs and VECs,
|
|
13
|
+
systems, tests, forecasts, the values read from results, and models collected, read by the core reader and solved.
|
|
14
|
+
Phase 3 is control flow: ``for`` loops (``step``, lists of strings), ``while`` loops, ``if`` blocks decided as the
|
|
15
|
+
program runs, subroutines (typed arguments, ``local``) and ``call``, included programs, ``exitloop``, ``return``,
|
|
16
|
+
``stop``, the program's arguments (``%0``, ``%1``) and names made from its variables (``{%s}``); the script keeps
|
|
17
|
+
them as Python blocks and functions, and steps mode runs them in Python, each statement inside a recorded step.
|
|
18
|
+
What has no pymetrix equivalent (graphs, tables, display) is left out with the reason: every line has a row.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from .control import WHILE_CAP, Flow, build, functions_of, ops_of
|
|
27
|
+
from .data import Outcome, Translator, _Page, _Py, _UNKNOWN
|
|
28
|
+
from .ir import Code, quote
|
|
29
|
+
from .parse import Program, parse_program
|
|
30
|
+
from .report import LEFT, NOTE, STATUSES, TRANSLATED, ProgramTranslation, ReportRow, TranslationReport
|
|
31
|
+
from .script import render
|
|
32
|
+
|
|
33
|
+
__all__ = ["STATUSES", "WHILE_CAP", "ProgramTranslation", "ReportRow", "TranslationReport", "parse_program", "translate_program"]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _source(source: Any) -> tuple[str, str, Path | None]:
|
|
37
|
+
"""The program's text, its file name ('' for text given directly) and its folder (for included programs)."""
|
|
38
|
+
if isinstance(source, Path) or (isinstance(source, str) and "\n" not in source and source.strip().lower().endswith(".prg")):
|
|
39
|
+
path = Path(source)
|
|
40
|
+
raw = path.read_bytes()
|
|
41
|
+
try:
|
|
42
|
+
text = raw.decode("utf-8-sig")
|
|
43
|
+
except UnicodeDecodeError:
|
|
44
|
+
text = raw.decode("cp1252")
|
|
45
|
+
return text, path.name, path.parent
|
|
46
|
+
return str(source), "", None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def translate_program(source: Any, bundle: Any = None, *, read_options: dict[str, Any] | None = None,
|
|
50
|
+
args: Any = (), objects: Any = None, folder: Any = None) -> ProgramTranslation:
|
|
51
|
+
"""An EViews program translated: ``.script`` (readable Python), ``.report`` (a row per line: translated,
|
|
52
|
+
translated with a note, left out or error, with the reason) and ``.run(session)`` (steps mode).
|
|
53
|
+
|
|
54
|
+
``source`` is the program's text, or the path of a ``.prg`` file. ``bundle`` is what its ``wfopen`` opens: the
|
|
55
|
+
bundle the export program wrote (``.evbundle``), or a CSV or Excel file the user saved from the workfile in
|
|
56
|
+
EViews; ``read_options`` are ``Dataset.read``'s options for that file (``time="obs", freq="Q"``). Without it,
|
|
57
|
+
``wfopen`` is an error saying how to make one; a program that starts with ``wfcreate`` needs none.
|
|
58
|
+
|
|
59
|
+
``args`` are the program's arguments (``%0``, ``%1``, ...: what follows the program's name in ``exec prog.prg
|
|
60
|
+
us 2020q1``), as strings or one string of words; they are the script's parameters (``arg0 = "us"`` at its top).
|
|
61
|
+
``objects`` are objects the program uses but does not make, by their EViews names: in EViews an add-in, a
|
|
62
|
+
database or another program makes them. A ``Model`` (or a model read, whose ``.model`` is one) is solved by the
|
|
63
|
+
program's model lines; a ``Dataset`` is a page. The script expects them under those names, and steps mode puts
|
|
64
|
+
them in the session. ``folder`` is where included programs are looked for (default: the program's own folder,
|
|
65
|
+
or the current one for text)."""
|
|
66
|
+
text, name, own_folder = _source(source)
|
|
67
|
+
program = parse_program(text)
|
|
68
|
+
translator = Translator(None if bundle is None else str(bundle), read_options)
|
|
69
|
+
given = _given(translator, objects)
|
|
70
|
+
top, arguments = _arguments(translator, args, text)
|
|
71
|
+
nodes = build(program, "", Path(folder) if folder is not None else own_folder)
|
|
72
|
+
flow = Flow(translator, nodes)
|
|
73
|
+
outcomes = flow.walk(nodes)
|
|
74
|
+
flow.finish()
|
|
75
|
+
_finish(translator, [o for o in _flat(outcomes) if not o.file])
|
|
76
|
+
rows = _rows(program, outcomes, name)
|
|
77
|
+
ops = tuple((0, op, "") for op in top) + ops_of(outcomes)
|
|
78
|
+
functions = functions_of(flow)
|
|
79
|
+
script, where = _script(program, outcomes, functions, flow, name, translator.uses_bundle, top, given)
|
|
80
|
+
where = {(name if not f else f, line): n for (f, line), n in where.items()}
|
|
81
|
+
pages = {p.eviews: p.var for p in translator.pages.values()}
|
|
82
|
+
sources = {name: program.source}
|
|
83
|
+
for o in _flat(outcomes):
|
|
84
|
+
if o.kind == "include" and getattr(o, "program", None) is not None:
|
|
85
|
+
sources.setdefault(o.included_file, o.program.source)
|
|
86
|
+
return ProgramTranslation(script, TranslationReport(tuple(rows), name), name, ops, pages, tuple(functions), dict(given),
|
|
87
|
+
arguments, sources, where)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _given(translator: Translator, objects: Any) -> dict[str, Any]:
|
|
91
|
+
"""The objects given to the translation, registered: models as models read, Datasets as pages."""
|
|
92
|
+
import keyword
|
|
93
|
+
|
|
94
|
+
from pymetrix import Dataset
|
|
95
|
+
from pymetrix.errors import SpecificationError
|
|
96
|
+
from pymetrix.models import Model
|
|
97
|
+
|
|
98
|
+
from .models import _Model, _Scenario
|
|
99
|
+
|
|
100
|
+
out: dict[str, Any] = {}
|
|
101
|
+
for key, value in dict(objects or {}).items():
|
|
102
|
+
var = str(key).lower()
|
|
103
|
+
if not var.isidentifier() or keyword.iskeyword(var) or var in translator.public:
|
|
104
|
+
raise SpecificationError(f"objects: {key!r} is not a name the script can use (a Python word or a pymetrix name)")
|
|
105
|
+
translator.taken[var] = f"given {var}"
|
|
106
|
+
model = value if isinstance(value, Model) else getattr(value, "model", None)
|
|
107
|
+
if isinstance(model, Model):
|
|
108
|
+
m = _Model(var, var, None, dirty=False, read=True, endogenous=list(model.endogenous), solving=var if model is value else "")
|
|
109
|
+
if not m.solving:
|
|
110
|
+
m.solving, _ = translator._name(f"{var}_model", f"model {var}_model")
|
|
111
|
+
m.given_code = f"{m.solving} = {var}.model"
|
|
112
|
+
m.scenarios["baseline"] = _Scenario("baseline", "_0")
|
|
113
|
+
m.given = True
|
|
114
|
+
translator.models[var] = m
|
|
115
|
+
translator.types[var] = "model"
|
|
116
|
+
elif isinstance(value, Dataset):
|
|
117
|
+
t = value.time_axis
|
|
118
|
+
freq = None
|
|
119
|
+
if t is not None:
|
|
120
|
+
code = str(t.freq).upper()
|
|
121
|
+
freq = "Y" if code.startswith(("Y", "A")) else code[:1] if code[:1] in ("Q", "M", "W", "D") else None
|
|
122
|
+
periods = value.frame.index.get_level_values(t.name) if t is not None else None
|
|
123
|
+
page = _Page(var, var, freq, set(value.names), first=str(periods.min()) if periods is not None and len(periods) else None,
|
|
124
|
+
last=str(periods.max()) if periods is not None and len(periods) else None)
|
|
125
|
+
translator.pages[var] = page
|
|
126
|
+
translator.current = translator.current or page
|
|
127
|
+
else:
|
|
128
|
+
raise SpecificationError(f"objects: {key!r} is a {type(value).__name__}: models and Datasets are taken")
|
|
129
|
+
out[var] = value
|
|
130
|
+
return out
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _arguments(translator: Translator, args: Any, text: str) -> tuple[list[Any], dict[str, str]]:
|
|
134
|
+
"""The program's arguments as the script's first lines (``arg0 = "us"``), and %0, %1 ... registered as strings
|
|
135
|
+
whose values are known when the program runs (a parameter of the script)."""
|
|
136
|
+
import re
|
|
137
|
+
|
|
138
|
+
if isinstance(args, str):
|
|
139
|
+
args = args.split()
|
|
140
|
+
values = [str(a) for a in (args or ())]
|
|
141
|
+
used = [int(m.group(1)) for m in re.finditer(r"%(\d+)\b", text)]
|
|
142
|
+
count = max([len(values), *(u + 1 for u in used)]) if (values or used) else 0
|
|
143
|
+
ops: list[Any] = []
|
|
144
|
+
arguments: dict[str, str] = {}
|
|
145
|
+
for i in range(count):
|
|
146
|
+
var, _ = translator._name(f"arg{i}", f"argument %{i}")
|
|
147
|
+
value = values[i] if i < len(values) else ""
|
|
148
|
+
translator.py[f"%{i}"] = _Py(var, "string", _UNKNOWN)
|
|
149
|
+
ops.append(Code(f"{var} = {quote(value)} # the program's argument %{i}" + ("" if i < len(values) else ": not given"), (var,)))
|
|
150
|
+
arguments[var] = value
|
|
151
|
+
return ops, arguments
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _flat(outcomes: list[Any]) -> list[Any]:
|
|
155
|
+
out = []
|
|
156
|
+
for o in outcomes:
|
|
157
|
+
if o is None:
|
|
158
|
+
continue
|
|
159
|
+
out.append(o)
|
|
160
|
+
out += _flat(o.children)
|
|
161
|
+
if o.else_outcome is not None:
|
|
162
|
+
out.append(o.else_outcome)
|
|
163
|
+
out += _flat(o.orelse)
|
|
164
|
+
if o.closer is not None:
|
|
165
|
+
out.append(o.closer)
|
|
166
|
+
return out
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _finish(translator: Translator, outcomes: list[Outcome]) -> None:
|
|
170
|
+
"""Models read at their last line when nothing used them; the model reader's problems at their lines; the lines
|
|
171
|
+
that build a model it refused, left out saying why."""
|
|
172
|
+
by_line = {o.statement.line: o for o in outcomes}
|
|
173
|
+
|
|
174
|
+
def add(o: Outcome, note: str) -> None:
|
|
175
|
+
o.reason = "; ".join(x for x in (o.reason, note) if x)
|
|
176
|
+
|
|
177
|
+
for line, ops, note in translator.finish_models():
|
|
178
|
+
o = by_line[line]
|
|
179
|
+
o.ops.extend(ops)
|
|
180
|
+
add(o, note)
|
|
181
|
+
for key, line in translator.building:
|
|
182
|
+
model = translator.models[key]
|
|
183
|
+
o = by_line.get(line)
|
|
184
|
+
if o is not None and model.refused and o.status in (TRANSLATED, NOTE):
|
|
185
|
+
o.status, o.reason, o.ops = LEFT, f"the model {model.eviews} is not read: {model.refused}", []
|
|
186
|
+
for line, problems in translator.refusals.items():
|
|
187
|
+
o = by_line.get(line)
|
|
188
|
+
if o is None or o.status == LEFT and o.reason.startswith("the model"):
|
|
189
|
+
continue
|
|
190
|
+
add(o, "; ".join(problems))
|
|
191
|
+
if o.status == TRANSLATED:
|
|
192
|
+
o.status = NOTE
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _python(outcome: Outcome) -> str:
|
|
196
|
+
from .script import op_code
|
|
197
|
+
|
|
198
|
+
return "\n".join(op_code(op) for op in outcome.ops)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _rows(program: Program, outcomes: list[Any], name: str, file: str = "") -> list[ReportRow]:
|
|
202
|
+
"""A row per line with text of the program (``file`` '' for the main one), and after an ``include`` line, the
|
|
203
|
+
rows of the included program under its name."""
|
|
204
|
+
by_line: dict[int, tuple[Outcome, bool]] = {}
|
|
205
|
+
includes: dict[int, Outcome] = {}
|
|
206
|
+
for o in _flat(outcomes):
|
|
207
|
+
if o.file != file:
|
|
208
|
+
continue
|
|
209
|
+
if o.kind == "include" and o.status in (TRANSLATED, NOTE):
|
|
210
|
+
includes[o.statement.line] = o
|
|
211
|
+
for line in range(o.statement.line, o.statement.last_line + 1):
|
|
212
|
+
by_line.setdefault(line, (o, line == o.statement.line))
|
|
213
|
+
shown = file or name
|
|
214
|
+
rows = []
|
|
215
|
+
for number, raw in enumerate(program.lines, start=1):
|
|
216
|
+
if not raw.strip():
|
|
217
|
+
continue
|
|
218
|
+
found = by_line.get(number)
|
|
219
|
+
if found is None:
|
|
220
|
+
if number in program.comments:
|
|
221
|
+
rows.append(ReportRow(number, TRANSLATED, raw, "# " + program.comments[number], "a comment", shown))
|
|
222
|
+
else:
|
|
223
|
+
rows.append(ReportRow(number, TRANSLATED, raw, "", "", shown))
|
|
224
|
+
continue
|
|
225
|
+
o, first = found
|
|
226
|
+
if first:
|
|
227
|
+
rows.append(ReportRow(number, o.status, raw, _python(o), o.reason, shown))
|
|
228
|
+
else:
|
|
229
|
+
rows.append(ReportRow(number, o.status, raw, "", f"continues line {o.statement.line}", shown))
|
|
230
|
+
inc = includes.get(number) if first else None
|
|
231
|
+
if inc is not None and inc.children is not None:
|
|
232
|
+
sub_program = _program_of(inc)
|
|
233
|
+
if sub_program is not None:
|
|
234
|
+
rows += _rows(sub_program, inc.children, name, _file_of(inc))
|
|
235
|
+
return rows
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _program_of(o: Outcome) -> Program | None:
|
|
239
|
+
return getattr(o, "program", None)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _file_of(o: Outcome) -> str:
|
|
243
|
+
return getattr(o, "included_file", "")
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _imports(text: str) -> list[str]:
|
|
247
|
+
"""pymetrix's names the script's code uses (``Equation(``, ``Dataset.read``, ``read_eviews(``), outside comments."""
|
|
248
|
+
import re
|
|
249
|
+
|
|
250
|
+
import pymetrix
|
|
251
|
+
|
|
252
|
+
public = set(pymetrix.__all__)
|
|
253
|
+
code = "\n".join(line for line in text.split("\n") if not line.lstrip().startswith("#"))
|
|
254
|
+
# strings and trailing comments out, in one pass from the left: a comment's apostrophe (the program's names)
|
|
255
|
+
# does not open a string, and a # inside a string does not start a comment
|
|
256
|
+
code = re.sub(r'"(?:[^"\\\n]|\\.)*"|\'(?:[^\'\\\n]|\\.)*\'|#[^\n]*', lambda m: "" if m.group().startswith("#") else '""', code)
|
|
257
|
+
found = {m.group(1) for m in re.finditer(r"(?<![\w.])([A-Za-z_]\w*)\s*[.(]", code)}
|
|
258
|
+
order = ["Dataset", "Matrix", "Sample"]
|
|
259
|
+
return [n for n in order if n in found and n in public] + sorted(n for n in found if n in public and n not in order)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _script(program: Program, outcomes: list[Any], functions: list[Any], flow: Flow, name: str, uses_bundle: bool,
|
|
263
|
+
top: list[Any], given: dict[str, Any]) -> tuple[str, dict[tuple[str, int], int]]:
|
|
264
|
+
programs: dict[str, Program] = {"": program}
|
|
265
|
+
for o in _flat(outcomes):
|
|
266
|
+
if o.kind == "include" and getattr(o, "program", None) is not None:
|
|
267
|
+
programs[o.included_file] = o.program
|
|
268
|
+
|
|
269
|
+
pairs = []
|
|
270
|
+
for _, d, _ in functions:
|
|
271
|
+
sub = next((x for x in flow.subs.values() if x.var == d.name and x.outcome is not None), None)
|
|
272
|
+
if sub is not None:
|
|
273
|
+
pairs.append((sub.outcome, d))
|
|
274
|
+
text, where = render(outcomes, pairs, programs, [op.code for op in top])
|
|
275
|
+
used = _imports(text)
|
|
276
|
+
title = f"{name}: an EViews program" if name else "An EViews program"
|
|
277
|
+
head = [f'"""{title}, translated by pymetrix-eviews (translate_program).',
|
|
278
|
+
"",
|
|
279
|
+
"Each EViews line is a comment above what it became; lines left out say why. The translation report has a row",
|
|
280
|
+
'for every line."""', ""]
|
|
281
|
+
if used:
|
|
282
|
+
head.append(f"from pymetrix import {', '.join(used)}")
|
|
283
|
+
if uses_bundle:
|
|
284
|
+
head.append("import pymetrix_eviews # noqa: F401 - reads the workfile's bundle (.evbundle)")
|
|
285
|
+
if any("eviews_dates." in line for line in text.split("\n") if not line.lstrip().startswith("#")):
|
|
286
|
+
head.append("import pymetrix_eviews.dates as eviews_dates # EViews's date numbers (@dateval, @datestr, ...)")
|
|
287
|
+
if given:
|
|
288
|
+
kinds = ", ".join(f"{k} (a {type(v).__name__})" for k, v in given.items())
|
|
289
|
+
head += ["", "# The objects the program uses but does not make (in EViews an add-in, a database or another program makes",
|
|
290
|
+
f"# them): give them before running this script, under these names: {kinds}"]
|
|
291
|
+
first = len(head) + 2 # the body starts after the head and a blank line (lines counted from 1)
|
|
292
|
+
return "\n".join(head) + "\n\n" + text + "\n", {k: first + i for k, i in where.items()}
|