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.
- pymetrix/__init__.py +187 -0
- pymetrix/_api.py +286 -0
- pymetrix/_capture.py +200 -0
- pymetrix/_lazy.py +39 -0
- pymetrix/_micro.py +79 -0
- pymetrix/_planned.py +13 -0
- pymetrix/_processes.py +113 -0
- pymetrix/_random.py +119 -0
- pymetrix/_serial.py +41 -0
- pymetrix/_version.py +1 -0
- pymetrix/adapters/__init__.py +34 -0
- pymetrix/adapters/arch.py +79 -0
- pymetrix/adapters/base.py +318 -0
- pymetrix/adapters/linearmodels.py +60 -0
- pymetrix/adapters/native.py +20 -0
- pymetrix/adapters/sklearn.py +53 -0
- pymetrix/adapters/statsmodels.py +221 -0
- pymetrix/ardl.py +301 -0
- pymetrix/arima.py +588 -0
- pymetrix/backend.py +27 -0
- pymetrix/bma.py +260 -0
- pymetrix/build.py +67 -0
- pymetrix/bvar.py +712 -0
- pymetrix/bvar_hierarchical.py +374 -0
- pymetrix/bvar_sv.py +307 -0
- pymetrix/calls.py +538 -0
- pymetrix/clogit.py +354 -0
- pymetrix/clogit_effects.py +469 -0
- pymetrix/codec.py +331 -0
- pymetrix/cointegrating_regression.py +371 -0
- pymetrix/coming_from.py +354 -0
- pymetrix/commands/__init__.py +55 -0
- pymetrix/commands/ardl.py +91 -0
- pymetrix/commands/arima.py +205 -0
- pymetrix/commands/breaks.py +63 -0
- pymetrix/commands/builtin.py +4069 -0
- pymetrix/commands/code.py +71 -0
- pymetrix/commands/contributions.py +61 -0
- pymetrix/commands/data_edit.py +237 -0
- pymetrix/commands/data_tools.py +293 -0
- pymetrix/commands/disaggregation.py +222 -0
- pymetrix/commands/events.py +139 -0
- pymetrix/commands/factors.py +137 -0
- pymetrix/commands/figures.py +1375 -0
- pymetrix/commands/forecast_evaluation.py +146 -0
- pymetrix/commands/forecasting.py +403 -0
- pymetrix/commands/inference.py +502 -0
- pymetrix/commands/markov.py +85 -0
- pymetrix/commands/matrices.py +432 -0
- pymetrix/commands/menus.py +258 -0
- pymetrix/commands/micro.py +469 -0
- pymetrix/commands/midas.py +62 -0
- pymetrix/commands/missing.py +71 -0
- pymetrix/commands/model_irf.py +81 -0
- pymetrix/commands/model_source.py +57 -0
- pymetrix/commands/model_tools.py +345 -0
- pymetrix/commands/nonparametric.py +107 -0
- pymetrix/commands/nowcast.py +413 -0
- pymetrix/commands/occbin.py +141 -0
- pymetrix/commands/panel.py +293 -0
- pymetrix/commands/perturbation.py +44 -0
- pymetrix/commands/policy.py +122 -0
- pymetrix/commands/project.py +715 -0
- pymetrix/commands/projections.py +174 -0
- pymetrix/commands/registry.py +189 -0
- pymetrix/commands/report.py +201 -0
- pymetrix/commands/samples.py +186 -0
- pymetrix/commands/seasonal.py +128 -0
- pymetrix/commands/selection.py +259 -0
- pymetrix/commands/session.py +1361 -0
- pymetrix/commands/statespace.py +367 -0
- pymetrix/commands/sweeps.py +215 -0
- pymetrix/commands/systems.py +91 -0
- pymetrix/commands/treatment.py +323 -0
- pymetrix/commands/var_extra.py +499 -0
- pymetrix/connectors.py +386 -0
- pymetrix/count_series.py +321 -0
- pymetrix/data/__init__.py +5 -0
- pymetrix/data/axes.py +28 -0
- pymetrix/data/coerce.py +85 -0
- pymetrix/data/conditions.py +209 -0
- pymetrix/data/dataset.py +1482 -0
- pymetrix/data/derived.py +187 -0
- pymetrix/data/each.py +231 -0
- pymetrix/data/sample.py +228 -0
- pymetrix/data/validate.py +174 -0
- pymetrix/datasets/__init__.py +80 -0
- pymetrix/datasets/anes96.parquet +0 -0
- pymetrix/datasets/card.parquet +0 -0
- pymetrix/datasets/grunfeld.parquet +0 -0
- pymetrix/datasets/jobtraining.parquet +0 -0
- pymetrix/datasets/mroz.parquet +0 -0
- pymetrix/datasets/nile.parquet +0 -0
- pymetrix/datasets/policy_panel.parquet +0 -0
- pymetrix/datasets/randhie.parquet +0 -0
- pymetrix/datasets/rd_sample.parquet +0 -0
- pymetrix/datasets/sample_macro.parquet +0 -0
- pymetrix/datasets/sample_monthly.parquet +0 -0
- pymetrix/datasets/synth_panel.parquet +0 -0
- pymetrix/datasets/wage_panel.parquet +0 -0
- pymetrix/demos.py +107 -0
- pymetrix/diffusion.py +106 -0
- pymetrix/disaggregation.py +610 -0
- pymetrix/disclosure.py +171 -0
- pymetrix/dml.py +380 -0
- pymetrix/errors.py +51 -0
- pymetrix/estimation/__init__.py +48 -0
- pymetrix/estimation/bayes_equation.py +405 -0
- pymetrix/estimation/covariance.py +80 -0
- pymetrix/estimation/criteria.py +161 -0
- pymetrix/estimation/design.py +268 -0
- pymetrix/estimation/direct.py +385 -0
- pymetrix/estimation/dynpanel.py +330 -0
- pymetrix/estimation/equation.py +373 -0
- pymetrix/estimation/families.py +81 -0
- pymetrix/estimation/fitted.py +342 -0
- pymetrix/estimation/gmm.py +735 -0
- pymetrix/estimation/lag_search.py +101 -0
- pymetrix/estimation/limited.py +711 -0
- pymetrix/estimation/methods.py +582 -0
- pymetrix/estimation/ml.py +333 -0
- pymetrix/estimation/numdiff.py +53 -0
- pymetrix/estimation/params.py +105 -0
- pymetrix/estimation/priors.py +210 -0
- pymetrix/estimation/quantile.py +198 -0
- pymetrix/estimation/registry.py +37 -0
- pymetrix/estimation/regression_extras.py +438 -0
- pymetrix/estimation/restrictions.py +131 -0
- pymetrix/estimation/robust.py +204 -0
- pymetrix/estimation/rolling.py +160 -0
- pymetrix/estimation/timeseries.py +784 -0
- pymetrix/ets.py +248 -0
- pymetrix/exercises/__init__.py +971 -0
- pymetrix/exercises/__main__.py +8 -0
- pymetrix/exercises/cli.py +251 -0
- pymetrix/expr/__init__.py +23 -0
- pymetrix/expr/compile.py +277 -0
- pymetrix/expr/diff.py +121 -0
- pymetrix/expr/evaluate.py +142 -0
- pymetrix/expr/functions.py +454 -0
- pymetrix/expr/nodes.py +342 -0
- pymetrix/expr/parser.py +345 -0
- pymetrix/ext/__init__.py +6 -0
- pymetrix/ext/arch.py +482 -0
- pymetrix/ext/browse_folders.py +377 -0
- pymetrix/ext/connector_search.py +315 -0
- pymetrix/ext/connectors.py +364 -0
- pymetrix/ext/dataflow_groups.py +160 -0
- pymetrix/ext/linearmodels.py +396 -0
- pymetrix/ext/sdmx_structure.py +182 -0
- pymetrix/ext/sklearn.py +824 -0
- pymetrix/extension.py +264 -0
- pymetrix/factors.py +344 -0
- pymetrix/favar.py +295 -0
- pymetrix/figure_code.py +751 -0
- pymetrix/figure_properties.py +152 -0
- pymetrix/figure_style.py +279 -0
- pymetrix/figures.py +3215 -0
- pymetrix/filters.py +390 -0
- pymetrix/forecasting.py +1066 -0
- pymetrix/forms.py +441 -0
- pymetrix/garch_in_mean.py +86 -0
- pymetrix/growth_at_risk.py +241 -0
- pymetrix/help.py +2058 -0
- pymetrix/historical_extra.py +314 -0
- pymetrix/howto/__init__.py +108 -0
- pymetrix/howto/bring-in-an-iris-or-dynare-model.md +139 -0
- pymetrix/howto/cointegration-in-a-short-sample.md +97 -0
- pymetrix/howto/estimate-and-test-an-equation.md +97 -0
- pymetrix/identification_extra.py +286 -0
- pymetrix/interactive_fe.py +309 -0
- pymetrix/interop.py +304 -0
- pymetrix/io/__init__.py +21 -0
- pymetrix/io/parquet.py +100 -0
- pymetrix/io/registry.py +235 -0
- pymetrix/io/tabular.py +45 -0
- pymetrix/jdemetra.py +28 -0
- pymetrix/markov.py +206 -0
- pymetrix/matrix.py +922 -0
- pymetrix/matrix_expr.py +265 -0
- pymetrix/mcp_server.py +425 -0
- pymetrix/metadata.py +263 -0
- pymetrix/midas.py +274 -0
- pymetrix/models/__init__.py +28 -0
- pymetrix/models/_kalman_compiled.py +59 -0
- pymetrix/models/_kalman_kernels.py +242 -0
- pymetrix/models/bayes.py +1041 -0
- pymetrix/models/bayes_nuts.py +188 -0
- pymetrix/models/calibrate.py +124 -0
- pymetrix/models/control.py +283 -0
- pymetrix/models/covariance.py +115 -0
- pymetrix/models/decompose.py +247 -0
- pymetrix/models/dsge_var.py +763 -0
- pymetrix/models/dynare.py +760 -0
- pymetrix/models/dynare_macros.py +632 -0
- pymetrix/models/estimation.py +1151 -0
- pymetrix/models/eviews.py +1991 -0
- pymetrix/models/fast.py +124 -0
- pymetrix/models/growth.py +142 -0
- pymetrix/models/iris.py +535 -0
- pymetrix/models/kalman_score.py +780 -0
- pymetrix/models/linear.py +827 -0
- pymetrix/models/links.py +285 -0
- pymetrix/models/measurement.py +365 -0
- pymetrix/models/model.py +1254 -0
- pymetrix/models/moments.py +137 -0
- pymetrix/models/occbin.py +588 -0
- pymetrix/models/occbin_filter.py +649 -0
- pymetrix/models/ordering.py +218 -0
- pymetrix/models/particle.py +619 -0
- pymetrix/models/perfect_foresight.py +521 -0
- pymetrix/models/perturbation.py +281 -0
- pymetrix/models/plans.py +392 -0
- pymetrix/models/policy.py +257 -0
- pymetrix/models/regimes.py +829 -0
- pymetrix/models/safe_eval.py +118 -0
- pymetrix/models/scenario.py +54 -0
- pymetrix/models/solution.py +143 -0
- pymetrix/models/solvers.py +406 -0
- pymetrix/models/source.py +1622 -0
- pymetrix/models/stochastic.py +741 -0
- pymetrix/models/system.py +490 -0
- pymetrix/models/templates.py +206 -0
- pymetrix/models/writers.py +653 -0
- pymetrix/ms_var.py +376 -0
- pymetrix/ms_var_bands.py +186 -0
- pymetrix/ms_var_em.py +400 -0
- pymetrix/nonlinear.py +303 -0
- pymetrix/nonlinear_extra.py +240 -0
- pymetrix/nonparametric.py +611 -0
- pymetrix/notation.py +313 -0
- pymetrix/nowcast.py +482 -0
- pymetrix/nuts.py +532 -0
- pymetrix/output.py +182 -0
- pymetrix/panel_time_series.py +309 -0
- pymetrix/panelvar.py +392 -0
- pymetrix/plugin_template.py +394 -0
- pymetrix/plugins.py +716 -0
- pymetrix/progress.py +72 -0
- pymetrix/projections.py +235 -0
- pymetrix/proxy.py +202 -0
- pymetrix/quantile_var.py +180 -0
- pymetrix/recessions.py +96 -0
- pymetrix/reconciliation.py +274 -0
- pymetrix/recovery.py +108 -0
- pymetrix/report.py +465 -0
- pymetrix/results.py +306 -0
- pymetrix/saved.py +359 -0
- pymetrix/schema.py +205 -0
- pymetrix/seasonal.py +325 -0
- pymetrix/selection.py +291 -0
- pymetrix/shiftshare.py +275 -0
- pymetrix/simulation.py +168 -0
- pymetrix/simulation_estimators.py +311 -0
- pymetrix/smooth_lp.py +207 -0
- pymetrix/smooth_transition.py +253 -0
- pymetrix/spatial.py +210 -0
- pymetrix/spectral.py +319 -0
- pymetrix/staggered.py +431 -0
- pymetrix/statespace.py +1471 -0
- pymetrix/stats/__init__.py +53 -0
- pymetrix/stats/adf_arrays.py +318 -0
- pymetrix/stats/base.py +198 -0
- pymetrix/stats/breaks.py +320 -0
- pymetrix/stats/compare.py +75 -0
- pymetrix/stats/data_tests.py +476 -0
- pymetrix/stats/density.py +152 -0
- pymetrix/stats/equation_tests.py +715 -0
- pymetrix/stats/evaluation.py +468 -0
- pymetrix/stats/forecast.py +31 -0
- pymetrix/stats/panel_cointegration.py +489 -0
- pymetrix/stats/panel_tests.py +641 -0
- pymetrix/stats/quandt_andrews.npz +0 -0
- pymetrix/stats/stability.py +138 -0
- pymetrix/stats/timeseries.py +112 -0
- pymetrix/stats/unit_root_extra.py +293 -0
- pymetrix/stats/var_tests.py +175 -0
- pymetrix/structural.py +320 -0
- pymetrix/summary_layout.py +171 -0
- pymetrix/sweeps.py +486 -0
- pymetrix/synthdid.py +210 -0
- pymetrix/systems.py +725 -0
- pymetrix/testing.py +550 -0
- pymetrix/themes.py +119 -0
- pymetrix/threads.py +115 -0
- pymetrix/toolkit.py +227 -0
- pymetrix/treatment.py +597 -0
- pymetrix/trust.py +78 -0
- pymetrix/tvpvar.py +351 -0
- pymetrix/ui/__init__.py +1 -0
- pymetrix/ui/active_window.py +243 -0
- pymetrix/ui/advanced_section.py +359 -0
- pymetrix/ui/chart_click.py +247 -0
- pymetrix/ui/chart_edit.py +386 -0
- pymetrix/ui/chart_format.py +305 -0
- pymetrix/ui/chart_look.py +56 -0
- pymetrix/ui/collector.py +65 -0
- pymetrix/ui/console_qt.py +164 -0
- pymetrix/ui/demo_chooser.py +112 -0
- pymetrix/ui/dialog_checks.py +259 -0
- pymetrix/ui/editor_qt.py +745 -0
- pymetrix/ui/exercises_qt.py +499 -0
- pymetrix/ui/extend.py +6 -0
- pymetrix/ui/fit.py +753 -0
- pymetrix/ui/form_keys.py +91 -0
- pymetrix/ui/formula_check.py +207 -0
- pymetrix/ui/help_qt.py +294 -0
- pymetrix/ui/history_qt.py +213 -0
- pymetrix/ui/icons.py +349 -0
- pymetrix/ui/jupyter.py +258 -0
- pymetrix/ui/keys.py +68 -0
- pymetrix/ui/matrix_qt.py +312 -0
- pymetrix/ui/messages.py +150 -0
- pymetrix/ui/metrics.py +122 -0
- pymetrix/ui/model_editor_qt.py +654 -0
- pymetrix/ui/next_steps.py +103 -0
- pymetrix/ui/palette.py +175 -0
- pymetrix/ui/plugins_qt.py +269 -0
- pymetrix/ui/qt.py +5559 -0
- pymetrix/ui/render.py +74 -0
- pymetrix/ui/report_qt.py +179 -0
- pymetrix/ui/series_browser_qt.py +820 -0
- pymetrix/ui/sheet_qt.py +863 -0
- pymetrix/ui/shortcut.py +122 -0
- pymetrix/ui/stats_panel.py +209 -0
- pymetrix/ui/text_size.py +144 -0
- pymetrix/ui/theme.py +168 -0
- pymetrix/ui/timers.py +42 -0
- pymetrix/ui/view_switcher.py +296 -0
- pymetrix/ui/workspaces.py +304 -0
- pymetrix/ui/zoom.py +46 -0
- pymetrix/var.py +1518 -0
- pymetrix/var_conditions.py +360 -0
- pymetrix/var_decompositions.py +78 -0
- pymetrix/varma.py +204 -0
- pymetrix/vecm.py +718 -0
- pymetrix/vecm_restrictions.py +155 -0
- pymetrix/views.py +1558 -0
- pymetrix/wording.py +1231 -0
- pymetrix/zerosign.py +254 -0
- pymetrix-0.1.0a20.dist-info/METADATA +136 -0
- pymetrix-0.1.0a20.dist-info/RECORD +350 -0
- pymetrix-0.1.0a20.dist-info/WHEEL +4 -0
- pymetrix-0.1.0a20.dist-info/entry_points.txt +5 -0
- pymetrix-0.1.0a20.dist-info/licenses/LICENSE +28 -0
- pymetrix-0.1.0a20.dist-info/licenses/THIRD-PARTY-NOTICES.md +124 -0
- pymetrix_app/__init__.py +189 -0
- pymetrix_app/__main__.py +5 -0
- pymetrix_app/icons/pymetrix.ico +0 -0
- 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
|
+
|