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.
@@ -0,0 +1,423 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """Context-dependent DEA 脚本(Seiford & Zhu 2003)。
4
+
5
+ 方法:
6
+ 1. 分层:对其余 DMU 反复运行输出导向径向 DEA,得到第 1 层、第 2 层……
7
+ 效率前沿;每层由输出扩张得分 φ = 1 的 DMU 组成。
8
+ 2. 吸引力(Attractiveness):DMU 相对更差层(层级 l+d)的输出导向得分 φ:
9
+ A = 1 / φ
10
+ 3. 进步(Progress):DMU 相对更好层(层级 l-d)的输出导向得分 φ:
11
+ P = φ
12
+ A、P 越大表示与比较层的距离越远;边界层或不可行时留空。
13
+
14
+ - 输出导向径向模型(CRS 为 Seiford-Zhu 原始设定,也可选 VRS):
15
+ max φ
16
+ s.t. X_ref·λ ≤ x_o, Y_ref·λ ≥ φ·y_o, λ ≥ 0(VRS 加 Σλ = 1)
17
+ - 非期望产出按“投入方向”并入投入块(越少越好)。
18
+ """
19
+
20
+ import argparse
21
+ import os
22
+ import sys
23
+ from collections.abc import Sequence
24
+ from dataclasses import dataclass, field
25
+
26
+ import numpy as np
27
+
28
+ from dea_core import (
29
+ ColumnNames,
30
+ DataCommandLine,
31
+ DataSettings,
32
+ DEAData,
33
+ EFFICIENCY_TOLERANCE,
34
+ MIN_SCALING_FACTOR,
35
+ SCORE_DECIMALS,
36
+ format_table,
37
+ round_score,
38
+ solve_linear_program,
39
+ write_csv_records,
40
+ )
41
+
42
+ # =============================== 用户配置区 ===============================
43
+ # 数据文件路径:支持 .csv / .xlsx / .xlsm;相对路径优先按当前工作目录,其次脚本所在目录解析
44
+ DATA_FILE = "sample_data.csv"
45
+ EXCEL_SHEET = 0 # Excel 工作表名或序号(0 开始);CSV 忽略
46
+
47
+ # DMU 标识列:可多列,自动用 "-" 拼接为唯一名称;如 ["城市代码", "年份"] → "110000-2021"
48
+ DMU_COLUMNS = ["城市代码", "年份"]
49
+
50
+ # 指标列名:按数据表的列名填写(三组变量分开设置)
51
+ INPUT_COLUMNS = ["资本投入", "劳动投入"] # 投入变量
52
+ DESIRABLE_OUTPUT_COLUMNS = ["GDP", "财政收入"] # 期望产出
53
+ UNDESIRABLE_OUTPUT_COLUMNS = ["工业废水排放量"] # 非期望产出(没有就写 [])
54
+
55
+ # 模型选项
56
+ COMPARISON_DISTANCE = 1 # A/P 比较的层间距 d(1=相邻层)
57
+ RETURNS_TO_SCALE = "crs" # "crs"=规模报酬不变(Seiford-Zhu 原始设定),"vrs"=可变
58
+ RESULT_FILE = None # 结果 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 ContextDependentResult:
77
+ """一次 Context-dependent DEA 求解的结果。"""
78
+
79
+ dmu_names: list[str]
80
+ layers: np.ndarray # 1 开始的层级编号
81
+ attractiveness: np.ndarray # A(无对应层或不可行为 NaN)
82
+ progress: np.ndarray # P(无对应层或不可行为 NaN)
83
+ layer_members: list[list[str]] # 每层的 DMU 名称
84
+ comparison_distance: int
85
+ returns_to_scale: str
86
+ notes: list[str] = field(default_factory=list)
87
+
88
+ def to_records(self) -> list[dict[str, object]]:
89
+ """把每个 DMU 展开成一条 CSV 记录。"""
90
+ records = []
91
+ for dmu_index, dmu_name in enumerate(self.dmu_names):
92
+ attractiveness = self.attractiveness[dmu_index]
93
+ progress = self.progress[dmu_index]
94
+ records.append({
95
+ "dmu": dmu_name,
96
+ "layer": int(self.layers[dmu_index]),
97
+ "attractiveness": (
98
+ None if np.isnan(attractiveness) else round_score(attractiveness)
99
+ ),
100
+ "progress": None if np.isnan(progress) else round_score(progress),
101
+ })
102
+ return records
103
+
104
+ def write_csv(self, path: str) -> None:
105
+ """写出 UTF-8-BOM 编码的结果 CSV。"""
106
+ write_csv_records(path, self.to_records())
107
+
108
+ def render_report(self, column_names: ColumnNames,
109
+ source_description: str | None = None) -> str:
110
+ """生成控制台报表文本。"""
111
+ returns_to_scale_description = (
112
+ "CRS 规模报酬不变" if self.returns_to_scale == "crs" else "VRS 规模报酬可变"
113
+ )
114
+ report_lines = [
115
+ "模型: Context-dependent DEA(Seiford & Zhu 2003) | 输出导向 | "
116
+ f"{returns_to_scale_description} | 比较距离 d={self.comparison_distance}"
117
+ ]
118
+ if source_description:
119
+ report_lines.append(f"数据: {source_description}")
120
+ undesirable_output_description = (
121
+ "、".join(column_names.undesirable_output_columns)
122
+ if column_names.undesirable_output_columns else "无"
123
+ )
124
+ report_lines.append(
125
+ f"变量: 投入[{'、'.join(column_names.input_columns)}] | "
126
+ f"期望产出[{'、'.join(column_names.desirable_output_columns)}] | "
127
+ f"非期望产出[{undesirable_output_description}]"
128
+ )
129
+ report_lines.append(f"DMU 数: {len(self.dmu_names)}")
130
+ report_lines.append("")
131
+
132
+ table_header = ["DMU", "层级", "吸引力 A", "进步 P"]
133
+ table_rows = []
134
+ for dmu_index, dmu_name in enumerate(self.dmu_names):
135
+ attractiveness = self.attractiveness[dmu_index]
136
+ progress = self.progress[dmu_index]
137
+ table_rows.append([
138
+ dmu_name,
139
+ str(int(self.layers[dmu_index])),
140
+ "-" if np.isnan(attractiveness)
141
+ else f"{round_score(attractiveness):.{SCORE_DECIMALS}f}",
142
+ "-" if np.isnan(progress)
143
+ else f"{round_score(progress):.{SCORE_DECIMALS}f}",
144
+ ])
145
+ report_lines.append(format_table(table_header, table_rows))
146
+ report_lines.append("")
147
+
148
+ for layer_index, member_names in enumerate(self.layer_members, start=1):
149
+ layer_tag = "(最优)" if layer_index == 1 else ""
150
+ report_lines.append(
151
+ f"第 {layer_index} 层{layer_tag}共 {len(member_names)} 个: "
152
+ f"{'、'.join(member_names)}"
153
+ )
154
+ report_lines.append("")
155
+ report_lines.append(
156
+ "说明: 吸引力 A 相对更差层(l+d),进步 P 相对更好层(l-d);"
157
+ "数值越大表示与比较层距离越远"
158
+ )
159
+ report_lines.append("说明: 边界层没有对应比较层,或线性规划不可行时 A/P 留空")
160
+ if column_names.undesirable_output_columns:
161
+ report_lines.append("说明: 非期望产出按投入方向处理(越少越好)")
162
+ report_lines.extend(f"提示: {note}" for note in self.notes[:10])
163
+ if len(self.notes) > 10:
164
+ report_lines.append(f"提示: 其余 {len(self.notes) - 10} 条类似提示已省略")
165
+ return "\n".join(report_lines)
166
+
167
+
168
+ @dataclass(frozen=True)
169
+ class OutputRadialContext:
170
+ """输出导向径向 DEA 的参考集上下文。"""
171
+
172
+ model_inputs: np.ndarray
173
+ desirable_outputs: np.ndarray
174
+ reference_indices: np.ndarray
175
+
176
+
177
+ class ContextDependentModel:
178
+ """Context-dependent DEA 求解器(输出导向分层 + 吸引力/进步)。"""
179
+
180
+ def __init__(self, comparison_distance: int = 1,
181
+ returns_to_scale: str = "crs",
182
+ efficiency_tolerance: float = EFFICIENCY_TOLERANCE):
183
+ if not isinstance(comparison_distance, int) or comparison_distance < 1:
184
+ raise ValueError("comparison_distance 必须为不小于 1 的整数")
185
+ returns_to_scale = returns_to_scale.lower()
186
+ if returns_to_scale not in ("crs", "vrs"):
187
+ raise ValueError("returns_to_scale 只能取 'crs' 或 'vrs'")
188
+ if efficiency_tolerance <= 0:
189
+ raise ValueError("efficiency_tolerance 必须为正数")
190
+ self.comparison_distance = comparison_distance
191
+ self.returns_to_scale = returns_to_scale
192
+ self.efficiency_tolerance = float(efficiency_tolerance)
193
+
194
+ def solve(self, data: DEAData) -> ContextDependentResult:
195
+ """分层并计算每个 DMU 的吸引力与进步。
196
+
197
+ 处理逻辑:输出导向径向 DEA 逐层识别并剔除有效单元 → 为每个 DMU
198
+ 记录层级 → 分别相对 l+d 与 l-d 层求解 A/P。
199
+ """
200
+ n_dmus = data.input_matrix.shape[1]
201
+ if n_dmus < 2:
202
+ raise ValueError("Context-dependent DEA 至少需要 2 个 DMU")
203
+ n_undesirable_outputs = data.undesirable_output_matrix.shape[0]
204
+ model_inputs = (
205
+ np.vstack([data.input_matrix, data.undesirable_output_matrix])
206
+ if n_undesirable_outputs else data.input_matrix
207
+ )
208
+ desirable_outputs = data.desirable_output_matrix
209
+
210
+ layer_indices = self._stratify(model_inputs, desirable_outputs)
211
+ layers = np.empty(n_dmus, dtype=int)
212
+ layer_members = [
213
+ [data.dmu_names[dmu_index] for dmu_index in layer]
214
+ for layer in layer_indices
215
+ ]
216
+ for layer_index, member_indices in enumerate(layer_indices, start=1):
217
+ layers[member_indices] = layer_index
218
+
219
+ attractiveness = np.full(n_dmus, np.nan)
220
+ progress = np.full(n_dmus, np.nan)
221
+ notes: list[str] = []
222
+ n_layers = len(layer_indices)
223
+ for layer_index, member_indices in enumerate(layer_indices):
224
+ worse_layer_index = layer_index + self.comparison_distance
225
+ better_layer_index = layer_index - self.comparison_distance
226
+ if worse_layer_index < n_layers:
227
+ context = OutputRadialContext(
228
+ model_inputs, desirable_outputs,
229
+ np.asarray(layer_indices[worse_layer_index]),
230
+ )
231
+ for dmu_index in member_indices:
232
+ phi = self._solve_output_radial(
233
+ context, dmu_index, require_success=False
234
+ )
235
+ if phi is None:
236
+ notes.append(
237
+ f"DMU '{data.dmu_names[dmu_index]}' 的吸引力求解不可行"
238
+ )
239
+ elif phi <= MIN_SCALING_FACTOR:
240
+ notes.append(
241
+ f"DMU '{data.dmu_names[dmu_index]}' 的吸引力比较层得分为 0"
242
+ )
243
+ else:
244
+ attractiveness[dmu_index] = 1.0 / phi
245
+ if better_layer_index >= 0:
246
+ context = OutputRadialContext(
247
+ model_inputs, desirable_outputs,
248
+ np.asarray(layer_indices[better_layer_index]),
249
+ )
250
+ for dmu_index in member_indices:
251
+ phi = self._solve_output_radial(
252
+ context, dmu_index, require_success=False
253
+ )
254
+ if phi is None:
255
+ notes.append(
256
+ f"DMU '{data.dmu_names[dmu_index]}' 的进步求解不可行"
257
+ )
258
+ else:
259
+ progress[dmu_index] = phi
260
+
261
+ if n_layers < self.comparison_distance + 1:
262
+ notes.append(
263
+ f"层数({n_layers})不足以比较距离 d={self.comparison_distance},"
264
+ "部分 A/P 留空"
265
+ )
266
+
267
+ return ContextDependentResult(
268
+ dmu_names=data.dmu_names,
269
+ layers=layers,
270
+ attractiveness=attractiveness,
271
+ progress=progress,
272
+ layer_members=layer_members,
273
+ comparison_distance=self.comparison_distance,
274
+ returns_to_scale=self.returns_to_scale,
275
+ notes=notes,
276
+ )
277
+
278
+ def _stratify(self, model_inputs: np.ndarray,
279
+ desirable_outputs: np.ndarray) -> list[list[int]]:
280
+ """反复剔除输出导向有效单元,得到各层前沿。
281
+
282
+ 处理逻辑:以剩余 DMU 为参考集计算每个 DMU 的输出导向得分 →
283
+ φ ≈ 1 的 DMU 组成当前层 → 从剩余集合剔除后重复。
284
+ """
285
+ remaining_indices = list(range(model_inputs.shape[1]))
286
+ layer_indices: list[list[int]] = []
287
+ while remaining_indices:
288
+ context = OutputRadialContext(
289
+ model_inputs, desirable_outputs, np.asarray(remaining_indices)
290
+ )
291
+ scores = {
292
+ dmu_index: self._solve_output_radial(context, dmu_index)
293
+ for dmu_index in remaining_indices
294
+ }
295
+ frontier = [
296
+ dmu_index for dmu_index in remaining_indices
297
+ if scores[dmu_index] <= 1.0 + self.efficiency_tolerance
298
+ ]
299
+ if not frontier:
300
+ raise RuntimeError("分层失败:剩余 DMU 中没有输出导向有效单元")
301
+ layer_indices.append(frontier)
302
+ frontier_set = set(frontier)
303
+ remaining_indices = [
304
+ dmu_index for dmu_index in remaining_indices
305
+ if dmu_index not in frontier_set
306
+ ]
307
+ return layer_indices
308
+
309
+ def _solve_output_radial(self, context: OutputRadialContext,
310
+ dmu_index: int,
311
+ require_success: bool = True) -> float | None:
312
+ """求解输出导向径向 DEA:参考集为 context.reference_indices 中的 DMU。
313
+
314
+ max φ
315
+ s.t. X_ref·λ ≤ x_o, Y_ref·λ ≥ φ·y_o, λ ≥ 0(VRS 加 Σλ = 1)
316
+ """
317
+ reference_inputs = context.model_inputs[:, context.reference_indices]
318
+ reference_outputs = context.desirable_outputs[:, context.reference_indices]
319
+ n_model_inputs = context.model_inputs.shape[0]
320
+ n_desirable_outputs = context.desirable_outputs.shape[0]
321
+ n_reference_dmus = context.reference_indices.size
322
+ n_variables = n_reference_dmus + 1
323
+ phi_column = n_reference_dmus
324
+
325
+ dmu_inputs = context.model_inputs[:, dmu_index]
326
+ dmu_outputs = context.desirable_outputs[:, dmu_index]
327
+
328
+ objective_coefficients = np.zeros(n_variables)
329
+ objective_coefficients[phi_column] = -1.0
330
+
331
+ inequality_matrix = np.zeros((n_model_inputs + n_desirable_outputs, n_variables))
332
+ inequality_rhs = np.zeros(n_model_inputs + n_desirable_outputs)
333
+ inequality_matrix[:n_model_inputs, :n_reference_dmus] = reference_inputs
334
+ inequality_rhs[:n_model_inputs] = dmu_inputs
335
+
336
+ output_rows = slice(n_model_inputs, n_model_inputs + n_desirable_outputs)
337
+ inequality_matrix[output_rows, :n_reference_dmus] = -reference_outputs
338
+ inequality_matrix[output_rows, phi_column] = dmu_outputs
339
+ inequality_rhs[output_rows] = 0.0
340
+
341
+ equality_matrix = None
342
+ equality_rhs = None
343
+ if self.returns_to_scale == "vrs":
344
+ equality_matrix = np.zeros((1, n_variables))
345
+ equality_matrix[0, :n_reference_dmus] = 1.0
346
+ equality_rhs = np.array([1.0])
347
+
348
+ solution = solve_linear_program(
349
+ objective_coefficients,
350
+ inequality_matrix=inequality_matrix, inequality_rhs=inequality_rhs,
351
+ equality_matrix=equality_matrix, equality_rhs=equality_rhs,
352
+ error_context=f"输出导向径向求解失败(第 {dmu_index + 1} 个 DMU)",
353
+ require_success=require_success,
354
+ )
355
+ if not solution.success:
356
+ return None
357
+ return float(solution.x[phi_column])
358
+
359
+
360
+ def build_parser() -> argparse.ArgumentParser:
361
+ argument_parser = argparse.ArgumentParser(
362
+ description="Context-dependent DEA(Seiford & Zhu 2003)分层、吸引力与进步;"
363
+ "不带参数时使用脚本配置区",
364
+ formatter_class=argparse.RawDescriptionHelpFormatter,
365
+ epilog=(
366
+ "示例:\n"
367
+ " python context_dependent_dea.py\n"
368
+ " python context_dependent_dea.py --demo --distance 2\n"
369
+ " python context_dependent_dea.py data.xlsx --returns-to-scale vrs\n"
370
+ ),
371
+ )
372
+ DATA_COMMAND_LINE.add_arguments(argument_parser)
373
+ argument_parser.add_argument("--distance", type=int, default=None,
374
+ help="A/P 比较的层间距 d(默认 COMPARISON_DISTANCE)")
375
+ argument_parser.add_argument("--returns-to-scale", "--rts",
376
+ choices=("crs", "vrs"), default=None,
377
+ help="规模报酬: crs=不变, vrs=可变;缺省用 RETURNS_TO_SCALE")
378
+ argument_parser.add_argument("--tolerance", "--tol", type=float, default=None,
379
+ help=f"判定 φ = 1 的容差(默认 {EFFICIENCY_TOLERANCE})")
380
+ return argument_parser
381
+
382
+
383
+ def main(argv: Sequence[str] | None = None) -> int:
384
+ args = build_parser().parse_args(argv)
385
+ try:
386
+ prepared = DATA_COMMAND_LINE.prepare(args)
387
+ comparison_distance = (
388
+ args.distance if args.distance is not None
389
+ else COMPARISON_DISTANCE
390
+ )
391
+ returns_to_scale = (
392
+ args.returns_to_scale if args.returns_to_scale is not None
393
+ else RETURNS_TO_SCALE
394
+ )
395
+ efficiency_tolerance = (
396
+ args.tolerance if args.tolerance is not None else EFFICIENCY_TOLERANCE
397
+ )
398
+ model = ContextDependentModel(
399
+ comparison_distance=comparison_distance,
400
+ returns_to_scale=returns_to_scale,
401
+ efficiency_tolerance=efficiency_tolerance,
402
+ )
403
+ result = model.solve(prepared.data)
404
+ except (ValueError, RuntimeError) as exc:
405
+ print(f"错误: {exc}", file=sys.stderr)
406
+ return 1
407
+
408
+ print(result.render_report(
409
+ prepared.column_names,
410
+ source_description=prepared.source_description,
411
+ ))
412
+ if prepared.result_file:
413
+ try:
414
+ result.write_csv(prepared.result_file)
415
+ except OSError as exc:
416
+ print(f"错误: 无法写入 {prepared.result_file}: {exc}", file=sys.stderr)
417
+ return 1
418
+ print(f"\n结果已写入: {prepared.result_file}")
419
+ return 0
420
+
421
+
422
+ if __name__ == "__main__":
423
+ sys.exit(main())