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
radial_models.py
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""CCR/BCC 径向数据包络分析脚本。
|
|
4
|
+
|
|
5
|
+
模型:
|
|
6
|
+
1. CCR(Charnes-Cooper-Rhodes 1978):规模报酬不变(CRS)的径向模型;
|
|
7
|
+
2. BCC(Banker-Charnes-Cooper 1984):规模报酬可变(VRS)的径向模型;
|
|
8
|
+
3. 导向:投入导向(给定产出,最小化投入)或产出导向(给定投入,最大化产出);
|
|
9
|
+
4. 评分口径:standard(得分最大为 1)或 super(有效单元可超过 1,
|
|
10
|
+
将自身移出参考集后重解);
|
|
11
|
+
5. 非期望产出:按“投入方向”处理(并入投入块,越少越好)。
|
|
12
|
+
|
|
13
|
+
得分统一为“越大越好”:投入导向用 θ;产出导向用 1/φ(CSV 同时保留原始 φ)。
|
|
14
|
+
标准得分 ≤ 1;超效率得分 ≥ 1。VRS 径向超效率可能不可行,此时超效率列留空、
|
|
15
|
+
最终得分按 1.0 处理并给出提示。
|
|
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
|
+
MIN_SCALING_FACTOR,
|
|
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
|
+
# 数据文件路径:支持 .csv / .xlsx / .xlsm;相对路径优先按当前工作目录,其次脚本所在目录解析
|
|
43
|
+
DATA_FILE = "sample_data.csv"
|
|
44
|
+
EXCEL_SHEET = 0 # Excel 工作表名或序号(0 开始);CSV 忽略
|
|
45
|
+
|
|
46
|
+
# DMU 标识列:可多列,自动用 "-" 拼接为唯一名称;如 ["城市代码", "年份"] → "110000-2021"
|
|
47
|
+
DMU_COLUMNS = ["城市代码", "年份"]
|
|
48
|
+
|
|
49
|
+
# 指标列名:按数据表的列名填写(三组变量分开设置)
|
|
50
|
+
INPUT_COLUMNS = ["资本投入", "劳动投入"] # 投入变量
|
|
51
|
+
DESIRABLE_OUTPUT_COLUMNS = ["GDP", "财政收入"] # 期望产出
|
|
52
|
+
UNDESIRABLE_OUTPUT_COLUMNS = ["工业废水排放量"] # 非期望产出(没有就写 [])
|
|
53
|
+
|
|
54
|
+
# 模型选项
|
|
55
|
+
ORIENTATION = "input" # "input"=投入导向,"output"=产出导向
|
|
56
|
+
RETURNS_TO_SCALE = "crs" # "crs"=规模报酬不变,"vrs"=规模报酬可变
|
|
57
|
+
SCORE_MODE = "super" # "super"=超效率(有效单元可 >1),"standard"=得分最大为 1
|
|
58
|
+
RESULT_FILE = None # 结果 CSV 输出路径,如 "dea_results.csv";None 表示不导出
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
DATA_COMMAND_LINE = DataCommandLine(
|
|
62
|
+
settings=DataSettings(
|
|
63
|
+
data_file=DATA_FILE,
|
|
64
|
+
excel_sheet=EXCEL_SHEET,
|
|
65
|
+
dmu_columns=tuple(DMU_COLUMNS),
|
|
66
|
+
input_columns=tuple(INPUT_COLUMNS),
|
|
67
|
+
desirable_output_columns=tuple(DESIRABLE_OUTPUT_COLUMNS),
|
|
68
|
+
undesirable_output_columns=tuple(UNDESIRABLE_OUTPUT_COLUMNS),
|
|
69
|
+
result_file=RESULT_FILE,
|
|
70
|
+
),
|
|
71
|
+
script_directory=os.path.dirname(os.path.abspath(__file__)),
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass
|
|
76
|
+
class RadialResult:
|
|
77
|
+
"""一次径向 DEA 求解的结果,含报表与 CSV 导出。"""
|
|
78
|
+
|
|
79
|
+
dmu_names: list[str] # DMU 名称
|
|
80
|
+
final_scores: np.ndarray # 最终得分(越大越好)
|
|
81
|
+
standard_scores: np.ndarray # 标准径向得分(≤ 1)
|
|
82
|
+
super_efficiency_scores: np.ndarray # 超效率得分(≥ 1;未计算或不可行为 NaN)
|
|
83
|
+
standard_radial_values: np.ndarray # 标准阶段原始值:投入导向 θ / 产出导向 φ
|
|
84
|
+
super_radial_values: np.ndarray # 超效率阶段原始值(未计算或不可行为 NaN)
|
|
85
|
+
efficiency_mask: np.ndarray # 是否标准径向有效(bool)
|
|
86
|
+
super_feasible: np.ndarray # 超效率线性规划是否求解成功(bool)
|
|
87
|
+
ranks: np.ndarray # 按最终得分的名次(并列取最小名次)
|
|
88
|
+
orientation: str
|
|
89
|
+
returns_to_scale: str
|
|
90
|
+
score_mode: str
|
|
91
|
+
notes: list[str] = field(default_factory=list)
|
|
92
|
+
|
|
93
|
+
def to_records(self) -> list[dict[str, object]]:
|
|
94
|
+
"""把每个 DMU 展开成一条可直接写 CSV 的记录。"""
|
|
95
|
+
records = []
|
|
96
|
+
for dmu_index, dmu_name in enumerate(self.dmu_names):
|
|
97
|
+
super_score = self.super_efficiency_scores[dmu_index]
|
|
98
|
+
super_radial_value = self.super_radial_values[dmu_index]
|
|
99
|
+
records.append({
|
|
100
|
+
"dmu": dmu_name,
|
|
101
|
+
"final_score": round_score(self.final_scores[dmu_index]),
|
|
102
|
+
"standard_score": round_score(self.standard_scores[dmu_index]),
|
|
103
|
+
"super_efficiency_score": (
|
|
104
|
+
None if np.isnan(super_score) else round_score(super_score)
|
|
105
|
+
),
|
|
106
|
+
"standard_radial_value": round_score(self.standard_radial_values[dmu_index]),
|
|
107
|
+
"super_radial_value": (
|
|
108
|
+
None if np.isnan(super_radial_value) else round_score(super_radial_value)
|
|
109
|
+
),
|
|
110
|
+
"super_feasible": int(self.super_feasible[dmu_index]),
|
|
111
|
+
"efficient": int(self.efficiency_mask[dmu_index]),
|
|
112
|
+
"rank": int(self.ranks[dmu_index]),
|
|
113
|
+
})
|
|
114
|
+
return records
|
|
115
|
+
|
|
116
|
+
def write_csv(self, path: str) -> None:
|
|
117
|
+
"""写出 UTF-8-BOM 编码的结果 CSV。"""
|
|
118
|
+
write_csv_records(path, self.to_records())
|
|
119
|
+
|
|
120
|
+
def render_report(self, column_names: ColumnNames,
|
|
121
|
+
source_description: str | None = None) -> str:
|
|
122
|
+
"""生成控制台报表文本。"""
|
|
123
|
+
model_name = "CCR" if self.returns_to_scale == "crs" else "BCC"
|
|
124
|
+
model_title = f"超效率 {model_name} 径向模型" if self.score_mode == "super" \
|
|
125
|
+
else f"{model_name} 径向模型(标准)"
|
|
126
|
+
orientation_description = "投入导向" if self.orientation == "input" else "产出导向"
|
|
127
|
+
returns_to_scale_description = (
|
|
128
|
+
"CRS 规模报酬不变" if self.returns_to_scale == "crs" else "VRS 规模报酬可变"
|
|
129
|
+
)
|
|
130
|
+
score_mode_description = (
|
|
131
|
+
"前沿取值可超过 1" if self.score_mode == "super" else "前沿取值最大为 1"
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
report_lines = [
|
|
135
|
+
f"模型: {model_title}({orientation_description}) | "
|
|
136
|
+
f"{returns_to_scale_description} | {score_mode_description}"
|
|
137
|
+
]
|
|
138
|
+
if source_description:
|
|
139
|
+
report_lines.append(f"数据: {source_description}")
|
|
140
|
+
undesirable_output_description = (
|
|
141
|
+
"、".join(column_names.undesirable_output_columns)
|
|
142
|
+
if column_names.undesirable_output_columns else "无"
|
|
143
|
+
)
|
|
144
|
+
report_lines.append(
|
|
145
|
+
f"变量: 投入[{'、'.join(column_names.input_columns)}] | "
|
|
146
|
+
f"期望产出[{'、'.join(column_names.desirable_output_columns)}] | "
|
|
147
|
+
f"非期望产出[{undesirable_output_description}]"
|
|
148
|
+
)
|
|
149
|
+
report_lines.append(f"DMU 数: {len(self.dmu_names)}")
|
|
150
|
+
report_lines.append("")
|
|
151
|
+
|
|
152
|
+
table_header = ["DMU", "得分", "标准径向", "超效率得分", "排名"]
|
|
153
|
+
table_rows = []
|
|
154
|
+
for dmu_index, dmu_name in enumerate(self.dmu_names):
|
|
155
|
+
super_score = self.super_efficiency_scores[dmu_index]
|
|
156
|
+
table_rows.append([
|
|
157
|
+
dmu_name,
|
|
158
|
+
f"{self.final_scores[dmu_index]:.{SCORE_DECIMALS}f}",
|
|
159
|
+
f"{self.standard_scores[dmu_index]:.{SCORE_DECIMALS}f}",
|
|
160
|
+
"-" if np.isnan(super_score) else f"{super_score:.{SCORE_DECIMALS}f}",
|
|
161
|
+
str(int(self.ranks[dmu_index])),
|
|
162
|
+
])
|
|
163
|
+
report_lines.append(format_table(table_header, table_rows))
|
|
164
|
+
report_lines.append("")
|
|
165
|
+
|
|
166
|
+
efficient_dmu_names = [self.dmu_names[i] for i in np.flatnonzero(self.efficiency_mask)]
|
|
167
|
+
report_lines.append(
|
|
168
|
+
f"有效 DMU(标准径向得分 = 1)共 {len(efficient_dmu_names)} 个: "
|
|
169
|
+
f"{'、'.join(efficient_dmu_names) if efficient_dmu_names else '无'}"
|
|
170
|
+
)
|
|
171
|
+
if self.orientation == "output":
|
|
172
|
+
report_lines.append("说明: 产出导向原始值为 φ,得分 = 1/φ(越大越好)")
|
|
173
|
+
if self.score_mode == "super":
|
|
174
|
+
report_lines.append(
|
|
175
|
+
"说明: 超效率阶段有效单元得分 ≥ 1;得分为 1 表示未能进一步区分"
|
|
176
|
+
)
|
|
177
|
+
if self.score_mode == "super":
|
|
178
|
+
infeasible_count = int(
|
|
179
|
+
np.count_nonzero(self.efficiency_mask & ~self.super_feasible)
|
|
180
|
+
)
|
|
181
|
+
if infeasible_count:
|
|
182
|
+
report_lines.append(
|
|
183
|
+
f"说明: {infeasible_count} 个有效 DMU 的径向超效率不可行,"
|
|
184
|
+
"最终得分按 1.0 处理;建议改用 CRS 或超效率 SBM"
|
|
185
|
+
)
|
|
186
|
+
if column_names.undesirable_output_columns:
|
|
187
|
+
report_lines.append("说明: 非期望产出按投入方向处理(越少越好)")
|
|
188
|
+
report_lines.append(
|
|
189
|
+
f"平均标准径向得分: {float(np.mean(self.standard_scores)):.{SCORE_DECIMALS}f}"
|
|
190
|
+
)
|
|
191
|
+
feasible_efficient_mask = self.efficiency_mask & self.super_feasible
|
|
192
|
+
if self.score_mode == "super" and np.any(feasible_efficient_mask):
|
|
193
|
+
average_super_efficiency = float(
|
|
194
|
+
np.mean(self.super_efficiency_scores[feasible_efficient_mask])
|
|
195
|
+
)
|
|
196
|
+
report_lines.append(
|
|
197
|
+
f"有效单元平均超效率: {average_super_efficiency:.{SCORE_DECIMALS}f}"
|
|
198
|
+
f"({int(np.count_nonzero(feasible_efficient_mask))} 个可行)"
|
|
199
|
+
)
|
|
200
|
+
report_lines.extend(f"提示: {note}" for note in self.notes[:10])
|
|
201
|
+
if len(self.notes) > 10:
|
|
202
|
+
report_lines.append(f"提示: 其余 {len(self.notes) - 10} 条类似提示已省略")
|
|
203
|
+
return "\n".join(report_lines)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class RadialModel:
|
|
207
|
+
"""CCR/BCC 径向模型求解器(投入或产出导向,可选超效率)。"""
|
|
208
|
+
|
|
209
|
+
def __init__(self, orientation: str = "input", returns_to_scale: str = "crs",
|
|
210
|
+
score_mode: str = "super",
|
|
211
|
+
efficiency_tolerance: float = EFFICIENCY_TOLERANCE):
|
|
212
|
+
orientation = orientation.lower()
|
|
213
|
+
returns_to_scale = returns_to_scale.lower()
|
|
214
|
+
score_mode = score_mode.lower()
|
|
215
|
+
if orientation not in ("input", "output"):
|
|
216
|
+
raise ValueError("orientation 只能取 'input' 或 'output'")
|
|
217
|
+
if returns_to_scale not in ("crs", "vrs"):
|
|
218
|
+
raise ValueError("returns_to_scale 只能取 'crs' 或 'vrs'")
|
|
219
|
+
if score_mode not in ("super", "standard"):
|
|
220
|
+
raise ValueError("score_mode 只能取 'super' 或 'standard'")
|
|
221
|
+
if efficiency_tolerance <= 0:
|
|
222
|
+
raise ValueError("efficiency_tolerance 必须为正数")
|
|
223
|
+
self.orientation = orientation
|
|
224
|
+
self.returns_to_scale = returns_to_scale
|
|
225
|
+
self.score_mode = score_mode
|
|
226
|
+
self.efficiency_tolerance = float(efficiency_tolerance)
|
|
227
|
+
|
|
228
|
+
def solve(self, data: DEAData) -> RadialResult:
|
|
229
|
+
"""执行两阶段求解:标准径向模型 → 对有效 DMU 追加超效率模型。"""
|
|
230
|
+
n_dmus = data.input_matrix.shape[1]
|
|
231
|
+
if self.score_mode == "super" and n_dmus < 2:
|
|
232
|
+
raise ValueError("超效率模式至少需要 2 个 DMU")
|
|
233
|
+
n_undesirable_outputs = data.undesirable_output_matrix.shape[0]
|
|
234
|
+
|
|
235
|
+
# 非期望产出并入投入块("坏产出按投入处理":越少越好)
|
|
236
|
+
model_inputs = (
|
|
237
|
+
np.vstack([data.input_matrix, data.undesirable_output_matrix])
|
|
238
|
+
if n_undesirable_outputs else data.input_matrix
|
|
239
|
+
)
|
|
240
|
+
desirable_outputs = data.desirable_output_matrix
|
|
241
|
+
|
|
242
|
+
standard_scores = np.empty(n_dmus)
|
|
243
|
+
standard_radial_values = np.empty(n_dmus)
|
|
244
|
+
for dmu_index in range(n_dmus):
|
|
245
|
+
score, radial_value = self._solve_standard_efficiency(
|
|
246
|
+
model_inputs, desirable_outputs, dmu_index
|
|
247
|
+
)
|
|
248
|
+
standard_scores[dmu_index] = score
|
|
249
|
+
standard_radial_values[dmu_index] = radial_value
|
|
250
|
+
|
|
251
|
+
efficiency_mask = np.asarray(
|
|
252
|
+
standard_scores >= 1.0 - self.efficiency_tolerance, dtype=bool
|
|
253
|
+
)
|
|
254
|
+
super_efficiency_scores = np.full(n_dmus, np.nan)
|
|
255
|
+
super_radial_values = np.full(n_dmus, np.nan)
|
|
256
|
+
super_feasible = np.zeros(n_dmus, dtype=bool)
|
|
257
|
+
notes: list[str] = []
|
|
258
|
+
|
|
259
|
+
if self.score_mode == "super":
|
|
260
|
+
final_scores = standard_scores.copy()
|
|
261
|
+
for dmu_index in np.flatnonzero(efficiency_mask):
|
|
262
|
+
feasible, super_score, super_radial_value, failure_message = (
|
|
263
|
+
self._solve_super_efficiency(
|
|
264
|
+
model_inputs, desirable_outputs, int(dmu_index)
|
|
265
|
+
)
|
|
266
|
+
)
|
|
267
|
+
if not feasible:
|
|
268
|
+
final_scores[dmu_index] = 1.0
|
|
269
|
+
note = (
|
|
270
|
+
f"有效 DMU '{data.dmu_names[dmu_index]}' 的径向超效率不可行"
|
|
271
|
+
f"({self.returns_to_scale}),最终得分按 1.0 处理"
|
|
272
|
+
)
|
|
273
|
+
notes.append(
|
|
274
|
+
f"{note}:{failure_message}" if failure_message else note
|
|
275
|
+
)
|
|
276
|
+
continue
|
|
277
|
+
super_feasible[dmu_index] = True
|
|
278
|
+
super_efficiency_scores[dmu_index] = super_score
|
|
279
|
+
super_radial_values[dmu_index] = super_radial_value
|
|
280
|
+
if super_score >= 1.0 - self.efficiency_tolerance:
|
|
281
|
+
final_scores[dmu_index] = super_score
|
|
282
|
+
else:
|
|
283
|
+
final_scores[dmu_index] = 1.0
|
|
284
|
+
notes.append(
|
|
285
|
+
f"有效 DMU '{data.dmu_names[dmu_index]}' 的超效率得分 "
|
|
286
|
+
f"{super_score:.6f} 小于 1,理论上不应出现(数值误差),"
|
|
287
|
+
"最终得分按 1.0 处理"
|
|
288
|
+
)
|
|
289
|
+
ranks = assign_ranks_with_ties(final_scores)
|
|
290
|
+
else:
|
|
291
|
+
final_scores = np.minimum(standard_scores, 1.0)
|
|
292
|
+
ranks = assign_ranks_with_ties(final_scores)
|
|
293
|
+
|
|
294
|
+
return RadialResult(
|
|
295
|
+
dmu_names=data.dmu_names,
|
|
296
|
+
final_scores=final_scores,
|
|
297
|
+
standard_scores=standard_scores,
|
|
298
|
+
super_efficiency_scores=super_efficiency_scores,
|
|
299
|
+
standard_radial_values=standard_radial_values,
|
|
300
|
+
super_radial_values=super_radial_values,
|
|
301
|
+
efficiency_mask=efficiency_mask,
|
|
302
|
+
super_feasible=super_feasible,
|
|
303
|
+
ranks=ranks,
|
|
304
|
+
orientation=self.orientation,
|
|
305
|
+
returns_to_scale=self.returns_to_scale,
|
|
306
|
+
score_mode=self.score_mode,
|
|
307
|
+
notes=notes,
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
def _solve_standard_efficiency(self, model_inputs: np.ndarray,
|
|
311
|
+
desirable_outputs: np.ndarray,
|
|
312
|
+
dmu_index: int) -> tuple[float, float]:
|
|
313
|
+
"""求解第 dmu_index 个 DMU 的标准 CCR/BCC 径向线性规划。
|
|
314
|
+
|
|
315
|
+
投入导向: min θ, Xλ ≤ θx_o, Yλ ≥ y_o, Σλ = 1(仅 VRS)
|
|
316
|
+
产出导向: max φ, Xλ ≤ x_o, Yλ ≥ φy_o, Σλ = 1(仅 VRS)
|
|
317
|
+
"""
|
|
318
|
+
n_inputs, n_dmus = model_inputs.shape
|
|
319
|
+
n_outputs = desirable_outputs.shape[0]
|
|
320
|
+
dmu_inputs = model_inputs[:, dmu_index]
|
|
321
|
+
dmu_outputs = desirable_outputs[:, dmu_index]
|
|
322
|
+
n_variables = n_dmus + 1
|
|
323
|
+
|
|
324
|
+
objective_coefficients = np.zeros(n_variables)
|
|
325
|
+
inequality_matrix = np.zeros((n_inputs + n_outputs, n_variables))
|
|
326
|
+
inequality_rhs = np.zeros(n_inputs + n_outputs)
|
|
327
|
+
inequality_matrix[:n_inputs, :n_dmus] = model_inputs
|
|
328
|
+
inequality_matrix[n_inputs:, :n_dmus] = -desirable_outputs
|
|
329
|
+
equality_matrix, equality_rhs = self._build_convexity_constraint(n_variables, n_dmus)
|
|
330
|
+
|
|
331
|
+
if self.orientation == "input":
|
|
332
|
+
objective_coefficients[n_dmus] = 1.0
|
|
333
|
+
inequality_matrix[:n_inputs, n_dmus] = -dmu_inputs
|
|
334
|
+
inequality_rhs[n_inputs:] = -dmu_outputs
|
|
335
|
+
solution = solve_linear_program(
|
|
336
|
+
objective_coefficients,
|
|
337
|
+
inequality_matrix=inequality_matrix, inequality_rhs=inequality_rhs,
|
|
338
|
+
equality_matrix=equality_matrix, equality_rhs=equality_rhs,
|
|
339
|
+
error_context=f"投入导向径向模型求解失败(第 {dmu_index + 1} 个 DMU)",
|
|
340
|
+
)
|
|
341
|
+
theta = float(solution.x[n_dmus])
|
|
342
|
+
return theta, theta
|
|
343
|
+
|
|
344
|
+
objective_coefficients[n_dmus] = -1.0
|
|
345
|
+
inequality_matrix[n_inputs:, n_dmus] = dmu_outputs
|
|
346
|
+
inequality_rhs[:n_inputs] = dmu_inputs
|
|
347
|
+
solution = solve_linear_program(
|
|
348
|
+
objective_coefficients,
|
|
349
|
+
inequality_matrix=inequality_matrix, inequality_rhs=inequality_rhs,
|
|
350
|
+
equality_matrix=equality_matrix, equality_rhs=equality_rhs,
|
|
351
|
+
error_context=f"产出导向径向模型求解失败(第 {dmu_index + 1} 个 DMU)",
|
|
352
|
+
)
|
|
353
|
+
phi = float(solution.x[n_dmus])
|
|
354
|
+
if phi <= MIN_SCALING_FACTOR:
|
|
355
|
+
raise RuntimeError(
|
|
356
|
+
f"产出导向径向模型扩张因子 φ 非正(第 {dmu_index + 1} 个 DMU),数据可能异常"
|
|
357
|
+
)
|
|
358
|
+
return 1.0 / phi, phi
|
|
359
|
+
|
|
360
|
+
def _solve_super_efficiency(self, model_inputs: np.ndarray,
|
|
361
|
+
desirable_outputs: np.ndarray,
|
|
362
|
+
dmu_index: int) -> tuple[bool, float, float, str]:
|
|
363
|
+
"""求解第 dmu_index 个 DMU 的超效率径向线性规划(自身移出参考集)。
|
|
364
|
+
|
|
365
|
+
投入导向: min θ, X_{≠o}λ ≤ θx_o, Y_{≠o}λ ≥ y_o, Σλ = 1(仅 VRS)
|
|
366
|
+
产出导向: max φ, X_{≠o}λ ≤ x_o, Y_{≠o}λ ≥ φy_o, Σλ = 1(仅 VRS)
|
|
367
|
+
"""
|
|
368
|
+
n_inputs, n_dmus = model_inputs.shape
|
|
369
|
+
n_outputs = desirable_outputs.shape[0]
|
|
370
|
+
dmu_inputs = model_inputs[:, dmu_index]
|
|
371
|
+
dmu_outputs = desirable_outputs[:, dmu_index]
|
|
372
|
+
|
|
373
|
+
other_dmu_mask = np.ones(n_dmus, dtype=bool)
|
|
374
|
+
other_dmu_mask[dmu_index] = False
|
|
375
|
+
other_inputs = model_inputs[:, other_dmu_mask]
|
|
376
|
+
other_outputs = desirable_outputs[:, other_dmu_mask]
|
|
377
|
+
n_other_dmus = n_dmus - 1
|
|
378
|
+
n_variables = n_other_dmus + 1
|
|
379
|
+
|
|
380
|
+
objective_coefficients = np.zeros(n_variables)
|
|
381
|
+
inequality_matrix = np.zeros((n_inputs + n_outputs, n_variables))
|
|
382
|
+
inequality_rhs = np.zeros(n_inputs + n_outputs)
|
|
383
|
+
inequality_matrix[:n_inputs, :n_other_dmus] = other_inputs
|
|
384
|
+
inequality_matrix[n_inputs:, :n_other_dmus] = -other_outputs
|
|
385
|
+
equality_matrix, equality_rhs = self._build_convexity_constraint(
|
|
386
|
+
n_variables, n_other_dmus
|
|
387
|
+
)
|
|
388
|
+
|
|
389
|
+
if self.orientation == "input":
|
|
390
|
+
objective_coefficients[n_other_dmus] = 1.0
|
|
391
|
+
inequality_matrix[:n_inputs, n_other_dmus] = -dmu_inputs
|
|
392
|
+
inequality_rhs[n_inputs:] = -dmu_outputs
|
|
393
|
+
solution = solve_linear_program(
|
|
394
|
+
objective_coefficients,
|
|
395
|
+
inequality_matrix=inequality_matrix, inequality_rhs=inequality_rhs,
|
|
396
|
+
equality_matrix=equality_matrix, equality_rhs=equality_rhs,
|
|
397
|
+
error_context=f"投入导向径向超效率求解失败(第 {dmu_index + 1} 个 DMU)",
|
|
398
|
+
require_success=False,
|
|
399
|
+
)
|
|
400
|
+
if not solution.success:
|
|
401
|
+
return False, float("nan"), float("nan"), solution.message
|
|
402
|
+
theta = float(solution.x[n_other_dmus])
|
|
403
|
+
return True, theta, theta, ""
|
|
404
|
+
|
|
405
|
+
objective_coefficients[n_other_dmus] = -1.0
|
|
406
|
+
inequality_matrix[n_inputs:, n_other_dmus] = dmu_outputs
|
|
407
|
+
inequality_rhs[:n_inputs] = dmu_inputs
|
|
408
|
+
solution = solve_linear_program(
|
|
409
|
+
objective_coefficients,
|
|
410
|
+
inequality_matrix=inequality_matrix, inequality_rhs=inequality_rhs,
|
|
411
|
+
equality_matrix=equality_matrix, equality_rhs=equality_rhs,
|
|
412
|
+
error_context=f"产出导向径向超效率求解失败(第 {dmu_index + 1} 个 DMU)",
|
|
413
|
+
require_success=False,
|
|
414
|
+
)
|
|
415
|
+
if not solution.success:
|
|
416
|
+
return False, float("nan"), float("nan"), solution.message
|
|
417
|
+
phi = float(solution.x[n_other_dmus])
|
|
418
|
+
if phi <= MIN_SCALING_FACTOR:
|
|
419
|
+
return False, float("nan"), phi, "产出导向超效率扩张因子 φ 过小"
|
|
420
|
+
return True, 1.0 / phi, phi, ""
|
|
421
|
+
|
|
422
|
+
def _build_convexity_constraint(
|
|
423
|
+
self, n_variables: int, n_lambdas: int
|
|
424
|
+
) -> tuple[np.ndarray | None, np.ndarray | None]:
|
|
425
|
+
"""构造 VRS 凸性约束 Σλ = 1;CRS 时返回 (None, None)。"""
|
|
426
|
+
if self.returns_to_scale == "crs":
|
|
427
|
+
return None, None
|
|
428
|
+
equality_matrix = np.zeros((1, n_variables))
|
|
429
|
+
equality_matrix[0, :n_lambdas] = 1.0
|
|
430
|
+
return equality_matrix, np.array([1.0])
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
434
|
+
argument_parser = argparse.ArgumentParser(
|
|
435
|
+
description="CCR/BCC 径向数据包络分析(投入/产出导向,可选超效率);"
|
|
436
|
+
"不带参数时使用脚本配置区",
|
|
437
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
438
|
+
epilog=(
|
|
439
|
+
"示例:\n"
|
|
440
|
+
" python radial_models.py\n"
|
|
441
|
+
" python radial_models.py data.xlsx --orientation output "
|
|
442
|
+
"--returns-to-scale vrs --result-file 结果.csv\n"
|
|
443
|
+
" python radial_models.py --demo --orientation input\n"
|
|
444
|
+
),
|
|
445
|
+
)
|
|
446
|
+
DATA_COMMAND_LINE.add_arguments(argument_parser)
|
|
447
|
+
argument_parser.add_argument("--orientation", "--orient",
|
|
448
|
+
choices=("input", "output"), default=None,
|
|
449
|
+
help="模型导向: input=投入导向, output=产出导向;"
|
|
450
|
+
"缺省用 ORIENTATION")
|
|
451
|
+
argument_parser.add_argument("--returns-to-scale", "--rts",
|
|
452
|
+
choices=("crs", "vrs"), default=None,
|
|
453
|
+
help="规模报酬: crs=不变, vrs=可变;缺省用 RETURNS_TO_SCALE")
|
|
454
|
+
argument_parser.add_argument("--score-mode", "--mode",
|
|
455
|
+
choices=("super", "standard"), default=None,
|
|
456
|
+
help="评分口径: super=可超过1, standard=最大为1;缺省用 SCORE_MODE")
|
|
457
|
+
argument_parser.add_argument("--tolerance", "--tol", type=float, default=None,
|
|
458
|
+
help=f"判定有效性的容差(默认 {EFFICIENCY_TOLERANCE})")
|
|
459
|
+
return argument_parser
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
463
|
+
args = build_parser().parse_args(argv)
|
|
464
|
+
try:
|
|
465
|
+
prepared = DATA_COMMAND_LINE.prepare(args)
|
|
466
|
+
orientation = args.orientation if args.orientation is not None else ORIENTATION
|
|
467
|
+
returns_to_scale = (
|
|
468
|
+
args.returns_to_scale if args.returns_to_scale is not None
|
|
469
|
+
else RETURNS_TO_SCALE
|
|
470
|
+
)
|
|
471
|
+
score_mode = (
|
|
472
|
+
args.score_mode if args.score_mode is not None else SCORE_MODE
|
|
473
|
+
)
|
|
474
|
+
efficiency_tolerance = (
|
|
475
|
+
args.tolerance if args.tolerance is not None else EFFICIENCY_TOLERANCE
|
|
476
|
+
)
|
|
477
|
+
model = RadialModel(
|
|
478
|
+
orientation=orientation,
|
|
479
|
+
returns_to_scale=returns_to_scale,
|
|
480
|
+
score_mode=score_mode,
|
|
481
|
+
efficiency_tolerance=efficiency_tolerance,
|
|
482
|
+
)
|
|
483
|
+
result = model.solve(prepared.data)
|
|
484
|
+
except (ValueError, RuntimeError) as exc:
|
|
485
|
+
print(f"错误: {exc}", file=sys.stderr)
|
|
486
|
+
return 1
|
|
487
|
+
|
|
488
|
+
print(result.render_report(
|
|
489
|
+
prepared.column_names,
|
|
490
|
+
source_description=prepared.source_description,
|
|
491
|
+
))
|
|
492
|
+
if prepared.result_file:
|
|
493
|
+
try:
|
|
494
|
+
result.write_csv(prepared.result_file)
|
|
495
|
+
except OSError as exc:
|
|
496
|
+
print(f"错误: 无法写入 {prepared.result_file}: {exc}", file=sys.stderr)
|
|
497
|
+
return 1
|
|
498
|
+
print(f"\n结果已写入: {prepared.result_file}")
|
|
499
|
+
return 0
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
if __name__ == "__main__":
|
|
503
|
+
sys.exit(main())
|