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
additive_models.py
ADDED
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""加性族数据包络分析脚本:Additive 与 RAM。
|
|
4
|
+
|
|
5
|
+
模型:
|
|
6
|
+
1. Additive(Charnes et al. 1985):最大化投入冗余与期望产出不足之和
|
|
7
|
+
max Σ_i s⁻_i + Σ_r s⁺_r
|
|
8
|
+
s.t. Xλ + s⁻ = x_o, Yλ - s⁺ = y_o, λ ≥ 0(VRS 加 Σλ = 1)
|
|
9
|
+
目标值为 0 表示有效;模型本身不提供 0-1 效率得分,排名按目标值升序。
|
|
10
|
+
2. RAM(Range-Adjusted Measure,Cooper et al. 1999):
|
|
11
|
+
以各指标极差的倒数为权重,最大化加权松弛和,并给出 RAM 得分
|
|
12
|
+
Γ = 1 - [Σ_i s⁻_i/R⁻_i + Σ_r s⁺_r/R⁺_r] / (有效指标数)
|
|
13
|
+
RAM 要求 VRS(规模报酬可变),得分 ∈ [0, 1]。
|
|
14
|
+
3. 非期望产出按“投入方向”并入投入块(越少越好)。
|
|
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
|
+
EFFICIENCY_TOLERANCE,
|
|
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
|
+
|
|
47
|
+
# 指标列名:按数据表的列名填写(三组变量分开设置)
|
|
48
|
+
INPUT_COLUMNS = ["资本投入", "劳动投入"] # 投入变量
|
|
49
|
+
DESIRABLE_OUTPUT_COLUMNS = ["GDP", "财政收入"] # 期望产出
|
|
50
|
+
UNDESIRABLE_OUTPUT_COLUMNS = ["工业废水排放量"] # 非期望产出(没有就写 [])
|
|
51
|
+
|
|
52
|
+
# 模型选项
|
|
53
|
+
MODEL = "ram" # "additive"=加性模型(目标值),"ram"=范围调整测度(得分)
|
|
54
|
+
RETURNS_TO_SCALE = "vrs" # "crs"=规模报酬不变,"vrs"=规模报酬可变;RAM 仅支持 vrs
|
|
55
|
+
RESULT_FILE = None # 结果 CSV 输出路径,如 "dea_results.csv";None 表示不导出
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
DATA_COMMAND_LINE = DataCommandLine(
|
|
59
|
+
settings=DataSettings(
|
|
60
|
+
data_file=DATA_FILE,
|
|
61
|
+
excel_sheet=EXCEL_SHEET,
|
|
62
|
+
dmu_columns=tuple(DMU_COLUMNS),
|
|
63
|
+
input_columns=tuple(INPUT_COLUMNS),
|
|
64
|
+
desirable_output_columns=tuple(DESIRABLE_OUTPUT_COLUMNS),
|
|
65
|
+
undesirable_output_columns=tuple(UNDESIRABLE_OUTPUT_COLUMNS),
|
|
66
|
+
result_file=RESULT_FILE,
|
|
67
|
+
),
|
|
68
|
+
script_directory=os.path.dirname(os.path.abspath(__file__)),
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class SlackSumResult:
|
|
74
|
+
"""Additive / RAM 的结果,含报表与 CSV 导出。"""
|
|
75
|
+
|
|
76
|
+
dmu_names: list[str]
|
|
77
|
+
model_name: str # "additive" / "ram"
|
|
78
|
+
measure_key: str # CSV 中的主指标列名
|
|
79
|
+
measure_label: str # 报表中的主指标名称
|
|
80
|
+
average_label: str # 报表中的平均值名称
|
|
81
|
+
measure_values: np.ndarray # 主指标(得分或目标值)
|
|
82
|
+
secondary_key: str | None # CSV 中的次指标列名(RAM 的目标值)
|
|
83
|
+
secondary_label: str | None # 报表中的次指标名称
|
|
84
|
+
secondary_values: np.ndarray | None # 次指标
|
|
85
|
+
efficiency_mask: np.ndarray
|
|
86
|
+
ranks: np.ndarray
|
|
87
|
+
input_slacks: np.ndarray # (n, m) 投入冗余(原单位)
|
|
88
|
+
desirable_output_slacks: np.ndarray # (n, s) 期望产出不足(原单位)
|
|
89
|
+
undesirable_output_slacks: np.ndarray # (n, b) 非期望产出冗余(原单位)
|
|
90
|
+
returns_to_scale: str
|
|
91
|
+
notes: list[str] = field(default_factory=list)
|
|
92
|
+
|
|
93
|
+
def to_records(self, column_names: ColumnNames) -> list[dict[str, object]]:
|
|
94
|
+
"""把每个 DMU 展开成一条可直接写 CSV 的记录。"""
|
|
95
|
+
if (len(column_names.input_columns) != self.input_slacks.shape[1]
|
|
96
|
+
or len(column_names.desirable_output_columns)
|
|
97
|
+
!= self.desirable_output_slacks.shape[1]
|
|
98
|
+
or len(column_names.undesirable_output_columns)
|
|
99
|
+
!= self.undesirable_output_slacks.shape[1]):
|
|
100
|
+
raise ValueError("指标名称数量与松弛矩阵不匹配")
|
|
101
|
+
|
|
102
|
+
records = []
|
|
103
|
+
for dmu_index, dmu_name in enumerate(self.dmu_names):
|
|
104
|
+
record: dict[str, object] = {
|
|
105
|
+
"dmu": dmu_name,
|
|
106
|
+
"model": self.model_name,
|
|
107
|
+
self.measure_key: round_score(self.measure_values[dmu_index]),
|
|
108
|
+
"efficient": int(self.efficiency_mask[dmu_index]),
|
|
109
|
+
"rank": int(self.ranks[dmu_index]),
|
|
110
|
+
}
|
|
111
|
+
if self.secondary_key is not None and self.secondary_values is not None:
|
|
112
|
+
record[self.secondary_key] = round_score(
|
|
113
|
+
self.secondary_values[dmu_index]
|
|
114
|
+
)
|
|
115
|
+
for indicator_index, column_name in enumerate(column_names.input_columns):
|
|
116
|
+
record[f"input_slack_{column_name}"] = round_score(
|
|
117
|
+
self.input_slacks[dmu_index, indicator_index]
|
|
118
|
+
)
|
|
119
|
+
for indicator_index, column_name in enumerate(
|
|
120
|
+
column_names.desirable_output_columns):
|
|
121
|
+
record[f"desirable_output_slack_{column_name}"] = round_score(
|
|
122
|
+
self.desirable_output_slacks[dmu_index, indicator_index]
|
|
123
|
+
)
|
|
124
|
+
for indicator_index, column_name in enumerate(
|
|
125
|
+
column_names.undesirable_output_columns):
|
|
126
|
+
record[f"undesirable_output_slack_{column_name}"] = round_score(
|
|
127
|
+
self.undesirable_output_slacks[dmu_index, indicator_index]
|
|
128
|
+
)
|
|
129
|
+
records.append(record)
|
|
130
|
+
return records
|
|
131
|
+
|
|
132
|
+
def write_csv(self, path: str, column_names: ColumnNames) -> None:
|
|
133
|
+
"""写出 UTF-8-BOM 编码的结果 CSV。"""
|
|
134
|
+
write_csv_records(path, self.to_records(column_names))
|
|
135
|
+
|
|
136
|
+
def render_report(self, column_names: ColumnNames,
|
|
137
|
+
source_description: str | None = None) -> str:
|
|
138
|
+
"""生成控制台报表文本。"""
|
|
139
|
+
model_title = (
|
|
140
|
+
"加性模型(Additive)" if self.model_name == "additive"
|
|
141
|
+
else "范围调整测度(RAM)"
|
|
142
|
+
)
|
|
143
|
+
returns_to_scale_description = (
|
|
144
|
+
"CRS 规模报酬不变" if self.returns_to_scale == "crs" else "VRS 规模报酬可变"
|
|
145
|
+
)
|
|
146
|
+
report_lines = [f"模型: {model_title} | {returns_to_scale_description}"]
|
|
147
|
+
if source_description:
|
|
148
|
+
report_lines.append(f"数据: {source_description}")
|
|
149
|
+
undesirable_output_description = (
|
|
150
|
+
"、".join(column_names.undesirable_output_columns)
|
|
151
|
+
if column_names.undesirable_output_columns else "无"
|
|
152
|
+
)
|
|
153
|
+
report_lines.append(
|
|
154
|
+
f"变量: 投入[{'、'.join(column_names.input_columns)}] | "
|
|
155
|
+
f"期望产出[{'、'.join(column_names.desirable_output_columns)}] | "
|
|
156
|
+
f"非期望产出[{undesirable_output_description}]"
|
|
157
|
+
)
|
|
158
|
+
report_lines.append(f"DMU 数: {len(self.dmu_names)}")
|
|
159
|
+
report_lines.append("")
|
|
160
|
+
|
|
161
|
+
table_header = ["DMU", self.measure_label]
|
|
162
|
+
if self.secondary_label is not None:
|
|
163
|
+
table_header.append(self.secondary_label)
|
|
164
|
+
table_header.append("排名")
|
|
165
|
+
table_rows = []
|
|
166
|
+
for dmu_index, dmu_name in enumerate(self.dmu_names):
|
|
167
|
+
row = [
|
|
168
|
+
dmu_name,
|
|
169
|
+
f"{round_score(self.measure_values[dmu_index]):.{SCORE_DECIMALS}f}",
|
|
170
|
+
]
|
|
171
|
+
if self.secondary_values is not None:
|
|
172
|
+
row.append(
|
|
173
|
+
f"{round_score(self.secondary_values[dmu_index]):.{SCORE_DECIMALS}f}"
|
|
174
|
+
)
|
|
175
|
+
row.append(str(int(self.ranks[dmu_index])))
|
|
176
|
+
table_rows.append(row)
|
|
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 共 {len(efficient_dmu_names)} 个: "
|
|
183
|
+
f"{'、'.join(efficient_dmu_names) if efficient_dmu_names else '无'}"
|
|
184
|
+
)
|
|
185
|
+
if self.model_name == "additive":
|
|
186
|
+
report_lines.append(
|
|
187
|
+
"说明: 加性模型报告松弛和(0 为有效),目标值越小越有效;"
|
|
188
|
+
"该模型不提供 0-1 效率得分"
|
|
189
|
+
)
|
|
190
|
+
else:
|
|
191
|
+
report_lines.append(
|
|
192
|
+
"说明: RAM 权重为指标极差的倒数;得分 = 1 - 加权松弛和 / 有效指标数"
|
|
193
|
+
)
|
|
194
|
+
if column_names.undesirable_output_columns:
|
|
195
|
+
report_lines.append("说明: 非期望产出按投入方向处理(越少越好)")
|
|
196
|
+
average_measure = round_score(float(np.mean(self.measure_values)))
|
|
197
|
+
report_lines.append(
|
|
198
|
+
f"{self.average_label}: {average_measure:.{SCORE_DECIMALS}f}"
|
|
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 SlackSumModel:
|
|
207
|
+
"""Additive / RAM 求解器。"""
|
|
208
|
+
|
|
209
|
+
def __init__(self, model_name: str = "ram", returns_to_scale: str = "vrs",
|
|
210
|
+
efficiency_tolerance: float = EFFICIENCY_TOLERANCE):
|
|
211
|
+
model_name = model_name.lower()
|
|
212
|
+
returns_to_scale = returns_to_scale.lower()
|
|
213
|
+
if model_name not in ("additive", "ram"):
|
|
214
|
+
raise ValueError("model_name 只能取 'additive' 或 'ram'")
|
|
215
|
+
if returns_to_scale not in ("crs", "vrs"):
|
|
216
|
+
raise ValueError("returns_to_scale 只能取 'crs' 或 'vrs'")
|
|
217
|
+
if model_name == "ram" and returns_to_scale != "vrs":
|
|
218
|
+
raise ValueError("RAM 需要 VRS;如需 CRS 请使用 additive 模型")
|
|
219
|
+
if efficiency_tolerance <= 0:
|
|
220
|
+
raise ValueError("efficiency_tolerance 必须为正数")
|
|
221
|
+
self.model_name = model_name
|
|
222
|
+
self.returns_to_scale = returns_to_scale
|
|
223
|
+
self.efficiency_tolerance = float(efficiency_tolerance)
|
|
224
|
+
|
|
225
|
+
def solve(self, data: DEAData) -> SlackSumResult:
|
|
226
|
+
"""求解全部 DMU 的 Additive 或 RAM 模型。
|
|
227
|
+
|
|
228
|
+
处理逻辑:把非期望产出并入投入块 → 构造 Additive 等权或 RAM 极差权重 →
|
|
229
|
+
逐个 DMU 求解加权松弛和 LP → 汇总目标值/得分、排名与松弛。
|
|
230
|
+
"""
|
|
231
|
+
n_dmus = data.input_matrix.shape[1]
|
|
232
|
+
n_inputs = data.input_matrix.shape[0]
|
|
233
|
+
n_desirable_outputs = data.desirable_output_matrix.shape[0]
|
|
234
|
+
n_undesirable_outputs = data.undesirable_output_matrix.shape[0]
|
|
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
|
+
model_input_weights, output_weights, active_indicator_count, notes = (
|
|
242
|
+
self._build_weights(model_inputs, desirable_outputs)
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
objectives = np.empty(n_dmus)
|
|
246
|
+
augmented_input_slacks = np.empty((n_dmus, model_inputs.shape[0]))
|
|
247
|
+
desirable_output_slacks = np.empty((n_dmus, n_desirable_outputs))
|
|
248
|
+
for dmu_index in range(n_dmus):
|
|
249
|
+
objective, input_slacks, output_slacks = self._solve_slack_sum(
|
|
250
|
+
model_inputs, desirable_outputs, model_input_weights,
|
|
251
|
+
output_weights, dmu_index,
|
|
252
|
+
)
|
|
253
|
+
objectives[dmu_index] = objective
|
|
254
|
+
augmented_input_slacks[dmu_index] = input_slacks
|
|
255
|
+
desirable_output_slacks[dmu_index] = output_slacks
|
|
256
|
+
|
|
257
|
+
objectives = np.maximum(objectives, 0.0) # 松弛和非负;清除求解器的 -0 抖动
|
|
258
|
+
efficiency_mask = np.asarray(
|
|
259
|
+
objectives <= self.efficiency_tolerance, dtype=bool
|
|
260
|
+
)
|
|
261
|
+
if self.model_name == "additive":
|
|
262
|
+
measure_key, measure_label = "additive_objective", "松弛和(0 为有效)"
|
|
263
|
+
average_label = "平均松弛和"
|
|
264
|
+
measure_values = objectives
|
|
265
|
+
secondary_key = secondary_label = secondary_values = None
|
|
266
|
+
ranks = assign_ranks_with_ties(-objectives)
|
|
267
|
+
else:
|
|
268
|
+
measure_key, measure_label = "ram_score", "RAM 得分"
|
|
269
|
+
average_label = "平均 RAM 得分"
|
|
270
|
+
measure_values = 1.0 - objectives / active_indicator_count
|
|
271
|
+
if np.any(measure_values < -self.efficiency_tolerance) or np.any(
|
|
272
|
+
measure_values > 1.0 + self.efficiency_tolerance):
|
|
273
|
+
notes.append("RAM 得分超出 [0, 1],已截断;请检查指标极差与数据单位")
|
|
274
|
+
measure_values = np.clip(measure_values, 0.0, 1.0)
|
|
275
|
+
secondary_key, secondary_label, secondary_values = (
|
|
276
|
+
"ram_objective", "加权松弛和", objectives
|
|
277
|
+
)
|
|
278
|
+
ranks = assign_ranks_with_ties(measure_values)
|
|
279
|
+
|
|
280
|
+
return SlackSumResult(
|
|
281
|
+
dmu_names=data.dmu_names,
|
|
282
|
+
model_name=self.model_name,
|
|
283
|
+
measure_key=measure_key,
|
|
284
|
+
measure_label=measure_label,
|
|
285
|
+
average_label=average_label,
|
|
286
|
+
measure_values=measure_values,
|
|
287
|
+
secondary_key=secondary_key,
|
|
288
|
+
secondary_label=secondary_label,
|
|
289
|
+
secondary_values=secondary_values,
|
|
290
|
+
efficiency_mask=efficiency_mask,
|
|
291
|
+
ranks=ranks,
|
|
292
|
+
input_slacks=augmented_input_slacks[:, :n_inputs],
|
|
293
|
+
desirable_output_slacks=desirable_output_slacks,
|
|
294
|
+
undesirable_output_slacks=augmented_input_slacks[:, n_inputs:],
|
|
295
|
+
returns_to_scale=self.returns_to_scale,
|
|
296
|
+
notes=notes,
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
def _build_weights(self, model_inputs: np.ndarray, desirable_outputs: np.ndarray
|
|
300
|
+
) -> tuple[np.ndarray, np.ndarray, int, list[str]]:
|
|
301
|
+
"""构造指标权重、有效指标数与提示。"""
|
|
302
|
+
notes: list[str] = []
|
|
303
|
+
if self.model_name == "additive":
|
|
304
|
+
return (
|
|
305
|
+
np.ones(model_inputs.shape[0]),
|
|
306
|
+
np.ones(desirable_outputs.shape[0]),
|
|
307
|
+
model_inputs.shape[0] + desirable_outputs.shape[0],
|
|
308
|
+
notes,
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
input_weights, active_input = self._range_weights(model_inputs)
|
|
312
|
+
output_weights, active_output = self._range_weights(desirable_outputs)
|
|
313
|
+
active_indicator_count = int(np.count_nonzero(active_input)
|
|
314
|
+
+ np.count_nonzero(active_output))
|
|
315
|
+
if active_indicator_count == 0:
|
|
316
|
+
raise ValueError("所有指标极差均为 0,无法计算 RAM")
|
|
317
|
+
if active_indicator_count < model_inputs.shape[0] + desirable_outputs.shape[0]:
|
|
318
|
+
notes.append("存在极差为 0 的指标,已从 RAM 权重与有效指标数中剔除")
|
|
319
|
+
return input_weights, output_weights, active_indicator_count, notes
|
|
320
|
+
|
|
321
|
+
@staticmethod
|
|
322
|
+
def _range_weights(matrix: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
323
|
+
"""按极差倒数构造 RAM 权重,极差为 0 的指标权重为 0。"""
|
|
324
|
+
ranges = matrix.max(axis=1) - matrix.min(axis=1)
|
|
325
|
+
active = ranges > 0
|
|
326
|
+
weights = np.zeros(ranges.shape[0])
|
|
327
|
+
weights[active] = 1.0 / ranges[active]
|
|
328
|
+
return weights, active
|
|
329
|
+
|
|
330
|
+
def _solve_slack_sum(self, model_inputs: np.ndarray, desirable_outputs: np.ndarray,
|
|
331
|
+
input_weights: np.ndarray, output_weights: np.ndarray,
|
|
332
|
+
dmu_index: int) -> tuple[float, np.ndarray, np.ndarray]:
|
|
333
|
+
"""求解第 dmu_index 个 DMU 的加权松弛和线性规划。
|
|
334
|
+
|
|
335
|
+
变量:λ (n)、s⁻ (m)、s⁺ (s);
|
|
336
|
+
max Σ_i w⁻_i·s⁻_i + Σ_r w⁺_r·s⁺_r
|
|
337
|
+
s.t. Xλ + s⁻ = x_o, Yλ - s⁺ = y_o, Σλ = 1(仅 VRS)
|
|
338
|
+
"""
|
|
339
|
+
n_model_inputs, n_dmus = model_inputs.shape
|
|
340
|
+
n_desirable_outputs = desirable_outputs.shape[0]
|
|
341
|
+
dmu_inputs = model_inputs[:, dmu_index]
|
|
342
|
+
dmu_outputs = desirable_outputs[:, dmu_index]
|
|
343
|
+
n_variables = n_dmus + n_model_inputs + n_desirable_outputs
|
|
344
|
+
|
|
345
|
+
objective_coefficients = np.zeros(n_variables)
|
|
346
|
+
objective_coefficients[n_dmus:n_dmus + n_model_inputs] = -input_weights
|
|
347
|
+
objective_coefficients[n_dmus + n_model_inputs:] = -output_weights
|
|
348
|
+
|
|
349
|
+
is_vrs = self.returns_to_scale == "vrs"
|
|
350
|
+
n_constraints = n_model_inputs + n_desirable_outputs + (1 if is_vrs else 0)
|
|
351
|
+
equality_matrix = np.zeros((n_constraints, n_variables))
|
|
352
|
+
equality_rhs = np.zeros(n_constraints)
|
|
353
|
+
|
|
354
|
+
equality_matrix[:n_model_inputs, :n_dmus] = model_inputs
|
|
355
|
+
equality_matrix[np.arange(n_model_inputs),
|
|
356
|
+
n_dmus + np.arange(n_model_inputs)] = 1.0
|
|
357
|
+
equality_rhs[:n_model_inputs] = dmu_inputs
|
|
358
|
+
|
|
359
|
+
output_rows = slice(n_model_inputs, n_model_inputs + n_desirable_outputs)
|
|
360
|
+
equality_matrix[output_rows, :n_dmus] = desirable_outputs
|
|
361
|
+
equality_matrix[n_model_inputs + np.arange(n_desirable_outputs),
|
|
362
|
+
n_dmus + n_model_inputs + np.arange(n_desirable_outputs)] = -1.0
|
|
363
|
+
equality_rhs[output_rows] = dmu_outputs
|
|
364
|
+
|
|
365
|
+
if is_vrs:
|
|
366
|
+
equality_matrix[n_constraints - 1, :n_dmus] = 1.0
|
|
367
|
+
equality_rhs[n_constraints - 1] = 1.0
|
|
368
|
+
|
|
369
|
+
solution = solve_linear_program(
|
|
370
|
+
objective_coefficients,
|
|
371
|
+
equality_matrix=equality_matrix, equality_rhs=equality_rhs,
|
|
372
|
+
error_context=f"{self.model_name} 求解失败(第 {dmu_index + 1} 个 DMU)",
|
|
373
|
+
)
|
|
374
|
+
input_slacks = solution.x[n_dmus:n_dmus + n_model_inputs]
|
|
375
|
+
output_slacks = solution.x[n_dmus + n_model_inputs:]
|
|
376
|
+
return float(-solution.fun), input_slacks, output_slacks
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
380
|
+
argument_parser = argparse.ArgumentParser(
|
|
381
|
+
description="加性模型(Additive)与范围调整测度(RAM);"
|
|
382
|
+
"不带参数时使用脚本配置区",
|
|
383
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
384
|
+
epilog=(
|
|
385
|
+
"示例:\n"
|
|
386
|
+
" python additive_models.py\n"
|
|
387
|
+
" python additive_models.py --demo --model additive --returns-to-scale crs\n"
|
|
388
|
+
" python additive_models.py data.xlsx --model ram --result-file 结果.csv\n"
|
|
389
|
+
),
|
|
390
|
+
)
|
|
391
|
+
DATA_COMMAND_LINE.add_arguments(argument_parser)
|
|
392
|
+
argument_parser.add_argument("--model", choices=("additive", "ram"), default=None,
|
|
393
|
+
help="模型: additive=加性(目标值), ram=范围调整(得分);"
|
|
394
|
+
"缺省用 MODEL")
|
|
395
|
+
argument_parser.add_argument("--returns-to-scale", "--rts",
|
|
396
|
+
choices=("crs", "vrs"), default=None,
|
|
397
|
+
help="规模报酬: crs=不变, vrs=可变;缺省用 RETURNS_TO_SCALE")
|
|
398
|
+
argument_parser.add_argument("--tolerance", "--tol", type=float, default=None,
|
|
399
|
+
help=f"判定有效性的容差(默认 {EFFICIENCY_TOLERANCE})")
|
|
400
|
+
return argument_parser
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
404
|
+
args = build_parser().parse_args(argv)
|
|
405
|
+
try:
|
|
406
|
+
prepared = DATA_COMMAND_LINE.prepare(args)
|
|
407
|
+
model_name = args.model if args.model is not None else MODEL
|
|
408
|
+
returns_to_scale = (
|
|
409
|
+
args.returns_to_scale if args.returns_to_scale is not None
|
|
410
|
+
else RETURNS_TO_SCALE
|
|
411
|
+
)
|
|
412
|
+
efficiency_tolerance = (
|
|
413
|
+
args.tolerance if args.tolerance is not None else EFFICIENCY_TOLERANCE
|
|
414
|
+
)
|
|
415
|
+
model = SlackSumModel(
|
|
416
|
+
model_name=model_name,
|
|
417
|
+
returns_to_scale=returns_to_scale,
|
|
418
|
+
efficiency_tolerance=efficiency_tolerance,
|
|
419
|
+
)
|
|
420
|
+
result = model.solve(prepared.data)
|
|
421
|
+
except (ValueError, RuntimeError) as exc:
|
|
422
|
+
print(f"错误: {exc}", file=sys.stderr)
|
|
423
|
+
return 1
|
|
424
|
+
|
|
425
|
+
print(result.render_report(
|
|
426
|
+
prepared.column_names,
|
|
427
|
+
source_description=prepared.source_description,
|
|
428
|
+
))
|
|
429
|
+
if prepared.result_file:
|
|
430
|
+
try:
|
|
431
|
+
result.write_csv(prepared.result_file, prepared.column_names)
|
|
432
|
+
except OSError as exc:
|
|
433
|
+
print(f"错误: 无法写入 {prepared.result_file}: {exc}", file=sys.stderr)
|
|
434
|
+
return 1
|
|
435
|
+
print(f"\n结果已写入: {prepared.result_file}")
|
|
436
|
+
return 0
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
if __name__ == "__main__":
|
|
440
|
+
sys.exit(main())
|