pymetrix 0.1.0a20__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.
Files changed (350) hide show
  1. pymetrix/__init__.py +187 -0
  2. pymetrix/_api.py +286 -0
  3. pymetrix/_capture.py +200 -0
  4. pymetrix/_lazy.py +39 -0
  5. pymetrix/_micro.py +79 -0
  6. pymetrix/_planned.py +13 -0
  7. pymetrix/_processes.py +113 -0
  8. pymetrix/_random.py +119 -0
  9. pymetrix/_serial.py +41 -0
  10. pymetrix/_version.py +1 -0
  11. pymetrix/adapters/__init__.py +34 -0
  12. pymetrix/adapters/arch.py +79 -0
  13. pymetrix/adapters/base.py +318 -0
  14. pymetrix/adapters/linearmodels.py +60 -0
  15. pymetrix/adapters/native.py +20 -0
  16. pymetrix/adapters/sklearn.py +53 -0
  17. pymetrix/adapters/statsmodels.py +221 -0
  18. pymetrix/ardl.py +301 -0
  19. pymetrix/arima.py +588 -0
  20. pymetrix/backend.py +27 -0
  21. pymetrix/bma.py +260 -0
  22. pymetrix/build.py +67 -0
  23. pymetrix/bvar.py +712 -0
  24. pymetrix/bvar_hierarchical.py +374 -0
  25. pymetrix/bvar_sv.py +307 -0
  26. pymetrix/calls.py +538 -0
  27. pymetrix/clogit.py +354 -0
  28. pymetrix/clogit_effects.py +469 -0
  29. pymetrix/codec.py +331 -0
  30. pymetrix/cointegrating_regression.py +371 -0
  31. pymetrix/coming_from.py +354 -0
  32. pymetrix/commands/__init__.py +55 -0
  33. pymetrix/commands/ardl.py +91 -0
  34. pymetrix/commands/arima.py +205 -0
  35. pymetrix/commands/breaks.py +63 -0
  36. pymetrix/commands/builtin.py +4069 -0
  37. pymetrix/commands/code.py +71 -0
  38. pymetrix/commands/contributions.py +61 -0
  39. pymetrix/commands/data_edit.py +237 -0
  40. pymetrix/commands/data_tools.py +293 -0
  41. pymetrix/commands/disaggregation.py +222 -0
  42. pymetrix/commands/events.py +139 -0
  43. pymetrix/commands/factors.py +137 -0
  44. pymetrix/commands/figures.py +1375 -0
  45. pymetrix/commands/forecast_evaluation.py +146 -0
  46. pymetrix/commands/forecasting.py +403 -0
  47. pymetrix/commands/inference.py +502 -0
  48. pymetrix/commands/markov.py +85 -0
  49. pymetrix/commands/matrices.py +432 -0
  50. pymetrix/commands/menus.py +258 -0
  51. pymetrix/commands/micro.py +469 -0
  52. pymetrix/commands/midas.py +62 -0
  53. pymetrix/commands/missing.py +71 -0
  54. pymetrix/commands/model_irf.py +81 -0
  55. pymetrix/commands/model_source.py +57 -0
  56. pymetrix/commands/model_tools.py +345 -0
  57. pymetrix/commands/nonparametric.py +107 -0
  58. pymetrix/commands/nowcast.py +413 -0
  59. pymetrix/commands/occbin.py +141 -0
  60. pymetrix/commands/panel.py +293 -0
  61. pymetrix/commands/perturbation.py +44 -0
  62. pymetrix/commands/policy.py +122 -0
  63. pymetrix/commands/project.py +715 -0
  64. pymetrix/commands/projections.py +174 -0
  65. pymetrix/commands/registry.py +189 -0
  66. pymetrix/commands/report.py +201 -0
  67. pymetrix/commands/samples.py +186 -0
  68. pymetrix/commands/seasonal.py +128 -0
  69. pymetrix/commands/selection.py +259 -0
  70. pymetrix/commands/session.py +1361 -0
  71. pymetrix/commands/statespace.py +367 -0
  72. pymetrix/commands/sweeps.py +215 -0
  73. pymetrix/commands/systems.py +91 -0
  74. pymetrix/commands/treatment.py +323 -0
  75. pymetrix/commands/var_extra.py +499 -0
  76. pymetrix/connectors.py +386 -0
  77. pymetrix/count_series.py +321 -0
  78. pymetrix/data/__init__.py +5 -0
  79. pymetrix/data/axes.py +28 -0
  80. pymetrix/data/coerce.py +85 -0
  81. pymetrix/data/conditions.py +209 -0
  82. pymetrix/data/dataset.py +1482 -0
  83. pymetrix/data/derived.py +187 -0
  84. pymetrix/data/each.py +231 -0
  85. pymetrix/data/sample.py +228 -0
  86. pymetrix/data/validate.py +174 -0
  87. pymetrix/datasets/__init__.py +80 -0
  88. pymetrix/datasets/anes96.parquet +0 -0
  89. pymetrix/datasets/card.parquet +0 -0
  90. pymetrix/datasets/grunfeld.parquet +0 -0
  91. pymetrix/datasets/jobtraining.parquet +0 -0
  92. pymetrix/datasets/mroz.parquet +0 -0
  93. pymetrix/datasets/nile.parquet +0 -0
  94. pymetrix/datasets/policy_panel.parquet +0 -0
  95. pymetrix/datasets/randhie.parquet +0 -0
  96. pymetrix/datasets/rd_sample.parquet +0 -0
  97. pymetrix/datasets/sample_macro.parquet +0 -0
  98. pymetrix/datasets/sample_monthly.parquet +0 -0
  99. pymetrix/datasets/synth_panel.parquet +0 -0
  100. pymetrix/datasets/wage_panel.parquet +0 -0
  101. pymetrix/demos.py +107 -0
  102. pymetrix/diffusion.py +106 -0
  103. pymetrix/disaggregation.py +610 -0
  104. pymetrix/disclosure.py +171 -0
  105. pymetrix/dml.py +380 -0
  106. pymetrix/errors.py +51 -0
  107. pymetrix/estimation/__init__.py +48 -0
  108. pymetrix/estimation/bayes_equation.py +405 -0
  109. pymetrix/estimation/covariance.py +80 -0
  110. pymetrix/estimation/criteria.py +161 -0
  111. pymetrix/estimation/design.py +268 -0
  112. pymetrix/estimation/direct.py +385 -0
  113. pymetrix/estimation/dynpanel.py +330 -0
  114. pymetrix/estimation/equation.py +373 -0
  115. pymetrix/estimation/families.py +81 -0
  116. pymetrix/estimation/fitted.py +342 -0
  117. pymetrix/estimation/gmm.py +735 -0
  118. pymetrix/estimation/lag_search.py +101 -0
  119. pymetrix/estimation/limited.py +711 -0
  120. pymetrix/estimation/methods.py +582 -0
  121. pymetrix/estimation/ml.py +333 -0
  122. pymetrix/estimation/numdiff.py +53 -0
  123. pymetrix/estimation/params.py +105 -0
  124. pymetrix/estimation/priors.py +210 -0
  125. pymetrix/estimation/quantile.py +198 -0
  126. pymetrix/estimation/registry.py +37 -0
  127. pymetrix/estimation/regression_extras.py +438 -0
  128. pymetrix/estimation/restrictions.py +131 -0
  129. pymetrix/estimation/robust.py +204 -0
  130. pymetrix/estimation/rolling.py +160 -0
  131. pymetrix/estimation/timeseries.py +784 -0
  132. pymetrix/ets.py +248 -0
  133. pymetrix/exercises/__init__.py +971 -0
  134. pymetrix/exercises/__main__.py +8 -0
  135. pymetrix/exercises/cli.py +251 -0
  136. pymetrix/expr/__init__.py +23 -0
  137. pymetrix/expr/compile.py +277 -0
  138. pymetrix/expr/diff.py +121 -0
  139. pymetrix/expr/evaluate.py +142 -0
  140. pymetrix/expr/functions.py +454 -0
  141. pymetrix/expr/nodes.py +342 -0
  142. pymetrix/expr/parser.py +345 -0
  143. pymetrix/ext/__init__.py +6 -0
  144. pymetrix/ext/arch.py +482 -0
  145. pymetrix/ext/browse_folders.py +377 -0
  146. pymetrix/ext/connector_search.py +315 -0
  147. pymetrix/ext/connectors.py +364 -0
  148. pymetrix/ext/dataflow_groups.py +160 -0
  149. pymetrix/ext/linearmodels.py +396 -0
  150. pymetrix/ext/sdmx_structure.py +182 -0
  151. pymetrix/ext/sklearn.py +824 -0
  152. pymetrix/extension.py +264 -0
  153. pymetrix/factors.py +344 -0
  154. pymetrix/favar.py +295 -0
  155. pymetrix/figure_code.py +751 -0
  156. pymetrix/figure_properties.py +152 -0
  157. pymetrix/figure_style.py +279 -0
  158. pymetrix/figures.py +3215 -0
  159. pymetrix/filters.py +390 -0
  160. pymetrix/forecasting.py +1066 -0
  161. pymetrix/forms.py +441 -0
  162. pymetrix/garch_in_mean.py +86 -0
  163. pymetrix/growth_at_risk.py +241 -0
  164. pymetrix/help.py +2058 -0
  165. pymetrix/historical_extra.py +314 -0
  166. pymetrix/howto/__init__.py +108 -0
  167. pymetrix/howto/bring-in-an-iris-or-dynare-model.md +139 -0
  168. pymetrix/howto/cointegration-in-a-short-sample.md +97 -0
  169. pymetrix/howto/estimate-and-test-an-equation.md +97 -0
  170. pymetrix/identification_extra.py +286 -0
  171. pymetrix/interactive_fe.py +309 -0
  172. pymetrix/interop.py +304 -0
  173. pymetrix/io/__init__.py +21 -0
  174. pymetrix/io/parquet.py +100 -0
  175. pymetrix/io/registry.py +235 -0
  176. pymetrix/io/tabular.py +45 -0
  177. pymetrix/jdemetra.py +28 -0
  178. pymetrix/markov.py +206 -0
  179. pymetrix/matrix.py +922 -0
  180. pymetrix/matrix_expr.py +265 -0
  181. pymetrix/mcp_server.py +425 -0
  182. pymetrix/metadata.py +263 -0
  183. pymetrix/midas.py +274 -0
  184. pymetrix/models/__init__.py +28 -0
  185. pymetrix/models/_kalman_compiled.py +59 -0
  186. pymetrix/models/_kalman_kernels.py +242 -0
  187. pymetrix/models/bayes.py +1041 -0
  188. pymetrix/models/bayes_nuts.py +188 -0
  189. pymetrix/models/calibrate.py +124 -0
  190. pymetrix/models/control.py +283 -0
  191. pymetrix/models/covariance.py +115 -0
  192. pymetrix/models/decompose.py +247 -0
  193. pymetrix/models/dsge_var.py +763 -0
  194. pymetrix/models/dynare.py +760 -0
  195. pymetrix/models/dynare_macros.py +632 -0
  196. pymetrix/models/estimation.py +1151 -0
  197. pymetrix/models/eviews.py +1991 -0
  198. pymetrix/models/fast.py +124 -0
  199. pymetrix/models/growth.py +142 -0
  200. pymetrix/models/iris.py +535 -0
  201. pymetrix/models/kalman_score.py +780 -0
  202. pymetrix/models/linear.py +827 -0
  203. pymetrix/models/links.py +285 -0
  204. pymetrix/models/measurement.py +365 -0
  205. pymetrix/models/model.py +1254 -0
  206. pymetrix/models/moments.py +137 -0
  207. pymetrix/models/occbin.py +588 -0
  208. pymetrix/models/occbin_filter.py +649 -0
  209. pymetrix/models/ordering.py +218 -0
  210. pymetrix/models/particle.py +619 -0
  211. pymetrix/models/perfect_foresight.py +521 -0
  212. pymetrix/models/perturbation.py +281 -0
  213. pymetrix/models/plans.py +392 -0
  214. pymetrix/models/policy.py +257 -0
  215. pymetrix/models/regimes.py +829 -0
  216. pymetrix/models/safe_eval.py +118 -0
  217. pymetrix/models/scenario.py +54 -0
  218. pymetrix/models/solution.py +143 -0
  219. pymetrix/models/solvers.py +406 -0
  220. pymetrix/models/source.py +1622 -0
  221. pymetrix/models/stochastic.py +741 -0
  222. pymetrix/models/system.py +490 -0
  223. pymetrix/models/templates.py +206 -0
  224. pymetrix/models/writers.py +653 -0
  225. pymetrix/ms_var.py +376 -0
  226. pymetrix/ms_var_bands.py +186 -0
  227. pymetrix/ms_var_em.py +400 -0
  228. pymetrix/nonlinear.py +303 -0
  229. pymetrix/nonlinear_extra.py +240 -0
  230. pymetrix/nonparametric.py +611 -0
  231. pymetrix/notation.py +313 -0
  232. pymetrix/nowcast.py +482 -0
  233. pymetrix/nuts.py +532 -0
  234. pymetrix/output.py +182 -0
  235. pymetrix/panel_time_series.py +309 -0
  236. pymetrix/panelvar.py +392 -0
  237. pymetrix/plugin_template.py +394 -0
  238. pymetrix/plugins.py +716 -0
  239. pymetrix/progress.py +72 -0
  240. pymetrix/projections.py +235 -0
  241. pymetrix/proxy.py +202 -0
  242. pymetrix/quantile_var.py +180 -0
  243. pymetrix/recessions.py +96 -0
  244. pymetrix/reconciliation.py +274 -0
  245. pymetrix/recovery.py +108 -0
  246. pymetrix/report.py +465 -0
  247. pymetrix/results.py +306 -0
  248. pymetrix/saved.py +359 -0
  249. pymetrix/schema.py +205 -0
  250. pymetrix/seasonal.py +325 -0
  251. pymetrix/selection.py +291 -0
  252. pymetrix/shiftshare.py +275 -0
  253. pymetrix/simulation.py +168 -0
  254. pymetrix/simulation_estimators.py +311 -0
  255. pymetrix/smooth_lp.py +207 -0
  256. pymetrix/smooth_transition.py +253 -0
  257. pymetrix/spatial.py +210 -0
  258. pymetrix/spectral.py +319 -0
  259. pymetrix/staggered.py +431 -0
  260. pymetrix/statespace.py +1471 -0
  261. pymetrix/stats/__init__.py +53 -0
  262. pymetrix/stats/adf_arrays.py +318 -0
  263. pymetrix/stats/base.py +198 -0
  264. pymetrix/stats/breaks.py +320 -0
  265. pymetrix/stats/compare.py +75 -0
  266. pymetrix/stats/data_tests.py +476 -0
  267. pymetrix/stats/density.py +152 -0
  268. pymetrix/stats/equation_tests.py +715 -0
  269. pymetrix/stats/evaluation.py +468 -0
  270. pymetrix/stats/forecast.py +31 -0
  271. pymetrix/stats/panel_cointegration.py +489 -0
  272. pymetrix/stats/panel_tests.py +641 -0
  273. pymetrix/stats/quandt_andrews.npz +0 -0
  274. pymetrix/stats/stability.py +138 -0
  275. pymetrix/stats/timeseries.py +112 -0
  276. pymetrix/stats/unit_root_extra.py +293 -0
  277. pymetrix/stats/var_tests.py +175 -0
  278. pymetrix/structural.py +320 -0
  279. pymetrix/summary_layout.py +171 -0
  280. pymetrix/sweeps.py +486 -0
  281. pymetrix/synthdid.py +210 -0
  282. pymetrix/systems.py +725 -0
  283. pymetrix/testing.py +550 -0
  284. pymetrix/themes.py +119 -0
  285. pymetrix/threads.py +115 -0
  286. pymetrix/toolkit.py +227 -0
  287. pymetrix/treatment.py +597 -0
  288. pymetrix/trust.py +78 -0
  289. pymetrix/tvpvar.py +351 -0
  290. pymetrix/ui/__init__.py +1 -0
  291. pymetrix/ui/active_window.py +243 -0
  292. pymetrix/ui/advanced_section.py +359 -0
  293. pymetrix/ui/chart_click.py +247 -0
  294. pymetrix/ui/chart_edit.py +386 -0
  295. pymetrix/ui/chart_format.py +305 -0
  296. pymetrix/ui/chart_look.py +56 -0
  297. pymetrix/ui/collector.py +65 -0
  298. pymetrix/ui/console_qt.py +164 -0
  299. pymetrix/ui/demo_chooser.py +112 -0
  300. pymetrix/ui/dialog_checks.py +259 -0
  301. pymetrix/ui/editor_qt.py +745 -0
  302. pymetrix/ui/exercises_qt.py +499 -0
  303. pymetrix/ui/extend.py +6 -0
  304. pymetrix/ui/fit.py +753 -0
  305. pymetrix/ui/form_keys.py +91 -0
  306. pymetrix/ui/formula_check.py +207 -0
  307. pymetrix/ui/help_qt.py +294 -0
  308. pymetrix/ui/history_qt.py +213 -0
  309. pymetrix/ui/icons.py +349 -0
  310. pymetrix/ui/jupyter.py +258 -0
  311. pymetrix/ui/keys.py +68 -0
  312. pymetrix/ui/matrix_qt.py +312 -0
  313. pymetrix/ui/messages.py +150 -0
  314. pymetrix/ui/metrics.py +122 -0
  315. pymetrix/ui/model_editor_qt.py +654 -0
  316. pymetrix/ui/next_steps.py +103 -0
  317. pymetrix/ui/palette.py +175 -0
  318. pymetrix/ui/plugins_qt.py +269 -0
  319. pymetrix/ui/qt.py +5559 -0
  320. pymetrix/ui/render.py +74 -0
  321. pymetrix/ui/report_qt.py +179 -0
  322. pymetrix/ui/series_browser_qt.py +820 -0
  323. pymetrix/ui/sheet_qt.py +863 -0
  324. pymetrix/ui/shortcut.py +122 -0
  325. pymetrix/ui/stats_panel.py +209 -0
  326. pymetrix/ui/text_size.py +144 -0
  327. pymetrix/ui/theme.py +168 -0
  328. pymetrix/ui/timers.py +42 -0
  329. pymetrix/ui/view_switcher.py +296 -0
  330. pymetrix/ui/workspaces.py +304 -0
  331. pymetrix/ui/zoom.py +46 -0
  332. pymetrix/var.py +1518 -0
  333. pymetrix/var_conditions.py +360 -0
  334. pymetrix/var_decompositions.py +78 -0
  335. pymetrix/varma.py +204 -0
  336. pymetrix/vecm.py +718 -0
  337. pymetrix/vecm_restrictions.py +155 -0
  338. pymetrix/views.py +1558 -0
  339. pymetrix/wording.py +1231 -0
  340. pymetrix/zerosign.py +254 -0
  341. pymetrix-0.1.0a20.dist-info/METADATA +136 -0
  342. pymetrix-0.1.0a20.dist-info/RECORD +350 -0
  343. pymetrix-0.1.0a20.dist-info/WHEEL +4 -0
  344. pymetrix-0.1.0a20.dist-info/entry_points.txt +5 -0
  345. pymetrix-0.1.0a20.dist-info/licenses/LICENSE +28 -0
  346. pymetrix-0.1.0a20.dist-info/licenses/THIRD-PARTY-NOTICES.md +124 -0
  347. pymetrix_app/__init__.py +189 -0
  348. pymetrix_app/__main__.py +5 -0
  349. pymetrix_app/icons/pymetrix.ico +0 -0
  350. pymetrix_app/icons/pymetrix.png +0 -0
