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.
cross_efficiency.py ADDED
@@ -0,0 +1,411 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """交叉效率(Cross-Efficiency)DEA 脚本。
4
+
5
+ 模型(Sexton et al. 1986;Doyle & Green 1994 二级目标):
6
+ 1. 对每个 DMU d,用 CCR 乘数型模型求其自评效率
7
+ max Σ_r u_r y_rd
8
+ s.t. Σ_i v_i x_id = 1
9
+ Σ_r u_r y_rj - Σ_i v_i x_ij ≤ 0 (所有 DMU)
10
+ u_r, v_i ≥ 0
11
+ 2. 固定自评效率后,用 Doyle-Green 二级目标选取唯一权重:
12
+ aggressive:min Σ_r u_r (Σ_{j≠d} y_rj)
13
+ benevolent:max Σ_r u_r (Σ_{j≠d} y_rj)
14
+ s.t. Σ_i v_i (Σ_{j≠d} x_ij) = 1
15
+ Σ_r u_r y_rd - E_dd·Σ_i v_i x_id = 0
16
+ Σ_r u_r y_rj - Σ_i v_i x_ij ≤ 0 (j≠d)
17
+ u_r, v_i ≥ 0
18
+ 3. 交叉效率 E_{d,k} = (Σ_r u_r^d y_rk) / (Σ_i v_i^d x_ik);
19
+ 交叉效率均值对每一列 k 在所有评价者(含自评)上取平均。
20
+
21
+ 非期望产出按“投入方向”并入投入块(越少越好)。CCR 为 CRS 乘数型。
22
+ """
23
+
24
+ import argparse
25
+ import os
26
+ import sys
27
+ from collections.abc import Sequence
28
+ from dataclasses import dataclass, field
29
+
30
+ import numpy as np
31
+
32
+ from dea_core import (
33
+ ColumnNames,
34
+ DataCommandLine,
35
+ DataSettings,
36
+ DEAData,
37
+ EFFICIENCY_TOLERANCE,
38
+ SCORE_DECIMALS,
39
+ assign_ranks_with_ties,
40
+ format_table,
41
+ round_score,
42
+ solve_linear_program,
43
+ write_csv_records,
44
+ )
45
+
46
+ # =============================== 用户配置区 ===============================
47
+ # 数据文件路径:支持 .csv / .xlsx / .xlsm;相对路径优先按当前工作目录,其次脚本所在目录解析
48
+ DATA_FILE = "sample_data.csv"
49
+ EXCEL_SHEET = 0 # Excel 工作表名或序号(0 开始);CSV 忽略
50
+
51
+ # DMU 标识列:可多列,自动用 "-" 拼接为唯一名称;如 ["城市代码", "年份"] → "110000-2021"
52
+ DMU_COLUMNS = ["城市代码", "年份"]
53
+
54
+ # 指标列名:按数据表的列名填写(三组变量分开设置)
55
+ INPUT_COLUMNS = ["资本投入", "劳动投入"] # 投入变量
56
+ DESIRABLE_OUTPUT_COLUMNS = ["GDP", "财政收入"] # 期望产出
57
+ UNDESIRABLE_OUTPUT_COLUMNS = ["工业废水排放量"] # 非期望产出(没有就写 [])
58
+
59
+ # 模型选项
60
+ SECONDARY_OBJECTIVE = "aggressive" # "aggressive"=进取型,"benevolent"=仁慈型
61
+ RESULT_FILE = None # 交叉效率均值 CSV;None 表示不导出
62
+ MATRIX_FILE = None # 完整交叉效率矩阵 CSV(长表);None 表示不导出
63
+
64
+
65
+ DATA_COMMAND_LINE = DataCommandLine(
66
+ settings=DataSettings(
67
+ data_file=DATA_FILE,
68
+ excel_sheet=EXCEL_SHEET,
69
+ dmu_columns=tuple(DMU_COLUMNS),
70
+ input_columns=tuple(INPUT_COLUMNS),
71
+ desirable_output_columns=tuple(DESIRABLE_OUTPUT_COLUMNS),
72
+ undesirable_output_columns=tuple(UNDESIRABLE_OUTPUT_COLUMNS),
73
+ result_file=RESULT_FILE,
74
+ ),
75
+ script_directory=os.path.dirname(os.path.abspath(__file__)),
76
+ )
77
+
78
+
79
+ @dataclass
80
+ class CrossEfficiencyResult:
81
+ """一次交叉效率求解的结果,含报表与 CSV/矩阵导出。"""
82
+
83
+ dmu_names: list[str]
84
+ self_efficiencies: np.ndarray # 自评效率(CCR)
85
+ cross_efficiency_matrix: np.ndarray # (n, n),行=评价者,列=被评价 DMU
86
+ average_cross_efficiencies: np.ndarray # 每列均值(含自评)
87
+ efficiency_mask: np.ndarray # 自评效率 = 1
88
+ ranks: np.ndarray # 按交叉效率均值排名
89
+ secondary_objective: str
90
+ notes: list[str] = field(default_factory=list)
91
+
92
+ def to_records(self) -> list[dict[str, object]]:
93
+ """把每个 DMU 展开成一条交叉效率均值记录。"""
94
+ records = []
95
+ for dmu_index, dmu_name in enumerate(self.dmu_names):
96
+ records.append({
97
+ "dmu": dmu_name,
98
+ "self_efficiency": round_score(self.self_efficiencies[dmu_index]),
99
+ "average_cross_efficiency": round_score(
100
+ self.average_cross_efficiencies[dmu_index]
101
+ ),
102
+ "efficient": int(self.efficiency_mask[dmu_index]),
103
+ "rank": int(self.ranks[dmu_index]),
104
+ })
105
+ return records
106
+
107
+ def write_csv(self, path: str) -> None:
108
+ """写出交叉效率均值 CSV。"""
109
+ write_csv_records(path, self.to_records())
110
+
111
+ def write_matrix_csv(self, path: str) -> None:
112
+ """写出完整交叉效率矩阵(长表:评价者、被评价 DMU、效率值)。"""
113
+ records = []
114
+ for evaluator_index, evaluator_name in enumerate(self.dmu_names):
115
+ for evaluated_index, evaluated_name in enumerate(self.dmu_names):
116
+ records.append({
117
+ "evaluator": evaluator_name,
118
+ "evaluated": evaluated_name,
119
+ "cross_efficiency": round_score(
120
+ self.cross_efficiency_matrix[evaluator_index, evaluated_index]
121
+ ),
122
+ })
123
+ write_csv_records(path, records)
124
+
125
+ def render_report(self, column_names: ColumnNames,
126
+ source_description: str | None = None) -> str:
127
+ """生成控制台报表文本。"""
128
+ objective_description = (
129
+ "进取型(aggressive)" if self.secondary_objective == "aggressive"
130
+ else "仁慈型(benevolent)"
131
+ )
132
+ report_lines = [
133
+ f"模型: 交叉效率 DEA(CCR 乘数型) | 二级目标: {objective_description}"
134
+ ]
135
+ if source_description:
136
+ report_lines.append(f"数据: {source_description}")
137
+ undesirable_output_description = (
138
+ "、".join(column_names.undesirable_output_columns)
139
+ if column_names.undesirable_output_columns else "无"
140
+ )
141
+ report_lines.append(
142
+ f"变量: 投入[{'、'.join(column_names.input_columns)}] | "
143
+ f"期望产出[{'、'.join(column_names.desirable_output_columns)}] | "
144
+ f"非期望产出[{undesirable_output_description}]"
145
+ )
146
+ report_lines.append(f"DMU 数: {len(self.dmu_names)}")
147
+ report_lines.append("")
148
+
149
+ table_header = ["DMU", "自评效率", "交叉效率均值", "排名"]
150
+ table_rows = []
151
+ for dmu_index, dmu_name in enumerate(self.dmu_names):
152
+ self_efficiency = round_score(self.self_efficiencies[dmu_index])
153
+ average_cross_efficiency = round_score(
154
+ self.average_cross_efficiencies[dmu_index]
155
+ )
156
+ table_rows.append([
157
+ dmu_name,
158
+ f"{self_efficiency:.{SCORE_DECIMALS}f}",
159
+ f"{average_cross_efficiency:.{SCORE_DECIMALS}f}",
160
+ str(int(self.ranks[dmu_index])),
161
+ ])
162
+ report_lines.append(format_table(table_header, table_rows))
163
+ report_lines.append("")
164
+
165
+ efficient_dmu_names = [self.dmu_names[i] for i in np.flatnonzero(self.efficiency_mask)]
166
+ report_lines.append(
167
+ f"自评有效 DMU(CCR = 1)共 {len(efficient_dmu_names)} 个: "
168
+ f"{'、'.join(efficient_dmu_names) if efficient_dmu_names else '无'}"
169
+ )
170
+ report_lines.append(
171
+ "说明: 交叉效率均值对每一列在所有评价者(含自评)上取平均;"
172
+ "二级目标用于在自评效率相同时确定唯一权重"
173
+ )
174
+ if column_names.undesirable_output_columns:
175
+ report_lines.append("说明: 非期望产出按投入方向处理(越少越好)")
176
+ average_self_efficiency = round_score(float(np.mean(self.self_efficiencies)))
177
+ average_cross_efficiency = round_score(
178
+ float(np.mean(self.average_cross_efficiencies))
179
+ )
180
+ report_lines.append(
181
+ f"平均自评效率: {average_self_efficiency:.{SCORE_DECIMALS}f}"
182
+ )
183
+ report_lines.append(
184
+ f"平均交叉效率: {average_cross_efficiency:.{SCORE_DECIMALS}f}"
185
+ )
186
+ report_lines.extend(f"提示: {note}" for note in self.notes[:10])
187
+ if len(self.notes) > 10:
188
+ report_lines.append(f"提示: 其余 {len(self.notes) - 10} 条类似提示已省略")
189
+ return "\n".join(report_lines)
190
+
191
+
192
+ class CrossEfficiencyModel:
193
+ """交叉效率 DEA 求解器(CCR 乘数型 + Doyle-Green 二级目标)。"""
194
+
195
+ def __init__(self, secondary_objective: str = "aggressive",
196
+ efficiency_tolerance: float = EFFICIENCY_TOLERANCE):
197
+ secondary_objective = secondary_objective.lower()
198
+ if secondary_objective not in ("aggressive", "benevolent"):
199
+ raise ValueError("secondary_objective 只能取 'aggressive' 或 'benevolent'")
200
+ if efficiency_tolerance <= 0:
201
+ raise ValueError("efficiency_tolerance 必须为正数")
202
+ self.secondary_objective = secondary_objective
203
+ self.efficiency_tolerance = float(efficiency_tolerance)
204
+
205
+ def solve(self, data: DEAData) -> CrossEfficiencyResult:
206
+ """求解所有 DMU 的自评效率与交叉效率矩阵。
207
+
208
+ 处理逻辑:逐个 DMU 求 CCR 自评效率 → 解 Doyle-Green 二级目标得到权重 →
209
+ 计算交叉效率矩阵与每列均值。
210
+ """
211
+ n_dmus = data.input_matrix.shape[1]
212
+ if n_dmus < 2:
213
+ raise ValueError("交叉效率至少需要 2 个 DMU")
214
+ n_undesirable_outputs = data.undesirable_output_matrix.shape[0]
215
+ model_inputs = (
216
+ np.vstack([data.input_matrix, data.undesirable_output_matrix])
217
+ if n_undesirable_outputs else data.input_matrix
218
+ )
219
+ desirable_outputs = data.desirable_output_matrix
220
+
221
+ self_efficiencies = np.empty(n_dmus)
222
+ cross_efficiency_matrix = np.empty((n_dmus, n_dmus))
223
+ for dmu_index in range(n_dmus):
224
+ self_efficiency = self._solve_self_efficiency(
225
+ model_inputs, desirable_outputs, dmu_index
226
+ )
227
+ self_efficiencies[dmu_index] = self_efficiency
228
+ input_weights, output_weights = self._solve_secondary_objective(
229
+ model_inputs, desirable_outputs, dmu_index, self_efficiency
230
+ )
231
+ for evaluated_index in range(n_dmus):
232
+ denominator = float(model_inputs[:, evaluated_index] @ input_weights)
233
+ assert denominator > 0, (
234
+ f"交叉效率分母非正:评价者 {data.dmu_names[dmu_index]},"
235
+ f"被评价 {data.dmu_names[evaluated_index]}"
236
+ )
237
+ cross_efficiency_matrix[dmu_index, evaluated_index] = float(
238
+ desirable_outputs[:, evaluated_index] @ output_weights
239
+ ) / denominator
240
+
241
+ # 二级目标已固定自评效率;用原值覆盖对角线以消除数值误差
242
+ np.fill_diagonal(cross_efficiency_matrix, self_efficiencies)
243
+ average_cross_efficiencies = np.mean(cross_efficiency_matrix, axis=0)
244
+ efficiency_mask = np.asarray(
245
+ self_efficiencies >= 1.0 - self.efficiency_tolerance, dtype=bool
246
+ )
247
+ ranks = assign_ranks_with_ties(average_cross_efficiencies)
248
+ notes: list[str] = []
249
+ if np.any(cross_efficiency_matrix > 1.0 + self.efficiency_tolerance):
250
+ notes.append("部分交叉效率超过 1,可能存在数值误差,请检查数据与求解结果")
251
+
252
+ return CrossEfficiencyResult(
253
+ dmu_names=data.dmu_names,
254
+ self_efficiencies=self_efficiencies,
255
+ cross_efficiency_matrix=cross_efficiency_matrix,
256
+ average_cross_efficiencies=average_cross_efficiencies,
257
+ efficiency_mask=efficiency_mask,
258
+ ranks=ranks,
259
+ secondary_objective=self.secondary_objective,
260
+ notes=notes,
261
+ )
262
+
263
+ def _solve_self_efficiency(self, model_inputs: np.ndarray,
264
+ desirable_outputs: np.ndarray,
265
+ dmu_index: int) -> float:
266
+ """求解第 dmu_index 个 DMU 的 CCR 自评效率(乘数型)。
267
+
268
+ max Σ_r u_r y_rd
269
+ s.t. Σ_i v_i x_id = 1
270
+ Σ_r u_r y_rj - Σ_i v_i x_ij ≤ 0(所有 DMU)
271
+ u, v ≥ 0
272
+ """
273
+ n_model_inputs, n_dmus = model_inputs.shape
274
+ n_desirable_outputs = desirable_outputs.shape[0]
275
+ n_variables = n_model_inputs + n_desirable_outputs
276
+
277
+ objective_coefficients = np.zeros(n_variables)
278
+ objective_coefficients[n_model_inputs:] = -desirable_outputs[:, dmu_index]
279
+
280
+ equality_matrix = np.zeros((1, n_variables))
281
+ equality_matrix[0, :n_model_inputs] = model_inputs[:, dmu_index]
282
+ equality_rhs = np.array([1.0])
283
+
284
+ inequality_matrix = np.zeros((n_dmus, n_variables))
285
+ inequality_matrix[:, :n_model_inputs] = -model_inputs.T
286
+ inequality_matrix[:, n_model_inputs:] = desirable_outputs.T
287
+ inequality_rhs = np.zeros(n_dmus)
288
+
289
+ solution = solve_linear_program(
290
+ objective_coefficients,
291
+ inequality_matrix=inequality_matrix, inequality_rhs=inequality_rhs,
292
+ equality_matrix=equality_matrix, equality_rhs=equality_rhs,
293
+ error_context=f"交叉效率自评求解失败(第 {dmu_index + 1} 个 DMU)",
294
+ )
295
+ return -float(solution.fun)
296
+
297
+ def _solve_secondary_objective(self, model_inputs: np.ndarray,
298
+ desirable_outputs: np.ndarray, dmu_index: int,
299
+ self_efficiency: float) -> tuple[np.ndarray, np.ndarray]:
300
+ """求解 Doyle-Green 二级目标,返回该 DMU 的输入/产出权重。
301
+
302
+ aggressive: min Σ_r u_r (Σ_{j≠d} y_rj)
303
+ benevolent: max Σ_r u_r (Σ_{j≠d} y_rj)
304
+ s.t. Σ_i v_i (Σ_{j≠d} x_ij) = 1
305
+ Σ_r u_r y_rd - E_dd·Σ_i v_i x_id = 0
306
+ Σ_r u_r y_rj - Σ_i v_i x_ij ≤ 0(j≠d)
307
+ u, v ≥ 0
308
+ """
309
+ n_model_inputs, n_dmus = model_inputs.shape
310
+ n_desirable_outputs = desirable_outputs.shape[0]
311
+ n_variables = n_model_inputs + n_desirable_outputs
312
+
313
+ peer_mask = np.ones(n_dmus, dtype=bool)
314
+ peer_mask[dmu_index] = False
315
+ peer_input_sums = np.sum(model_inputs[:, peer_mask], axis=1)
316
+ peer_output_sums = np.sum(desirable_outputs[:, peer_mask], axis=1)
317
+
318
+ objective_coefficients = np.zeros(n_variables)
319
+ objective_coefficients[n_model_inputs:] = (
320
+ peer_output_sums if self.secondary_objective == "aggressive"
321
+ else -peer_output_sums
322
+ )
323
+
324
+ equality_matrix = np.zeros((2, n_variables))
325
+ equality_matrix[0, :n_model_inputs] = peer_input_sums
326
+ equality_matrix[1, :n_model_inputs] = -self_efficiency * model_inputs[:, dmu_index]
327
+ equality_matrix[1, n_model_inputs:] = desirable_outputs[:, dmu_index]
328
+ equality_rhs = np.array([1.0, 0.0])
329
+
330
+ inequality_matrix = np.zeros((n_dmus - 1, n_variables))
331
+ inequality_matrix[:, :n_model_inputs] = -model_inputs[:, peer_mask].T
332
+ inequality_matrix[:, n_model_inputs:] = desirable_outputs[:, peer_mask].T
333
+ inequality_rhs = np.zeros(n_dmus - 1)
334
+
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
+ input_weights = solution.x[:n_model_inputs]
342
+ output_weights = solution.x[n_model_inputs:]
343
+ return input_weights, output_weights
344
+
345
+
346
+ def build_parser() -> argparse.ArgumentParser:
347
+ argument_parser = argparse.ArgumentParser(
348
+ description="交叉效率 DEA(CCR 乘数型 + Doyle-Green 二级目标);"
349
+ "不带参数时使用脚本配置区",
350
+ formatter_class=argparse.RawDescriptionHelpFormatter,
351
+ epilog=(
352
+ "示例:\n"
353
+ " python cross_efficiency.py\n"
354
+ " python cross_efficiency.py --demo --objective benevolent\n"
355
+ " python cross_efficiency.py data.xlsx --matrix-file 矩阵.csv\n"
356
+ ),
357
+ )
358
+ DATA_COMMAND_LINE.add_arguments(argument_parser)
359
+ argument_parser.add_argument("--objective", choices=("aggressive", "benevolent"),
360
+ default=None,
361
+ help="二级目标: aggressive=进取型, benevolent=仁慈型;"
362
+ "缺省用 SECONDARY_OBJECTIVE")
363
+ argument_parser.add_argument("--matrix-file", metavar="文件", default=None,
364
+ help="完整交叉效率矩阵 CSV(长表);缺省用 MATRIX_FILE")
365
+ argument_parser.add_argument("--tolerance", "--tol", type=float, default=None,
366
+ help=f"判定自评有效的容差(默认 {EFFICIENCY_TOLERANCE})")
367
+ return argument_parser
368
+
369
+
370
+ def main(argv: Sequence[str] | None = None) -> int:
371
+ args = build_parser().parse_args(argv)
372
+ try:
373
+ prepared = DATA_COMMAND_LINE.prepare(args)
374
+ secondary_objective = (
375
+ args.objective if args.objective is not None
376
+ else SECONDARY_OBJECTIVE
377
+ )
378
+ efficiency_tolerance = (
379
+ args.tolerance if args.tolerance is not None else EFFICIENCY_TOLERANCE
380
+ )
381
+ matrix_file = (
382
+ args.matrix_file if args.matrix_file is not None else MATRIX_FILE
383
+ )
384
+ model = CrossEfficiencyModel(
385
+ secondary_objective=secondary_objective,
386
+ efficiency_tolerance=efficiency_tolerance,
387
+ )
388
+ result = model.solve(prepared.data)
389
+ except (ValueError, RuntimeError) as exc:
390
+ print(f"错误: {exc}", file=sys.stderr)
391
+ return 1
392
+
393
+ print(result.render_report(
394
+ prepared.column_names,
395
+ source_description=prepared.source_description,
396
+ ))
397
+ try:
398
+ if prepared.result_file:
399
+ result.write_csv(prepared.result_file)
400
+ print(f"\n结果已写入: {prepared.result_file}")
401
+ if matrix_file:
402
+ result.write_matrix_csv(matrix_file)
403
+ print(f"交叉效率矩阵已写入: {matrix_file}")
404
+ except OSError as exc:
405
+ print(f"错误: 无法写入结果文件: {exc}", file=sys.stderr)
406
+ return 1
407
+ return 0
408
+
409
+
410
+ if __name__ == "__main__":
411
+ sys.exit(main())