dea-toolkit 0.1.0__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.
dea_tobit.py ADDED
@@ -0,0 +1,344 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """DEA-Tobit:效率得分对环境变量的截断回归。
4
+
5
+ 第一步:用投入导向径向 DEA(CRS/VRS)计算效率 θ∈(0,1];
6
+ 第二步:以 θ 为因变量、环境变量为自变量做上限为 1 的 Tobit MLE:
7
+ θ_i = z_i·β + ε_i, ε_i ~ N(0, σ²)
8
+ 观测 θ_i = 1 视为在 1 处右截断。
9
+ 非期望产出按投入方向并入投入块(由 RadialModel 处理)。
10
+ """
11
+
12
+ import argparse
13
+ import os
14
+ import sys
15
+ from collections.abc import Sequence
16
+ from dataclasses import dataclass, field
17
+
18
+ import numpy as np
19
+ from scipy.optimize import minimize
20
+ from scipy.stats import norm
21
+
22
+ from dea_core import (
23
+ ColumnNames,
24
+ DataCommandLine,
25
+ DataSettings,
26
+ DEAData,
27
+ EFFICIENCY_TOLERANCE,
28
+ SCORE_DECIMALS,
29
+ format_table,
30
+ round_score,
31
+ write_csv_records,
32
+ )
33
+ from radial_models import RadialModel
34
+
35
+ # =============================== 用户配置区 ===============================
36
+ DATA_FILE = "sample_data.csv"
37
+ EXCEL_SHEET = 0
38
+
39
+ DMU_COLUMNS = ["城市代码", "年份"]
40
+ INPUT_COLUMNS = ["资本投入", "劳动投入"]
41
+ DESIRABLE_OUTPUT_COLUMNS = ["GDP", "财政收入"]
42
+ UNDESIRABLE_OUTPUT_COLUMNS = ["工业废水排放量"]
43
+ ENVIRONMENT_COLUMNS = ["产业结构"]
44
+
45
+ RETURNS_TO_SCALE = "vrs" # "crs" 或 "vrs"
46
+ CENSOR_LIMIT = 1.0 # 效率得分的右截断点
47
+ RESULT_FILE = None # 结果 CSV 输出路径;None 表示不导出
48
+
49
+
50
+ DATA_COMMAND_LINE = DataCommandLine(
51
+ settings=DataSettings(
52
+ data_file=DATA_FILE,
53
+ excel_sheet=EXCEL_SHEET,
54
+ dmu_columns=tuple(DMU_COLUMNS),
55
+ input_columns=tuple(INPUT_COLUMNS),
56
+ desirable_output_columns=tuple(DESIRABLE_OUTPUT_COLUMNS),
57
+ undesirable_output_columns=tuple(UNDESIRABLE_OUTPUT_COLUMNS),
58
+ environment_columns=tuple(ENVIRONMENT_COLUMNS),
59
+ result_file=RESULT_FILE,
60
+ ),
61
+ script_directory=os.path.dirname(os.path.abspath(__file__)),
62
+ )
63
+
64
+
65
+ @dataclass
66
+ class TobitResult:
67
+ """DEA-Tobit 结果。"""
68
+
69
+ variable_names: list[str]
70
+ coefficients: np.ndarray
71
+ standard_errors: np.ndarray
72
+ z_values: np.ndarray
73
+ p_values: np.ndarray
74
+ sigma: float
75
+ efficiencies: np.ndarray
76
+ censored_count: int
77
+ censor_limit: float
78
+ returns_to_scale: str
79
+ notes: list[str] = field(default_factory=list)
80
+
81
+ def to_records(self) -> list[dict[str, object]]:
82
+ """把每个回归系数展开成一条 CSV 记录。"""
83
+ records = []
84
+ for index, name in enumerate(self.variable_names):
85
+ records.append({
86
+ "variable": name,
87
+ "coefficient": round_score(self.coefficients[index]),
88
+ "standard_error": round_score(self.standard_errors[index]),
89
+ "z_value": round_score(self.z_values[index]),
90
+ "p_value": round_score(self.p_values[index]),
91
+ })
92
+ return records
93
+
94
+ def write_csv(self, path: str) -> None:
95
+ """写出 UTF-8-BOM 编码的结果 CSV。"""
96
+ write_csv_records(path, self.to_records())
97
+
98
+ def render_report(self, column_names: ColumnNames,
99
+ source_description: str | None = None) -> str:
100
+ """生成控制台报表文本。"""
101
+ returns_to_scale_description = (
102
+ "CRS 规模报酬不变" if self.returns_to_scale == "crs" else "VRS 规模报酬可变"
103
+ )
104
+ report_lines = [
105
+ f"模型: DEA-Tobit | {returns_to_scale_description} | "
106
+ f"右截断点 {self.censor_limit}"
107
+ ]
108
+ if source_description:
109
+ report_lines.append(f"数据: {source_description}")
110
+ report_lines.append(
111
+ f"环境变量: {'、'.join(column_names.environment_columns)} | "
112
+ f"DMU 数: {len(self.efficiencies)} | 截断观测: {self.censored_count}"
113
+ )
114
+ report_lines.append("")
115
+
116
+ table_rows = []
117
+ for index, name in enumerate(self.variable_names):
118
+ table_rows.append([
119
+ name,
120
+ f"{round_score(self.coefficients[index]):.{SCORE_DECIMALS}f}",
121
+ f"{round_score(self.standard_errors[index]):.{SCORE_DECIMALS}f}",
122
+ f"{round_score(self.z_values[index]):.{SCORE_DECIMALS}f}",
123
+ f"{round_score(self.p_values[index]):.{SCORE_DECIMALS}f}",
124
+ ])
125
+ report_lines.append(format_table(
126
+ ["变量", "系数", "标准误", "z", "p"], table_rows
127
+ ))
128
+ report_lines.append("")
129
+ report_lines.append(f"sigma: {round_score(self.sigma):.{SCORE_DECIMALS}f}")
130
+ report_lines.append(
131
+ "说明: 第一阶段为投入导向径向 DEA;第二阶段为上限 1 的 Tobit MLE"
132
+ )
133
+ report_lines.extend(f"提示: {note}" for note in self.notes[:10])
134
+ return "\n".join(report_lines)
135
+
136
+
137
+ class TobitModel:
138
+ """DEA-Tobit 求解器。"""
139
+
140
+ def __init__(self, returns_to_scale: str = "vrs",
141
+ censor_limit: float = 1.0,
142
+ efficiency_tolerance: float = EFFICIENCY_TOLERANCE):
143
+ returns_to_scale = returns_to_scale.lower()
144
+ if returns_to_scale not in ("crs", "vrs"):
145
+ raise ValueError("returns_to_scale 只能取 'crs' 或 'vrs'")
146
+ if censor_limit <= 0:
147
+ raise ValueError("censor_limit 必须为正数")
148
+ self.returns_to_scale = returns_to_scale
149
+ self.censor_limit = float(censor_limit)
150
+ self.efficiency_tolerance = float(efficiency_tolerance)
151
+
152
+ def solve(self, data: DEAData,
153
+ column_names: ColumnNames | None = None) -> TobitResult:
154
+ """执行两阶段 DEA-Tobit。"""
155
+ if data.environment_matrix.shape[0] == 0:
156
+ raise ValueError("DEA-Tobit 至少需要 1 个环境变量列")
157
+ radial_model = RadialModel(
158
+ orientation="input",
159
+ returns_to_scale=self.returns_to_scale,
160
+ score_mode="standard",
161
+ efficiency_tolerance=self.efficiency_tolerance,
162
+ )
163
+ efficiencies = radial_model.solve(data).standard_scores
164
+ design = np.column_stack([
165
+ np.ones(data.input_matrix.shape[1]), data.environment_matrix.T
166
+ ])
167
+ environment_names = (
168
+ list(column_names.environment_columns)
169
+ if column_names is not None and column_names.environment_columns
170
+ else [f"环境变量{index + 1}"
171
+ for index in range(data.environment_matrix.shape[0])]
172
+ )
173
+ if len(environment_names) != data.environment_matrix.shape[0]:
174
+ raise ValueError("环境变量列名数量与矩阵行数不一致")
175
+ variable_names = ["常数项", *environment_names]
176
+ coefficients, standard_errors, z_values, p_values, sigma, notes = (
177
+ self._fit_tobit(efficiencies, design)
178
+ )
179
+ censored_count = int(np.count_nonzero(
180
+ efficiencies >= self.censor_limit - self.efficiency_tolerance
181
+ ))
182
+ return TobitResult(
183
+ variable_names=variable_names,
184
+ coefficients=coefficients,
185
+ standard_errors=standard_errors,
186
+ z_values=z_values,
187
+ p_values=p_values,
188
+ sigma=sigma,
189
+ efficiencies=efficiencies,
190
+ censored_count=censored_count,
191
+ censor_limit=self.censor_limit,
192
+ returns_to_scale=self.returns_to_scale,
193
+ notes=notes,
194
+ )
195
+
196
+ def _fit_tobit(self, y: np.ndarray, design: np.ndarray
197
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, float, list[str]]:
198
+ """拟合右截断 Tobit,并返回系数、标准误、z、p、sigma 与提示。"""
199
+ y = np.asarray(y, dtype=float)
200
+ n_parameters = design.shape[1]
201
+ initial_coefficients, *_ = np.linalg.lstsq(design, y, rcond=None)
202
+ residual_std = float(np.std(y - design @ initial_coefficients, ddof=1))
203
+ initial_sigma = max(residual_std, 1e-3)
204
+ censored = y >= self.censor_limit - self.efficiency_tolerance
205
+ observed = ~censored
206
+ observed_y = y[observed]
207
+ observed_design = design[observed]
208
+ censored_design = design[censored]
209
+ observed_count = int(np.count_nonzero(observed))
210
+ notes: list[str] = []
211
+ if observed_count < n_parameters:
212
+ notes.append("非截断观测不足,Tobit 估计可能不稳定")
213
+
214
+ def negative_log_likelihood(parameters: np.ndarray) -> float:
215
+ coefficients = parameters[:n_parameters]
216
+ sigma = np.exp(parameters[-1])
217
+ log_likelihood = 0.0
218
+ if observed_count:
219
+ standardized = (
220
+ observed_y - observed_design @ coefficients
221
+ ) / sigma
222
+ log_likelihood += float(np.sum(
223
+ -np.log(sigma) + norm.logpdf(standardized)
224
+ ))
225
+ if np.any(censored):
226
+ upper = (
227
+ self.censor_limit - censored_design @ coefficients
228
+ ) / sigma
229
+ log_likelihood += float(np.sum(norm.logsf(upper)))
230
+ return -log_likelihood
231
+
232
+ result = minimize(
233
+ negative_log_likelihood,
234
+ np.concatenate([initial_coefficients, [np.log(initial_sigma)]]),
235
+ method="L-BFGS-B",
236
+ bounds=[(None, None)] * n_parameters + [(-20.0, 20.0)],
237
+ )
238
+ if not result.success:
239
+ raise RuntimeError(f"Tobit 估计失败: {result.message}")
240
+ coefficients = result.x[:n_parameters]
241
+ sigma = float(np.exp(result.x[-1]))
242
+ standard_errors, z_values, p_values = self._standard_errors(
243
+ coefficients, sigma, negative_log_likelihood
244
+ )
245
+ return coefficients, standard_errors, z_values, p_values, sigma, notes
246
+
247
+ @staticmethod
248
+ def _standard_errors(coefficients: np.ndarray, sigma: float,
249
+ negative_log_likelihood) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
250
+ """用数值 Hessian 计算渐近标准误、z 与双侧 p 值。"""
251
+ parameters = np.concatenate([coefficients, [np.log(sigma)]])
252
+ n_parameters = parameters.size
253
+ hessian = np.zeros((n_parameters, n_parameters))
254
+ step = 1e-4
255
+ for row in range(n_parameters):
256
+ for column in range(n_parameters):
257
+ plus_plus = parameters.copy()
258
+ plus_minus = parameters.copy()
259
+ minus_plus = parameters.copy()
260
+ minus_minus = parameters.copy()
261
+ plus_plus[row] += step
262
+ plus_plus[column] += step
263
+ plus_minus[row] += step
264
+ plus_minus[column] -= step
265
+ minus_plus[row] -= step
266
+ minus_plus[column] += step
267
+ minus_minus[row] -= step
268
+ minus_minus[column] -= step
269
+ hessian[row, column] = (
270
+ negative_log_likelihood(plus_plus)
271
+ - negative_log_likelihood(plus_minus)
272
+ - negative_log_likelihood(minus_plus)
273
+ + negative_log_likelihood(minus_minus)
274
+ ) / (4.0 * step ** 2)
275
+ try:
276
+ covariance = np.linalg.inv(hessian)
277
+ standard_errors = np.sqrt(np.maximum(np.diag(covariance), 0.0))
278
+ except np.linalg.LinAlgError:
279
+ standard_errors = np.full(n_parameters, np.nan)
280
+ z_values = coefficients / standard_errors[:coefficients.size]
281
+ p_values = 2.0 * norm.sf(np.abs(z_values))
282
+ return standard_errors[:coefficients.size], z_values, p_values
283
+
284
+
285
+ def build_parser() -> argparse.ArgumentParser:
286
+ argument_parser = argparse.ArgumentParser(
287
+ description="DEA-Tobit:径向 DEA 效率对环境变量的上限截断回归;"
288
+ "不带参数时使用脚本配置区",
289
+ formatter_class=argparse.RawDescriptionHelpFormatter,
290
+ epilog=(
291
+ "示例:\n"
292
+ " python dea_tobit.py --demo\n"
293
+ " python dea_tobit.py data.xlsx --environment-columns 产业结构\n"
294
+ ),
295
+ )
296
+ DATA_COMMAND_LINE.add_arguments(argument_parser)
297
+ argument_parser.add_argument("--returns-to-scale", "--rts",
298
+ choices=("crs", "vrs"), default=None,
299
+ help="第一阶段规模报酬: crs=不变, vrs=可变;"
300
+ "缺省用 RETURNS_TO_SCALE")
301
+ argument_parser.add_argument("--censor-limit", type=float, default=None,
302
+ help="效率右截断点;缺省用 CENSOR_LIMIT")
303
+ return argument_parser
304
+
305
+
306
+ def main(argv: Sequence[str] | None = None) -> int:
307
+ args = build_parser().parse_args(argv)
308
+ try:
309
+ prepared = DATA_COMMAND_LINE.prepare(args)
310
+ returns_to_scale = (
311
+ args.returns_to_scale if args.returns_to_scale is not None
312
+ else RETURNS_TO_SCALE
313
+ )
314
+ censor_limit = (
315
+ args.censor_limit if args.censor_limit is not None
316
+ else CENSOR_LIMIT
317
+ )
318
+ efficiency_tolerance = EFFICIENCY_TOLERANCE
319
+ model = TobitModel(
320
+ returns_to_scale=returns_to_scale,
321
+ censor_limit=censor_limit,
322
+ efficiency_tolerance=efficiency_tolerance,
323
+ )
324
+ result = model.solve(prepared.data, prepared.column_names)
325
+ except (ValueError, RuntimeError) as exc:
326
+ print(f"错误: {exc}", file=sys.stderr)
327
+ return 1
328
+
329
+ print(result.render_report(
330
+ prepared.column_names,
331
+ source_description=prepared.source_description,
332
+ ))
333
+ if prepared.result_file:
334
+ try:
335
+ result.write_csv(prepared.result_file)
336
+ except OSError as exc:
337
+ print(f"错误: 无法写入 {prepared.result_file}: {exc}", file=sys.stderr)
338
+ return 1
339
+ print(f"\n结果已写入: {prepared.result_file}")
340
+ return 0
341
+
342
+
343
+ if __name__ == "__main__":
344
+ sys.exit(main())