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
super_sbm.py
ADDED
|
@@ -0,0 +1,590 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""超效率 SBM(Slack-Based Measure)数据包络分析脚本。
|
|
4
|
+
|
|
5
|
+
模型:
|
|
6
|
+
1. 标准 SBM(Tone 2001,非导向):效率得分 ρ ∈ (0, 1],有效单元为 1;
|
|
7
|
+
2. 超效率 SBM(Tone 2002,非导向):对 ρ = 1 的单元,将其自身移出参考集
|
|
8
|
+
后重解,并要求投影点不优于自身(x̄ ≥ x₀、ȳ ≤ y₀),得分 δ ≥ 1;非有效
|
|
9
|
+
单元沿用标准 SBM 得分(两阶段法);
|
|
10
|
+
3. 非期望产出:按“投入方向”处理(并入投入块,越少越好),保证排序一致。
|
|
11
|
+
|
|
12
|
+
数据:CSV / Excel(.xlsx/.xlsm)均可;每个 DMU 一行;所有指标须为正数。
|
|
13
|
+
面板数据中 DMU 是“城市-年份”观测,可用多列自动拼接名称。
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import os
|
|
18
|
+
import sys
|
|
19
|
+
from collections.abc import Sequence
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
|
|
22
|
+
import numpy as np
|
|
23
|
+
|
|
24
|
+
from dea_core import (
|
|
25
|
+
ColumnNames,
|
|
26
|
+
DataCommandLine,
|
|
27
|
+
DataSettings,
|
|
28
|
+
DEAData,
|
|
29
|
+
EFFICIENCY_TOLERANCE,
|
|
30
|
+
MIN_SCALING_FACTOR,
|
|
31
|
+
SCORE_DECIMALS,
|
|
32
|
+
assign_ranks_with_ties,
|
|
33
|
+
format_table,
|
|
34
|
+
round_score,
|
|
35
|
+
solve_linear_program,
|
|
36
|
+
write_csv_records,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
# =============================== 用户配置区 ===============================
|
|
40
|
+
# 数据文件路径:支持 .csv / .xlsx / .xlsm;相对路径优先按当前工作目录,其次脚本所在目录解析
|
|
41
|
+
DATA_FILE = "sample_data.csv"
|
|
42
|
+
EXCEL_SHEET = 0 # Excel 工作表名或序号(0 开始);CSV 忽略
|
|
43
|
+
|
|
44
|
+
# DMU 标识列:可多列,自动用 "-" 拼接为唯一名称;如 ["城市代码", "年份"] → "110000-2021"
|
|
45
|
+
# 若数据里已有一列唯一编号,写 DMU_COLUMNS = ["编号列名"] 即可
|
|
46
|
+
DMU_COLUMNS = ["城市代码", "年份"]
|
|
47
|
+
|
|
48
|
+
# 指标列名:按数据表的列名填写(三组变量分开设置)
|
|
49
|
+
INPUT_COLUMNS = ["资本投入", "劳动投入"] # 投入变量
|
|
50
|
+
DESIRABLE_OUTPUT_COLUMNS = ["GDP", "财政收入"] # 期望产出
|
|
51
|
+
UNDESIRABLE_OUTPUT_COLUMNS = ["工业废水排放量"] # 非期望产出(没有就写 [])
|
|
52
|
+
|
|
53
|
+
# 模型选项
|
|
54
|
+
RETURNS_TO_SCALE = "crs" # "crs"=规模报酬不变,"vrs"=规模报酬可变
|
|
55
|
+
SCORE_MODE = "super" # "super"=超效率(有效单元可 >1),"standard"=得分最大为 1
|
|
56
|
+
# 加权 SBM:None 表示等权(即标准/超效率 SBM);给出时按组归一化到和为 1。
|
|
57
|
+
# INPUT_WEIGHTS 的顺序为 INPUT_COLUMNS + UNDESIRABLE_OUTPUT_COLUMNS,OUTPUT_WEIGHTS 对应 DESIRABLE_OUTPUT_COLUMNS。
|
|
58
|
+
INPUT_WEIGHTS = None
|
|
59
|
+
OUTPUT_WEIGHTS = None
|
|
60
|
+
RESULT_FILE = None # 结果 CSV 输出路径,如 "dea_results.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 SBMResult:
|
|
79
|
+
"""一次 DEA 求解的结果,含报表与 CSV 导出。"""
|
|
80
|
+
|
|
81
|
+
dmu_names: list[str] # DMU 名称
|
|
82
|
+
final_scores: np.ndarray # 最终得分(按 score_mode 规则)
|
|
83
|
+
standard_scores: np.ndarray # 标准 SBM 得分(Tone 2001)
|
|
84
|
+
super_efficiency_scores: np.ndarray # 超效率 SBM 原始值(未计算处为 NaN)
|
|
85
|
+
efficiency_mask: np.ndarray # 是否 SBM 有效(bool)
|
|
86
|
+
ranks: np.ndarray # 按最终得分的名次(并列取最小名次)
|
|
87
|
+
input_slacks: np.ndarray # (n, m) 投入冗余(原单位)
|
|
88
|
+
desirable_output_slacks: np.ndarray # (n, g) 期望产出不足(原单位)
|
|
89
|
+
undesirable_output_slacks: np.ndarray # (n, b) 非期望产出冗余(原单位)
|
|
90
|
+
returns_to_scale: str
|
|
91
|
+
score_mode: str
|
|
92
|
+
weighted: bool = False
|
|
93
|
+
notes: list[str] = field(default_factory=list)
|
|
94
|
+
|
|
95
|
+
def to_records(self, column_names: ColumnNames) -> list[dict[str, object]]:
|
|
96
|
+
"""把每个 DMU 展开成一条可直接写 CSV 的记录。"""
|
|
97
|
+
n_inputs = self.input_slacks.shape[1]
|
|
98
|
+
n_desirable_outputs = self.desirable_output_slacks.shape[1]
|
|
99
|
+
n_undesirable_outputs = self.undesirable_output_slacks.shape[1]
|
|
100
|
+
if (len(column_names.input_columns) != n_inputs
|
|
101
|
+
or len(column_names.desirable_output_columns) != n_desirable_outputs
|
|
102
|
+
or len(column_names.undesirable_output_columns) != n_undesirable_outputs):
|
|
103
|
+
raise ValueError("指标名称数量与松弛矩阵不匹配")
|
|
104
|
+
|
|
105
|
+
records = []
|
|
106
|
+
for dmu_index, dmu_name in enumerate(self.dmu_names):
|
|
107
|
+
raw_super_score = self.super_efficiency_scores[dmu_index]
|
|
108
|
+
record = {
|
|
109
|
+
"dmu": dmu_name,
|
|
110
|
+
"final_score": round_score(self.final_scores[dmu_index]),
|
|
111
|
+
"standard_sbm_score": round_score(self.standard_scores[dmu_index]),
|
|
112
|
+
"super_efficiency_score": (
|
|
113
|
+
None if np.isnan(raw_super_score)
|
|
114
|
+
else round_score(raw_super_score)
|
|
115
|
+
),
|
|
116
|
+
"efficient": int(self.efficiency_mask[dmu_index]),
|
|
117
|
+
"rank": int(self.ranks[dmu_index]),
|
|
118
|
+
}
|
|
119
|
+
for indicator_index, column_name in enumerate(column_names.input_columns):
|
|
120
|
+
record[f"input_slack_{column_name}"] = round_score(
|
|
121
|
+
self.input_slacks[dmu_index, indicator_index]
|
|
122
|
+
)
|
|
123
|
+
for indicator_index, column_name in enumerate(column_names.desirable_output_columns):
|
|
124
|
+
record[f"desirable_output_slack_{column_name}"] = round_score(
|
|
125
|
+
self.desirable_output_slacks[dmu_index, indicator_index]
|
|
126
|
+
)
|
|
127
|
+
for indicator_index, column_name in enumerate(column_names.undesirable_output_columns):
|
|
128
|
+
record[f"undesirable_output_slack_{column_name}"] = round_score(
|
|
129
|
+
self.undesirable_output_slacks[dmu_index, indicator_index]
|
|
130
|
+
)
|
|
131
|
+
records.append(record)
|
|
132
|
+
return records
|
|
133
|
+
|
|
134
|
+
def write_csv(self, path: str, column_names: ColumnNames) -> None:
|
|
135
|
+
"""写出 UTF-8-BOM 编码的结果 CSV。"""
|
|
136
|
+
write_csv_records(path, self.to_records(column_names))
|
|
137
|
+
|
|
138
|
+
def render_report(self, column_names: ColumnNames,
|
|
139
|
+
source_description: str | None = None) -> str:
|
|
140
|
+
"""生成控制台报表文本。"""
|
|
141
|
+
if self.score_mode == "super":
|
|
142
|
+
model_title = "超效率加权 SBM" if self.weighted else "超效率 SBM(Tone 2002)"
|
|
143
|
+
score_mode_description = "前沿取值可超过 1"
|
|
144
|
+
else:
|
|
145
|
+
model_title = "标准加权 SBM" if self.weighted else "标准 SBM(Tone 2001)"
|
|
146
|
+
score_mode_description = "前沿取值最大为 1"
|
|
147
|
+
returns_to_scale_description = (
|
|
148
|
+
"CRS 规模报酬不变" if self.returns_to_scale == "crs" else "VRS 规模报酬可变"
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
report_lines = [f"模型: {model_title} | {returns_to_scale_description} | {score_mode_description}"]
|
|
152
|
+
if source_description:
|
|
153
|
+
report_lines.append(f"数据: {source_description}")
|
|
154
|
+
undesirable_output_description = (
|
|
155
|
+
"、".join(column_names.undesirable_output_columns)
|
|
156
|
+
if column_names.undesirable_output_columns else "无"
|
|
157
|
+
)
|
|
158
|
+
report_lines.append(
|
|
159
|
+
f"变量: 投入[{'、'.join(column_names.input_columns)}] | "
|
|
160
|
+
f"期望产出[{'、'.join(column_names.desirable_output_columns)}] | "
|
|
161
|
+
f"非期望产出[{undesirable_output_description}]"
|
|
162
|
+
)
|
|
163
|
+
report_lines.append(f"DMU 数: {len(self.dmu_names)}")
|
|
164
|
+
report_lines.append("")
|
|
165
|
+
|
|
166
|
+
table_header = ["DMU", "得分", "标准SBM", "超效率原值", "排名"]
|
|
167
|
+
table_rows = []
|
|
168
|
+
for dmu_index, dmu_name in enumerate(self.dmu_names):
|
|
169
|
+
raw_super_score = self.super_efficiency_scores[dmu_index]
|
|
170
|
+
table_rows.append([
|
|
171
|
+
dmu_name,
|
|
172
|
+
f"{self.final_scores[dmu_index]:.{SCORE_DECIMALS}f}",
|
|
173
|
+
f"{self.standard_scores[dmu_index]:.{SCORE_DECIMALS}f}",
|
|
174
|
+
"-" if np.isnan(raw_super_score) else f"{raw_super_score:.{SCORE_DECIMALS}f}",
|
|
175
|
+
str(int(self.ranks[dmu_index])),
|
|
176
|
+
])
|
|
177
|
+
report_lines.append(format_table(table_header, table_rows))
|
|
178
|
+
report_lines.append("")
|
|
179
|
+
|
|
180
|
+
efficient_dmu_names = [self.dmu_names[i] for i in np.flatnonzero(self.efficiency_mask)]
|
|
181
|
+
report_lines.append(
|
|
182
|
+
f"有效 DMU(标准 SBM = 1)共 {len(efficient_dmu_names)} 个: "
|
|
183
|
+
f"{'、'.join(efficient_dmu_names) if efficient_dmu_names else '无'}"
|
|
184
|
+
)
|
|
185
|
+
if self.score_mode == "super":
|
|
186
|
+
report_lines.append(
|
|
187
|
+
"说明: 超效率阶段有效单元得分 ≥ 1;得分为 1 表示未能进一步区分"
|
|
188
|
+
"(弱有效或与其余单元共面)"
|
|
189
|
+
)
|
|
190
|
+
if column_names.undesirable_output_columns:
|
|
191
|
+
report_lines.append("说明: 非期望产出按投入方向处理(越少越好)")
|
|
192
|
+
if self.weighted:
|
|
193
|
+
report_lines.append("说明: 使用自定义权重(各指标组已归一化到和为 1)")
|
|
194
|
+
report_lines.append(
|
|
195
|
+
f"平均标准 SBM 得分: {float(np.mean(self.standard_scores)):.{SCORE_DECIMALS}f}"
|
|
196
|
+
)
|
|
197
|
+
if self.score_mode == "super" and np.any(self.efficiency_mask):
|
|
198
|
+
average_super_efficiency = float(
|
|
199
|
+
np.mean(self.super_efficiency_scores[self.efficiency_mask])
|
|
200
|
+
)
|
|
201
|
+
report_lines.append(
|
|
202
|
+
f"有效单元平均超效率: {average_super_efficiency:.{SCORE_DECIMALS}f}"
|
|
203
|
+
f"({int(np.count_nonzero(self.efficiency_mask))} 个)"
|
|
204
|
+
)
|
|
205
|
+
report_lines.append("投入冗余 / 期望产出不足 / 非期望产出冗余可用 --result-file 导出 CSV 查看")
|
|
206
|
+
report_lines.extend(f"提示: {note}" for note in self.notes[:10])
|
|
207
|
+
if len(self.notes) > 10:
|
|
208
|
+
report_lines.append(f"提示: 其余 {len(self.notes) - 10} 条类似提示已省略")
|
|
209
|
+
return "\n".join(report_lines)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
@dataclass(frozen=True)
|
|
213
|
+
class SBMWeights:
|
|
214
|
+
"""加权 SBM 的投入块与期望产出权重。"""
|
|
215
|
+
|
|
216
|
+
input_weights: Sequence[float] | None = None
|
|
217
|
+
output_weights: Sequence[float] | None = None
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class SBMModel:
|
|
221
|
+
"""标准 SBM(Tone 2001)与超效率 SBM(Tone 2002)求解器(非导向)。"""
|
|
222
|
+
|
|
223
|
+
def __init__(self, returns_to_scale: str = "crs", score_mode: str = "super",
|
|
224
|
+
efficiency_tolerance: float = EFFICIENCY_TOLERANCE,
|
|
225
|
+
weights: SBMWeights | None = None):
|
|
226
|
+
returns_to_scale = returns_to_scale.lower()
|
|
227
|
+
score_mode = score_mode.lower()
|
|
228
|
+
if returns_to_scale not in ("crs", "vrs"):
|
|
229
|
+
raise ValueError("returns_to_scale 只能取 'crs' 或 'vrs'")
|
|
230
|
+
if score_mode not in ("super", "standard"):
|
|
231
|
+
raise ValueError("score_mode 只能取 'super' 或 'standard'")
|
|
232
|
+
if efficiency_tolerance <= 0:
|
|
233
|
+
raise ValueError("efficiency_tolerance 必须为正数")
|
|
234
|
+
weights = weights if weights is not None else SBMWeights()
|
|
235
|
+
self.returns_to_scale = returns_to_scale
|
|
236
|
+
self.score_mode = score_mode
|
|
237
|
+
self.efficiency_tolerance = float(efficiency_tolerance)
|
|
238
|
+
self.weights = weights
|
|
239
|
+
self.input_weights = (
|
|
240
|
+
None if weights.input_weights is None
|
|
241
|
+
else np.asarray(weights.input_weights, dtype=float).ravel()
|
|
242
|
+
)
|
|
243
|
+
self.output_weights = (
|
|
244
|
+
None if weights.output_weights is None
|
|
245
|
+
else np.asarray(weights.output_weights, dtype=float).ravel()
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
def solve(self, data: DEAData) -> SBMResult:
|
|
249
|
+
"""执行两阶段求解:标准 SBM → 对有效 DMU 追加超效率 SBM。"""
|
|
250
|
+
n_dmus = data.input_matrix.shape[1]
|
|
251
|
+
if self.score_mode == "super" and n_dmus < 2:
|
|
252
|
+
raise ValueError("超效率模式至少需要 2 个 DMU")
|
|
253
|
+
n_inputs = data.input_matrix.shape[0]
|
|
254
|
+
n_desirable_outputs = data.desirable_output_matrix.shape[0]
|
|
255
|
+
n_undesirable_outputs = data.undesirable_output_matrix.shape[0]
|
|
256
|
+
|
|
257
|
+
# 非期望产出并入投入块("坏产出按投入处理":越少越好)
|
|
258
|
+
model_input_block = (
|
|
259
|
+
np.vstack([data.input_matrix, data.undesirable_output_matrix])
|
|
260
|
+
if n_undesirable_outputs else data.input_matrix
|
|
261
|
+
)
|
|
262
|
+
model_input_weights, output_weights, weighted = self._resolve_weights(
|
|
263
|
+
model_input_block.shape[0], n_desirable_outputs
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
standard_scores = np.empty(n_dmus)
|
|
267
|
+
augmented_input_slacks = np.empty((n_dmus, n_inputs + n_undesirable_outputs))
|
|
268
|
+
desirable_output_slacks = np.empty((n_dmus, n_desirable_outputs))
|
|
269
|
+
for dmu_index in range(n_dmus):
|
|
270
|
+
standard_score, input_slacks, output_slacks = self._solve_standard_sbm(
|
|
271
|
+
model_input_block, data.desirable_output_matrix, dmu_index,
|
|
272
|
+
model_input_weights, output_weights,
|
|
273
|
+
)
|
|
274
|
+
standard_scores[dmu_index] = standard_score
|
|
275
|
+
augmented_input_slacks[dmu_index] = input_slacks
|
|
276
|
+
desirable_output_slacks[dmu_index] = output_slacks
|
|
277
|
+
|
|
278
|
+
efficiency_mask = np.asarray(
|
|
279
|
+
standard_scores >= 1.0 - self.efficiency_tolerance, dtype=bool
|
|
280
|
+
)
|
|
281
|
+
super_efficiency_scores = np.full(n_dmus, np.nan)
|
|
282
|
+
notes: list[str] = []
|
|
283
|
+
if weighted:
|
|
284
|
+
notes.append("使用自定义权重(投入块与期望产出权重各自归一化到和为 1)")
|
|
285
|
+
|
|
286
|
+
if self.score_mode == "super":
|
|
287
|
+
final_scores = standard_scores.copy()
|
|
288
|
+
for dmu_index in np.flatnonzero(efficiency_mask):
|
|
289
|
+
raw_super_score = self._solve_super_sbm(
|
|
290
|
+
model_input_block, data.desirable_output_matrix, int(dmu_index),
|
|
291
|
+
model_input_weights, output_weights,
|
|
292
|
+
)
|
|
293
|
+
super_efficiency_scores[dmu_index] = raw_super_score
|
|
294
|
+
if raw_super_score >= 1.0 - self.efficiency_tolerance:
|
|
295
|
+
final_scores[dmu_index] = raw_super_score
|
|
296
|
+
else:
|
|
297
|
+
final_scores[dmu_index] = 1.0
|
|
298
|
+
notes.append(
|
|
299
|
+
f"有效 DMU '{data.dmu_names[dmu_index]}' 的超效率原始值 "
|
|
300
|
+
f"{raw_super_score:.6f} 小于 1,"
|
|
301
|
+
"理论上不应出现(数值误差),最终得分按 1.0 处理"
|
|
302
|
+
)
|
|
303
|
+
ranks = assign_ranks_with_ties(final_scores)
|
|
304
|
+
else:
|
|
305
|
+
final_scores = np.minimum(standard_scores, 1.0)
|
|
306
|
+
ranks = assign_ranks_with_ties(final_scores)
|
|
307
|
+
|
|
308
|
+
return SBMResult(
|
|
309
|
+
dmu_names=data.dmu_names,
|
|
310
|
+
final_scores=final_scores,
|
|
311
|
+
standard_scores=standard_scores,
|
|
312
|
+
super_efficiency_scores=super_efficiency_scores,
|
|
313
|
+
efficiency_mask=efficiency_mask,
|
|
314
|
+
ranks=ranks,
|
|
315
|
+
input_slacks=augmented_input_slacks[:, :n_inputs],
|
|
316
|
+
desirable_output_slacks=desirable_output_slacks,
|
|
317
|
+
undesirable_output_slacks=augmented_input_slacks[:, n_inputs:],
|
|
318
|
+
returns_to_scale=self.returns_to_scale,
|
|
319
|
+
score_mode=self.score_mode,
|
|
320
|
+
weighted=weighted,
|
|
321
|
+
notes=notes,
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
def _resolve_weights(self, n_model_inputs: int,
|
|
325
|
+
n_desirable_outputs: int) -> tuple[np.ndarray, np.ndarray, bool]:
|
|
326
|
+
"""解析并归一化投入块权重与期望产出权重。"""
|
|
327
|
+
input_weights = self._normalize_weights(
|
|
328
|
+
self.input_weights, n_model_inputs, "投入块权重"
|
|
329
|
+
)
|
|
330
|
+
output_weights = self._normalize_weights(
|
|
331
|
+
self.output_weights, n_desirable_outputs, "期望产出权重"
|
|
332
|
+
)
|
|
333
|
+
return input_weights, output_weights, (
|
|
334
|
+
self.input_weights is not None or self.output_weights is not None
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
@staticmethod
|
|
338
|
+
def _normalize_weights(weights: np.ndarray | None, count: int,
|
|
339
|
+
label: str) -> np.ndarray:
|
|
340
|
+
"""校验一组权重并归一化到和为 1;None 表示等权。"""
|
|
341
|
+
if weights is None:
|
|
342
|
+
return np.full(count, 1.0 / count)
|
|
343
|
+
if weights.size != count:
|
|
344
|
+
raise ValueError(f"{label}数量 ({weights.size}) 与模型指标数 ({count}) 不一致")
|
|
345
|
+
if not np.isfinite(weights).all() or (weights <= 0).any():
|
|
346
|
+
raise ValueError(f"{label}必须全部为正数")
|
|
347
|
+
return weights / weights.sum()
|
|
348
|
+
|
|
349
|
+
def _solve_standard_sbm(self, model_inputs: np.ndarray, desirable_outputs: np.ndarray,
|
|
350
|
+
dmu_index: int, input_weights: np.ndarray,
|
|
351
|
+
output_weights: np.ndarray) -> tuple[float, np.ndarray, np.ndarray]:
|
|
352
|
+
"""求解第 dmu_index 个 DMU 的标准 SBM(Tone 2001)线性规划。
|
|
353
|
+
|
|
354
|
+
分式规划经 Charnes-Cooper 变换后(变量 Λ = t·λ, S⁻ = t·s⁻, S⁺ = t·s⁺):
|
|
355
|
+
min t - Σ_i w⁻_i·S⁻_i / x_io
|
|
356
|
+
s.t. XΛ + S⁻ - t·x_o = 0
|
|
357
|
+
YΛ - S⁺ - t·y_o = 0
|
|
358
|
+
t + Σ_r w⁺_r·S⁺_r / y_ro = 1
|
|
359
|
+
ΣΛ - t = 0 (仅 VRS)
|
|
360
|
+
Λ, S⁻, S⁺, t ≥ 0
|
|
361
|
+
"""
|
|
362
|
+
n_model_inputs, n_dmus = model_inputs.shape
|
|
363
|
+
n_desirable_outputs = desirable_outputs.shape[0]
|
|
364
|
+
dmu_inputs = model_inputs[:, dmu_index]
|
|
365
|
+
dmu_outputs = desirable_outputs[:, dmu_index]
|
|
366
|
+
|
|
367
|
+
scale_column = n_dmus + n_model_inputs + n_desirable_outputs
|
|
368
|
+
n_variables = scale_column + 1
|
|
369
|
+
objective_coefficients = np.zeros(n_variables)
|
|
370
|
+
objective_coefficients[n_dmus:n_dmus + n_model_inputs] = (
|
|
371
|
+
-input_weights / dmu_inputs
|
|
372
|
+
)
|
|
373
|
+
objective_coefficients[scale_column] = 1.0
|
|
374
|
+
|
|
375
|
+
n_constraints = n_model_inputs + n_desirable_outputs + 1 + (
|
|
376
|
+
1 if self.returns_to_scale == "vrs" else 0
|
|
377
|
+
)
|
|
378
|
+
constraint_matrix = np.zeros((n_constraints, n_variables))
|
|
379
|
+
constraint_rhs = np.zeros(n_constraints)
|
|
380
|
+
|
|
381
|
+
constraint_matrix[:n_model_inputs, :n_dmus] = model_inputs # 投入约束
|
|
382
|
+
constraint_matrix[np.arange(n_model_inputs),
|
|
383
|
+
n_dmus + np.arange(n_model_inputs)] = 1.0
|
|
384
|
+
constraint_matrix[:n_model_inputs, scale_column] = -dmu_inputs
|
|
385
|
+
|
|
386
|
+
output_rows = slice(n_model_inputs, n_model_inputs + n_desirable_outputs)
|
|
387
|
+
constraint_matrix[output_rows, :n_dmus] = desirable_outputs # 产出约束
|
|
388
|
+
constraint_matrix[n_model_inputs + np.arange(n_desirable_outputs),
|
|
389
|
+
n_dmus + n_model_inputs + np.arange(n_desirable_outputs)] = -1.0
|
|
390
|
+
constraint_matrix[output_rows, scale_column] = -dmu_outputs
|
|
391
|
+
|
|
392
|
+
normalization_row = n_model_inputs + n_desirable_outputs
|
|
393
|
+
constraint_matrix[normalization_row,
|
|
394
|
+
n_dmus + n_model_inputs:scale_column] = (
|
|
395
|
+
output_weights / dmu_outputs
|
|
396
|
+
)
|
|
397
|
+
constraint_matrix[normalization_row, scale_column] = 1.0
|
|
398
|
+
constraint_rhs[normalization_row] = 1.0
|
|
399
|
+
|
|
400
|
+
if self.returns_to_scale == "vrs": # 凸性约束
|
|
401
|
+
convexity_row = normalization_row + 1
|
|
402
|
+
constraint_matrix[convexity_row, :n_dmus] = 1.0
|
|
403
|
+
constraint_matrix[convexity_row, scale_column] = -1.0
|
|
404
|
+
|
|
405
|
+
# 此类线性规划问题约束少、规模小;实测关闭 presolve 明显更快且结果一致
|
|
406
|
+
solution = solve_linear_program(
|
|
407
|
+
objective_coefficients,
|
|
408
|
+
equality_matrix=constraint_matrix, equality_rhs=constraint_rhs,
|
|
409
|
+
error_context=f"标准 SBM 求解失败(第 {dmu_index + 1} 个 DMU)",
|
|
410
|
+
)
|
|
411
|
+
|
|
412
|
+
scaling_factor = solution.x[scale_column]
|
|
413
|
+
if scaling_factor <= MIN_SCALING_FACTOR:
|
|
414
|
+
raise RuntimeError(
|
|
415
|
+
f"标准 SBM 缩放因子 t 非正(第 {dmu_index + 1} 个 DMU),数据可能异常"
|
|
416
|
+
)
|
|
417
|
+
input_slacks = solution.x[n_dmus:n_dmus + n_model_inputs] / scaling_factor
|
|
418
|
+
desirable_output_slacks = solution.x[
|
|
419
|
+
n_dmus + n_model_inputs:scale_column
|
|
420
|
+
] / scaling_factor
|
|
421
|
+
return float(solution.fun), input_slacks, desirable_output_slacks
|
|
422
|
+
|
|
423
|
+
def _solve_super_sbm(self, model_inputs: np.ndarray, desirable_outputs: np.ndarray,
|
|
424
|
+
dmu_index: int, input_weights: np.ndarray,
|
|
425
|
+
output_weights: np.ndarray) -> float:
|
|
426
|
+
"""求解第 dmu_index 个 DMU 的超效率 SBM(Tone 2002)线性规划。
|
|
427
|
+
|
|
428
|
+
将 DMU 移出参考集,并要求投影点不优于自身(x̄ ≥ x_o, ȳ ≤ y_o)。
|
|
429
|
+
经 Charnes-Cooper 变换(变量 X̄ = t·x̄, Ȳ = t·ȳ, Λ = t·λ):
|
|
430
|
+
min Σ_i w⁻_i·X̄_i / x_io
|
|
431
|
+
s.t. X̄ ≥ X_{≠o}·Λ, Ȳ ≤ Y_{≠o}·Λ
|
|
432
|
+
X̄ ≥ t·x_o, Ȳ ≤ t·y_o (自身水平约束)
|
|
433
|
+
Σ_r w⁺_r·Ȳ_r / y_ro = 1
|
|
434
|
+
ΣΛ - t = 0 (仅 VRS)
|
|
435
|
+
X̄, Ȳ, Λ, t ≥ 0
|
|
436
|
+
"""
|
|
437
|
+
n_model_inputs, n_dmus = model_inputs.shape
|
|
438
|
+
n_desirable_outputs = desirable_outputs.shape[0]
|
|
439
|
+
dmu_inputs = model_inputs[:, dmu_index]
|
|
440
|
+
dmu_outputs = desirable_outputs[:, dmu_index]
|
|
441
|
+
|
|
442
|
+
other_dmu_mask = np.ones(n_dmus, dtype=bool)
|
|
443
|
+
other_dmu_mask[dmu_index] = False
|
|
444
|
+
other_inputs = model_inputs[:, other_dmu_mask]
|
|
445
|
+
other_outputs = desirable_outputs[:, other_dmu_mask]
|
|
446
|
+
n_other_dmus = n_dmus - 1
|
|
447
|
+
|
|
448
|
+
is_vrs = self.returns_to_scale == "vrs"
|
|
449
|
+
lambda_start_column = n_model_inputs + n_desirable_outputs
|
|
450
|
+
scale_column = lambda_start_column + n_other_dmus
|
|
451
|
+
n_variables = scale_column + 1
|
|
452
|
+
|
|
453
|
+
objective_coefficients = np.zeros(n_variables)
|
|
454
|
+
objective_coefficients[:n_model_inputs] = input_weights / dmu_inputs
|
|
455
|
+
|
|
456
|
+
inequality_matrix = np.zeros((2 * n_model_inputs + 2 * n_desirable_outputs, n_variables))
|
|
457
|
+
inequality_rhs = np.zeros(2 * n_model_inputs + 2 * n_desirable_outputs)
|
|
458
|
+
|
|
459
|
+
inequality_matrix[:n_model_inputs, :n_model_inputs] = -np.eye(n_model_inputs)
|
|
460
|
+
inequality_matrix[:n_model_inputs,
|
|
461
|
+
lambda_start_column:scale_column] = other_inputs
|
|
462
|
+
|
|
463
|
+
output_rows = slice(n_model_inputs, n_model_inputs + n_desirable_outputs)
|
|
464
|
+
inequality_matrix[output_rows,
|
|
465
|
+
n_model_inputs:n_model_inputs + n_desirable_outputs] = (
|
|
466
|
+
np.eye(n_desirable_outputs)
|
|
467
|
+
)
|
|
468
|
+
inequality_matrix[output_rows,
|
|
469
|
+
lambda_start_column:scale_column] = -other_outputs
|
|
470
|
+
|
|
471
|
+
anchor_input_rows = slice(n_model_inputs + n_desirable_outputs,
|
|
472
|
+
2 * n_model_inputs + n_desirable_outputs)
|
|
473
|
+
inequality_matrix[anchor_input_rows, :n_model_inputs] = -np.eye(n_model_inputs)
|
|
474
|
+
inequality_matrix[np.arange(n_model_inputs + n_desirable_outputs,
|
|
475
|
+
2 * n_model_inputs + n_desirable_outputs),
|
|
476
|
+
scale_column] = dmu_inputs
|
|
477
|
+
|
|
478
|
+
anchor_output_rows = slice(2 * n_model_inputs + n_desirable_outputs,
|
|
479
|
+
2 * n_model_inputs + 2 * n_desirable_outputs)
|
|
480
|
+
inequality_matrix[anchor_output_rows,
|
|
481
|
+
n_model_inputs:n_model_inputs + n_desirable_outputs] = (
|
|
482
|
+
np.eye(n_desirable_outputs)
|
|
483
|
+
)
|
|
484
|
+
inequality_matrix[np.arange(2 * n_model_inputs + n_desirable_outputs,
|
|
485
|
+
2 * n_model_inputs + 2 * n_desirable_outputs),
|
|
486
|
+
scale_column] = -dmu_outputs
|
|
487
|
+
|
|
488
|
+
equality_matrix = np.zeros((2 if is_vrs else 1, n_variables))
|
|
489
|
+
equality_rhs = np.zeros(equality_matrix.shape[0])
|
|
490
|
+
equality_matrix[0, n_model_inputs:n_model_inputs + n_desirable_outputs] = (
|
|
491
|
+
output_weights / dmu_outputs
|
|
492
|
+
)
|
|
493
|
+
equality_rhs[0] = 1.0
|
|
494
|
+
if is_vrs:
|
|
495
|
+
equality_matrix[1, lambda_start_column:scale_column] = 1.0
|
|
496
|
+
equality_matrix[1, scale_column] = -1.0
|
|
497
|
+
|
|
498
|
+
# 此类线性规划问题约束少、规模小;实测关闭 presolve 明显更快且结果一致
|
|
499
|
+
solution = solve_linear_program(
|
|
500
|
+
objective_coefficients,
|
|
501
|
+
inequality_matrix=inequality_matrix, inequality_rhs=inequality_rhs,
|
|
502
|
+
equality_matrix=equality_matrix, equality_rhs=equality_rhs,
|
|
503
|
+
error_context=f"超效率 SBM 求解失败(第 {dmu_index + 1} 个 DMU)",
|
|
504
|
+
)
|
|
505
|
+
return float(solution.fun)
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
509
|
+
argument_parser = argparse.ArgumentParser(
|
|
510
|
+
description="超效率 SBM(Tone 2002)与标准 SBM(Tone 2001)计算;不带参数时使用脚本配置区",
|
|
511
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
512
|
+
epilog=(
|
|
513
|
+
"示例:\n"
|
|
514
|
+
" python super_sbm.py\n"
|
|
515
|
+
" python super_sbm.py data.xlsx --sheet Sheet1 --input-columns x1 x2 "
|
|
516
|
+
"--desirable-output-columns y1 y2 --undesirable-output-columns b1 "
|
|
517
|
+
"--result-file 结果.csv\n"
|
|
518
|
+
" python super_sbm.py --demo --returns-to-scale vrs\n"
|
|
519
|
+
),
|
|
520
|
+
)
|
|
521
|
+
DATA_COMMAND_LINE.add_arguments(argument_parser)
|
|
522
|
+
argument_parser.add_argument("--returns-to-scale", "--rts",
|
|
523
|
+
choices=("crs", "vrs"), default=None,
|
|
524
|
+
help="规模报酬: crs=不变, vrs=可变;缺省用 RETURNS_TO_SCALE")
|
|
525
|
+
argument_parser.add_argument("--score-mode", "--mode",
|
|
526
|
+
choices=("super", "standard"), default=None,
|
|
527
|
+
help="评分口径: super=可超过1, standard=最大为1;缺省用 SCORE_MODE")
|
|
528
|
+
argument_parser.add_argument("--tolerance", "--tol", type=float, default=None,
|
|
529
|
+
help=f"判定有效性的容差(默认 {EFFICIENCY_TOLERANCE})")
|
|
530
|
+
argument_parser.add_argument("--input-weights", nargs="+", type=float, metavar="权重",
|
|
531
|
+
default=None,
|
|
532
|
+
help="投入块权重(顺序:投入列 + 非期望产出列);None 表示等权")
|
|
533
|
+
argument_parser.add_argument("--output-weights", nargs="+", type=float, metavar="权重",
|
|
534
|
+
default=None,
|
|
535
|
+
help="期望产出权重;None 表示等权")
|
|
536
|
+
return argument_parser
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
540
|
+
args = build_parser().parse_args(argv)
|
|
541
|
+
try:
|
|
542
|
+
prepared = DATA_COMMAND_LINE.prepare(args)
|
|
543
|
+
returns_to_scale = (
|
|
544
|
+
args.returns_to_scale if args.returns_to_scale is not None
|
|
545
|
+
else RETURNS_TO_SCALE
|
|
546
|
+
)
|
|
547
|
+
score_mode = (
|
|
548
|
+
args.score_mode if args.score_mode is not None else SCORE_MODE
|
|
549
|
+
)
|
|
550
|
+
efficiency_tolerance = (
|
|
551
|
+
args.tolerance if args.tolerance is not None else EFFICIENCY_TOLERANCE
|
|
552
|
+
)
|
|
553
|
+
input_weights = (
|
|
554
|
+
args.input_weights if args.input_weights is not None else INPUT_WEIGHTS
|
|
555
|
+
)
|
|
556
|
+
output_weights = (
|
|
557
|
+
args.output_weights if args.output_weights is not None else OUTPUT_WEIGHTS
|
|
558
|
+
)
|
|
559
|
+
input_weights = tuple(input_weights) if input_weights is not None else None
|
|
560
|
+
output_weights = tuple(output_weights) if output_weights is not None else None
|
|
561
|
+
model = SBMModel(
|
|
562
|
+
returns_to_scale=returns_to_scale,
|
|
563
|
+
score_mode=score_mode,
|
|
564
|
+
efficiency_tolerance=efficiency_tolerance,
|
|
565
|
+
weights=SBMWeights(
|
|
566
|
+
input_weights=input_weights,
|
|
567
|
+
output_weights=output_weights,
|
|
568
|
+
),
|
|
569
|
+
)
|
|
570
|
+
result = model.solve(prepared.data)
|
|
571
|
+
except (ValueError, RuntimeError) as exc:
|
|
572
|
+
print(f"错误: {exc}", file=sys.stderr)
|
|
573
|
+
return 1
|
|
574
|
+
|
|
575
|
+
print(result.render_report(
|
|
576
|
+
prepared.column_names,
|
|
577
|
+
source_description=prepared.source_description,
|
|
578
|
+
))
|
|
579
|
+
if prepared.result_file:
|
|
580
|
+
try:
|
|
581
|
+
result.write_csv(prepared.result_file, prepared.column_names)
|
|
582
|
+
except OSError as exc:
|
|
583
|
+
print(f"错误: 无法写入 {prepared.result_file}: {exc}", file=sys.stderr)
|
|
584
|
+
return 1
|
|
585
|
+
print(f"\n结果已写入: {prepared.result_file}")
|
|
586
|
+
return 0
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
if __name__ == "__main__":
|
|
590
|
+
sys.exit(main())
|