aigroup-econ-mcp 0.4.2__py3-none-any.whl → 1.4.3__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.
- .gitignore +253 -0
- PKG-INFO +710 -0
- README.md +672 -0
- __init__.py +14 -0
- aigroup_econ_mcp-1.4.3.dist-info/METADATA +710 -0
- aigroup_econ_mcp-1.4.3.dist-info/RECORD +92 -0
- aigroup_econ_mcp-1.4.3.dist-info/entry_points.txt +2 -0
- aigroup_econ_mcp-1.4.3.dist-info/licenses/LICENSE +21 -0
- cli.py +28 -0
- econometrics/README.md +18 -0
- econometrics/__init__.py +191 -0
- econometrics/advanced_methods/modern_computing_machine_learning/__init__.py +0 -0
- econometrics/basic_parametric_estimation/__init__.py +31 -0
- econometrics/basic_parametric_estimation/gmm/__init__.py +13 -0
- econometrics/basic_parametric_estimation/gmm/gmm_model.py +256 -0
- econometrics/basic_parametric_estimation/mle/__init__.py +13 -0
- econometrics/basic_parametric_estimation/mle/mle_model.py +241 -0
- econometrics/basic_parametric_estimation/ols/__init__.py +13 -0
- econometrics/basic_parametric_estimation/ols/ols_model.py +141 -0
- econometrics/causal_inference/causal_identification_strategy/__init__.py +0 -0
- econometrics/missing_data/missing_data_measurement_error/__init__.py +0 -0
- econometrics/model_specification_diagnostics_robust_inference/README.md +173 -0
- econometrics/model_specification_diagnostics_robust_inference/__init__.py +78 -0
- econometrics/model_specification_diagnostics_robust_inference/diagnostic_tests/__init__.py +20 -0
- econometrics/model_specification_diagnostics_robust_inference/diagnostic_tests/diagnostic_tests_model.py +149 -0
- econometrics/model_specification_diagnostics_robust_inference/generalized_least_squares/__init__.py +15 -0
- econometrics/model_specification_diagnostics_robust_inference/generalized_least_squares/gls_model.py +130 -0
- econometrics/model_specification_diagnostics_robust_inference/model_selection/__init__.py +18 -0
- econometrics/model_specification_diagnostics_robust_inference/model_selection/model_selection_model.py +286 -0
- econometrics/model_specification_diagnostics_robust_inference/regularization/__init__.py +15 -0
- econometrics/model_specification_diagnostics_robust_inference/regularization/regularization_model.py +177 -0
- econometrics/model_specification_diagnostics_robust_inference/robust_errors/__init__.py +15 -0
- econometrics/model_specification_diagnostics_robust_inference/robust_errors/robust_errors_model.py +122 -0
- econometrics/model_specification_diagnostics_robust_inference/simultaneous_equations/__init__.py +15 -0
- econometrics/model_specification_diagnostics_robust_inference/simultaneous_equations/simultaneous_equations_model.py +246 -0
- econometrics/model_specification_diagnostics_robust_inference/weighted_least_squares/__init__.py +15 -0
- econometrics/model_specification_diagnostics_robust_inference/weighted_least_squares/wls_model.py +127 -0
- econometrics/nonparametric/nonparametric_semiparametric_methods/__init__.py +0 -0
- econometrics/spatial_econometrics/spatial_econometrics_new/__init__.py +0 -0
- econometrics/specific_data_modeling/micro_discrete_limited_data/__init__.py +0 -0
- econometrics/specific_data_modeling/survival_duration_data/__init__.py +0 -0
- econometrics/specific_data_modeling/time_series_panel_data/__init__.py +143 -0
- econometrics/specific_data_modeling/time_series_panel_data/arima_model.py +104 -0
- econometrics/specific_data_modeling/time_series_panel_data/cointegration_vecm.py +334 -0
- econometrics/specific_data_modeling/time_series_panel_data/dynamic_panel_models.py +653 -0
- econometrics/specific_data_modeling/time_series_panel_data/exponential_smoothing.py +176 -0
- econometrics/specific_data_modeling/time_series_panel_data/garch_model.py +198 -0
- econometrics/specific_data_modeling/time_series_panel_data/panel_diagnostics.py +125 -0
- econometrics/specific_data_modeling/time_series_panel_data/panel_var.py +60 -0
- econometrics/specific_data_modeling/time_series_panel_data/structural_break_tests.py +87 -0
- econometrics/specific_data_modeling/time_series_panel_data/time_varying_parameter_models.py +106 -0
- econometrics/specific_data_modeling/time_series_panel_data/unit_root_tests.py +204 -0
- econometrics/specific_data_modeling/time_series_panel_data/var_svar_model.py +372 -0
- econometrics/statistical_inference/statistical_inference_techniques/__init__.py +0 -0
- econometrics/statistics/distribution_decomposition_methods/__init__.py +0 -0
- econometrics/tests/basic_parametric_estimation_tests/__init__.py +3 -0
- econometrics/tests/basic_parametric_estimation_tests/test_gmm.py +128 -0
- econometrics/tests/basic_parametric_estimation_tests/test_mle.py +127 -0
- econometrics/tests/basic_parametric_estimation_tests/test_ols.py +100 -0
- econometrics/tests/model_specification_diagnostics_tests/__init__.py +3 -0
- econometrics/tests/model_specification_diagnostics_tests/test_diagnostic_tests.py +86 -0
- econometrics/tests/model_specification_diagnostics_tests/test_robust_errors.py +89 -0
- econometrics/tests/specific_data_modeling_tests/__init__.py +3 -0
- econometrics/tests/specific_data_modeling_tests/test_arima.py +98 -0
- econometrics/tests/specific_data_modeling_tests/test_dynamic_panel.py +198 -0
- econometrics/tests/specific_data_modeling_tests/test_exponential_smoothing.py +105 -0
- econometrics/tests/specific_data_modeling_tests/test_garch.py +118 -0
- econometrics/tests/specific_data_modeling_tests/test_unit_root.py +156 -0
- econometrics/tests/specific_data_modeling_tests/test_var.py +124 -0
- prompts/__init__.py +0 -0
- prompts/analysis_guides.py +43 -0
- pyproject.toml +78 -0
- resources/MCP_MASTER_GUIDE.md +422 -0
- resources/MCP_TOOLS_DATA_FORMAT_GUIDE.md +185 -0
- resources/__init__.py +0 -0
- server.py +83 -0
- tools/README.md +88 -0
- tools/__init__.py +45 -0
- tools/data_loader.py +213 -0
- tools/decorators.py +38 -0
- tools/econometrics_adapter.py +286 -0
- tools/mcp_tool_groups/__init__.py +1 -0
- tools/mcp_tool_groups/basic_parametric_tools.py +173 -0
- tools/mcp_tool_groups/model_specification_tools.py +402 -0
- tools/mcp_tool_groups/time_series_tools.py +494 -0
- tools/mcp_tools_registry.py +114 -0
- tools/model_specification_adapter.py +369 -0
- tools/output_formatter.py +563 -0
- tools/time_series_panel_data_adapter.py +858 -0
- tools/time_series_panel_data_tools.py +65 -0
- aigroup_econ_mcp/__init__.py +0 -19
- aigroup_econ_mcp/cli.py +0 -82
- aigroup_econ_mcp/config.py +0 -561
- aigroup_econ_mcp/server.py +0 -452
- aigroup_econ_mcp/tools/__init__.py +0 -18
- aigroup_econ_mcp/tools/base.py +0 -470
- aigroup_econ_mcp/tools/cache.py +0 -533
- aigroup_econ_mcp/tools/data_loader.py +0 -171
- aigroup_econ_mcp/tools/file_parser.py +0 -829
- aigroup_econ_mcp/tools/machine_learning.py +0 -60
- aigroup_econ_mcp/tools/ml_ensemble.py +0 -210
- aigroup_econ_mcp/tools/ml_evaluation.py +0 -272
- aigroup_econ_mcp/tools/ml_models.py +0 -54
- aigroup_econ_mcp/tools/ml_regularization.py +0 -172
- aigroup_econ_mcp/tools/monitoring.py +0 -555
- aigroup_econ_mcp/tools/optimized_example.py +0 -229
- aigroup_econ_mcp/tools/panel_data.py +0 -553
- aigroup_econ_mcp/tools/regression.py +0 -214
- aigroup_econ_mcp/tools/statistics.py +0 -154
- aigroup_econ_mcp/tools/time_series.py +0 -667
- aigroup_econ_mcp/tools/timeout.py +0 -283
- aigroup_econ_mcp/tools/tool_handlers.py +0 -378
- aigroup_econ_mcp/tools/tool_registry.py +0 -170
- aigroup_econ_mcp/tools/validation.py +0 -482
- aigroup_econ_mcp-0.4.2.dist-info/METADATA +0 -360
- aigroup_econ_mcp-0.4.2.dist-info/RECORD +0 -29
- aigroup_econ_mcp-0.4.2.dist-info/entry_points.txt +0 -2
- /aigroup_econ_mcp-0.4.2.dist-info/licenses/LICENSE → /LICENSE +0 -0
- {aigroup_econ_mcp-0.4.2.dist-info → aigroup_econ_mcp-1.4.3.dist-info}/WHEEL +0 -0
aigroup_econ_mcp/tools/base.py
DELETED
|
@@ -1,470 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
工具模块基类和装饰器
|
|
3
|
-
整合了工具基类、装饰器、错误处理和优化组件
|
|
4
|
-
"""
|
|
5
|
-
|
|
6
|
-
import functools
|
|
7
|
-
from typing import Any, Dict, List, Optional, Callable, Type
|
|
8
|
-
from functools import wraps
|
|
9
|
-
from mcp.server.session import ServerSession
|
|
10
|
-
from mcp.server.fastmcp import Context
|
|
11
|
-
from mcp.types import CallToolResult, TextContent
|
|
12
|
-
|
|
13
|
-
from .validation import ValidationError, validate_econometric_data, validate_model_parameters
|
|
14
|
-
from .cache import cache_result, cache_model, global_econometric_cache
|
|
15
|
-
from .monitoring import monitor_performance, track_progress, global_performance_monitor
|
|
16
|
-
from .file_parser import FileParser
|
|
17
|
-
from ..config import get_config, econometric_config
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
# ============================================================================
|
|
21
|
-
# 错误类定义
|
|
22
|
-
# ============================================================================
|
|
23
|
-
|
|
24
|
-
class EconometricToolError(Exception):
|
|
25
|
-
"""计量经济学工具错误基类"""
|
|
26
|
-
|
|
27
|
-
def __init__(self, message: str, tool_name: str = None, original_error: Exception = None):
|
|
28
|
-
self.message = message
|
|
29
|
-
self.tool_name = tool_name
|
|
30
|
-
self.original_error = original_error
|
|
31
|
-
super().__init__(self.message)
|
|
32
|
-
|
|
33
|
-
def __str__(self):
|
|
34
|
-
base_msg = f"计量经济学工具错误"
|
|
35
|
-
if self.tool_name:
|
|
36
|
-
base_msg += f" ({self.tool_name})"
|
|
37
|
-
base_msg += f": {self.message}"
|
|
38
|
-
if self.original_error:
|
|
39
|
-
base_msg += f"\n原始错误: {self.original_error}"
|
|
40
|
-
return base_msg
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
class DataValidationError(EconometricToolError):
|
|
44
|
-
"""数据验证错误"""
|
|
45
|
-
pass
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
class ModelFittingError(EconometricToolError):
|
|
49
|
-
"""模型拟合错误"""
|
|
50
|
-
pass
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
class ConfigurationError(EconometricToolError):
|
|
54
|
-
"""配置错误"""
|
|
55
|
-
pass
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
# ============================================================================
|
|
59
|
-
# 装饰器函数
|
|
60
|
-
# ============================================================================
|
|
61
|
-
|
|
62
|
-
def with_file_input(tool_type: str):
|
|
63
|
-
"""
|
|
64
|
-
为工具函数添加文件输入支持的装饰器
|
|
65
|
-
|
|
66
|
-
支持两种输入方式:
|
|
67
|
-
1. file_path: CSV/JSON文件路径
|
|
68
|
-
2. file_content: 文件内容字符串
|
|
69
|
-
|
|
70
|
-
Args:
|
|
71
|
-
tool_type: 工具类型 ('single_var', 'multi_var_dict', 'regression', 'panel', 'time_series')
|
|
72
|
-
|
|
73
|
-
使用示例:
|
|
74
|
-
@with_file_input('regression')
|
|
75
|
-
async def my_tool(ctx, y_data=None, x_data=None, file_path=None, file_content=None, file_format='auto', **kwargs):
|
|
76
|
-
# 如果提供了file_path或file_content,数据会被自动填充
|
|
77
|
-
pass
|
|
78
|
-
"""
|
|
79
|
-
def decorator(func: Callable) -> Callable:
|
|
80
|
-
@wraps(func)
|
|
81
|
-
async def wrapper(*args, **kwargs):
|
|
82
|
-
# 提取上下文和文件参数
|
|
83
|
-
ctx = args[0] if args else kwargs.get('ctx')
|
|
84
|
-
file_path = kwargs.get('file_path')
|
|
85
|
-
file_content = kwargs.get('file_content')
|
|
86
|
-
file_format = kwargs.get('file_format', 'auto')
|
|
87
|
-
|
|
88
|
-
# 优先处理file_path
|
|
89
|
-
if file_path:
|
|
90
|
-
try:
|
|
91
|
-
await ctx.info(f"检测到文件路径输入: {file_path}")
|
|
92
|
-
|
|
93
|
-
# 从文件路径解析
|
|
94
|
-
parsed = FileParser.parse_file_path(file_path, file_format)
|
|
95
|
-
|
|
96
|
-
await ctx.info(
|
|
97
|
-
f"文件解析成功:{parsed['n_variables']}个变量,"
|
|
98
|
-
f"{parsed['n_observations']}个观测"
|
|
99
|
-
)
|
|
100
|
-
|
|
101
|
-
# 转换为工具格式
|
|
102
|
-
converted = FileParser.convert_to_tool_format(parsed, tool_type)
|
|
103
|
-
|
|
104
|
-
# 更新kwargs
|
|
105
|
-
kwargs.update(converted)
|
|
106
|
-
|
|
107
|
-
await ctx.info(f"数据已转换为{tool_type}格式")
|
|
108
|
-
|
|
109
|
-
except Exception as e:
|
|
110
|
-
await ctx.error(f"文件解析失败: {str(e)}")
|
|
111
|
-
return CallToolResult(
|
|
112
|
-
content=[TextContent(type="text", text=f"文件解析错误: {str(e)}")],
|
|
113
|
-
isError=True
|
|
114
|
-
)
|
|
115
|
-
|
|
116
|
-
# 如果没有file_path但有file_content,处理文件内容
|
|
117
|
-
elif file_content:
|
|
118
|
-
try:
|
|
119
|
-
await ctx.info("检测到文件内容输入,开始解析...")
|
|
120
|
-
|
|
121
|
-
# 解析文件内容
|
|
122
|
-
parsed = FileParser.parse_file_content(file_content, file_format)
|
|
123
|
-
|
|
124
|
-
await ctx.info(
|
|
125
|
-
f"文件解析成功:{parsed['n_variables']}个变量,"
|
|
126
|
-
f"{parsed['n_observations']}个观测"
|
|
127
|
-
)
|
|
128
|
-
|
|
129
|
-
# 转换为工具格式
|
|
130
|
-
converted = FileParser.convert_to_tool_format(parsed, tool_type)
|
|
131
|
-
|
|
132
|
-
# 更新kwargs
|
|
133
|
-
kwargs.update(converted)
|
|
134
|
-
|
|
135
|
-
await ctx.info(f"数据已转换为{tool_type}格式")
|
|
136
|
-
|
|
137
|
-
except Exception as e:
|
|
138
|
-
await ctx.error(f"文件解析失败: {str(e)}")
|
|
139
|
-
return CallToolResult(
|
|
140
|
-
content=[TextContent(type="text", text=f"文件解析错误: {str(e)}")],
|
|
141
|
-
isError=True
|
|
142
|
-
)
|
|
143
|
-
|
|
144
|
-
# 调用原函数
|
|
145
|
-
return await func(*args, **kwargs)
|
|
146
|
-
|
|
147
|
-
return wrapper
|
|
148
|
-
return decorator
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
def with_error_handling(func: Callable) -> Callable:
|
|
152
|
-
"""
|
|
153
|
-
为工具函数添加统一错误处理的装饰器
|
|
154
|
-
"""
|
|
155
|
-
@wraps(func)
|
|
156
|
-
async def wrapper(*args, **kwargs):
|
|
157
|
-
ctx = args[0] if args else kwargs.get('ctx')
|
|
158
|
-
tool_name = func.__name__
|
|
159
|
-
|
|
160
|
-
try:
|
|
161
|
-
return await func(*args, **kwargs)
|
|
162
|
-
except Exception as e:
|
|
163
|
-
await ctx.error(f"{tool_name}执行出错: {str(e)}")
|
|
164
|
-
return CallToolResult(
|
|
165
|
-
content=[TextContent(type="text", text=f"错误: {str(e)}")],
|
|
166
|
-
isError=True
|
|
167
|
-
)
|
|
168
|
-
|
|
169
|
-
return wrapper
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
def with_logging(func: Callable) -> Callable:
|
|
173
|
-
"""
|
|
174
|
-
为工具函数添加日志记录的装饰器
|
|
175
|
-
"""
|
|
176
|
-
@wraps(func)
|
|
177
|
-
async def wrapper(*args, **kwargs):
|
|
178
|
-
ctx = args[0] if args else kwargs.get('ctx')
|
|
179
|
-
tool_name = func.__name__
|
|
180
|
-
|
|
181
|
-
await ctx.info(f"开始执行 {tool_name}")
|
|
182
|
-
result = await func(*args, **kwargs)
|
|
183
|
-
await ctx.info(f"{tool_name} 执行完成")
|
|
184
|
-
|
|
185
|
-
return result
|
|
186
|
-
|
|
187
|
-
return wrapper
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
def with_file_support_decorator(
|
|
191
|
-
tool_type: str,
|
|
192
|
-
enable_error_handling: bool = True,
|
|
193
|
-
enable_logging: bool = True
|
|
194
|
-
):
|
|
195
|
-
"""
|
|
196
|
-
组合装饰器:为计量经济学工具添加文件支持和其他标准功能
|
|
197
|
-
|
|
198
|
-
Args:
|
|
199
|
-
tool_type: 工具类型
|
|
200
|
-
enable_error_handling: 是否启用错误处理
|
|
201
|
-
enable_logging: 是否启用日志记录
|
|
202
|
-
|
|
203
|
-
使用示例:
|
|
204
|
-
@with_file_support_decorator('regression')
|
|
205
|
-
async def ols_regression(ctx, y_data=None, x_data=None, **kwargs):
|
|
206
|
-
# 只需要编写核心业务逻辑
|
|
207
|
-
pass
|
|
208
|
-
"""
|
|
209
|
-
def decorator(func: Callable) -> Callable:
|
|
210
|
-
wrapped = func
|
|
211
|
-
|
|
212
|
-
if enable_error_handling:
|
|
213
|
-
wrapped = with_error_handling(wrapped)
|
|
214
|
-
|
|
215
|
-
wrapped = with_file_input(tool_type)(wrapped)
|
|
216
|
-
|
|
217
|
-
if enable_logging:
|
|
218
|
-
wrapped = with_logging(wrapped)
|
|
219
|
-
|
|
220
|
-
return wrapped
|
|
221
|
-
|
|
222
|
-
return decorator
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
# ============================================================================
|
|
226
|
-
# 工具基类
|
|
227
|
-
# ============================================================================
|
|
228
|
-
|
|
229
|
-
class EconometricTool:
|
|
230
|
-
"""
|
|
231
|
-
计量经济学工具基类
|
|
232
|
-
提供统一的参数验证、缓存、性能监控和错误处理
|
|
233
|
-
"""
|
|
234
|
-
|
|
235
|
-
def __init__(self, tool_name: str):
|
|
236
|
-
"""
|
|
237
|
-
初始化工具
|
|
238
|
-
|
|
239
|
-
Args:
|
|
240
|
-
tool_name: 工具名称
|
|
241
|
-
"""
|
|
242
|
-
self.tool_name = tool_name
|
|
243
|
-
self._cache_enabled = get_config("cache_enabled", True)
|
|
244
|
-
self._monitoring_enabled = get_config("monitoring_enabled", True)
|
|
245
|
-
self._validation_strict = get_config("data_validation_strict", True)
|
|
246
|
-
|
|
247
|
-
def _validate_input_data(self, data: Any, data_type: str = "generic") -> Any:
|
|
248
|
-
"""
|
|
249
|
-
验证输入数据
|
|
250
|
-
|
|
251
|
-
Args:
|
|
252
|
-
data: 输入数据
|
|
253
|
-
data_type: 数据类型
|
|
254
|
-
|
|
255
|
-
Returns:
|
|
256
|
-
Any: 验证后的数据
|
|
257
|
-
|
|
258
|
-
Raises:
|
|
259
|
-
DataValidationError: 数据验证失败
|
|
260
|
-
"""
|
|
261
|
-
try:
|
|
262
|
-
if data_type == "econometric":
|
|
263
|
-
return validate_econometric_data(data)
|
|
264
|
-
elif data_type == "time_series":
|
|
265
|
-
from .validation import validate_time_series_data
|
|
266
|
-
return validate_time_series_data(data)
|
|
267
|
-
elif data_type == "model_parameters":
|
|
268
|
-
return validate_model_parameters(data)
|
|
269
|
-
else:
|
|
270
|
-
return data
|
|
271
|
-
except ValidationError as e:
|
|
272
|
-
error_msg = f"数据验证失败: {e.message}"
|
|
273
|
-
if self._validation_strict:
|
|
274
|
-
raise DataValidationError(error_msg, self.tool_name, e)
|
|
275
|
-
else:
|
|
276
|
-
# 在非严格模式下记录警告并继续
|
|
277
|
-
import warnings
|
|
278
|
-
warnings.warn(f"{self.tool_name}: {error_msg}")
|
|
279
|
-
return data
|
|
280
|
-
|
|
281
|
-
def _handle_errors(self, func: Callable) -> Callable:
|
|
282
|
-
"""
|
|
283
|
-
错误处理装饰器
|
|
284
|
-
|
|
285
|
-
Args:
|
|
286
|
-
func: 被装饰的函数
|
|
287
|
-
|
|
288
|
-
Returns:
|
|
289
|
-
Callable: 装饰后的函数
|
|
290
|
-
"""
|
|
291
|
-
@functools.wraps(func)
|
|
292
|
-
def wrapper(*args, **kwargs):
|
|
293
|
-
try:
|
|
294
|
-
return func(*args, **kwargs)
|
|
295
|
-
except (DataValidationError, ModelFittingError, ConfigurationError):
|
|
296
|
-
# 重新抛出已知的错误类型
|
|
297
|
-
raise
|
|
298
|
-
except ValidationError as e:
|
|
299
|
-
# 转换验证错误
|
|
300
|
-
raise DataValidationError(f"参数验证失败: {e.message}", self.tool_name, e)
|
|
301
|
-
except Exception as e:
|
|
302
|
-
# 处理其他未知错误
|
|
303
|
-
error_msg = f"执行过程中发生未知错误: {str(e)}"
|
|
304
|
-
raise EconometricToolError(error_msg, self.tool_name, e)
|
|
305
|
-
|
|
306
|
-
return wrapper
|
|
307
|
-
|
|
308
|
-
def _apply_optimizations(self, func: Callable) -> Callable:
|
|
309
|
-
"""
|
|
310
|
-
应用优化装饰器
|
|
311
|
-
|
|
312
|
-
Args:
|
|
313
|
-
func: 被装饰的函数
|
|
314
|
-
|
|
315
|
-
Returns:
|
|
316
|
-
Callable: 优化后的函数
|
|
317
|
-
"""
|
|
318
|
-
# 应用性能监控
|
|
319
|
-
if self._monitoring_enabled:
|
|
320
|
-
func = monitor_performance(self.tool_name)(func)
|
|
321
|
-
|
|
322
|
-
# 应用缓存
|
|
323
|
-
if self._cache_enabled:
|
|
324
|
-
cache_config = econometric_config.get_cache_config()
|
|
325
|
-
func = cache_result(ttl=cache_config["ttl"], max_size=cache_config["max_size"])(func)
|
|
326
|
-
|
|
327
|
-
# 应用错误处理
|
|
328
|
-
func = self._handle_errors(func)
|
|
329
|
-
|
|
330
|
-
return func
|
|
331
|
-
|
|
332
|
-
def create_optimized_function(self, func: Callable) -> Callable:
|
|
333
|
-
"""
|
|
334
|
-
创建优化函数
|
|
335
|
-
|
|
336
|
-
Args:
|
|
337
|
-
func: 原始函数
|
|
338
|
-
|
|
339
|
-
Returns:
|
|
340
|
-
Callable: 优化后的函数
|
|
341
|
-
"""
|
|
342
|
-
return self._apply_optimizations(func)
|
|
343
|
-
|
|
344
|
-
def execute_with_progress(self, total_steps: int, description: str = ""):
|
|
345
|
-
"""
|
|
346
|
-
进度跟踪上下文管理器
|
|
347
|
-
|
|
348
|
-
Args:
|
|
349
|
-
total_steps: 总步骤数
|
|
350
|
-
description: 进度描述
|
|
351
|
-
|
|
352
|
-
Returns:
|
|
353
|
-
ContextManager: 进度跟踪上下文管理器
|
|
354
|
-
"""
|
|
355
|
-
return track_progress(total_steps, f"{self.tool_name}: {description}")
|
|
356
|
-
|
|
357
|
-
def get_performance_stats(self) -> Dict[str, Any]:
|
|
358
|
-
"""
|
|
359
|
-
获取性能统计
|
|
360
|
-
|
|
361
|
-
Returns:
|
|
362
|
-
Dict[str, Any]: 性能统计信息
|
|
363
|
-
"""
|
|
364
|
-
if not self._monitoring_enabled:
|
|
365
|
-
return {}
|
|
366
|
-
|
|
367
|
-
stats = global_performance_monitor.get_function_stats(self.tool_name)
|
|
368
|
-
if stats:
|
|
369
|
-
return {
|
|
370
|
-
"execution_time": stats.execution_time,
|
|
371
|
-
"peak_memory_mb": stats.peak_memory_mb,
|
|
372
|
-
"cpu_percent": stats.cpu_percent,
|
|
373
|
-
"timestamp": stats.timestamp
|
|
374
|
-
}
|
|
375
|
-
return {}
|
|
376
|
-
|
|
377
|
-
def get_cache_stats(self) -> Dict[str, Any]:
|
|
378
|
-
"""
|
|
379
|
-
获取缓存统计
|
|
380
|
-
|
|
381
|
-
Returns:
|
|
382
|
-
Dict[str, Any]: 缓存统计信息
|
|
383
|
-
"""
|
|
384
|
-
if not self._cache_enabled:
|
|
385
|
-
return {}
|
|
386
|
-
|
|
387
|
-
return global_econometric_cache.result_cache.get_function_cache_stats(self.tool_name) or {}
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
# ============================================================================
|
|
391
|
-
# 便捷装饰器函数
|
|
392
|
-
# ============================================================================
|
|
393
|
-
|
|
394
|
-
def econometric_tool_with_optimization(tool_name: str = None):
|
|
395
|
-
"""
|
|
396
|
-
计量经济学工具装饰器(带优化)
|
|
397
|
-
|
|
398
|
-
应用缓存、性能监控和错误处理
|
|
399
|
-
|
|
400
|
-
Args:
|
|
401
|
-
tool_name: 工具名称
|
|
402
|
-
|
|
403
|
-
Returns:
|
|
404
|
-
Callable: 装饰器函数
|
|
405
|
-
|
|
406
|
-
使用示例:
|
|
407
|
-
@econometric_tool_with_optimization('my_analysis')
|
|
408
|
-
def my_analysis(data):
|
|
409
|
-
# 自动获得缓存、监控和错误处理
|
|
410
|
-
pass
|
|
411
|
-
"""
|
|
412
|
-
def decorator(func):
|
|
413
|
-
name = tool_name or func.__name__
|
|
414
|
-
tool = EconometricTool(name)
|
|
415
|
-
return tool.create_optimized_function(func)
|
|
416
|
-
|
|
417
|
-
return decorator
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
def validate_input(data_type: str = "generic"):
|
|
421
|
-
"""
|
|
422
|
-
输入验证装饰器
|
|
423
|
-
|
|
424
|
-
Args:
|
|
425
|
-
data_type: 数据类型
|
|
426
|
-
|
|
427
|
-
Returns:
|
|
428
|
-
Callable: 装饰器函数
|
|
429
|
-
"""
|
|
430
|
-
def decorator(func):
|
|
431
|
-
@functools.wraps(func)
|
|
432
|
-
def wrapper(*args, **kwargs):
|
|
433
|
-
# 验证第一个位置参数(通常是数据)
|
|
434
|
-
if args:
|
|
435
|
-
validated_args = list(args)
|
|
436
|
-
validated_args[0] = EconometricTool(func.__name__)._validate_input_data(args[0], data_type)
|
|
437
|
-
args = tuple(validated_args)
|
|
438
|
-
|
|
439
|
-
# 验证关键字参数
|
|
440
|
-
validated_kwargs = {}
|
|
441
|
-
for key, value in kwargs.items():
|
|
442
|
-
if key in ["data", "y_data", "x_data"]:
|
|
443
|
-
validated_kwargs[key] = EconometricTool(func.__name__)._validate_input_data(value, data_type)
|
|
444
|
-
else:
|
|
445
|
-
validated_kwargs[key] = value
|
|
446
|
-
|
|
447
|
-
return func(*args, **validated_kwargs)
|
|
448
|
-
|
|
449
|
-
return wrapper
|
|
450
|
-
|
|
451
|
-
return decorator
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
# 导出主要类和函数
|
|
455
|
-
__all__ = [
|
|
456
|
-
# 错误类
|
|
457
|
-
"EconometricToolError",
|
|
458
|
-
"DataValidationError",
|
|
459
|
-
"ModelFittingError",
|
|
460
|
-
"ConfigurationError",
|
|
461
|
-
# 基类
|
|
462
|
-
"EconometricTool",
|
|
463
|
-
# 装饰器
|
|
464
|
-
"with_file_input",
|
|
465
|
-
"with_error_handling",
|
|
466
|
-
"with_logging",
|
|
467
|
-
"with_file_support_decorator",
|
|
468
|
-
"econometric_tool_with_optimization",
|
|
469
|
-
"validate_input"
|
|
470
|
-
]
|