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
undesirable_sbm.py
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""严格非期望产出 SBM(Tone 2003)脚本。
|
|
4
|
+
|
|
5
|
+
模型(非导向):
|
|
6
|
+
ρ = [1 - (1/m)·Σ_i s⁻_i/x_io] /
|
|
7
|
+
[1 + (1/(s+b))·(Σ_r s⁺_r/y_ro + Σ_q s^b_q/b_qo)]
|
|
8
|
+
s.t. Xλ + s⁻ = x_o
|
|
9
|
+
Yλ - s⁺ = y_o
|
|
10
|
+
Bλ + s^b = b_o
|
|
11
|
+
λ ≥ 0(VRS 加 Σλ = 1)
|
|
12
|
+
s⁻, s⁺, s^b ≥ 0
|
|
13
|
+
其中 B 为非期望产出:投影要求 Bλ ≤ b_o,s^b 为“非期望产出冗余”。
|
|
14
|
+
本模型把非期望产出作为越少越好的产出处理(强可处置),与
|
|
15
|
+
`super_sbm.py` 把非期望产出并入投入块的简化做法不同。
|
|
16
|
+
|
|
17
|
+
Charnes-Cooper 变换后:变量 Λ=tλ、S⁻=ts⁻、S⁺=ts⁺、S^b=ts^b、t。
|
|
18
|
+
min t - (1/m)·Σ_i S⁻_i/x_io
|
|
19
|
+
s.t. XΛ + S⁻ - t·x_o = 0
|
|
20
|
+
YΛ - S⁺ - t·y_o = 0
|
|
21
|
+
BΛ + S^b - t·b_o = 0
|
|
22
|
+
t + (1/(s+b))·(Σ_r S⁺_r/y_ro + Σ_q S^b_q/b_qo) = 1
|
|
23
|
+
ΣΛ - t = 0(仅 VRS)
|
|
24
|
+
Λ, S⁻, S⁺, S^b, t ≥ 0
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
import argparse
|
|
28
|
+
import os
|
|
29
|
+
import sys
|
|
30
|
+
from collections.abc import Sequence
|
|
31
|
+
from dataclasses import dataclass, field
|
|
32
|
+
|
|
33
|
+
import numpy as np
|
|
34
|
+
|
|
35
|
+
from dea_core import (
|
|
36
|
+
ColumnNames,
|
|
37
|
+
DataCommandLine,
|
|
38
|
+
DataSettings,
|
|
39
|
+
DEAData,
|
|
40
|
+
EFFICIENCY_TOLERANCE,
|
|
41
|
+
MIN_SCALING_FACTOR,
|
|
42
|
+
SCORE_DECIMALS,
|
|
43
|
+
assign_ranks_with_ties,
|
|
44
|
+
format_table,
|
|
45
|
+
round_score,
|
|
46
|
+
solve_linear_program,
|
|
47
|
+
write_csv_records,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
# =============================== 用户配置区 ===============================
|
|
51
|
+
DATA_FILE = "sample_data.csv"
|
|
52
|
+
EXCEL_SHEET = 0
|
|
53
|
+
|
|
54
|
+
DMU_COLUMNS = ["城市代码", "年份"]
|
|
55
|
+
INPUT_COLUMNS = ["资本投入", "劳动投入"]
|
|
56
|
+
DESIRABLE_OUTPUT_COLUMNS = ["GDP", "财政收入"]
|
|
57
|
+
UNDESIRABLE_OUTPUT_COLUMNS = ["工业废水排放量"]
|
|
58
|
+
|
|
59
|
+
RETURNS_TO_SCALE = "crs" # "crs"=规模报酬不变,"vrs"=规模报酬可变
|
|
60
|
+
RESULT_FILE = None # 结果 CSV 输出路径;None 表示不导出
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
DATA_COMMAND_LINE = DataCommandLine(
|
|
64
|
+
settings=DataSettings(
|
|
65
|
+
data_file=DATA_FILE,
|
|
66
|
+
excel_sheet=EXCEL_SHEET,
|
|
67
|
+
dmu_columns=tuple(DMU_COLUMNS),
|
|
68
|
+
input_columns=tuple(INPUT_COLUMNS),
|
|
69
|
+
desirable_output_columns=tuple(DESIRABLE_OUTPUT_COLUMNS),
|
|
70
|
+
undesirable_output_columns=tuple(UNDESIRABLE_OUTPUT_COLUMNS),
|
|
71
|
+
result_file=RESULT_FILE,
|
|
72
|
+
),
|
|
73
|
+
script_directory=os.path.dirname(os.path.abspath(__file__)),
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass
|
|
78
|
+
class UndesirableSBMResult:
|
|
79
|
+
"""严格非期望产出 SBM 的结果,含报表与 CSV 导出。"""
|
|
80
|
+
|
|
81
|
+
dmu_names: list[str]
|
|
82
|
+
scores: np.ndarray
|
|
83
|
+
efficiency_mask: np.ndarray
|
|
84
|
+
ranks: np.ndarray
|
|
85
|
+
input_slacks: np.ndarray
|
|
86
|
+
desirable_output_slacks: np.ndarray
|
|
87
|
+
undesirable_output_slacks: np.ndarray
|
|
88
|
+
returns_to_scale: str
|
|
89
|
+
notes: list[str] = field(default_factory=list)
|
|
90
|
+
|
|
91
|
+
def to_records(self, column_names: ColumnNames) -> list[dict[str, object]]:
|
|
92
|
+
"""把每个 DMU 展开成一条 CSV 记录。"""
|
|
93
|
+
if (len(column_names.input_columns) != self.input_slacks.shape[1]
|
|
94
|
+
or len(column_names.desirable_output_columns)
|
|
95
|
+
!= self.desirable_output_slacks.shape[1]
|
|
96
|
+
or len(column_names.undesirable_output_columns)
|
|
97
|
+
!= self.undesirable_output_slacks.shape[1]):
|
|
98
|
+
raise ValueError("指标名称数量与松弛矩阵不匹配")
|
|
99
|
+
|
|
100
|
+
records = []
|
|
101
|
+
for dmu_index, dmu_name in enumerate(self.dmu_names):
|
|
102
|
+
record: dict[str, object] = {
|
|
103
|
+
"dmu": dmu_name,
|
|
104
|
+
"score": round_score(self.scores[dmu_index]),
|
|
105
|
+
"efficient": int(self.efficiency_mask[dmu_index]),
|
|
106
|
+
"rank": int(self.ranks[dmu_index]),
|
|
107
|
+
}
|
|
108
|
+
for indicator_index, column_name in enumerate(column_names.input_columns):
|
|
109
|
+
record[f"input_slack_{column_name}"] = round_score(
|
|
110
|
+
self.input_slacks[dmu_index, indicator_index]
|
|
111
|
+
)
|
|
112
|
+
for indicator_index, column_name in enumerate(
|
|
113
|
+
column_names.desirable_output_columns):
|
|
114
|
+
record[f"desirable_output_slack_{column_name}"] = round_score(
|
|
115
|
+
self.desirable_output_slacks[dmu_index, indicator_index]
|
|
116
|
+
)
|
|
117
|
+
for indicator_index, column_name in enumerate(
|
|
118
|
+
column_names.undesirable_output_columns):
|
|
119
|
+
record[f"undesirable_output_slack_{column_name}"] = round_score(
|
|
120
|
+
self.undesirable_output_slacks[dmu_index, indicator_index]
|
|
121
|
+
)
|
|
122
|
+
records.append(record)
|
|
123
|
+
return records
|
|
124
|
+
|
|
125
|
+
def write_csv(self, path: str, column_names: ColumnNames) -> None:
|
|
126
|
+
"""写出 UTF-8-BOM 编码的结果 CSV。"""
|
|
127
|
+
write_csv_records(path, self.to_records(column_names))
|
|
128
|
+
|
|
129
|
+
def render_report(self, column_names: ColumnNames,
|
|
130
|
+
source_description: str | None = None) -> str:
|
|
131
|
+
"""生成控制台报表文本。"""
|
|
132
|
+
returns_to_scale_description = (
|
|
133
|
+
"CRS 规模报酬不变" if self.returns_to_scale == "crs" else "VRS 规模报酬可变"
|
|
134
|
+
)
|
|
135
|
+
report_lines = [
|
|
136
|
+
f"模型: SBM-Undesirable(Tone 2003) | {returns_to_scale_description}"
|
|
137
|
+
]
|
|
138
|
+
if source_description:
|
|
139
|
+
report_lines.append(f"数据: {source_description}")
|
|
140
|
+
report_lines.append(
|
|
141
|
+
f"变量: 投入[{'、'.join(column_names.input_columns)}] | "
|
|
142
|
+
f"期望产出[{'、'.join(column_names.desirable_output_columns)}] | "
|
|
143
|
+
f"非期望产出[{'、'.join(column_names.undesirable_output_columns)}]"
|
|
144
|
+
)
|
|
145
|
+
report_lines.append(f"DMU 数: {len(self.dmu_names)}")
|
|
146
|
+
report_lines.append("")
|
|
147
|
+
|
|
148
|
+
table_rows = []
|
|
149
|
+
for dmu_index, dmu_name in enumerate(self.dmu_names):
|
|
150
|
+
table_rows.append([
|
|
151
|
+
dmu_name,
|
|
152
|
+
f"{round_score(self.scores[dmu_index]):.{SCORE_DECIMALS}f}",
|
|
153
|
+
str(int(self.ranks[dmu_index])),
|
|
154
|
+
])
|
|
155
|
+
report_lines.append(format_table(["DMU", "得分", "排名"], table_rows))
|
|
156
|
+
report_lines.append("")
|
|
157
|
+
|
|
158
|
+
efficient_names = [self.dmu_names[i] for i in np.flatnonzero(self.efficiency_mask)]
|
|
159
|
+
report_lines.append(
|
|
160
|
+
f"有效 DMU(ρ = 1)共 {len(efficient_names)} 个: "
|
|
161
|
+
f"{'、'.join(efficient_names) if efficient_names else '无'}"
|
|
162
|
+
)
|
|
163
|
+
report_lines.append(
|
|
164
|
+
"说明: 非期望产出作为越少越好的产出进入分母;松弛可用 --result-file 导出 CSV 查看"
|
|
165
|
+
)
|
|
166
|
+
report_lines.append(
|
|
167
|
+
f"平均得分: {round_score(float(np.mean(self.scores))):.{SCORE_DECIMALS}f}"
|
|
168
|
+
)
|
|
169
|
+
report_lines.extend(f"提示: {note}" for note in self.notes[:10])
|
|
170
|
+
return "\n".join(report_lines)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class UndesirableSBMModel:
|
|
174
|
+
"""严格非期望产出 SBM 求解器。"""
|
|
175
|
+
|
|
176
|
+
def __init__(self, returns_to_scale: str = "crs",
|
|
177
|
+
efficiency_tolerance: float = EFFICIENCY_TOLERANCE):
|
|
178
|
+
returns_to_scale = returns_to_scale.lower()
|
|
179
|
+
if returns_to_scale not in ("crs", "vrs"):
|
|
180
|
+
raise ValueError("returns_to_scale 只能取 'crs' 或 'vrs'")
|
|
181
|
+
if efficiency_tolerance <= 0:
|
|
182
|
+
raise ValueError("efficiency_tolerance 必须为正数")
|
|
183
|
+
self.returns_to_scale = returns_to_scale
|
|
184
|
+
self.efficiency_tolerance = float(efficiency_tolerance)
|
|
185
|
+
|
|
186
|
+
def solve(self, data: DEAData) -> UndesirableSBMResult:
|
|
187
|
+
"""求解全部 DMU 的严格非期望产出 SBM。
|
|
188
|
+
|
|
189
|
+
处理逻辑:逐个 DMU 用 Charnes-Cooper 变换后的 LP 求标准 SBM-Undesirable
|
|
190
|
+
得分、松弛、有效标记与排名。
|
|
191
|
+
"""
|
|
192
|
+
n_dmus = data.input_matrix.shape[1]
|
|
193
|
+
n_inputs = data.input_matrix.shape[0]
|
|
194
|
+
n_desirable_outputs = data.desirable_output_matrix.shape[0]
|
|
195
|
+
n_undesirable_outputs = data.undesirable_output_matrix.shape[0]
|
|
196
|
+
if n_undesirable_outputs == 0:
|
|
197
|
+
raise ValueError("严格非期望产出 SBM 至少需要 1 个非期望产出列")
|
|
198
|
+
|
|
199
|
+
scores = np.empty(n_dmus)
|
|
200
|
+
input_slacks = np.empty((n_dmus, n_inputs))
|
|
201
|
+
desirable_output_slacks = np.empty((n_dmus, n_desirable_outputs))
|
|
202
|
+
undesirable_output_slacks = np.empty((n_dmus, n_undesirable_outputs))
|
|
203
|
+
for dmu_index in range(n_dmus):
|
|
204
|
+
score, slacks_in, slacks_good, slacks_bad = self._solve_standard(
|
|
205
|
+
data, dmu_index
|
|
206
|
+
)
|
|
207
|
+
scores[dmu_index] = score
|
|
208
|
+
input_slacks[dmu_index] = slacks_in
|
|
209
|
+
desirable_output_slacks[dmu_index] = slacks_good
|
|
210
|
+
undesirable_output_slacks[dmu_index] = slacks_bad
|
|
211
|
+
|
|
212
|
+
efficiency_mask = np.asarray(
|
|
213
|
+
scores >= 1.0 - self.efficiency_tolerance, dtype=bool
|
|
214
|
+
)
|
|
215
|
+
ranks = assign_ranks_with_ties(scores)
|
|
216
|
+
return UndesirableSBMResult(
|
|
217
|
+
dmu_names=data.dmu_names,
|
|
218
|
+
scores=scores,
|
|
219
|
+
efficiency_mask=efficiency_mask,
|
|
220
|
+
ranks=ranks,
|
|
221
|
+
input_slacks=input_slacks,
|
|
222
|
+
desirable_output_slacks=desirable_output_slacks,
|
|
223
|
+
undesirable_output_slacks=undesirable_output_slacks,
|
|
224
|
+
returns_to_scale=self.returns_to_scale,
|
|
225
|
+
notes=[],
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
def _solve_standard(self, data: DEAData, dmu_index: int
|
|
229
|
+
) -> tuple[float, np.ndarray, np.ndarray, np.ndarray]:
|
|
230
|
+
"""求解第 dmu_index 个 DMU 的 LP。"""
|
|
231
|
+
X = data.input_matrix
|
|
232
|
+
Y = data.desirable_output_matrix
|
|
233
|
+
B = data.undesirable_output_matrix
|
|
234
|
+
n_dmus = X.shape[1]
|
|
235
|
+
m = X.shape[0]
|
|
236
|
+
s = Y.shape[0]
|
|
237
|
+
b = B.shape[0]
|
|
238
|
+
x_o = X[:, dmu_index]
|
|
239
|
+
y_o = Y[:, dmu_index]
|
|
240
|
+
b_o = B[:, dmu_index]
|
|
241
|
+
|
|
242
|
+
input_slack_start = n_dmus
|
|
243
|
+
good_slack_start = input_slack_start + m
|
|
244
|
+
bad_slack_start = good_slack_start + s
|
|
245
|
+
scale_column = bad_slack_start + b
|
|
246
|
+
n_variables = scale_column + 1
|
|
247
|
+
|
|
248
|
+
objective_coefficients = np.zeros(n_variables)
|
|
249
|
+
objective_coefficients[scale_column] = 1.0
|
|
250
|
+
objective_coefficients[input_slack_start:input_slack_start + m] = (
|
|
251
|
+
-1.0 / (m * x_o)
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
is_vrs = self.returns_to_scale == "vrs"
|
|
255
|
+
n_constraints = m + s + b + 1 + (1 if is_vrs else 0)
|
|
256
|
+
equality_matrix = np.zeros((n_constraints, n_variables))
|
|
257
|
+
equality_rhs = np.zeros(n_constraints)
|
|
258
|
+
|
|
259
|
+
equality_matrix[:m, :n_dmus] = X
|
|
260
|
+
equality_matrix[np.arange(m), input_slack_start + np.arange(m)] = 1.0
|
|
261
|
+
equality_matrix[:m, scale_column] = -x_o
|
|
262
|
+
equality_rhs[:m] = 0.0
|
|
263
|
+
|
|
264
|
+
good_rows = slice(m, m + s)
|
|
265
|
+
equality_matrix[good_rows, :n_dmus] = Y
|
|
266
|
+
equality_matrix[m + np.arange(s), good_slack_start + np.arange(s)] = -1.0
|
|
267
|
+
equality_matrix[good_rows, scale_column] = -y_o
|
|
268
|
+
equality_rhs[good_rows] = 0.0
|
|
269
|
+
|
|
270
|
+
bad_rows = slice(m + s, m + s + b)
|
|
271
|
+
equality_matrix[bad_rows, :n_dmus] = B
|
|
272
|
+
equality_matrix[m + s + np.arange(b), bad_slack_start + np.arange(b)] = 1.0
|
|
273
|
+
equality_matrix[bad_rows, scale_column] = -b_o
|
|
274
|
+
equality_rhs[bad_rows] = 0.0
|
|
275
|
+
|
|
276
|
+
normalization_row = m + s + b
|
|
277
|
+
denominator_count = s + b
|
|
278
|
+
equality_matrix[normalization_row,
|
|
279
|
+
good_slack_start:good_slack_start + s] = (
|
|
280
|
+
1.0 / (denominator_count * y_o)
|
|
281
|
+
)
|
|
282
|
+
equality_matrix[normalization_row,
|
|
283
|
+
bad_slack_start:bad_slack_start + b] = (
|
|
284
|
+
1.0 / (denominator_count * b_o)
|
|
285
|
+
)
|
|
286
|
+
equality_matrix[normalization_row, scale_column] = 1.0
|
|
287
|
+
equality_rhs[normalization_row] = 1.0
|
|
288
|
+
|
|
289
|
+
if is_vrs:
|
|
290
|
+
equality_matrix[normalization_row + 1, :n_dmus] = 1.0
|
|
291
|
+
equality_matrix[normalization_row + 1, scale_column] = -1.0
|
|
292
|
+
|
|
293
|
+
solution = solve_linear_program(
|
|
294
|
+
objective_coefficients,
|
|
295
|
+
equality_matrix=equality_matrix, equality_rhs=equality_rhs,
|
|
296
|
+
error_context=f"SBM-Undesirable 求解失败(第 {dmu_index + 1} 个 DMU)",
|
|
297
|
+
)
|
|
298
|
+
scaling_factor = float(solution.x[scale_column])
|
|
299
|
+
if scaling_factor <= MIN_SCALING_FACTOR:
|
|
300
|
+
raise RuntimeError(
|
|
301
|
+
f"SBM-Undesirable 缩放因子 t 非正(第 {dmu_index + 1} 个 DMU)"
|
|
302
|
+
)
|
|
303
|
+
input_slacks = solution.x[input_slack_start:input_slack_start + m]
|
|
304
|
+
good_slacks = solution.x[good_slack_start:good_slack_start + s]
|
|
305
|
+
bad_slacks = solution.x[bad_slack_start:bad_slack_start + b]
|
|
306
|
+
return (
|
|
307
|
+
float(solution.fun),
|
|
308
|
+
input_slacks / scaling_factor,
|
|
309
|
+
good_slacks / scaling_factor,
|
|
310
|
+
bad_slacks / scaling_factor,
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
315
|
+
argument_parser = argparse.ArgumentParser(
|
|
316
|
+
description="严格非期望产出 SBM(Tone 2003);不带参数时使用脚本配置区",
|
|
317
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
318
|
+
epilog=(
|
|
319
|
+
"示例:\n"
|
|
320
|
+
" python undesirable_sbm.py\n"
|
|
321
|
+
" python undesirable_sbm.py --demo --returns-to-scale vrs\n"
|
|
322
|
+
),
|
|
323
|
+
)
|
|
324
|
+
DATA_COMMAND_LINE.add_arguments(argument_parser)
|
|
325
|
+
argument_parser.add_argument("--returns-to-scale", "--rts",
|
|
326
|
+
choices=("crs", "vrs"), default=None,
|
|
327
|
+
help="规模报酬: crs=不变, vrs=可变;缺省用 RETURNS_TO_SCALE")
|
|
328
|
+
argument_parser.add_argument("--tolerance", "--tol", type=float, default=None,
|
|
329
|
+
help=f"判定有效性的容差(默认 {EFFICIENCY_TOLERANCE})")
|
|
330
|
+
return argument_parser
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
334
|
+
args = build_parser().parse_args(argv)
|
|
335
|
+
try:
|
|
336
|
+
prepared = DATA_COMMAND_LINE.prepare(args)
|
|
337
|
+
returns_to_scale = (
|
|
338
|
+
args.returns_to_scale if args.returns_to_scale is not None
|
|
339
|
+
else RETURNS_TO_SCALE
|
|
340
|
+
)
|
|
341
|
+
efficiency_tolerance = (
|
|
342
|
+
args.tolerance if args.tolerance is not None else EFFICIENCY_TOLERANCE
|
|
343
|
+
)
|
|
344
|
+
model = UndesirableSBMModel(
|
|
345
|
+
returns_to_scale=returns_to_scale,
|
|
346
|
+
efficiency_tolerance=efficiency_tolerance,
|
|
347
|
+
)
|
|
348
|
+
result = model.solve(prepared.data)
|
|
349
|
+
except (ValueError, RuntimeError) as exc:
|
|
350
|
+
print(f"错误: {exc}", file=sys.stderr)
|
|
351
|
+
return 1
|
|
352
|
+
|
|
353
|
+
print(result.render_report(
|
|
354
|
+
prepared.column_names,
|
|
355
|
+
source_description=prepared.source_description,
|
|
356
|
+
))
|
|
357
|
+
if prepared.result_file:
|
|
358
|
+
try:
|
|
359
|
+
result.write_csv(prepared.result_file, prepared.column_names)
|
|
360
|
+
except OSError as exc:
|
|
361
|
+
print(f"错误: 无法写入 {prepared.result_file}: {exc}", file=sys.stderr)
|
|
362
|
+
return 1
|
|
363
|
+
print(f"\n结果已写入: {prepared.result_file}")
|
|
364
|
+
return 0
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
if __name__ == "__main__":
|
|
368
|
+
sys.exit(main())
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""弱可处置性方向距离函数(Weak-Disposability DDF)脚本。
|
|
4
|
+
|
|
5
|
+
模型:
|
|
6
|
+
max β
|
|
7
|
+
s.t. Xλ + β·x_o ≤ x_o
|
|
8
|
+
Yλ - β·y_o ≥ y_o
|
|
9
|
+
Bλ + β·b_o = b_o
|
|
10
|
+
λ ≥ 0(VRS 加 Σλ = 1)
|
|
11
|
+
β ≥ 0
|
|
12
|
+
其中非期望产出使用等式约束(弱可处置):投影 (1-β)b_o,不能自由处置减少,
|
|
13
|
+
β 同时表示投入收缩、期望产出扩张与非期望产出缩减的比例。
|
|
14
|
+
|
|
15
|
+
与 `directional_distance.py` 的强可处置版本不同:该脚本把非期望产出作为
|
|
16
|
+
独立产出块处理,适合需要弱可处置性假设的环境效率分析。
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import os
|
|
21
|
+
import sys
|
|
22
|
+
from collections.abc import Sequence
|
|
23
|
+
from dataclasses import dataclass, field
|
|
24
|
+
|
|
25
|
+
import numpy as np
|
|
26
|
+
|
|
27
|
+
from dea_core import (
|
|
28
|
+
ColumnNames,
|
|
29
|
+
DataCommandLine,
|
|
30
|
+
DataSettings,
|
|
31
|
+
DEAData,
|
|
32
|
+
EFFICIENCY_TOLERANCE,
|
|
33
|
+
SCORE_DECIMALS,
|
|
34
|
+
assign_ranks_with_ties,
|
|
35
|
+
format_table,
|
|
36
|
+
round_score,
|
|
37
|
+
solve_linear_program,
|
|
38
|
+
write_csv_records,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
# =============================== 用户配置区 ===============================
|
|
42
|
+
DATA_FILE = "sample_data.csv"
|
|
43
|
+
EXCEL_SHEET = 0
|
|
44
|
+
|
|
45
|
+
DMU_COLUMNS = ["城市代码", "年份"]
|
|
46
|
+
INPUT_COLUMNS = ["资本投入", "劳动投入"]
|
|
47
|
+
DESIRABLE_OUTPUT_COLUMNS = ["GDP", "财政收入"]
|
|
48
|
+
UNDESIRABLE_OUTPUT_COLUMNS = ["工业废水排放量"]
|
|
49
|
+
|
|
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
|
+
result_file=RESULT_FILE,
|
|
63
|
+
),
|
|
64
|
+
script_directory=os.path.dirname(os.path.abspath(__file__)),
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass
|
|
69
|
+
class WeakDisposabilityDDFResult:
|
|
70
|
+
"""弱可处置性 DDF 的结果。"""
|
|
71
|
+
|
|
72
|
+
dmu_names: list[str]
|
|
73
|
+
directional_distances: np.ndarray
|
|
74
|
+
efficiency_mask: np.ndarray
|
|
75
|
+
ranks: np.ndarray
|
|
76
|
+
input_slacks: np.ndarray
|
|
77
|
+
desirable_output_slacks: np.ndarray
|
|
78
|
+
undesirable_output_slacks: np.ndarray
|
|
79
|
+
returns_to_scale: str
|
|
80
|
+
notes: list[str] = field(default_factory=list)
|
|
81
|
+
|
|
82
|
+
def to_records(self, column_names: ColumnNames) -> list[dict[str, object]]:
|
|
83
|
+
"""把每个 DMU 展开成一条 CSV 记录。"""
|
|
84
|
+
records = []
|
|
85
|
+
for dmu_index, dmu_name in enumerate(self.dmu_names):
|
|
86
|
+
record: dict[str, object] = {
|
|
87
|
+
"dmu": dmu_name,
|
|
88
|
+
"directional_distance": round_score(
|
|
89
|
+
self.directional_distances[dmu_index]
|
|
90
|
+
),
|
|
91
|
+
"efficient": int(self.efficiency_mask[dmu_index]),
|
|
92
|
+
"rank": int(self.ranks[dmu_index]),
|
|
93
|
+
}
|
|
94
|
+
for indicator_index, column_name in enumerate(column_names.input_columns):
|
|
95
|
+
record[f"input_slack_{column_name}"] = round_score(
|
|
96
|
+
self.input_slacks[dmu_index, indicator_index]
|
|
97
|
+
)
|
|
98
|
+
for indicator_index, column_name in enumerate(
|
|
99
|
+
column_names.desirable_output_columns):
|
|
100
|
+
record[f"desirable_output_slack_{column_name}"] = round_score(
|
|
101
|
+
self.desirable_output_slacks[dmu_index, indicator_index]
|
|
102
|
+
)
|
|
103
|
+
for indicator_index, column_name in enumerate(
|
|
104
|
+
column_names.undesirable_output_columns):
|
|
105
|
+
record[f"undesirable_output_slack_{column_name}"] = round_score(
|
|
106
|
+
self.undesirable_output_slacks[dmu_index, indicator_index]
|
|
107
|
+
)
|
|
108
|
+
records.append(record)
|
|
109
|
+
return records
|
|
110
|
+
|
|
111
|
+
def write_csv(self, path: str, column_names: ColumnNames) -> None:
|
|
112
|
+
"""写出 UTF-8-BOM 编码的结果 CSV。"""
|
|
113
|
+
write_csv_records(path, self.to_records(column_names))
|
|
114
|
+
|
|
115
|
+
def render_report(self, column_names: ColumnNames,
|
|
116
|
+
source_description: str | None = None) -> str:
|
|
117
|
+
"""生成控制台报表文本。"""
|
|
118
|
+
returns_to_scale_description = (
|
|
119
|
+
"CRS 规模报酬不变" if self.returns_to_scale == "crs" else "VRS 规模报酬可变"
|
|
120
|
+
)
|
|
121
|
+
report_lines = [
|
|
122
|
+
f"模型: 弱可处置性 DDF(Weak Disposability) | {returns_to_scale_description}"
|
|
123
|
+
]
|
|
124
|
+
if source_description:
|
|
125
|
+
report_lines.append(f"数据: {source_description}")
|
|
126
|
+
report_lines.append(
|
|
127
|
+
f"变量: 投入[{'、'.join(column_names.input_columns)}] | "
|
|
128
|
+
f"期望产出[{'、'.join(column_names.desirable_output_columns)}] | "
|
|
129
|
+
f"非期望产出[{'、'.join(column_names.undesirable_output_columns)}]"
|
|
130
|
+
)
|
|
131
|
+
report_lines.append(f"DMU 数: {len(self.dmu_names)}")
|
|
132
|
+
report_lines.append("")
|
|
133
|
+
|
|
134
|
+
table_rows = []
|
|
135
|
+
for dmu_index, dmu_name in enumerate(self.dmu_names):
|
|
136
|
+
beta = round_score(self.directional_distances[dmu_index])
|
|
137
|
+
table_rows.append([
|
|
138
|
+
dmu_name,
|
|
139
|
+
f"{beta:.{SCORE_DECIMALS}f}",
|
|
140
|
+
str(int(self.ranks[dmu_index])),
|
|
141
|
+
])
|
|
142
|
+
report_lines.append(format_table(["DMU", "方向距离 β(0 为有效)", "排名"], table_rows))
|
|
143
|
+
report_lines.append("")
|
|
144
|
+
|
|
145
|
+
efficient_names = [self.dmu_names[i] for i in np.flatnonzero(self.efficiency_mask)]
|
|
146
|
+
report_lines.append(
|
|
147
|
+
f"有效 DMU(β = 0)共 {len(efficient_names)} 个: "
|
|
148
|
+
f"{'、'.join(efficient_names) if efficient_names else '无'}"
|
|
149
|
+
)
|
|
150
|
+
report_lines.append(
|
|
151
|
+
"说明: 非期望产出采用等式弱可处置约束,不能自由处置减少;β 越大越无效"
|
|
152
|
+
)
|
|
153
|
+
average_beta = round_score(float(np.mean(self.directional_distances)))
|
|
154
|
+
report_lines.append(
|
|
155
|
+
f"平均方向距离 β: {average_beta:.{SCORE_DECIMALS}f}"
|
|
156
|
+
)
|
|
157
|
+
report_lines.extend(f"提示: {note}" for note in self.notes[:10])
|
|
158
|
+
return "\n".join(report_lines)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class WeakDisposabilityDDFModel:
|
|
162
|
+
"""弱可处置性 DDF 求解器。"""
|
|
163
|
+
|
|
164
|
+
def __init__(self, returns_to_scale: str = "crs",
|
|
165
|
+
efficiency_tolerance: float = EFFICIENCY_TOLERANCE):
|
|
166
|
+
returns_to_scale = returns_to_scale.lower()
|
|
167
|
+
if returns_to_scale not in ("crs", "vrs"):
|
|
168
|
+
raise ValueError("returns_to_scale 只能取 'crs' 或 'vrs'")
|
|
169
|
+
if efficiency_tolerance <= 0:
|
|
170
|
+
raise ValueError("efficiency_tolerance 必须为正数")
|
|
171
|
+
self.returns_to_scale = returns_to_scale
|
|
172
|
+
self.efficiency_tolerance = float(efficiency_tolerance)
|
|
173
|
+
|
|
174
|
+
def solve(self, data: DEAData) -> WeakDisposabilityDDFResult:
|
|
175
|
+
"""求解全部 DMU 的弱可处置性 DDF。
|
|
176
|
+
|
|
177
|
+
处理逻辑:逐个 DMU 求解方向 g=(x_o, y_o, b_o) 的 DDF LP,
|
|
178
|
+
非期望产出使用等式弱可处置约束,汇总 β、排名与投影松弛。
|
|
179
|
+
"""
|
|
180
|
+
n_dmus = data.input_matrix.shape[1]
|
|
181
|
+
if data.undesirable_output_matrix.shape[0] == 0:
|
|
182
|
+
raise ValueError("弱可处置性 DDF 至少需要 1 个非期望产出列")
|
|
183
|
+
betas = np.empty(n_dmus)
|
|
184
|
+
input_slacks = np.empty((n_dmus, data.input_matrix.shape[0]))
|
|
185
|
+
desirable_slacks = np.empty(
|
|
186
|
+
(n_dmus, data.desirable_output_matrix.shape[0])
|
|
187
|
+
)
|
|
188
|
+
undesirable_slacks = np.zeros(
|
|
189
|
+
(n_dmus, data.undesirable_output_matrix.shape[0])
|
|
190
|
+
)
|
|
191
|
+
for dmu_index in range(n_dmus):
|
|
192
|
+
beta, slacks_in, slacks_good = self._solve_directional(
|
|
193
|
+
data, dmu_index
|
|
194
|
+
)
|
|
195
|
+
betas[dmu_index] = beta
|
|
196
|
+
input_slacks[dmu_index] = slacks_in
|
|
197
|
+
desirable_slacks[dmu_index] = slacks_good
|
|
198
|
+
|
|
199
|
+
efficiency_mask = np.asarray(betas <= self.efficiency_tolerance, dtype=bool)
|
|
200
|
+
return WeakDisposabilityDDFResult(
|
|
201
|
+
dmu_names=data.dmu_names,
|
|
202
|
+
directional_distances=betas,
|
|
203
|
+
efficiency_mask=efficiency_mask,
|
|
204
|
+
ranks=assign_ranks_with_ties(-betas),
|
|
205
|
+
input_slacks=input_slacks,
|
|
206
|
+
desirable_output_slacks=desirable_slacks,
|
|
207
|
+
undesirable_output_slacks=undesirable_slacks,
|
|
208
|
+
returns_to_scale=self.returns_to_scale,
|
|
209
|
+
notes=[],
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
def _solve_directional(self, data: DEAData, dmu_index: int
|
|
213
|
+
) -> tuple[float, np.ndarray, np.ndarray]:
|
|
214
|
+
"""求解第 dmu_index 个 DMU 的弱可处置性 DDF 线性规划。"""
|
|
215
|
+
X = data.input_matrix
|
|
216
|
+
Y = data.desirable_output_matrix
|
|
217
|
+
B = data.undesirable_output_matrix
|
|
218
|
+
n_dmus = X.shape[1]
|
|
219
|
+
m = X.shape[0]
|
|
220
|
+
s = Y.shape[0]
|
|
221
|
+
b = B.shape[0]
|
|
222
|
+
x_o = X[:, dmu_index]
|
|
223
|
+
y_o = Y[:, dmu_index]
|
|
224
|
+
b_o = B[:, dmu_index]
|
|
225
|
+
|
|
226
|
+
n_variables = n_dmus + 1
|
|
227
|
+
beta_column = n_dmus
|
|
228
|
+
objective_coefficients = np.zeros(n_variables)
|
|
229
|
+
objective_coefficients[beta_column] = -1.0
|
|
230
|
+
|
|
231
|
+
n_inequalities = m + s
|
|
232
|
+
inequality_matrix = np.zeros((n_inequalities + b, n_variables))
|
|
233
|
+
inequality_rhs = np.zeros(n_inequalities + b)
|
|
234
|
+
inequality_matrix[:m, :n_dmus] = X
|
|
235
|
+
inequality_matrix[:m, beta_column] = x_o
|
|
236
|
+
inequality_rhs[:m] = x_o
|
|
237
|
+
|
|
238
|
+
good_rows = slice(m, m + s)
|
|
239
|
+
inequality_matrix[good_rows, :n_dmus] = -Y
|
|
240
|
+
inequality_matrix[good_rows, beta_column] = y_o
|
|
241
|
+
inequality_rhs[good_rows] = -y_o
|
|
242
|
+
|
|
243
|
+
bad_rows = slice(m + s, m + s + b)
|
|
244
|
+
inequality_matrix[bad_rows, :n_dmus] = B
|
|
245
|
+
inequality_matrix[bad_rows, beta_column] = b_o
|
|
246
|
+
equality_rhs = b_o
|
|
247
|
+
equality_matrix = inequality_matrix[bad_rows]
|
|
248
|
+
equality_matrix_rhs = equality_rhs
|
|
249
|
+
inequality_matrix = inequality_matrix[:n_inequalities]
|
|
250
|
+
inequality_rhs = inequality_rhs[:n_inequalities]
|
|
251
|
+
|
|
252
|
+
is_vrs = self.returns_to_scale == "vrs"
|
|
253
|
+
if is_vrs:
|
|
254
|
+
equality_matrix = np.vstack([equality_matrix, np.zeros((1, n_variables))])
|
|
255
|
+
equality_matrix_rhs = np.concatenate([equality_matrix_rhs, [1.0]])
|
|
256
|
+
equality_matrix[-1, :n_dmus] = 1.0
|
|
257
|
+
|
|
258
|
+
solution = solve_linear_program(
|
|
259
|
+
objective_coefficients,
|
|
260
|
+
inequality_matrix=inequality_matrix, inequality_rhs=inequality_rhs,
|
|
261
|
+
equality_matrix=equality_matrix, equality_rhs=equality_matrix_rhs,
|
|
262
|
+
error_context=f"弱可处置性 DDF 求解失败(第 {dmu_index + 1} 个 DMU)",
|
|
263
|
+
)
|
|
264
|
+
beta = float(solution.x[beta_column])
|
|
265
|
+
lambdas = solution.x[:n_dmus]
|
|
266
|
+
input_slacks = x_o - X @ lambdas - beta * x_o
|
|
267
|
+
good_slacks = Y @ lambdas - beta * y_o - y_o
|
|
268
|
+
return beta, np.maximum(input_slacks, 0.0), np.maximum(good_slacks, 0.0)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
272
|
+
argument_parser = argparse.ArgumentParser(
|
|
273
|
+
description="弱可处置性方向距离函数(Weak Disposability DDF);"
|
|
274
|
+
"不带参数时使用脚本配置区",
|
|
275
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
276
|
+
epilog=(
|
|
277
|
+
"示例:\n"
|
|
278
|
+
" python weak_disposability_ddf.py\n"
|
|
279
|
+
" python weak_disposability_ddf.py --demo --returns-to-scale vrs\n"
|
|
280
|
+
),
|
|
281
|
+
)
|
|
282
|
+
DATA_COMMAND_LINE.add_arguments(argument_parser)
|
|
283
|
+
argument_parser.add_argument("--returns-to-scale", "--rts",
|
|
284
|
+
choices=("crs", "vrs"), default=None,
|
|
285
|
+
help="规模报酬: crs=不变, vrs=可变;缺省用 RETURNS_TO_SCALE")
|
|
286
|
+
argument_parser.add_argument("--tolerance", "--tol", type=float, default=None,
|
|
287
|
+
help=f"判定 β = 0 的容差(默认 {EFFICIENCY_TOLERANCE})")
|
|
288
|
+
return argument_parser
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
292
|
+
args = build_parser().parse_args(argv)
|
|
293
|
+
try:
|
|
294
|
+
prepared = DATA_COMMAND_LINE.prepare(args)
|
|
295
|
+
returns_to_scale = (
|
|
296
|
+
args.returns_to_scale if args.returns_to_scale is not None
|
|
297
|
+
else RETURNS_TO_SCALE
|
|
298
|
+
)
|
|
299
|
+
efficiency_tolerance = (
|
|
300
|
+
args.tolerance if args.tolerance is not None else EFFICIENCY_TOLERANCE
|
|
301
|
+
)
|
|
302
|
+
model = WeakDisposabilityDDFModel(
|
|
303
|
+
returns_to_scale=returns_to_scale,
|
|
304
|
+
efficiency_tolerance=efficiency_tolerance,
|
|
305
|
+
)
|
|
306
|
+
result = model.solve(prepared.data)
|
|
307
|
+
except (ValueError, RuntimeError) as exc:
|
|
308
|
+
print(f"错误: {exc}", file=sys.stderr)
|
|
309
|
+
return 1
|
|
310
|
+
|
|
311
|
+
print(result.render_report(
|
|
312
|
+
prepared.column_names,
|
|
313
|
+
source_description=prepared.source_description,
|
|
314
|
+
))
|
|
315
|
+
if prepared.result_file:
|
|
316
|
+
try:
|
|
317
|
+
result.write_csv(prepared.result_file, prepared.column_names)
|
|
318
|
+
except OSError as exc:
|
|
319
|
+
print(f"错误: 无法写入 {prepared.result_file}: {exc}", file=sys.stderr)
|
|
320
|
+
return 1
|
|
321
|
+
print(f"\n结果已写入: {prepared.result_file}")
|
|
322
|
+
return 0
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
if __name__ == "__main__":
|
|
326
|
+
sys.exit(main())
|