pymetrix/__init__.py ADDED
@@ -0,0 +1,187 @@
1
+ """pymetrix: econometrics and economic modelling.
2
+
3
+ Four verbs cover the package: ``fit`` (specification + data -> fitted object),
4
+ ``solve`` (model + data -> Solution), ``predict``/``forecast``, and
5
+ ``linearize``/``steady_state``.
6
+
7
+ Only working features are exported here. Planned ones (GMM, quantile regression,
8
+ principal components and factor models, Monte Carlo, sign restrictions) exist in
9
+ their modules as placeholders that raise ``NotImplementedError`` naming the build stage.
10
+ """
11
+
12
+ from ._version import __version__
13
+ from .data import CodeList, Dataset, EntityAxis, Sample, TimeAxis
14
+ from .estimation import (
15
+ ARMA,
16
+ GARCH,
17
+ GMM,
18
+ FittedGMM,
19
+ MomentGMM,
20
+ IV,
21
+ ML,
22
+ OLS,
23
+ Bayes,
24
+ Cluster,
25
+ Draws,
26
+ Equation,
27
+ FittedEquation,
28
+ Heckman,
29
+ Logit,
30
+ Multinomial,
31
+ NegativeBinomial,
32
+ OrderedLogit,
33
+ OrderedProbit,
34
+ PointEstimate,
35
+ Poisson,
36
+ Probit,
37
+ Quantile,
38
+ RobustLS,
39
+ Tobit,
40
+ ZeroInflatedPoisson,
41
+ marginal_effects,
42
+ RollingFit,
43
+ quantile_process,
44
+ )
45
+ from .filters import HP, BaxterKing, ChristianoFitzgerald, Hamilton, MovingAverage
46
+ from .seasonal import STL, Classical
47
+ from .forecasting import Backtest, ForecastRound, ForecastStore, backtest, combine_forecasts, diebold_mariano
48
+ from .report import Report, report_templates
49
+ from .demos import demo, demos
50
+ from .themes import Theme, get_theme, set_theme, themes
51
+ from .threads import get_blas_threads, set_blas_threads
52
+ from ._random import get_random_generator, random_generator, set_random_generator
53
+ from .disaggregation import FittedDisaggregation, TemporalDisaggregation, aggregation_matrix
54
+ from .reconciliation import Reconciliation, reconcile
55
+ from .models.dynare import DynareModel, read_mod
56
+ from .models.iris import read_iris
57
+ from .models.eviews import eviews_series, read_eviews, read_eviews_sspace, read_eviews_xml
58
+ from .models.bayes import Identification, Posterior
59
+ from .models.dsge_var import FittedDSGEVAR
60
+ from .sweeps import ScenarioSet, SweepResult, compare_solutions, scenarios, sweep
61
+ from .models.occbin import OccBinPath, occbin
62
+ from .models.occbin_filter import OccBinFilter, occbin_filter
63
+ from .models.regimes import Regime, RegimeFilter, parse_regimes, regime_filter
64
+ from .models.links import Link
65
+ from .models.source import ModelSource
66
+ from .models.writers import export_model
67
+ from .models.perturbation import SecondOrderSolution, second_order
68
+ from .models.particle import ParticleFilter, particle_filter
69
+ from .models.policy import OptimalPolicy, OSRResult, optimal_policy, osr
70
+ from .models.control import OptimalControl, optimal_control
71
+ from .errors import DataError, NotFoundError, PlannedError, PyMetrixError, SpecificationError
72
+ from .stats.breaks import StructuralBreaks, bai_perron
73
+ from .treatment import DiD, RDD, EventStudy, SyntheticControl, TreatmentEffect, did, event_study, rdd, synthetic_control, treatment_effect
74
+ from .estimation import priors
75
+ from .midas import MIDAS, FittedMIDAS
76
+ from .nowcast import Bridge, DynamicFactor, FittedBridge, FittedDynamicFactor, News
77
+ from . import nowcast # nowcast.combine and the ragged-edge tools, as scripts name them
78
+ from .factors import PCA, FactorModel, FittedFactorModel, FittedPCA
79
+ from .ardl import ARDL, FittedARDL
80
+ from .markov import FittedMarkovSwitching, MarkovSwitching
81
+ from .metadata import Adjustment, DatasetMeta, Measure, Param, Prices, Provenance, Role, Status, Variable, Vintage
82
+ from .models import Fallback, FittedModel, GaussSeidel, LinearModel, MeasurementMap, Model, ModelCheck, ModelError, ModelSystem, Newton, Parameter, ParameterSet, PerfectForesight, FirstOrder, Scenario, Solution, templates
83
+ from .statespace import StateSpaceSystem
84
+ from .systems import FIML
85
+ from .systems import SUR, FittedSystem, System, SystemOLS, ThreeSLS, TwoSLS
86
+ from .bvar import FittedBVAR, Minnesota, NormalWishart
87
+ from .var_conditions import Bounds
88
+ from .bvar_hierarchical import GLP
89
+ from .statespace import FittedStateSpace, StateSpace, UnobservedComponents
90
+ from .ets import ExponentialSmoothing, FittedExponentialSmoothing
91
+ from .matrix import Matrix
92
+ from .arima import SARIMA, STLForecast, Theta, FittedSARIMA, FittedSTLForecast, FittedTheta
93
+ from .bma import BMA, FittedBMA
94
+ from .nonlinear import FittedThresholdAR, ThresholdAR, terasvirta
95
+ from .smooth_transition import FittedSmoothTransitionAR, SmoothTransitionAR
96
+ from .proxy import ProxySVAR
97
+ from .tvpvar import TVPVAR, FittedTVPVAR
98
+ from .bvar_sv import BVARSV, FittedBVARSV
99
+ from .favar import FittedFAVAR, favar
100
+ from .ms_var import MSVAR, FittedMSVAR
101
+ from .quantile_var import FittedQuantileVAR, QuantileVAR
102
+ from .spatial import SpatialModel, knn_weights, spatial_diagnostics, spatial_regression
103
+ from .spectral import CrossSpectrum, FittedARFIMA, Spectrum, arfima, cross_spectrum, gph, local_whittle, periodogram, spectrum
104
+ from .structural import AB, StructuralEstimate
105
+ from .identification_extra import HeteroskedasticitySVAR, MaxShare
106
+ from .estimation.direct import ols
107
+ from .estimation.regression_extras import CochraneOrcutt, MultiplicativeHeteroskedasticity, PraisWinsten, StochasticFrontier, cox_test, j_test
108
+ from .nonparametric import (KernelDensity, KernelRegression, PartiallyLinear, SemiparametricGARCH, kde, kernel_regression,
109
+ nonparametric_autoregression, partially_linear, semiparametric_garch)
110
+ from .count_series import SeriesModel, acd, ach, inar, poisson_autoregression
111
+ from .garch_in_mean import garch_in_mean
112
+ from .nonlinear_extra import FittedThresholdVAR, bilinear, threshold_var
113
+ from .varma import FittedVARMA, varma
114
+ from .synthdid import SyntheticDiD, synthetic_did
115
+ from .cointegrating_regression import CointegratingRegression, cointegrating_regression, gregory_hansen
116
+ from .panel_time_series import PanelMeanGroup, PooledMeanGroup, cce, mean_group, pooled_mean_group
117
+ from .diffusion import diffusion
118
+ from .estimation.gmm import MinimumDistance, anderson_rubin, anderson_rubin_set, c_test, minimum_distance, stock_wright
119
+ from .simulation import MonteCarlo, MonteCarloResult
120
+ from .simulation_estimators import SimulationEstimate, efficient_method_of_moments, indirect_inference, simulated_moments
121
+ from .staggered import BaconDecomposition, StaggeredDiD, bacon_decomposition, staggered_did
122
+ from .dml import FittedDoubleML, double_ml
123
+ from .shiftshare import FittedShiftShare, shift_share
124
+ from .interactive_fe import FittedInteractiveFE, interactive_fe
125
+ from .clogit import FittedConditionalLogit, choice_logit, conditional_logit
126
+ from .clogit_effects import ConditionalLogitEffects, clogit_effects
127
+ from .projections import FittedLocalProjection, LocalProjection
128
+ from .smooth_lp import FittedSmoothLocalProjection
129
+ from .growth_at_risk import GrowthAtRisk, growth_at_risk
130
+ from .var import FEVD, IRF, VAR, Cholesky, FittedVAR, LongRun, Restricted, SignRestrictions
131
+ from .vecm import VECM, FittedVECM, JohansenResult, johansen
132
+ from .output import Figure, Table, show
133
+ from .data.coerce import as_dataset
134
+ from .selection import as_selection, fit_each, test_each
135
+ from .figures import coefficient_figure, heatmap_figure, house_style, set_house_style, surface_figure
136
+ from .saved import SavedResult, load_result, save_result
137
+ from .stats import TestResult, binary_scores, compare, forecast_accuracy, model_confidence_set, spa
138
+ from .plugins import PluginInfo, plugin_table, registry
139
+ from .selection import Results, Selection
140
+ from . import toolkit
141
+
142
+ # bundled reference plugins (they register their methods, variances and tests on import)
143
+ from .ext.arch import APARCH, EGARCH, FIGARCH, TARCH
144
+ from .ext.linearmodels import IVGMM, LIML, Between, FamaMacBeth, FirstDifference, RandomEffects
145
+ from .ext.sklearn import Bagging, ElasticNet, FittedLearner, GradientBoosting, Lasso, NearestNeighbours, NeuralNetwork, RandomForest, Ridge
146
+ from .ext.connectors import register_sdmx_provider # and the fred://, worldbank:// and sdmx:// readers
147
+ from .views import _attach_all, figure_of
148
+ from .recessions import recession_series, recessions
149
+
150
+ dataset = as_dataset # pymetrix.dataset(df): a plain DataFrame as a Dataset
151
+
152
+ _attach_all() # every result type with views: to_frame(view) and a notebook display (pymetrix.views)
153
+ del _attach_all
154
+
155
+ __all__ = [
156
+ "FittedDoubleML", "double_ml", "FittedShiftShare", "shift_share", "FittedInteractiveFE", "interactive_fe", "FittedConditionalLogit",
157
+ "choice_logit", "conditional_logit", "ConditionalLogitEffects", "clogit_effects",
158
+ "VECM", "FittedVECM", "JohansenResult", "johansen", "FEVD", "IRF", "Cholesky", "FittedVAR", "LongRun", "Restricted", "SignRestrictions", "HP", "ARDL", "FittedARDL", "Matrix", "SARIMA", "FittedSARIMA", "Theta", "FittedTheta", "STLForecast", "FittedSTLForecast", "MarkovSwitching", "FittedMarkovSwitching", "MIDAS", "FittedMIDAS", "Bridge", "FittedBridge", "DynamicFactor", "FittedDynamicFactor", "News", "nowcast", "PCA", "FittedPCA", "FactorModel", "FittedFactorModel", "read_mod", "DynareModel", "read_iris", "read_eviews", "read_eviews_xml", "read_eviews_sspace", "eviews_series", "Posterior", "Identification", "priors", "sweep", "scenarios", "compare_solutions", "SweepResult", "ScenarioSet", "occbin", "OccBinPath", "occbin_filter", "OccBinFilter", "Regime", "RegimeFilter", "parse_regimes", "regime_filter", "Link", "ModelSource", "export_model", "second_order", "SecondOrderSolution", "particle_filter", "ParticleFilter", "optimal_policy", "osr", "OptimalPolicy", "OSRResult", "optimal_control", "OptimalControl", "PyMetrixError", "DataError", "NotFoundError", "SpecificationError", "PlannedError", "Quantile", "quantile_process", "RobustLS", "Report", "report_templates", "demo", "demos", "Theme", "get_theme", "set_theme", "themes", "get_blas_threads", "set_blas_threads", "get_random_generator", "set_random_generator", "random_generator", "TemporalDisaggregation", "FittedDisaggregation", "aggregation_matrix", "reconcile", "Reconciliation", "register_sdmx_provider", "Backtest", "ForecastRound", "ForecastStore", "backtest", "combine_forecasts", "diebold_mariano", "ExponentialSmoothing", "FittedExponentialSmoothing", "BMA", "FittedBMA", "ThresholdAR", "FittedThresholdAR", "terasvirta", "Bagging", "ElasticNet", "FittedLearner", "GradientBoosting", "Lasso", "NearestNeighbours", "NeuralNetwork", "RandomForest", "Ridge", "STL", "Classical", "BaxterKing", "ChristianoFitzgerald", "Hamilton", "MovingAverage",
159
+ "APARCH", "ARMA", "EGARCH", "FIGARCH", "TARCH", "GARCH", "IVGMM", "LIML", "RandomEffects", "Between", "FirstDifference", "FamaMacBeth", "IV", "GMM", "MomentGMM", "FittedGMM", "ML", "OLS", "ols", "bai_perron", "StructuralBreaks", "did", "DiD", "event_study", "EventStudy", "rdd", "RDD", "treatment_effect", "TreatmentEffect", "synthetic_control", "SyntheticControl", "Heckman", "Multinomial", "NegativeBinomial", "OrderedLogit", "OrderedProbit", "Tobit", "ZeroInflatedPoisson", "marginal_effects", "VAR", "Bounds", "Adjustment", "Bayes", "Cluster",
160
+ "as_dataset", "dataset", "as_selection", "fit_each", "test_each", "CodeList", "Dataset", "DatasetMeta", "Sample", "Draws", "EntityAxis", "Equation", "Figure", "figure_of", "coefficient_figure", "heatmap_figure", "surface_figure", "house_style", "set_house_style", "recessions", "recession_series", "FittedEquation", "SavedResult", "load_result", "save_result", "Fallback", "GaussSeidel", "LinearModel", "Logit", "Measure", "Model", "ModelCheck", "ModelError", "ModelSystem", "Parameter", "ParameterSet", "MeasurementMap", "StateSpaceSystem", "FittedModel", "FittedDSGEVAR", "templates",
161
+ "Newton", "Param", "PerfectForesight", "FirstOrder", "PointEstimate", "Poisson", "Prices", "Probit",
162
+ "Provenance", "Role", "RollingFit", "Scenario", "Solution", "StateSpace", "FittedStateSpace", "UnobservedComponents", "LocalProjection", "FittedLocalProjection", "FittedSmoothLocalProjection", "SmoothTransitionAR", "FittedSmoothTransitionAR", "ProxySVAR", "TVPVAR", "FittedTVPVAR", "BVARSV", "FittedBVARSV", "FittedFAVAR", "favar", "MSVAR", "FittedMSVAR", "FittedQuantileVAR", "QuantileVAR", "SpatialModel", "knn_weights", "spatial_diagnostics", "spatial_regression", "CrossSpectrum", "FittedARFIMA", "Spectrum", "arfima", "cross_spectrum", "gph", "local_whittle", "periodogram", "spectrum", "AB", "StructuralEstimate", "MaxShare", "HeteroskedasticitySVAR", "CochraneOrcutt", "PraisWinsten", "MultiplicativeHeteroskedasticity", "StochasticFrontier", "j_test", "cox_test", "KernelDensity", "KernelRegression", "PartiallyLinear", "SemiparametricGARCH", "kde", "kernel_regression", "nonparametric_autoregression", "partially_linear", "semiparametric_garch", "SeriesModel", "acd", "ach", "inar", "poisson_autoregression", "garch_in_mean", "FittedThresholdVAR", "bilinear", "threshold_var", "FittedVARMA", "varma", "SyntheticDiD", "synthetic_did", "CointegratingRegression", "cointegrating_regression", "gregory_hansen", "PanelMeanGroup", "PooledMeanGroup", "cce", "mean_group", "pooled_mean_group", "diffusion", "MonteCarlo", "MonteCarloResult", "SimulationEstimate", "MinimumDistance", "minimum_distance", "c_test", "anderson_rubin", "anderson_rubin_set", "stock_wright", "indirect_inference", "simulated_moments", "efficient_method_of_moments", "staggered_did", "StaggeredDiD", "bacon_decomposition", "BaconDecomposition", "growth_at_risk", "GrowthAtRisk", "Status", "System", "FittedSystem", "SUR", "ThreeSLS", "FIML", "TwoSLS", "SystemOLS", "Minnesota", "NormalWishart", "GLP", "FittedBVAR", "Table",
163
+ "Selection", "PluginInfo", "toolkit", "show", "Results", "TestResult", "TimeAxis", "plugin_table", "registry", "Variable", "Vintage", "compare", "forecast_accuracy", "model_confidence_set", "spa", "binary_scores", "__version__",
164
+ ]
165
+
166
+
167
+ # the finance plugin's names, when it is installed (pip install pymetrix[finance]): from pymetrix import value_at_risk
168
+ _FINANCE = ('AbnormalReturns', 'BlackLittermanPosterior', 'CDSCurve', 'FactorModel', 'FittedCopula', 'FittedDCCCopula', 'FittedDNS', 'FittedHAR', 'FittedMGARCH', 'FittedTVCopula', 'FittedVine', 'FittedVolSurface', 'MertonModel', 'OptionValuation', 'Performance', 'Portfolio', 'RiskContributions', 'RiskForecast', 'StrategyBacktest', 'VolatilitySmile', 'YieldCurve', 'abnormal_returns', 'backtest_strategy', 'black_litterman', 'bond_measures', 'cds_curve', 'compare_copulas', 'copula', 'dcc_copula', 'dynamic_nelson_siegel', 'factor_model', 'har', 'heston_price', 'implied_volatility', 'merton', 'merton_point', 'mgarch', 'optimize_portfolio', 'option_price', 'performance', 'realized_measures', 'returns', 'risk_contributions', 'risk_parity_weights', 'tv_copula', 'value_at_risk', 'vine_copula', 'vol_surface', 'yield_curve')
169
+
170
+
171
+ _SEASONAL = ("TramoSeats", "X13") # the pymetrix-seasonal plugin's methods: X-13ARIMA-SEATS and TRAMO-SEATS
172
+
173
+
174
+ def __getattr__(name: str):
175
+ if name in _SEASONAL:
176
+ try:
177
+ import pymetrix_seasonal
178
+ except ImportError:
179
+ raise AttributeError(f'pymetrix.{name} is in the seasonal-adjustment plugin: pip install "pymetrix-seasonal[jdemetra]"') from None
180
+ return getattr(pymetrix_seasonal, name)
181
+ if name in _FINANCE:
182
+ try:
183
+ import pymetrix_finance
184
+ except ImportError:
185
+ raise AttributeError(f"pymetrix.{name} is in the finance plugin: pip install pymetrix[finance]") from None
186
+ return getattr(pymetrix_finance, name)
187
+ raise AttributeError(f"module 'pymetrix' has no attribute {name!r}")
pymetrix/_api.py ADDED
@@ -0,0 +1,286 @@
1
+ """The ``@api`` decorator and call recording, without the command layer (so core modules can import it).
2
+
3
+ See ``pymetrix.calls`` for what a recorded call is.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import functools
9
+ import inspect
10
+ import re
11
+ import threading
12
+ from collections.abc import Callable, Mapping
13
+ from dataclasses import dataclass
14
+ from typing import TYPE_CHECKING, Any
15
+
16
+ from .errors import SpecificationError
17
+
18
+ if TYPE_CHECKING:
19
+ from .calls import Call
20
+
21
+ __all__ = ["API_CALLS", "CallSpec", "Recorder", "api", "call_migration", "recording", "renamed_arguments"]
22
+
23
+ _CALL_ID = re.compile(r"^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$")
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class CallSpec:
28
+ """What ``@api`` knows about a public function: its ID, schema version, plugin and where it lives."""
29
+
30
+ id: str
31
+ version: int
32
+ function: Callable[..., Any] # the undecorated function
33
+ plugin: str
34
+ plugin_version: str
35
+ show: Callable[[Any], Any] | None = None # arguments always written in generated code, even at their default
36
+
37
+ @property
38
+ def kind(self) -> str:
39
+ """``"method"`` (first parameter ``self``), ``"classmethod"`` (``cls``) or ``"function"``."""
40
+ first = next(iter(self.signature.parameters), "")
41
+ return {"self": "method", "cls": "classmethod"}.get(first, "function")
42
+
43
+ @functools.cached_property
44
+ def signature(self) -> inspect.Signature:
45
+ return inspect.signature(self.function)
46
+
47
+ @property
48
+ def owner(self) -> Any:
49
+ """The class a method or classmethod belongs to (None for functions)."""
50
+ if self.kind == "function":
51
+ return None
52
+ import importlib
53
+
54
+ obj: Any = importlib.import_module(self.function.__module__)
55
+ for part in self.function.__qualname__.split(".")[:-1]:
56
+ obj = getattr(obj, part)
57
+ return obj
58
+
59
+ @property
60
+ def name(self) -> str:
61
+ return self.function.__name__
62
+
63
+ def schema(self) -> dict[str, Any]:
64
+ from .schema import json_schema
65
+
66
+ return json_schema(self.function)
67
+
68
+
69
+ API_CALLS: dict[str, CallSpec] = {}
70
+ _MIGRATIONS: dict[tuple[str, int], Callable[[dict[str, Any]], dict[str, Any]]] = {}
71
+
72
+
73
+ def _snake(name: str) -> str:
74
+ return re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "_", name).lower()
75
+
76
+
77
+ def api(id: str | None = None, version: int = 1, show: Callable[[Any], Any] | None = None,
78
+ as_dataset: bool = True) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
79
+ """Make a public function or method a recorded call (see the module docstring). ``id`` defaults to
80
+ ``plugin:class.method`` in lower case (``pymetrix:equation.fit``). ``show(arguments)`` names arguments that
81
+ generated code writes even at their default (``vintage='latest'``). ``as_dataset=False``: a ``data`` argument
82
+ given as plain pandas is passed on as it is, for functions that take arrays rather than a ``Dataset``."""
83
+
84
+ def decorate(fn: Callable[..., Any]) -> Callable[..., Any]:
85
+ from .plugins import current_plugin
86
+
87
+ plugin = current_plugin()
88
+ cid = id or f"{plugin.prefix.replace('-', '_')}:{'.'.join(_snake(p) for p in fn.__qualname__.split('.'))}"
89
+ if not _CALL_ID.match(cid):
90
+ raise SpecificationError(f"call ID {cid!r} must look like 'plugin:name' or 'plugin:class.method' (lower case)")
91
+ known = API_CALLS.get(cid)
92
+ if known is not None and (known.function.__module__, known.function.__qualname__) != (fn.__module__, fn.__qualname__):
93
+ raise SpecificationError(f"call ID {cid!r} is already used by {known.function.__module__}.{known.function.__qualname__}")
94
+ spec = CallSpec(cid, version, fn, plugin.name, plugin.version, show)
95
+ API_CALLS[cid] = spec
96
+ names = list(inspect.signature(fn).parameters)
97
+ data_at = names.index("data") if "data" in names and as_dataset else None # plain DataFrames are accepted wherever data is
98
+
99
+ @functools.wraps(fn)
100
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
101
+ if data_at is not None:
102
+ args, kwargs = _coerce_data(args, kwargs, data_at)
103
+ recorder = _STATE.recorder
104
+ if recorder is None or _STATE.depth:
105
+ return fn(*args, **kwargs)
106
+ _STATE.depth += 1
107
+ try:
108
+ call = recorder.make(spec, args, kwargs)
109
+ result = fn(*args, **kwargs)
110
+ finally:
111
+ _STATE.depth -= 1
112
+ recorder.done(call, result)
113
+ return result
114
+
115
+ wrapper.__api__ = spec # type: ignore[attr-defined]
116
+ return wrapper
117
+
118
+ return decorate
119
+
120
+
121
+ def _coerce_data(args: tuple[Any, ...], kwargs: dict[str, Any], at: int) -> tuple[tuple[Any, ...], dict[str, Any]]:
122
+ import pandas as pd
123
+
124
+ if len(args) > at and isinstance(args[at], (pd.DataFrame, pd.Series)):
125
+ from .data.coerce import as_dataset
126
+
127
+ args = (*args[:at], as_dataset(args[at]), *args[at + 1:])
128
+ elif isinstance(kwargs.get("data"), (pd.DataFrame, pd.Series)):
129
+ from .data.coerce import as_dataset
130
+
131
+ kwargs = {**kwargs, "data": as_dataset(kwargs["data"])}
132
+ return args, kwargs
133
+
134
+
135
+ def call_migration(call_id: str, from_version: int):
136
+ """Register a function turning a call's arguments saved at ``from_version`` into those of the next version."""
137
+
138
+ def decorate(fn: Callable[[dict[str, Any]], dict[str, Any]]) -> Callable[[dict[str, Any]], dict[str, Any]]:
139
+ _MIGRATIONS[(call_id, from_version)] = fn
140
+ return fn
141
+
142
+ return decorate
143
+
144
+
145
+ class _BothNames(SpecificationError, TypeError):
146
+ """An argument given by both its old and its new name: a SpecificationError, and still the TypeError it was."""
147
+
148
+
149
+ def renamed_arguments(**renames: str) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
150
+ """Accept keyword arguments by their old names (old=new), with a DeprecationWarning; both names at once raise a
151
+ SpecificationError (also a TypeError). Put it above ``@api``, so
152
+ the call is recorded under the new names; saved calls with the old names need a ``call_migration``. For a
153
+ settings class, wrap its ``__init__`` and add the old field names to ``codec.FIELD_ALIASES``."""
154
+
155
+ def decorate(fn: Callable[..., Any]) -> Callable[..., Any]:
156
+ name = fn.__qualname__.removesuffix(".__init__") # Scenario(), FittedVAR.proxy_svar()
157
+
158
+ @functools.wraps(fn)
159
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
160
+ for old, new in renames.items():
161
+ if old in kwargs:
162
+ import warnings
163
+
164
+ if new in kwargs:
165
+ raise _BothNames(f"{name}() got both {old!r} and {new!r}; {old!r} is now called {new!r}")
166
+ warnings.warn(f"argument {old!r} of {name}() is now called {new!r}", DeprecationWarning, stacklevel=2)
167
+ kwargs[new] = kwargs.pop(old)
168
+ return fn(*args, **kwargs)
169
+
170
+ return wrapper
171
+
172
+ return decorate
173
+
174
+
175
+ # -- recording --------------------------------------------------------------------------------------------------------
176
+
177
+
178
+ class _State(threading.local):
179
+ def __init__(self) -> None:
180
+ self.recorder: Recorder | None = None
181
+ self.depth = 0 # inside a recorded call: calls it makes are part of it, not steps of their own
182
+
183
+
184
+ _STATE = _State()
185
+
186
+
187
+ class Recorder:
188
+ """Collects the outermost ``@api`` calls made while a session records. ``failed`` says a call could not be
189
+ recorded (an argument that is neither a setting nor a named object), so the code is kept as typed code."""
190
+
191
+ def __init__(self, objects: Mapping[str, Any] | None = None, source: str = "script") -> None:
192
+ self.objects = objects if objects is not None else {}
193
+ self.source = source
194
+ self.calls: list[tuple[Call, Any]] = []
195
+ self.failed = False
196
+ self._made: dict[int, Call] = {} # results of recorded calls not yet used, by identity: a chain uses them
197
+
198
+ def _names(self) -> dict[int, str]:
199
+ return {id(v): k for k, v in self.objects.items()}
200
+
201
+ def make(self, spec: CallSpec, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Call | None:
202
+ try:
203
+ bound = spec.signature.bind(*args, **kwargs)
204
+ except TypeError:
205
+ return None # the call itself will raise
206
+ bound.apply_defaults()
207
+ values = dict(bound.arguments)
208
+ names = self._names()
209
+
210
+ def nested(value: Any) -> Any: # a named object is used by name, even if a call in this cell made it
211
+ return None if id(value) in names else self._chained(value)
212
+ try:
213
+ target = None
214
+ if spec.kind != "function":
215
+ first = values.pop(next(iter(spec.signature.parameters))) # self, or cls (which the call's ID names)
216
+ target = nested(first) or _encode_argument(first, names) if spec.kind == "method" else None
217
+ arguments = {k: nested(v) or _encode_argument(v, names) for k, v in values.items()}
218
+ except Exception: # noqa: BLE001 - SerialisationError: an argument that cannot be recorded
219
+ self.failed = True
220
+ return None
221
+ from .calls import Call
222
+
223
+ return Call(spec.id, spec.version, target, arguments, source=self.source)
224
+
225
+ def done(self, call: Call | None, result: Any) -> None:
226
+ if call is not None:
227
+ self.calls.append((call, result))
228
+ self._made[id(result)] = call
229
+
230
+ def _chained(self, value: Any) -> Any:
231
+ """A value that an earlier call just returned (``data.over(...).fit(...)``): that call, nested in this one."""
232
+ call = self._made.pop(id(value), None) if not isinstance(value, (bool, int, float, str, type(None))) else None
233
+ if call is None:
234
+ return None
235
+ self.calls = [(c, r) for c, r in self.calls if c is not call]
236
+ return _nested_call(call)
237
+
238
+
239
+ def _nested_call(call: Call) -> dict[str, Any]:
240
+ """``call`` as the value of an argument or receiver of another call: ``{"$call": ...}``."""
241
+ return {"$call": {"function": call.function, "version": call.version, "receiver": call.receiver, "arguments": dict(call.arguments)}}
242
+
243
+
244
+ def _encode_argument(value: Any, names: Mapping[int, str]) -> Any:
245
+ """Named objects (datasets, results, a named equation or sample) by name, as the code that uses them names
246
+ them; other settings and specifications by value. Numbers, text and tuples are always values."""
247
+ from .codec import Ref, SerialisationError, encode
248
+
249
+ if isinstance(value, Ref):
250
+ return {"$ref": value.name}
251
+ name = None if value is None or isinstance(value, (bool, int, float, str, tuple)) else names.get(id(value))
252
+ if name is not None:
253
+ return {"$ref": name}
254
+ try:
255
+ return encode(value, names)
256
+ except SerialisationError:
257
+ raise SerialisationError(f"a {type(value).__name__} that is not a named object cannot be recorded") from None
258
+
259
+
260
+ class recording:
261
+ """``with recording(session.objects) as rec:`` collects the ``@api`` calls made inside the block in ``rec.calls``."""
262
+
263
+ def __init__(self, objects: Mapping[str, Any] | None = None, source: str = "script") -> None:
264
+ self.recorder = Recorder(objects, source)
265
+ self._previous: tuple[Recorder | None, int] | None = None
266
+
267
+ def __enter__(self) -> Recorder:
268
+ self._previous = (_STATE.recorder, _STATE.depth)
269
+ _STATE.recorder, _STATE.depth = self.recorder, 0
270
+ return self.recorder
271
+
272
+ def __exit__(self, *exc: Any) -> None:
273
+ assert self._previous is not None
274
+ _STATE.recorder, _STATE.depth = self._previous
275
+
276
+
277
+ class _quiet:
278
+ """Run pymetrix functions without recording them (a call being replayed records itself, not its parts)."""
279
+
280
+ def __enter__(self) -> None:
281
+ _STATE.depth += 1
282
+
283
+ def __exit__(self, *exc: Any) -> None:
284
+ _STATE.depth -= 1
285
+
286
+