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.
dynamic_sbm.py ADDED
@@ -0,0 +1,506 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """Tone-Tsutsui(2010)动态 SBM 脚本。
4
+
5
+ 面板要求:同一实体在每个期别都有观测(平衡面板);使用期别列与实体列。
6
+ 结转变量分为好结转(越多越好)和坏结转(越少越好);当前期非期望产出
7
+ 按投入方向并入投入块。
8
+
9
+ 模型(非导向动态 SBM):
10
+ ρ = [1/T Σ_t (1 - 1/(m+n_bad))·(Σ s⁻_it/x_iot + Σ s^bad_ct/z^bad_cot)]
11
+ /
12
+ [1/T Σ_t (1 + 1/(s+n_good))·(Σ s⁺_rt/y_rot + Σ s^good_ct/z^good_cot)]
13
+ s.t. X_t λ_t + s⁻_t = x_ot
14
+ Y_t λ_t - s⁺_t = y_ot
15
+ G_t λ_t - s^good_t = g_ot
16
+ B_t λ_t + s^bad_t = b_ot
17
+ G_t λ_t = G_t λ_{t+1}, B_t λ_t = B_t λ_{t+1}(结转连续性)
18
+ Σλ_t = 1(VRS)
19
+ λ, s ≥ 0
20
+ 经 Charnes-Cooper 变换后求解;同时输出综合得分与各期得分。
21
+ """
22
+
23
+ import argparse
24
+ import os
25
+ import sys
26
+ from collections.abc import Sequence
27
+ from dataclasses import dataclass, field
28
+
29
+ import numpy as np
30
+
31
+ from dea_core import (
32
+ ColumnNames,
33
+ DataCommandLine,
34
+ DataSettings,
35
+ DEAData,
36
+ EFFICIENCY_TOLERANCE,
37
+ MIN_SCALING_FACTOR,
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
+ DATA_FILE = "sample_data.csv"
48
+ EXCEL_SHEET = 0
49
+
50
+ DMU_COLUMNS = ["城市代码", "年份"]
51
+ PERIOD_COLUMN = "年份"
52
+ ENTITY_COLUMNS = ["城市代码"]
53
+ INPUT_COLUMNS = ["资本投入", "劳动投入"]
54
+ DESIRABLE_OUTPUT_COLUMNS = ["GDP", "财政收入"]
55
+ UNDESIRABLE_OUTPUT_COLUMNS = ["工业废水排放量"]
56
+ GOOD_CARRY_OVER_COLUMNS = ["资本存量"]
57
+ BAD_CARRY_OVER_COLUMNS = []
58
+
59
+ RETURNS_TO_SCALE = "crs" # "crs" 或 "vrs"
60
+ RESULT_FILE = None # 结果 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
+ period_column=PERIOD_COLUMN,
72
+ entity_columns=tuple(ENTITY_COLUMNS),
73
+ good_carry_over_columns=tuple(GOOD_CARRY_OVER_COLUMNS),
74
+ bad_carry_over_columns=tuple(BAD_CARRY_OVER_COLUMNS),
75
+ result_file=RESULT_FILE,
76
+ ),
77
+ script_directory=os.path.dirname(os.path.abspath(__file__)),
78
+ )
79
+
80
+
81
+ @dataclass
82
+ class DynamicPanel:
83
+ """按期别整理的动态面板矩阵。"""
84
+
85
+ entities: list[str]
86
+ periods: list[str]
87
+ input_matrices: list[np.ndarray]
88
+ desirable_output_matrices: list[np.ndarray]
89
+ good_carry_over_matrices: list[np.ndarray]
90
+ bad_carry_over_matrices: list[np.ndarray]
91
+
92
+
93
+ @dataclass
94
+ class DynamicSBMResult:
95
+ """动态 SBM 结果。"""
96
+
97
+ entities: list[str]
98
+ periods: list[str]
99
+ overall_scores: np.ndarray
100
+ period_scores: np.ndarray
101
+ efficiency_mask: np.ndarray
102
+ ranks: np.ndarray
103
+ returns_to_scale: str
104
+ notes: list[str] = field(default_factory=list)
105
+
106
+ def to_records(self) -> list[dict[str, object]]:
107
+ """把每个实体展开成一条 CSV 记录。"""
108
+ records = []
109
+ for entity_index, entity in enumerate(self.entities):
110
+ record: dict[str, object] = {
111
+ "entity": entity,
112
+ "overall_score": round_score(self.overall_scores[entity_index]),
113
+ "efficient": int(self.efficiency_mask[entity_index]),
114
+ "rank": int(self.ranks[entity_index]),
115
+ }
116
+ for period_index, period in enumerate(self.periods):
117
+ record[f"period_score_{period}"] = round_score(
118
+ self.period_scores[entity_index, period_index]
119
+ )
120
+ records.append(record)
121
+ return records
122
+
123
+ def write_csv(self, path: str) -> None:
124
+ """写出 UTF-8-BOM 编码的结果 CSV。"""
125
+ write_csv_records(path, self.to_records())
126
+
127
+ def render_report(self, column_names: ColumnNames,
128
+ source_description: str | None = None) -> str:
129
+ """生成控制台报表文本。"""
130
+ returns_to_scale_description = (
131
+ "CRS 规模报酬不变" if self.returns_to_scale == "crs" else "VRS 规模报酬可变"
132
+ )
133
+ report_lines = [
134
+ f"模型: Tone-Tsutsui 动态 SBM | {returns_to_scale_description}"
135
+ ]
136
+ if source_description:
137
+ report_lines.append(f"数据: {source_description}")
138
+ report_lines.append(
139
+ f"变量: 投入[{'、'.join(column_names.input_columns)}] | "
140
+ f"期望产出[{'、'.join(column_names.desirable_output_columns)}] | "
141
+ f"非期望产出[{'、'.join(column_names.undesirable_output_columns) or '无'}] | "
142
+ f"好结转[{'、'.join(column_names.good_carry_over_columns) or '无'}] | "
143
+ f"坏结转[{'、'.join(column_names.bad_carry_over_columns) or '无'}]"
144
+ )
145
+ report_lines.append(
146
+ f"实体数: {len(self.entities)} | 期别数: {len(self.periods)}"
147
+ )
148
+ report_lines.append("")
149
+
150
+ table_header = ["实体", "综合得分", *self.periods, "排名"]
151
+ table_rows = []
152
+ for entity_index, entity in enumerate(self.entities):
153
+ row = [
154
+ entity,
155
+ f"{round_score(self.overall_scores[entity_index]):.{SCORE_DECIMALS}f}",
156
+ ]
157
+ for period_index in range(len(self.periods)):
158
+ period_score = round_score(
159
+ self.period_scores[entity_index, period_index]
160
+ )
161
+ row.append(f"{period_score:.{SCORE_DECIMALS}f}")
162
+ row.append(str(int(self.ranks[entity_index])))
163
+ table_rows.append(row)
164
+ report_lines.append(format_table(table_header, table_rows))
165
+ report_lines.append("")
166
+
167
+ efficient_names = [self.entities[i] for i in np.flatnonzero(self.efficiency_mask)]
168
+ report_lines.append(
169
+ f"综合有效实体共 {len(efficient_names)} 个: "
170
+ f"{'、'.join(efficient_names) if efficient_names else '无'}"
171
+ )
172
+ report_lines.append(
173
+ "说明: 综合得分由各期投入/期望产出/结转松弛汇总得到;"
174
+ "期别得分取最优解下各期单独效率"
175
+ )
176
+ if column_names.undesirable_output_columns:
177
+ report_lines.append("说明: 当前期非期望产出按投入方向处理(越少越好)")
178
+ report_lines.extend(f"提示: {note}" for note in self.notes[:10])
179
+ return "\n".join(report_lines)
180
+
181
+
182
+ class DynamicSBMModel:
183
+ """Tone-Tsutsui 非导向动态 SBM 求解器。"""
184
+
185
+ def __init__(self, returns_to_scale: str = "crs",
186
+ efficiency_tolerance: float = EFFICIENCY_TOLERANCE):
187
+ returns_to_scale = returns_to_scale.lower()
188
+ if returns_to_scale not in ("crs", "vrs"):
189
+ raise ValueError("returns_to_scale 只能取 'crs' 或 'vrs'")
190
+ if efficiency_tolerance <= 0:
191
+ raise ValueError("efficiency_tolerance 必须为正数")
192
+ self.returns_to_scale = returns_to_scale
193
+ self.efficiency_tolerance = float(efficiency_tolerance)
194
+
195
+ def solve(self, data: DEAData) -> DynamicSBMResult:
196
+ """求解所有实体的动态 SBM。
197
+
198
+ 处理逻辑:校验平衡面板 → 按期别整理投入/产出/结转矩阵 → 每个实体
199
+ 求解一个跨期 LP → 计算综合得分与期别得分。
200
+ """
201
+ panel = self._build_panel(data)
202
+ if len(panel.periods) < 2:
203
+ raise ValueError("动态 SBM 至少需要 2 个期别")
204
+ if len(panel.entities) < 2:
205
+ raise ValueError("动态 SBM 至少需要 2 个实体")
206
+
207
+ overall_scores = np.empty(len(panel.entities))
208
+ period_scores = np.empty((len(panel.entities), len(panel.periods)))
209
+ notes: list[str] = []
210
+ for entity_index in range(len(panel.entities)):
211
+ overall, per_period = self._solve_entity(panel, entity_index)
212
+ overall_scores[entity_index] = overall
213
+ period_scores[entity_index] = per_period
214
+
215
+ efficiency_mask = np.asarray(
216
+ overall_scores >= 1.0 - self.efficiency_tolerance, dtype=bool
217
+ )
218
+ return DynamicSBMResult(
219
+ entities=panel.entities,
220
+ periods=panel.periods,
221
+ overall_scores=overall_scores,
222
+ period_scores=period_scores,
223
+ efficiency_mask=efficiency_mask,
224
+ ranks=assign_ranks_with_ties(overall_scores),
225
+ returns_to_scale=self.returns_to_scale,
226
+ notes=notes,
227
+ )
228
+
229
+ def _build_panel(self, data: DEAData) -> DynamicPanel:
230
+ """校验平衡面板并整理各期矩阵。"""
231
+ periods = sorted(set(data.periods))
232
+ entities = sorted(set(data.entities))
233
+ if not periods or not entities or any(not value for value in periods + entities):
234
+ raise ValueError("动态 SBM 需要非空的期别列与实体列")
235
+ if (data.good_carry_over_matrix.size
236
+ and (data.good_carry_over_matrix <= 0).any()):
237
+ raise ValueError("动态 SBM 要求好结转变量为正数")
238
+ if (data.bad_carry_over_matrix.size
239
+ and (data.bad_carry_over_matrix <= 0).any()):
240
+ raise ValueError("动态 SBM 要求坏结转变量为正数")
241
+
242
+ row_lookup: dict[tuple[str, str], int] = {}
243
+ for row_index, (period, entity) in enumerate(zip(data.periods, data.entities)):
244
+ key = (period, entity)
245
+ if key in row_lookup:
246
+ raise ValueError(f"实体 '{entity}' 在期别 '{period}' 存在重复观测")
247
+ row_lookup[key] = row_index
248
+ expected = {(period, entity) for period in periods for entity in entities}
249
+ missing = expected - set(row_lookup)
250
+ if missing:
251
+ raise ValueError(f"面板不平衡,缺少实体-期别观测: {sorted(missing)[:5]}")
252
+
253
+ input_matrices, desirable_matrices = [], []
254
+ good_matrices, bad_matrices = [], []
255
+ for period in periods:
256
+ indices = [row_lookup[(period, entity)] for entity in entities]
257
+ current_inputs = data.input_matrix[:, indices]
258
+ if data.undesirable_output_matrix.shape[0]:
259
+ current_inputs = np.vstack([
260
+ current_inputs, data.undesirable_output_matrix[:, indices]
261
+ ])
262
+ input_matrices.append(current_inputs)
263
+ desirable_matrices.append(data.desirable_output_matrix[:, indices])
264
+ good_matrices.append(data.good_carry_over_matrix[:, indices])
265
+ bad_matrices.append(data.bad_carry_over_matrix[:, indices])
266
+ return DynamicPanel(
267
+ entities=entities,
268
+ periods=periods,
269
+ input_matrices=input_matrices,
270
+ desirable_output_matrices=desirable_matrices,
271
+ good_carry_over_matrices=good_matrices,
272
+ bad_carry_over_matrices=bad_matrices,
273
+ )
274
+
275
+ def _solve_entity(self, panel: DynamicPanel, entity_index: int
276
+ ) -> tuple[float, np.ndarray]:
277
+ """求解单个实体跨所有期别的动态 SBM。"""
278
+ n_entities = len(panel.entities)
279
+ n_periods = len(panel.periods)
280
+ n_inputs = panel.input_matrices[0].shape[0]
281
+ n_outputs = panel.desirable_output_matrices[0].shape[0]
282
+ n_good = panel.good_carry_over_matrices[0].shape[0]
283
+ n_bad = panel.bad_carry_over_matrices[0].shape[0]
284
+ block_size = n_entities + n_inputs + n_outputs + n_good + n_bad
285
+ tau_column = block_size * n_periods
286
+ n_variables = tau_column + 1
287
+
288
+ objective_coefficients = np.zeros(n_variables)
289
+ objective_coefficients[tau_column] = 1.0
290
+ period_norm_inputs = n_periods * (n_inputs + n_bad)
291
+ period_norm_outputs = n_periods * (n_outputs + n_good)
292
+
293
+ equalities: list[np.ndarray] = []
294
+ rhs: list[float] = []
295
+
296
+ for period_index in range(n_periods):
297
+ start = period_index * block_size
298
+ lambda_start = start
299
+ slack_input_start = lambda_start + n_entities
300
+ slack_good_output_start = slack_input_start + n_inputs
301
+ slack_good_carry_start = slack_good_output_start + n_outputs
302
+ slack_bad_carry_start = slack_good_carry_start + n_good
303
+ lambda_end = lambda_start + n_entities
304
+
305
+ x_o = panel.input_matrices[period_index][:, entity_index]
306
+ y_o = panel.desirable_output_matrices[period_index][:, entity_index]
307
+ g_o = panel.good_carry_over_matrices[period_index][:, entity_index]
308
+ b_o = panel.bad_carry_over_matrices[period_index][:, entity_index]
309
+
310
+ objective_coefficients[slack_input_start:slack_input_start + n_inputs] = (
311
+ -1.0 / (period_norm_inputs * x_o)
312
+ )
313
+ if n_bad:
314
+ objective_coefficients[
315
+ slack_bad_carry_start:slack_bad_carry_start + n_bad
316
+ ] = -1.0 / (period_norm_inputs * b_o)
317
+
318
+ for input_index in range(n_inputs):
319
+ row = np.zeros(n_variables)
320
+ row[lambda_start:lambda_end] = panel.input_matrices[period_index][input_index]
321
+ row[slack_input_start + input_index] = 1.0
322
+ row[tau_column] = -x_o[input_index]
323
+ equalities.append(row)
324
+ rhs.append(0.0)
325
+
326
+ for output_index in range(n_outputs):
327
+ row = np.zeros(n_variables)
328
+ row[lambda_start:lambda_end] = (
329
+ panel.desirable_output_matrices[period_index][output_index]
330
+ )
331
+ row[slack_good_output_start + output_index] = -1.0
332
+ row[tau_column] = -y_o[output_index]
333
+ equalities.append(row)
334
+ rhs.append(0.0)
335
+
336
+ for carry_index in range(n_good):
337
+ row = np.zeros(n_variables)
338
+ row[lambda_start:lambda_end] = (
339
+ panel.good_carry_over_matrices[period_index][carry_index]
340
+ )
341
+ row[slack_good_carry_start + carry_index] = -1.0
342
+ row[tau_column] = -g_o[carry_index]
343
+ equalities.append(row)
344
+ rhs.append(0.0)
345
+
346
+ for carry_index in range(n_bad):
347
+ row = np.zeros(n_variables)
348
+ row[lambda_start:lambda_end] = (
349
+ panel.bad_carry_over_matrices[period_index][carry_index]
350
+ )
351
+ row[slack_bad_carry_start + carry_index] = 1.0
352
+ row[tau_column] = -b_o[carry_index]
353
+ equalities.append(row)
354
+ rhs.append(0.0)
355
+
356
+ if self.returns_to_scale == "vrs":
357
+ row = np.zeros(n_variables)
358
+ row[lambda_start:lambda_end] = 1.0
359
+ row[tau_column] = -1.0
360
+ equalities.append(row)
361
+ rhs.append(0.0)
362
+
363
+ normalization = np.zeros(n_variables)
364
+ normalization[tau_column] = 1.0
365
+ for period_index in range(n_periods):
366
+ start = period_index * block_size
367
+ slack_good_output_start = start + n_entities + n_inputs
368
+ slack_good_carry_start = slack_good_output_start + n_outputs
369
+ y_o = panel.desirable_output_matrices[period_index][:, entity_index]
370
+ g_o = panel.good_carry_over_matrices[period_index][:, entity_index]
371
+ normalization[
372
+ slack_good_output_start:slack_good_output_start + n_outputs
373
+ ] = 1.0 / (period_norm_outputs * y_o)
374
+ if n_good:
375
+ normalization[
376
+ slack_good_carry_start:slack_good_carry_start + n_good
377
+ ] = 1.0 / (period_norm_outputs * g_o)
378
+ equalities.append(normalization)
379
+ rhs.append(1.0)
380
+
381
+ for period_index in range(n_periods - 1):
382
+ current_start = period_index * block_size
383
+ next_start = (period_index + 1) * block_size
384
+ for carry_index in range(n_good):
385
+ row = np.zeros(n_variables)
386
+ row[current_start:current_start + n_entities] = (
387
+ panel.good_carry_over_matrices[period_index][carry_index]
388
+ )
389
+ row[next_start:next_start + n_entities] = -(
390
+ panel.good_carry_over_matrices[period_index][carry_index]
391
+ )
392
+ equalities.append(row)
393
+ rhs.append(0.0)
394
+ for carry_index in range(n_bad):
395
+ row = np.zeros(n_variables)
396
+ row[current_start:current_start + n_entities] = (
397
+ panel.bad_carry_over_matrices[period_index][carry_index]
398
+ )
399
+ row[next_start:next_start + n_entities] = -(
400
+ panel.bad_carry_over_matrices[period_index][carry_index]
401
+ )
402
+ equalities.append(row)
403
+ rhs.append(0.0)
404
+
405
+ solution = solve_linear_program(
406
+ objective_coefficients,
407
+ equality_matrix=np.asarray(equalities), equality_rhs=np.asarray(rhs),
408
+ error_context=f"动态 SBM 求解失败(实体 {panel.entities[entity_index]})",
409
+ )
410
+ tau = float(solution.x[tau_column])
411
+ if tau <= MIN_SCALING_FACTOR:
412
+ raise RuntimeError(f"动态 SBM 缩放因子非正(实体 {panel.entities[entity_index]})")
413
+ overall = float(solution.fun)
414
+ period_scores = np.empty(n_periods)
415
+ for period_index in range(n_periods):
416
+ start = period_index * block_size
417
+ slack_input_start = start + n_entities
418
+ slack_good_output_start = slack_input_start + n_inputs
419
+ slack_good_carry_start = slack_good_output_start + n_outputs
420
+ slack_bad_carry_start = slack_good_carry_start + n_good
421
+ x_o = panel.input_matrices[period_index][:, entity_index]
422
+ y_o = panel.desirable_output_matrices[period_index][:, entity_index]
423
+ g_o = panel.good_carry_over_matrices[period_index][:, entity_index]
424
+ b_o = panel.bad_carry_over_matrices[period_index][:, entity_index]
425
+ input_slacks = solution.x[
426
+ slack_input_start:slack_input_start + n_inputs
427
+ ] / tau
428
+ good_output_slacks = solution.x[
429
+ slack_good_output_start:slack_good_output_start + n_outputs
430
+ ] / tau
431
+ good_carry_slacks = solution.x[
432
+ slack_good_carry_start:slack_good_carry_start + n_good
433
+ ] / tau if n_good else np.zeros(0)
434
+ bad_carry_slacks = solution.x[
435
+ slack_bad_carry_start:slack_bad_carry_start + n_bad
436
+ ] / tau if n_bad else np.zeros(0)
437
+ input_inefficiency = (
438
+ np.sum(input_slacks / x_o) / (n_inputs + n_bad)
439
+ + (np.sum(bad_carry_slacks / b_o) / (n_inputs + n_bad) if n_bad else 0.0)
440
+ )
441
+ output_inefficiency = (
442
+ np.sum(good_output_slacks / y_o) / (n_outputs + n_good)
443
+ + (np.sum(good_carry_slacks / g_o) / (n_outputs + n_good) if n_good else 0.0)
444
+ )
445
+ period_scores[period_index] = (
446
+ (1.0 - input_inefficiency) / (1.0 + output_inefficiency)
447
+ )
448
+ return overall, period_scores
449
+
450
+
451
+ def build_parser() -> argparse.ArgumentParser:
452
+ argument_parser = argparse.ArgumentParser(
453
+ description="Tone-Tsutsui 动态 SBM(好/坏结转);"
454
+ "不带参数时使用脚本配置区",
455
+ formatter_class=argparse.RawDescriptionHelpFormatter,
456
+ epilog=(
457
+ "示例:\n"
458
+ " python dynamic_sbm.py --demo\n"
459
+ " python dynamic_sbm.py --demo --returns-to-scale vrs\n"
460
+ ),
461
+ )
462
+ DATA_COMMAND_LINE.add_arguments(argument_parser)
463
+ argument_parser.add_argument("--returns-to-scale", "--rts",
464
+ choices=("crs", "vrs"), default=None,
465
+ help="规模报酬: crs=不变, vrs=可变;缺省用 RETURNS_TO_SCALE")
466
+ argument_parser.add_argument("--tolerance", "--tol", type=float, default=None,
467
+ help=f"判定有效性的容差(默认 {EFFICIENCY_TOLERANCE})")
468
+ return argument_parser
469
+
470
+
471
+ def main(argv: Sequence[str] | None = None) -> int:
472
+ args = build_parser().parse_args(argv)
473
+ try:
474
+ prepared = DATA_COMMAND_LINE.prepare(args)
475
+ returns_to_scale = (
476
+ args.returns_to_scale if args.returns_to_scale is not None
477
+ else RETURNS_TO_SCALE
478
+ )
479
+ efficiency_tolerance = (
480
+ args.tolerance if args.tolerance is not None else EFFICIENCY_TOLERANCE
481
+ )
482
+ model = DynamicSBMModel(
483
+ returns_to_scale=returns_to_scale,
484
+ efficiency_tolerance=efficiency_tolerance,
485
+ )
486
+ result = model.solve(prepared.data)
487
+ except (ValueError, RuntimeError) as exc:
488
+ print(f"错误: {exc}", file=sys.stderr)
489
+ return 1
490
+
491
+ print(result.render_report(
492
+ prepared.column_names,
493
+ source_description=prepared.source_description,
494
+ ))
495
+ if prepared.result_file:
496
+ try:
497
+ result.write_csv(prepared.result_file)
498
+ except OSError as exc:
499
+ print(f"错误: 无法写入 {prepared.result_file}: {exc}", file=sys.stderr)
500
+ return 1
501
+ print(f"\n结果已写入: {prepared.result_file}")
502
+ return 0
503
+
504
+
505
+ if __name__ == "__main__":
506
+ sys.exit(main())