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
interval_dea.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""区间/模糊 DEA:投入产出的不确定性边界。
|
|
4
|
+
|
|
5
|
+
模型:
|
|
6
|
+
数据按相对不确定度 p 构造区间:
|
|
7
|
+
x ∈ [x(1-p), x(1+p)], y ∈ [y(1-p), y(1+p)]
|
|
8
|
+
对每个 DMU 计算投入导向径向效率的下界与上界:
|
|
9
|
+
- 下界(最差情形):自身投入取上界、产出取下界;其他 DMU 投入取下界、
|
|
10
|
+
产出取上界;
|
|
11
|
+
- 上界(最好情形):自身投入取下界、产出取上界;其他 DMU 投入取上界、
|
|
12
|
+
产出取下界;
|
|
13
|
+
- 中心得分:原始数据下的径向效率。
|
|
14
|
+
`MODE="fuzzy"` 使用三角模糊数的 α=0 支撑区间(上/下界)和 α=1 中心,
|
|
15
|
+
采用对称相对扩散 p。
|
|
16
|
+
|
|
17
|
+
非期望产出按投入方向并入投入块(越少越好),并随投入区间变化。
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
import argparse
|
|
21
|
+
import os
|
|
22
|
+
import sys
|
|
23
|
+
from collections.abc import Sequence
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
|
|
26
|
+
import numpy as np
|
|
27
|
+
|
|
28
|
+
from dea_core import (
|
|
29
|
+
ColumnNames,
|
|
30
|
+
DataCommandLine,
|
|
31
|
+
DataSettings,
|
|
32
|
+
DEAData,
|
|
33
|
+
EFFICIENCY_TOLERANCE,
|
|
34
|
+
SCORE_DECIMALS,
|
|
35
|
+
assign_ranks_with_ties,
|
|
36
|
+
format_table,
|
|
37
|
+
round_score,
|
|
38
|
+
solve_linear_program,
|
|
39
|
+
write_csv_records,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
# =============================== 用户配置区 ===============================
|
|
43
|
+
DATA_FILE = "sample_data.csv"
|
|
44
|
+
EXCEL_SHEET = 0
|
|
45
|
+
|
|
46
|
+
DMU_COLUMNS = ["城市代码", "年份"]
|
|
47
|
+
INPUT_COLUMNS = ["资本投入", "劳动投入"]
|
|
48
|
+
DESIRABLE_OUTPUT_COLUMNS = ["GDP", "财政收入"]
|
|
49
|
+
UNDESIRABLE_OUTPUT_COLUMNS = ["工业废水排放量"]
|
|
50
|
+
|
|
51
|
+
MODE = "interval" # "interval" 或 "fuzzy"
|
|
52
|
+
UNCERTAINTY_PERCENT = 0.05 # 相对扩散比例,例如 0.05 = ±5%
|
|
53
|
+
RETURNS_TO_SCALE = "crs" # "crs" 或 "vrs"
|
|
54
|
+
RESULT_FILE = None # 结果 CSV 输出路径;None 表示不导出
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
DATA_COMMAND_LINE = DataCommandLine(
|
|
58
|
+
settings=DataSettings(
|
|
59
|
+
data_file=DATA_FILE,
|
|
60
|
+
excel_sheet=EXCEL_SHEET,
|
|
61
|
+
dmu_columns=tuple(DMU_COLUMNS),
|
|
62
|
+
input_columns=tuple(INPUT_COLUMNS),
|
|
63
|
+
desirable_output_columns=tuple(DESIRABLE_OUTPUT_COLUMNS),
|
|
64
|
+
undesirable_output_columns=tuple(UNDESIRABLE_OUTPUT_COLUMNS),
|
|
65
|
+
result_file=RESULT_FILE,
|
|
66
|
+
),
|
|
67
|
+
script_directory=os.path.dirname(os.path.abspath(__file__)),
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class IntervalDEAResult:
|
|
73
|
+
"""区间/模糊 DEA 结果。"""
|
|
74
|
+
|
|
75
|
+
dmu_names: list[str]
|
|
76
|
+
lower_scores: np.ndarray
|
|
77
|
+
upper_scores: np.ndarray
|
|
78
|
+
center_scores: np.ndarray
|
|
79
|
+
efficiency_mask: np.ndarray
|
|
80
|
+
ranks: np.ndarray
|
|
81
|
+
mode: str
|
|
82
|
+
uncertainty_percent: float
|
|
83
|
+
returns_to_scale: str
|
|
84
|
+
notes: list[str] = field(default_factory=list)
|
|
85
|
+
|
|
86
|
+
def to_records(self) -> list[dict[str, object]]:
|
|
87
|
+
"""把每个 DMU 展开成一条 CSV 记录。"""
|
|
88
|
+
records = []
|
|
89
|
+
for index, dmu_name in enumerate(self.dmu_names):
|
|
90
|
+
lower = self.lower_scores[index]
|
|
91
|
+
upper = self.upper_scores[index]
|
|
92
|
+
midpoint = 0.5 * (lower + upper)
|
|
93
|
+
records.append({
|
|
94
|
+
"dmu": dmu_name,
|
|
95
|
+
"lower_score": None if np.isnan(lower) else round_score(lower),
|
|
96
|
+
"upper_score": None if np.isnan(upper) else round_score(upper),
|
|
97
|
+
"center_score": round_score(self.center_scores[index]),
|
|
98
|
+
"midpoint_score": None if np.isnan(midpoint) else round_score(midpoint),
|
|
99
|
+
"efficient": int(self.efficiency_mask[index]),
|
|
100
|
+
"rank": int(self.ranks[index]),
|
|
101
|
+
})
|
|
102
|
+
return records
|
|
103
|
+
|
|
104
|
+
def write_csv(self, path: str) -> None:
|
|
105
|
+
"""写出 UTF-8-BOM 编码的结果 CSV。"""
|
|
106
|
+
write_csv_records(path, self.to_records())
|
|
107
|
+
|
|
108
|
+
def render_report(self, column_names: ColumnNames,
|
|
109
|
+
source_description: str | None = None) -> str:
|
|
110
|
+
"""生成控制台报表文本。"""
|
|
111
|
+
mode_description = "三角模糊(α=0 支撑/α=1 中心)" if self.mode == "fuzzy" else "区间"
|
|
112
|
+
returns_to_scale_description = (
|
|
113
|
+
"CRS 规模报酬不变" if self.returns_to_scale == "crs" else "VRS 规模报酬可变"
|
|
114
|
+
)
|
|
115
|
+
report_lines = [
|
|
116
|
+
f"模型: {mode_description} DEA | {returns_to_scale_description} | "
|
|
117
|
+
f"不确定度 ±{self.uncertainty_percent:.2%}"
|
|
118
|
+
]
|
|
119
|
+
if source_description:
|
|
120
|
+
report_lines.append(f"数据: {source_description}")
|
|
121
|
+
report_lines.append(
|
|
122
|
+
f"投入: {'、'.join(column_names.input_columns)} | "
|
|
123
|
+
f"期望产出: {'、'.join(column_names.desirable_output_columns)} | "
|
|
124
|
+
f"非期望产出: {'、'.join(column_names.undesirable_output_columns) or '无'}"
|
|
125
|
+
)
|
|
126
|
+
report_lines.append(f"DMU 数: {len(self.dmu_names)}")
|
|
127
|
+
report_lines.append("")
|
|
128
|
+
|
|
129
|
+
table_rows = []
|
|
130
|
+
for index, dmu_name in enumerate(self.dmu_names):
|
|
131
|
+
lower = self.lower_scores[index]
|
|
132
|
+
upper = self.upper_scores[index]
|
|
133
|
+
table_rows.append([
|
|
134
|
+
dmu_name,
|
|
135
|
+
"-" if np.isnan(lower)
|
|
136
|
+
else f"{round_score(lower):.{SCORE_DECIMALS}f}",
|
|
137
|
+
"-" if np.isnan(upper)
|
|
138
|
+
else f"{round_score(upper):.{SCORE_DECIMALS}f}",
|
|
139
|
+
f"{round_score(self.center_scores[index]):.{SCORE_DECIMALS}f}",
|
|
140
|
+
str(int(self.ranks[index])),
|
|
141
|
+
])
|
|
142
|
+
report_lines.append(format_table(
|
|
143
|
+
["DMU", "下界", "上界", "中心", "排名"], table_rows
|
|
144
|
+
))
|
|
145
|
+
report_lines.append("")
|
|
146
|
+
report_lines.append(
|
|
147
|
+
"说明: 下界/上界为自身与参考集在区间端点的最差/最好径向效率;"
|
|
148
|
+
"排名按区间中点"
|
|
149
|
+
)
|
|
150
|
+
if column_names.undesirable_output_columns:
|
|
151
|
+
report_lines.append("说明: 非期望产出按投入方向处理(越少越好)")
|
|
152
|
+
report_lines.extend(f"提示: {note}" for note in self.notes[:10])
|
|
153
|
+
return "\n".join(report_lines)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class IntervalDEAModel:
|
|
157
|
+
"""区间/模糊 DEA 求解器(投入导向径向)。"""
|
|
158
|
+
|
|
159
|
+
def __init__(self, mode: str = "interval",
|
|
160
|
+
uncertainty_percent: float = 0.05,
|
|
161
|
+
returns_to_scale: str = "crs",
|
|
162
|
+
efficiency_tolerance: float = EFFICIENCY_TOLERANCE):
|
|
163
|
+
mode = mode.lower()
|
|
164
|
+
returns_to_scale = returns_to_scale.lower()
|
|
165
|
+
if mode not in ("interval", "fuzzy"):
|
|
166
|
+
raise ValueError("mode 只能取 'interval' 或 'fuzzy'")
|
|
167
|
+
if not 0 <= uncertainty_percent < 1:
|
|
168
|
+
raise ValueError("uncertainty_percent 必须在 [0, 1) 内")
|
|
169
|
+
if returns_to_scale not in ("crs", "vrs"):
|
|
170
|
+
raise ValueError("returns_to_scale 只能取 'crs' 或 'vrs'")
|
|
171
|
+
self.mode = mode
|
|
172
|
+
self.uncertainty_percent = float(uncertainty_percent)
|
|
173
|
+
self.returns_to_scale = returns_to_scale
|
|
174
|
+
self.efficiency_tolerance = float(efficiency_tolerance)
|
|
175
|
+
|
|
176
|
+
def solve(self, data: DEAData) -> IntervalDEAResult:
|
|
177
|
+
"""计算中心、下界与上界效率。"""
|
|
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
|
+
spread = self.uncertainty_percent
|
|
185
|
+
n_dmus = model_inputs.shape[1]
|
|
186
|
+
center_scores = np.empty(n_dmus)
|
|
187
|
+
lower_scores = np.empty(n_dmus)
|
|
188
|
+
upper_scores = np.empty(n_dmus)
|
|
189
|
+
notes: list[str] = []
|
|
190
|
+
for dmu_index in range(n_dmus):
|
|
191
|
+
center = self._solve_radial(
|
|
192
|
+
model_inputs, outputs, model_inputs, outputs, dmu_index
|
|
193
|
+
)
|
|
194
|
+
if center is None:
|
|
195
|
+
raise RuntimeError(
|
|
196
|
+
f"区间 DEA 中心效率求解失败(第 {dmu_index + 1} 个 DMU)"
|
|
197
|
+
)
|
|
198
|
+
center_scores[dmu_index] = center
|
|
199
|
+
# 下界:自身投入取上界、产出取下界,其他 DMU 取相反端点
|
|
200
|
+
lower = self._solve_radial(
|
|
201
|
+
model_inputs * (1.0 + spread), outputs * (1.0 - spread),
|
|
202
|
+
model_inputs * (1.0 - spread), outputs * (1.0 + spread),
|
|
203
|
+
dmu_index,
|
|
204
|
+
)
|
|
205
|
+
# 上界:自身投入取下界、产出取上界,其他 DMU 取相反端点
|
|
206
|
+
upper = self._solve_radial(
|
|
207
|
+
model_inputs * (1.0 - spread), outputs * (1.0 + spread),
|
|
208
|
+
model_inputs * (1.0 + spread), outputs * (1.0 - spread),
|
|
209
|
+
dmu_index,
|
|
210
|
+
)
|
|
211
|
+
if lower is None or upper is None:
|
|
212
|
+
notes.append(
|
|
213
|
+
f"DMU '{data.dmu_names[dmu_index]}' 的区间端点 LP 不可行,区间留空"
|
|
214
|
+
)
|
|
215
|
+
lower_scores[dmu_index] = np.nan
|
|
216
|
+
upper_scores[dmu_index] = np.nan
|
|
217
|
+
continue
|
|
218
|
+
if lower > upper:
|
|
219
|
+
lower, upper = upper, lower
|
|
220
|
+
lower_scores[dmu_index] = lower
|
|
221
|
+
upper_scores[dmu_index] = upper
|
|
222
|
+
efficiency_mask = np.asarray(
|
|
223
|
+
center_scores >= 1.0 - self.efficiency_tolerance, dtype=bool
|
|
224
|
+
)
|
|
225
|
+
midpoints = 0.5 * (lower_scores + upper_scores)
|
|
226
|
+
rank_basis = np.where(np.isnan(midpoints), center_scores, midpoints)
|
|
227
|
+
return IntervalDEAResult(
|
|
228
|
+
dmu_names=data.dmu_names,
|
|
229
|
+
lower_scores=lower_scores,
|
|
230
|
+
upper_scores=upper_scores,
|
|
231
|
+
center_scores=center_scores,
|
|
232
|
+
efficiency_mask=efficiency_mask,
|
|
233
|
+
ranks=assign_ranks_with_ties(rank_basis),
|
|
234
|
+
mode=self.mode,
|
|
235
|
+
uncertainty_percent=spread,
|
|
236
|
+
returns_to_scale=self.returns_to_scale,
|
|
237
|
+
notes=notes,
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
def _solve_radial(self, own_inputs: np.ndarray, own_outputs: np.ndarray,
|
|
241
|
+
peer_inputs: np.ndarray, peer_outputs: np.ndarray,
|
|
242
|
+
dmu_index: int) -> float | None:
|
|
243
|
+
"""在给定端点数据下求解投入导向径向效率。"""
|
|
244
|
+
n_inputs, n_dmus = peer_inputs.shape
|
|
245
|
+
n_outputs = peer_outputs.shape[0]
|
|
246
|
+
n_variables = n_dmus + 1
|
|
247
|
+
theta_column = n_dmus
|
|
248
|
+
objective = np.zeros(n_variables)
|
|
249
|
+
objective[theta_column] = 1.0
|
|
250
|
+
inequality = np.zeros((n_inputs + n_outputs, n_variables))
|
|
251
|
+
inequality[:n_inputs, :n_dmus] = peer_inputs
|
|
252
|
+
inequality[:n_inputs, theta_column] = -own_inputs[:, dmu_index]
|
|
253
|
+
inequality[n_inputs:, :n_dmus] = -peer_outputs
|
|
254
|
+
rhs = np.zeros(n_inputs + n_outputs)
|
|
255
|
+
rhs[n_inputs:] = -own_outputs[:, dmu_index]
|
|
256
|
+
equality_matrix, equality_rhs = self._convexity(n_variables, n_dmus)
|
|
257
|
+
solution = solve_linear_program(
|
|
258
|
+
objective,
|
|
259
|
+
inequality_matrix=inequality, inequality_rhs=rhs,
|
|
260
|
+
equality_matrix=equality_matrix, equality_rhs=equality_rhs,
|
|
261
|
+
error_context=f"区间 DEA 求解失败(第 {dmu_index + 1} 个 DMU)",
|
|
262
|
+
require_success=False,
|
|
263
|
+
)
|
|
264
|
+
if not solution.success:
|
|
265
|
+
return None
|
|
266
|
+
return float(solution.x[theta_column])
|
|
267
|
+
|
|
268
|
+
def _convexity(self, n_variables: int, n_dmus: int
|
|
269
|
+
) -> tuple[np.ndarray | None, np.ndarray | None]:
|
|
270
|
+
"""构造 VRS 凸性约束。"""
|
|
271
|
+
if self.returns_to_scale == "crs":
|
|
272
|
+
return None, None
|
|
273
|
+
equality = np.zeros((1, n_variables))
|
|
274
|
+
equality[0, :n_dmus] = 1.0
|
|
275
|
+
return equality, np.array([1.0])
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
279
|
+
argument_parser = argparse.ArgumentParser(
|
|
280
|
+
description="区间/模糊 DEA:投入产出的相对不确定度边界;"
|
|
281
|
+
"不带参数时使用脚本配置区",
|
|
282
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
283
|
+
epilog=(
|
|
284
|
+
"示例:\n"
|
|
285
|
+
" python interval_dea.py --demo --uncertainty 0.05\n"
|
|
286
|
+
" python interval_dea.py --demo --mode fuzzy --uncertainty 0.1\n"
|
|
287
|
+
),
|
|
288
|
+
)
|
|
289
|
+
DATA_COMMAND_LINE.add_arguments(argument_parser)
|
|
290
|
+
argument_parser.add_argument("--mode", choices=("interval", "fuzzy"), default=None,
|
|
291
|
+
help="模式: interval 或 fuzzy;缺省用 MODE")
|
|
292
|
+
argument_parser.add_argument("--uncertainty", type=float, default=None,
|
|
293
|
+
help="相对不确定度;缺省用 UNCERTAINTY_PERCENT")
|
|
294
|
+
argument_parser.add_argument("--returns-to-scale", "--rts",
|
|
295
|
+
choices=("crs", "vrs"), default=None,
|
|
296
|
+
help="规模报酬: crs=不变, vrs=可变;缺省用 RETURNS_TO_SCALE")
|
|
297
|
+
return argument_parser
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
301
|
+
args = build_parser().parse_args(argv)
|
|
302
|
+
try:
|
|
303
|
+
prepared = DATA_COMMAND_LINE.prepare(args)
|
|
304
|
+
mode = args.mode if args.mode is not None else MODE
|
|
305
|
+
uncertainty_percent = (
|
|
306
|
+
args.uncertainty if args.uncertainty is not None
|
|
307
|
+
else UNCERTAINTY_PERCENT
|
|
308
|
+
)
|
|
309
|
+
returns_to_scale = (
|
|
310
|
+
args.returns_to_scale if args.returns_to_scale is not None
|
|
311
|
+
else RETURNS_TO_SCALE
|
|
312
|
+
)
|
|
313
|
+
efficiency_tolerance = EFFICIENCY_TOLERANCE
|
|
314
|
+
model = IntervalDEAModel(
|
|
315
|
+
mode=mode,
|
|
316
|
+
uncertainty_percent=uncertainty_percent,
|
|
317
|
+
returns_to_scale=returns_to_scale,
|
|
318
|
+
efficiency_tolerance=efficiency_tolerance,
|
|
319
|
+
)
|
|
320
|
+
result = model.solve(prepared.data)
|
|
321
|
+
except (ValueError, RuntimeError) as exc:
|
|
322
|
+
print(f"错误: {exc}", file=sys.stderr)
|
|
323
|
+
return 1
|
|
324
|
+
|
|
325
|
+
print(result.render_report(
|
|
326
|
+
prepared.column_names,
|
|
327
|
+
source_description=prepared.source_description,
|
|
328
|
+
))
|
|
329
|
+
if prepared.result_file:
|
|
330
|
+
try:
|
|
331
|
+
result.write_csv(prepared.result_file)
|
|
332
|
+
except OSError as exc:
|
|
333
|
+
print(f"错误: 无法写入 {prepared.result_file}: {exc}", file=sys.stderr)
|
|
334
|
+
return 1
|
|
335
|
+
print(f"\n结果已写入: {prepared.result_file}")
|
|
336
|
+
return 0
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
if __name__ == "__main__":
|
|
340
|
+
sys.exit(main())
|
inverse_dea.py
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""反推型 Inverse DEA:给定产出目标,求最小径向投入。
|
|
4
|
+
|
|
5
|
+
模型(投入导向,CRS/VRS):
|
|
6
|
+
min α
|
|
7
|
+
s.t. X·λ ≤ α·x_o
|
|
8
|
+
Y·λ ≥ f·y_o
|
|
9
|
+
λ ≥ 0(VRS 加 Σλ = 1)
|
|
10
|
+
α ≥ 0
|
|
11
|
+
其中 f 为目标产出倍数(TARGET_OUTPUT_FACTOR),α 为所需投入相对原投入的比例;
|
|
12
|
+
所需投入为 α·x_o。该模型采用比例投入调整,是 Inverse DEA 的径向简化版本。
|
|
13
|
+
|
|
14
|
+
当前不处理非期望产出;若数据含非期望产出列,报表会提示忽略。
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import argparse
|
|
18
|
+
import os
|
|
19
|
+
import sys
|
|
20
|
+
from collections.abc import Sequence
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
|
|
25
|
+
from dea_core import (
|
|
26
|
+
ColumnNames,
|
|
27
|
+
DataCommandLine,
|
|
28
|
+
DataSettings,
|
|
29
|
+
DEAData,
|
|
30
|
+
SCORE_DECIMALS,
|
|
31
|
+
format_table,
|
|
32
|
+
round_score,
|
|
33
|
+
solve_linear_program,
|
|
34
|
+
write_csv_records,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
# =============================== 用户配置区 ===============================
|
|
38
|
+
DATA_FILE = "sample_data.csv"
|
|
39
|
+
EXCEL_SHEET = 0
|
|
40
|
+
|
|
41
|
+
DMU_COLUMNS = ["城市代码", "年份"]
|
|
42
|
+
INPUT_COLUMNS = ["资本投入", "劳动投入"]
|
|
43
|
+
DESIRABLE_OUTPUT_COLUMNS = ["GDP", "财政收入"]
|
|
44
|
+
UNDESIRABLE_OUTPUT_COLUMNS = [] # Inverse DEA 当前不处理非期望产出
|
|
45
|
+
|
|
46
|
+
TARGET_OUTPUT_FACTOR = 1.1 # 目标产出 = 原产出 × f
|
|
47
|
+
RETURNS_TO_SCALE = "crs" # "crs" 或 "vrs"
|
|
48
|
+
RESULT_FILE = None # 结果 CSV 输出路径;None 表示不导出
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
DATA_COMMAND_LINE = DataCommandLine(
|
|
52
|
+
settings=DataSettings(
|
|
53
|
+
data_file=DATA_FILE,
|
|
54
|
+
excel_sheet=EXCEL_SHEET,
|
|
55
|
+
dmu_columns=tuple(DMU_COLUMNS),
|
|
56
|
+
input_columns=tuple(INPUT_COLUMNS),
|
|
57
|
+
desirable_output_columns=tuple(DESIRABLE_OUTPUT_COLUMNS),
|
|
58
|
+
undesirable_output_columns=tuple(UNDESIRABLE_OUTPUT_COLUMNS),
|
|
59
|
+
result_file=RESULT_FILE,
|
|
60
|
+
),
|
|
61
|
+
script_directory=os.path.dirname(os.path.abspath(__file__)),
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass
|
|
66
|
+
class InverseDEAResult:
|
|
67
|
+
"""Inverse DEA 结果。"""
|
|
68
|
+
|
|
69
|
+
dmu_names: list[str]
|
|
70
|
+
target_output_factor: float
|
|
71
|
+
input_multipliers: np.ndarray
|
|
72
|
+
required_inputs: np.ndarray
|
|
73
|
+
feasible_mask: np.ndarray
|
|
74
|
+
returns_to_scale: str
|
|
75
|
+
notes: list[str] = field(default_factory=list)
|
|
76
|
+
|
|
77
|
+
def to_records(self, column_names: ColumnNames) -> list[dict[str, object]]:
|
|
78
|
+
"""把每个 DMU 展开成一条 CSV 记录。"""
|
|
79
|
+
records = []
|
|
80
|
+
for dmu_index, dmu_name in enumerate(self.dmu_names):
|
|
81
|
+
record: dict[str, object] = {
|
|
82
|
+
"dmu": dmu_name,
|
|
83
|
+
"target_output_factor": self.target_output_factor,
|
|
84
|
+
"input_multiplier": (
|
|
85
|
+
None if not self.feasible_mask[dmu_index]
|
|
86
|
+
else round_score(self.input_multipliers[dmu_index])
|
|
87
|
+
),
|
|
88
|
+
"feasible": int(self.feasible_mask[dmu_index]),
|
|
89
|
+
}
|
|
90
|
+
for input_index, name in enumerate(column_names.input_columns):
|
|
91
|
+
record[f"required_input_{name}"] = (
|
|
92
|
+
None if not self.feasible_mask[dmu_index]
|
|
93
|
+
else round_score(self.required_inputs[dmu_index, input_index])
|
|
94
|
+
)
|
|
95
|
+
records.append(record)
|
|
96
|
+
return records
|
|
97
|
+
|
|
98
|
+
def write_csv(self, path: str, column_names: ColumnNames) -> None:
|
|
99
|
+
"""写出 UTF-8-BOM 编码的结果 CSV。"""
|
|
100
|
+
write_csv_records(path, self.to_records(column_names))
|
|
101
|
+
|
|
102
|
+
def render_report(self, column_names: ColumnNames,
|
|
103
|
+
source_description: str | None = None) -> str:
|
|
104
|
+
"""生成控制台报表文本。"""
|
|
105
|
+
returns_to_scale_description = (
|
|
106
|
+
"CRS 规模报酬不变" if self.returns_to_scale == "crs" else "VRS 规模报酬可变"
|
|
107
|
+
)
|
|
108
|
+
report_lines = [
|
|
109
|
+
f"模型: Inverse DEA(比例投入反推) | {returns_to_scale_description} | "
|
|
110
|
+
f"目标产出倍数 f={self.target_output_factor}"
|
|
111
|
+
]
|
|
112
|
+
if source_description:
|
|
113
|
+
report_lines.append(f"数据: {source_description}")
|
|
114
|
+
report_lines.append(
|
|
115
|
+
f"投入: {'、'.join(column_names.input_columns)} | "
|
|
116
|
+
f"目标产出: {'、'.join(column_names.desirable_output_columns)} × f"
|
|
117
|
+
)
|
|
118
|
+
report_lines.append(f"DMU 数: {len(self.dmu_names)}")
|
|
119
|
+
report_lines.append("")
|
|
120
|
+
|
|
121
|
+
table_rows = []
|
|
122
|
+
for dmu_index, dmu_name in enumerate(self.dmu_names):
|
|
123
|
+
if self.feasible_mask[dmu_index]:
|
|
124
|
+
multiplier = round_score(self.input_multipliers[dmu_index])
|
|
125
|
+
table_rows.append([
|
|
126
|
+
dmu_name,
|
|
127
|
+
f"{multiplier:.{SCORE_DECIMALS}f}",
|
|
128
|
+
f"{self.target_output_factor:.{SCORE_DECIMALS}f}",
|
|
129
|
+
])
|
|
130
|
+
else:
|
|
131
|
+
table_rows.append([dmu_name, "-", "-"])
|
|
132
|
+
report_lines.append(format_table(
|
|
133
|
+
["DMU", "投入倍数 α", "目标产出倍数 f"], table_rows
|
|
134
|
+
))
|
|
135
|
+
report_lines.append("")
|
|
136
|
+
report_lines.append(
|
|
137
|
+
"说明: 所需投入 = α × 原投入;当前采用比例投入调整,"
|
|
138
|
+
"不是逐项非比例反推"
|
|
139
|
+
)
|
|
140
|
+
report_lines.extend(f"提示: {note}" for note in self.notes[:10])
|
|
141
|
+
return "\n".join(report_lines)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class InverseDEAModel:
|
|
145
|
+
"""Inverse DEA 求解器(比例投入)。"""
|
|
146
|
+
|
|
147
|
+
def __init__(self, target_output_factor: float = 1.1,
|
|
148
|
+
returns_to_scale: str = "crs"):
|
|
149
|
+
if target_output_factor <= 0:
|
|
150
|
+
raise ValueError("target_output_factor 必须为正数")
|
|
151
|
+
returns_to_scale = returns_to_scale.lower()
|
|
152
|
+
if returns_to_scale not in ("crs", "vrs"):
|
|
153
|
+
raise ValueError("returns_to_scale 只能取 'crs' 或 'vrs'")
|
|
154
|
+
self.target_output_factor = float(target_output_factor)
|
|
155
|
+
self.returns_to_scale = returns_to_scale
|
|
156
|
+
|
|
157
|
+
def solve(self, data: DEAData) -> InverseDEAResult:
|
|
158
|
+
"""对所有 DMU 求目标产出下的最小比例投入。"""
|
|
159
|
+
X = data.input_matrix
|
|
160
|
+
Y = data.desirable_output_matrix
|
|
161
|
+
n_dmus = X.shape[1]
|
|
162
|
+
n_inputs = X.shape[0]
|
|
163
|
+
multipliers = np.full(n_dmus, np.nan)
|
|
164
|
+
required_inputs = np.full((n_dmus, n_inputs), np.nan)
|
|
165
|
+
feasible_mask = np.zeros(n_dmus, dtype=bool)
|
|
166
|
+
notes: list[str] = []
|
|
167
|
+
if data.undesirable_output_matrix.shape[0]:
|
|
168
|
+
notes.append("Inverse DEA 暂未纳入非期望产出;当前期非期望产出已被忽略")
|
|
169
|
+
|
|
170
|
+
for dmu_index in range(n_dmus):
|
|
171
|
+
success, multiplier = self._solve_dmu(X, Y, dmu_index)
|
|
172
|
+
if not success:
|
|
173
|
+
notes.append(f"DMU '{data.dmu_names[dmu_index]}' 的目标产出不可行")
|
|
174
|
+
continue
|
|
175
|
+
feasible_mask[dmu_index] = True
|
|
176
|
+
multipliers[dmu_index] = multiplier
|
|
177
|
+
required_inputs[dmu_index] = multiplier * X[:, dmu_index]
|
|
178
|
+
|
|
179
|
+
return InverseDEAResult(
|
|
180
|
+
dmu_names=data.dmu_names,
|
|
181
|
+
target_output_factor=self.target_output_factor,
|
|
182
|
+
input_multipliers=multipliers,
|
|
183
|
+
required_inputs=required_inputs,
|
|
184
|
+
feasible_mask=feasible_mask,
|
|
185
|
+
returns_to_scale=self.returns_to_scale,
|
|
186
|
+
notes=notes,
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
def _solve_dmu(self, X: np.ndarray, Y: np.ndarray,
|
|
190
|
+
dmu_index: int) -> tuple[bool, float]:
|
|
191
|
+
"""求解单个 DMU 的 min α 反推模型。"""
|
|
192
|
+
n_inputs, n_dmus = X.shape
|
|
193
|
+
n_outputs = Y.shape[0]
|
|
194
|
+
n_variables = n_dmus + 1
|
|
195
|
+
alpha_column = n_dmus
|
|
196
|
+
x_o = X[:, dmu_index]
|
|
197
|
+
y_o = Y[:, dmu_index]
|
|
198
|
+
|
|
199
|
+
objective = np.zeros(n_variables)
|
|
200
|
+
objective[alpha_column] = 1.0
|
|
201
|
+
inequality_matrix = np.zeros((n_inputs + n_outputs, n_variables))
|
|
202
|
+
inequality_matrix[:n_inputs, :n_dmus] = X
|
|
203
|
+
inequality_matrix[:n_inputs, alpha_column] = -x_o
|
|
204
|
+
inequality_matrix[n_inputs:, :n_dmus] = -Y
|
|
205
|
+
inequality_rhs = np.zeros(n_inputs + n_outputs)
|
|
206
|
+
inequality_rhs[n_inputs:] = -self.target_output_factor * y_o
|
|
207
|
+
|
|
208
|
+
equality_matrix = None
|
|
209
|
+
equality_rhs = None
|
|
210
|
+
if self.returns_to_scale == "vrs":
|
|
211
|
+
equality_matrix = np.zeros((1, n_variables))
|
|
212
|
+
equality_matrix[0, :n_dmus] = 1.0
|
|
213
|
+
equality_rhs = np.array([1.0])
|
|
214
|
+
|
|
215
|
+
solution = solve_linear_program(
|
|
216
|
+
objective,
|
|
217
|
+
inequality_matrix=inequality_matrix, inequality_rhs=inequality_rhs,
|
|
218
|
+
equality_matrix=equality_matrix, equality_rhs=equality_rhs,
|
|
219
|
+
error_context=f"Inverse DEA 求解失败(第 {dmu_index + 1} 个 DMU)",
|
|
220
|
+
require_success=False,
|
|
221
|
+
)
|
|
222
|
+
if not solution.success:
|
|
223
|
+
return False, np.nan
|
|
224
|
+
return True, float(solution.x[alpha_column])
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
228
|
+
argument_parser = argparse.ArgumentParser(
|
|
229
|
+
description="Inverse DEA:给定产出目标求最小比例投入;"
|
|
230
|
+
"不带参数时使用脚本配置区",
|
|
231
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
232
|
+
epilog=(
|
|
233
|
+
"示例:\n"
|
|
234
|
+
" python inverse_dea.py --demo --factor 1.1\n"
|
|
235
|
+
" python inverse_dea.py data.xlsx --factor 1.2 --returns-to-scale vrs\n"
|
|
236
|
+
),
|
|
237
|
+
)
|
|
238
|
+
DATA_COMMAND_LINE.add_arguments(argument_parser)
|
|
239
|
+
argument_parser.add_argument("--factor", type=float, default=None,
|
|
240
|
+
help="目标产出倍数;缺省用 TARGET_OUTPUT_FACTOR")
|
|
241
|
+
argument_parser.add_argument("--returns-to-scale", "--rts",
|
|
242
|
+
choices=("crs", "vrs"), default=None,
|
|
243
|
+
help="规模报酬: crs=不变, vrs=可变;缺省用 RETURNS_TO_SCALE")
|
|
244
|
+
return argument_parser
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
248
|
+
args = build_parser().parse_args(argv)
|
|
249
|
+
try:
|
|
250
|
+
prepared = DATA_COMMAND_LINE.prepare(args)
|
|
251
|
+
target_output_factor = (
|
|
252
|
+
args.factor if args.factor is not None else TARGET_OUTPUT_FACTOR
|
|
253
|
+
)
|
|
254
|
+
returns_to_scale = (
|
|
255
|
+
args.returns_to_scale if args.returns_to_scale is not None
|
|
256
|
+
else RETURNS_TO_SCALE
|
|
257
|
+
)
|
|
258
|
+
model = InverseDEAModel(
|
|
259
|
+
target_output_factor=target_output_factor,
|
|
260
|
+
returns_to_scale=returns_to_scale,
|
|
261
|
+
)
|
|
262
|
+
result = model.solve(prepared.data)
|
|
263
|
+
except (ValueError, RuntimeError) as exc:
|
|
264
|
+
print(f"错误: {exc}", file=sys.stderr)
|
|
265
|
+
return 1
|
|
266
|
+
|
|
267
|
+
print(result.render_report(
|
|
268
|
+
prepared.column_names,
|
|
269
|
+
source_description=prepared.source_description,
|
|
270
|
+
))
|
|
271
|
+
if prepared.result_file:
|
|
272
|
+
try:
|
|
273
|
+
result.write_csv(prepared.result_file, prepared.column_names)
|
|
274
|
+
except OSError as exc:
|
|
275
|
+
print(f"错误: 无法写入 {prepared.result_file}: {exc}", file=sys.stderr)
|
|
276
|
+
return 1
|
|
277
|
+
print(f"\n结果已写入: {prepared.result_file}")
|
|
278
|
+
return 0
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
if __name__ == "__main__":
|
|
282
|
+
sys.exit(main())
|