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.
- additive_models.py +440 -0
- bootstrap_dea.py +449 -0
- by_production.py +326 -0
- context_dependent_dea.py +423 -0
- cross_efficiency.py +411 -0
- dea_core.py +949 -0
- dea_tobit.py +344 -0
- dea_toolkit-0.1.0.dist-info/METADATA +533 -0
- dea_toolkit-0.1.0.dist-info/RECORD +28 -0
- dea_toolkit-0.1.0.dist-info/WHEEL +5 -0
- dea_toolkit-0.1.0.dist-info/entry_points.txt +22 -0
- dea_toolkit-0.1.0.dist-info/licenses/LICENSE +21 -0
- dea_toolkit-0.1.0.dist-info/top_level.txt +22 -0
- directional_distance.py +379 -0
- dynamic_sbm.py +506 -0
- interval_dea.py +340 -0
- inverse_dea.py +282 -0
- malmquist_index.py +596 -0
- meta_frontier.py +314 -0
- radial_models.py +503 -0
- stochastic_dea.py +332 -0
- super_sbm.py +590 -0
- three_stage_dea.py +376 -0
- two_stage_dea.py +290 -0
- undesirable_sbm.py +368 -0
- weak_disposability_ddf.py +326 -0
- weight_restricted_dea.py +313 -0
- window_analysis.py +330 -0
meta_frontier.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""共同前沿(Meta-frontier)DEA 脚本。
|
|
4
|
+
|
|
5
|
+
方法:
|
|
6
|
+
1. 对每个分组 g,以组内 DMU 为参考集计算组前沿投入导向径向效率 θ_g;
|
|
7
|
+
2. 以全部 DMU 为参考集计算共同前沿效率 θ_meta;
|
|
8
|
+
3. 技术落差比 TGR = θ_meta / θ_g(输入导向效率 ≤ 1,TGR ≤ 1)。
|
|
9
|
+
|
|
10
|
+
模型(投入导向径向,CRS/VRS):
|
|
11
|
+
min θ
|
|
12
|
+
s.t. X_ref·λ ≤ θ·x_o
|
|
13
|
+
Y_ref·λ ≥ y_o
|
|
14
|
+
λ ≥ 0(VRS 加 Σλ = 1)
|
|
15
|
+
非期望产出按投入方向并入投入块(越少越好)。
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import os
|
|
20
|
+
import sys
|
|
21
|
+
from collections.abc import Sequence
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
|
|
24
|
+
import numpy as np
|
|
25
|
+
|
|
26
|
+
from dea_core import (
|
|
27
|
+
ColumnNames,
|
|
28
|
+
DataCommandLine,
|
|
29
|
+
DataSettings,
|
|
30
|
+
DEAData,
|
|
31
|
+
EFFICIENCY_TOLERANCE,
|
|
32
|
+
SCORE_DECIMALS,
|
|
33
|
+
assign_ranks_with_ties,
|
|
34
|
+
format_table,
|
|
35
|
+
round_score,
|
|
36
|
+
solve_linear_program,
|
|
37
|
+
write_csv_records,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
# =============================== 用户配置区 ===============================
|
|
41
|
+
DATA_FILE = "sample_data.csv"
|
|
42
|
+
EXCEL_SHEET = 0
|
|
43
|
+
|
|
44
|
+
DMU_COLUMNS = ["城市代码", "年份"]
|
|
45
|
+
INPUT_COLUMNS = ["资本投入", "劳动投入"]
|
|
46
|
+
DESIRABLE_OUTPUT_COLUMNS = ["GDP", "财政收入"]
|
|
47
|
+
UNDESIRABLE_OUTPUT_COLUMNS = ["工业废水排放量"]
|
|
48
|
+
|
|
49
|
+
GROUP_COLUMN = "区域" # 分组列(如东/中/西部)
|
|
50
|
+
RETURNS_TO_SCALE = "crs" # "crs"=规模报酬不变,"vrs"=规模报酬可变
|
|
51
|
+
RESULT_FILE = None # 结果 CSV 输出路径;None 表示不导出
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
DATA_COMMAND_LINE = DataCommandLine(
|
|
55
|
+
settings=DataSettings(
|
|
56
|
+
data_file=DATA_FILE,
|
|
57
|
+
excel_sheet=EXCEL_SHEET,
|
|
58
|
+
dmu_columns=tuple(DMU_COLUMNS),
|
|
59
|
+
input_columns=tuple(INPUT_COLUMNS),
|
|
60
|
+
desirable_output_columns=tuple(DESIRABLE_OUTPUT_COLUMNS),
|
|
61
|
+
undesirable_output_columns=tuple(UNDESIRABLE_OUTPUT_COLUMNS),
|
|
62
|
+
group_column=GROUP_COLUMN,
|
|
63
|
+
result_file=RESULT_FILE,
|
|
64
|
+
),
|
|
65
|
+
script_directory=os.path.dirname(os.path.abspath(__file__)),
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass
|
|
70
|
+
class MetaFrontierResult:
|
|
71
|
+
"""共同前沿结果。"""
|
|
72
|
+
|
|
73
|
+
dmu_names: list[str]
|
|
74
|
+
groups: list[str]
|
|
75
|
+
group_efficiencies: np.ndarray
|
|
76
|
+
meta_efficiencies: np.ndarray
|
|
77
|
+
technology_gap_ratios: np.ndarray
|
|
78
|
+
efficiency_mask: np.ndarray
|
|
79
|
+
ranks: np.ndarray
|
|
80
|
+
returns_to_scale: str
|
|
81
|
+
notes: list[str] = field(default_factory=list)
|
|
82
|
+
|
|
83
|
+
def to_records(self) -> list[dict[str, object]]:
|
|
84
|
+
"""把每个 DMU 展开成一条 CSV 记录。"""
|
|
85
|
+
records = []
|
|
86
|
+
for dmu_index, dmu_name in enumerate(self.dmu_names):
|
|
87
|
+
records.append({
|
|
88
|
+
"dmu": dmu_name,
|
|
89
|
+
"group": self.groups[dmu_index],
|
|
90
|
+
"group_efficiency": round_score(self.group_efficiencies[dmu_index]),
|
|
91
|
+
"meta_efficiency": round_score(self.meta_efficiencies[dmu_index]),
|
|
92
|
+
"technology_gap_ratio": round_score(
|
|
93
|
+
self.technology_gap_ratios[dmu_index]
|
|
94
|
+
),
|
|
95
|
+
"efficient": int(self.efficiency_mask[dmu_index]),
|
|
96
|
+
"rank": int(self.ranks[dmu_index]),
|
|
97
|
+
})
|
|
98
|
+
return records
|
|
99
|
+
|
|
100
|
+
def write_csv(self, path: str) -> None:
|
|
101
|
+
"""写出 UTF-8-BOM 编码的结果 CSV。"""
|
|
102
|
+
write_csv_records(path, self.to_records())
|
|
103
|
+
|
|
104
|
+
def render_report(self, column_names: ColumnNames,
|
|
105
|
+
source_description: str | None = None) -> str:
|
|
106
|
+
"""生成控制台报表文本。"""
|
|
107
|
+
returns_to_scale_description = (
|
|
108
|
+
"CRS 规模报酬不变" if self.returns_to_scale == "crs" else "VRS 规模报酬可变"
|
|
109
|
+
)
|
|
110
|
+
report_lines = [
|
|
111
|
+
f"模型: 共同前沿 Meta-frontier(投入导向径向) | {returns_to_scale_description}"
|
|
112
|
+
]
|
|
113
|
+
if source_description:
|
|
114
|
+
report_lines.append(f"数据: {source_description}")
|
|
115
|
+
report_lines.append(
|
|
116
|
+
f"变量: 投入[{'、'.join(column_names.input_columns)}] | "
|
|
117
|
+
f"期望产出[{'、'.join(column_names.desirable_output_columns)}] | "
|
|
118
|
+
f"非期望产出[{'、'.join(column_names.undesirable_output_columns) or '无'}]"
|
|
119
|
+
)
|
|
120
|
+
report_lines.append(f"DMU 数: {len(self.dmu_names)}")
|
|
121
|
+
report_lines.append("")
|
|
122
|
+
|
|
123
|
+
table_rows = []
|
|
124
|
+
for dmu_index, dmu_name in enumerate(self.dmu_names):
|
|
125
|
+
group_efficiency = round_score(self.group_efficiencies[dmu_index])
|
|
126
|
+
meta_efficiency = round_score(self.meta_efficiencies[dmu_index])
|
|
127
|
+
technology_gap_ratio = round_score(
|
|
128
|
+
self.technology_gap_ratios[dmu_index]
|
|
129
|
+
)
|
|
130
|
+
table_rows.append([
|
|
131
|
+
dmu_name,
|
|
132
|
+
self.groups[dmu_index],
|
|
133
|
+
f"{group_efficiency:.{SCORE_DECIMALS}f}",
|
|
134
|
+
f"{meta_efficiency:.{SCORE_DECIMALS}f}",
|
|
135
|
+
f"{technology_gap_ratio:.{SCORE_DECIMALS}f}",
|
|
136
|
+
str(int(self.ranks[dmu_index])),
|
|
137
|
+
])
|
|
138
|
+
report_lines.append(format_table(
|
|
139
|
+
["DMU", "分组", "组前沿", "共同前沿", "TGR", "排名"], table_rows
|
|
140
|
+
))
|
|
141
|
+
report_lines.append("")
|
|
142
|
+
|
|
143
|
+
efficient_names = [self.dmu_names[i] for i in np.flatnonzero(self.efficiency_mask)]
|
|
144
|
+
report_lines.append(
|
|
145
|
+
f"共同前沿有效 DMU 共 {len(efficient_names)} 个: "
|
|
146
|
+
f"{'、'.join(efficient_names) if efficient_names else '无'}"
|
|
147
|
+
)
|
|
148
|
+
report_lines.append(
|
|
149
|
+
"说明: TGR = 共同前沿效率 / 组前沿效率,≤ 1;越接近 1 说明组前沿越接近共同前沿"
|
|
150
|
+
)
|
|
151
|
+
if column_names.undesirable_output_columns:
|
|
152
|
+
report_lines.append("说明: 非期望产出按投入方向处理(越少越好)")
|
|
153
|
+
report_lines.extend(f"提示: {note}" for note in self.notes[:10])
|
|
154
|
+
return "\n".join(report_lines)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class MetaFrontierModel:
|
|
158
|
+
"""共同前沿求解器(投入导向径向)。"""
|
|
159
|
+
|
|
160
|
+
def __init__(self, returns_to_scale: str = "crs",
|
|
161
|
+
efficiency_tolerance: float = EFFICIENCY_TOLERANCE):
|
|
162
|
+
returns_to_scale = returns_to_scale.lower()
|
|
163
|
+
if returns_to_scale not in ("crs", "vrs"):
|
|
164
|
+
raise ValueError("returns_to_scale 只能取 'crs' 或 'vrs'")
|
|
165
|
+
if efficiency_tolerance <= 0:
|
|
166
|
+
raise ValueError("efficiency_tolerance 必须为正数")
|
|
167
|
+
self.returns_to_scale = returns_to_scale
|
|
168
|
+
self.efficiency_tolerance = float(efficiency_tolerance)
|
|
169
|
+
|
|
170
|
+
def solve(self, data: DEAData) -> MetaFrontierResult:
|
|
171
|
+
"""计算组前沿、共同前沿与技术落差比。
|
|
172
|
+
|
|
173
|
+
处理逻辑:对每个 DMU 分别以本组 DMU 与全部 DMU 为参考集求投入导向
|
|
174
|
+
径向效率 → 计算 TGR = 共同前沿效率 / 组前沿效率 → 排名。
|
|
175
|
+
"""
|
|
176
|
+
if any(not group for group in data.groups):
|
|
177
|
+
raise ValueError("共同前沿需要每个 DMU 都有非空分组(GROUP_COLUMN)")
|
|
178
|
+
n_undesirable = data.undesirable_output_matrix.shape[0]
|
|
179
|
+
model_inputs = (
|
|
180
|
+
np.vstack([data.input_matrix, data.undesirable_output_matrix])
|
|
181
|
+
if n_undesirable else data.input_matrix
|
|
182
|
+
)
|
|
183
|
+
outputs = data.desirable_output_matrix
|
|
184
|
+
group_labels = np.asarray(data.groups)
|
|
185
|
+
all_indices = np.arange(data.input_matrix.shape[1])
|
|
186
|
+
|
|
187
|
+
meta_efficiencies = np.empty(data.input_matrix.shape[1])
|
|
188
|
+
group_efficiencies = np.empty(data.input_matrix.shape[1])
|
|
189
|
+
for dmu_index in all_indices:
|
|
190
|
+
meta_efficiencies[dmu_index] = self._solve_radial(
|
|
191
|
+
model_inputs, outputs, all_indices, int(dmu_index)
|
|
192
|
+
)
|
|
193
|
+
group_indices = np.flatnonzero(group_labels == group_labels[dmu_index])
|
|
194
|
+
group_efficiencies[dmu_index] = self._solve_radial(
|
|
195
|
+
model_inputs, outputs, group_indices, int(dmu_index)
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
technology_gap_ratios = np.divide(
|
|
199
|
+
meta_efficiencies, group_efficiencies,
|
|
200
|
+
out=np.full_like(meta_efficiencies, np.nan), where=group_efficiencies > 0,
|
|
201
|
+
)
|
|
202
|
+
notes: list[str] = []
|
|
203
|
+
if np.any(technology_gap_ratios > 1.0 + self.efficiency_tolerance):
|
|
204
|
+
notes.append("部分 TGR 大于 1,可能存在数值误差,请检查分组与参考集")
|
|
205
|
+
efficiency_mask = np.asarray(
|
|
206
|
+
meta_efficiencies >= 1.0 - self.efficiency_tolerance, dtype=bool
|
|
207
|
+
)
|
|
208
|
+
return MetaFrontierResult(
|
|
209
|
+
dmu_names=data.dmu_names,
|
|
210
|
+
groups=list(data.groups),
|
|
211
|
+
group_efficiencies=group_efficiencies,
|
|
212
|
+
meta_efficiencies=meta_efficiencies,
|
|
213
|
+
technology_gap_ratios=technology_gap_ratios,
|
|
214
|
+
efficiency_mask=efficiency_mask,
|
|
215
|
+
ranks=assign_ranks_with_ties(meta_efficiencies),
|
|
216
|
+
returns_to_scale=self.returns_to_scale,
|
|
217
|
+
notes=notes,
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
def _solve_radial(self, model_inputs: np.ndarray, outputs: np.ndarray,
|
|
221
|
+
reference_indices: np.ndarray, dmu_index: int) -> float:
|
|
222
|
+
"""求解第 dmu_index 个 DMU 的投入导向径向效率。"""
|
|
223
|
+
reference_inputs = model_inputs[:, reference_indices]
|
|
224
|
+
reference_outputs = outputs[:, reference_indices]
|
|
225
|
+
n_inputs = model_inputs.shape[0]
|
|
226
|
+
n_outputs = outputs.shape[0]
|
|
227
|
+
n_reference_dmus = reference_indices.size
|
|
228
|
+
n_variables = n_reference_dmus + 1
|
|
229
|
+
theta_column = n_reference_dmus
|
|
230
|
+
dmu_inputs = model_inputs[:, dmu_index]
|
|
231
|
+
dmu_outputs = outputs[:, dmu_index]
|
|
232
|
+
|
|
233
|
+
objective_coefficients = np.zeros(n_variables)
|
|
234
|
+
objective_coefficients[theta_column] = 1.0
|
|
235
|
+
|
|
236
|
+
inequality_matrix = np.zeros((n_inputs + n_outputs, n_variables))
|
|
237
|
+
inequality_rhs = np.zeros(n_inputs + n_outputs)
|
|
238
|
+
inequality_matrix[:n_inputs, :n_reference_dmus] = reference_inputs
|
|
239
|
+
inequality_matrix[:n_inputs, theta_column] = -dmu_inputs
|
|
240
|
+
inequality_matrix[n_inputs:, :n_reference_dmus] = -reference_outputs
|
|
241
|
+
inequality_rhs[n_inputs:] = -dmu_outputs
|
|
242
|
+
|
|
243
|
+
equality_matrix = None
|
|
244
|
+
equality_rhs = None
|
|
245
|
+
if self.returns_to_scale == "vrs":
|
|
246
|
+
equality_matrix = np.zeros((1, n_variables))
|
|
247
|
+
equality_matrix[0, :n_reference_dmus] = 1.0
|
|
248
|
+
equality_rhs = np.array([1.0])
|
|
249
|
+
|
|
250
|
+
solution = solve_linear_program(
|
|
251
|
+
objective_coefficients,
|
|
252
|
+
inequality_matrix=inequality_matrix, inequality_rhs=inequality_rhs,
|
|
253
|
+
equality_matrix=equality_matrix, equality_rhs=equality_rhs,
|
|
254
|
+
error_context=f"共同前沿径向求解失败(第 {dmu_index + 1} 个 DMU)",
|
|
255
|
+
)
|
|
256
|
+
return float(solution.x[theta_column])
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
260
|
+
argument_parser = argparse.ArgumentParser(
|
|
261
|
+
description="共同前沿 Meta-frontier(投入导向径向);"
|
|
262
|
+
"不带参数时使用脚本配置区",
|
|
263
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
264
|
+
epilog=(
|
|
265
|
+
"示例:\n"
|
|
266
|
+
" python meta_frontier.py --demo\n"
|
|
267
|
+
" python meta_frontier.py data.xlsx --group-column 区域 --returns-to-scale vrs\n"
|
|
268
|
+
),
|
|
269
|
+
)
|
|
270
|
+
DATA_COMMAND_LINE.add_arguments(argument_parser)
|
|
271
|
+
argument_parser.add_argument("--returns-to-scale", "--rts",
|
|
272
|
+
choices=("crs", "vrs"), default=None,
|
|
273
|
+
help="规模报酬: crs=不变, vrs=可变;缺省用 RETURNS_TO_SCALE")
|
|
274
|
+
argument_parser.add_argument("--tolerance", "--tol", type=float, default=None,
|
|
275
|
+
help=f"判定有效性的容差(默认 {EFFICIENCY_TOLERANCE})")
|
|
276
|
+
return argument_parser
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
280
|
+
args = build_parser().parse_args(argv)
|
|
281
|
+
try:
|
|
282
|
+
prepared = DATA_COMMAND_LINE.prepare(args)
|
|
283
|
+
returns_to_scale = (
|
|
284
|
+
args.returns_to_scale if args.returns_to_scale is not None
|
|
285
|
+
else RETURNS_TO_SCALE
|
|
286
|
+
)
|
|
287
|
+
efficiency_tolerance = (
|
|
288
|
+
args.tolerance if args.tolerance is not None else EFFICIENCY_TOLERANCE
|
|
289
|
+
)
|
|
290
|
+
model = MetaFrontierModel(
|
|
291
|
+
returns_to_scale=returns_to_scale,
|
|
292
|
+
efficiency_tolerance=efficiency_tolerance,
|
|
293
|
+
)
|
|
294
|
+
result = model.solve(prepared.data)
|
|
295
|
+
except (ValueError, RuntimeError) as exc:
|
|
296
|
+
print(f"错误: {exc}", file=sys.stderr)
|
|
297
|
+
return 1
|
|
298
|
+
|
|
299
|
+
print(result.render_report(
|
|
300
|
+
prepared.column_names,
|
|
301
|
+
source_description=prepared.source_description,
|
|
302
|
+
))
|
|
303
|
+
if prepared.result_file:
|
|
304
|
+
try:
|
|
305
|
+
result.write_csv(prepared.result_file)
|
|
306
|
+
except OSError as exc:
|
|
307
|
+
print(f"错误: 无法写入 {prepared.result_file}: {exc}", file=sys.stderr)
|
|
308
|
+
return 1
|
|
309
|
+
print(f"\n结果已写入: {prepared.result_file}")
|
|
310
|
+
return 0
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
if __name__ == "__main__":
|
|
314
|
+
sys.exit(main())
|