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
bootstrap_dea.py
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""Simar-Wilson Bootstrap DEA 脚本。
|
|
4
|
+
|
|
5
|
+
方法(Simar & Wilson 1998,同质平滑 bootstrap):
|
|
6
|
+
1. 用输入导向径向 DEA(CRS/VRS)计算原始效率 θ_i;
|
|
7
|
+
2. 对效率分布做平滑重抽样(双边反射到 [0, 1] 内并做方差校正):
|
|
8
|
+
θ* = β + h·ε(超过 1 时反射为 2-θ*)
|
|
9
|
+
θ** = β̄ + (θ* - β̄) / sqrt(1 + h²/σ²)
|
|
10
|
+
其中 β 为从原始效率中有放回抽取的样本,h 为平滑带宽;
|
|
11
|
+
3. 生成伪数据 x*_i = (θ_i/θ**_i)·x_i,y*_i = y_i(非期望产出随投入块缩放),
|
|
12
|
+
在伪样本上重新求解 DEA,得到 bootstrap 效率;
|
|
13
|
+
4. 重复 B 次,计算偏差、偏差校正得分与百分位置信区间。
|
|
14
|
+
|
|
15
|
+
- 默认自动带宽采用 Silverman 经验规则,也可手动指定;h=0 表示不平滑;
|
|
16
|
+
- 非期望产出按“投入方向”并入投入块(越少越好);
|
|
17
|
+
- 这是同质 bootstrap,不处理环境变量或异质前沿;校正得分可能超过 1。
|
|
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
|
+
SCORE_DECIMALS,
|
|
35
|
+
assign_ranks_with_ties,
|
|
36
|
+
format_table,
|
|
37
|
+
round_score,
|
|
38
|
+
write_csv_records,
|
|
39
|
+
)
|
|
40
|
+
from radial_models import RadialModel
|
|
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
|
+
RETURNS_TO_SCALE = "crs" # "crs"=规模报酬不变,"vrs"=规模报酬可变
|
|
57
|
+
BOOTSTRAP_REPETITIONS = 200 # bootstrap 重复次数 B(正式分析建议 1000+)
|
|
58
|
+
CONFIDENCE_LEVEL = 0.95 # 置信区间水平
|
|
59
|
+
RANDOM_SEED = 2026 # 随机种子;None 表示不固定
|
|
60
|
+
SMOOTHING_BANDWIDTH = None # None=Silverman 自动带宽;0=不平滑;正数=手动带宽
|
|
61
|
+
RESULT_FILE = None # 结果 CSV 输出路径;None 表示不导出
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
DATA_COMMAND_LINE = DataCommandLine(
|
|
65
|
+
settings=DataSettings(
|
|
66
|
+
data_file=DATA_FILE,
|
|
67
|
+
excel_sheet=EXCEL_SHEET,
|
|
68
|
+
dmu_columns=tuple(DMU_COLUMNS),
|
|
69
|
+
input_columns=tuple(INPUT_COLUMNS),
|
|
70
|
+
desirable_output_columns=tuple(DESIRABLE_OUTPUT_COLUMNS),
|
|
71
|
+
undesirable_output_columns=tuple(UNDESIRABLE_OUTPUT_COLUMNS),
|
|
72
|
+
result_file=RESULT_FILE,
|
|
73
|
+
),
|
|
74
|
+
script_directory=os.path.dirname(os.path.abspath(__file__)),
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass(frozen=True)
|
|
79
|
+
class BootstrapSettings:
|
|
80
|
+
"""Simar-Wilson bootstrap 的模型设置。"""
|
|
81
|
+
|
|
82
|
+
returns_to_scale: str = RETURNS_TO_SCALE
|
|
83
|
+
repetitions: int = BOOTSTRAP_REPETITIONS
|
|
84
|
+
confidence_level: float = CONFIDENCE_LEVEL
|
|
85
|
+
random_seed: int | None = RANDOM_SEED
|
|
86
|
+
smoothing_bandwidth: float | None = SMOOTHING_BANDWIDTH
|
|
87
|
+
efficiency_tolerance: float = EFFICIENCY_TOLERANCE
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass
|
|
91
|
+
class BootstrapDEAResult:
|
|
92
|
+
"""一次 Bootstrap DEA 的结果,含报表与 CSV 导出。"""
|
|
93
|
+
|
|
94
|
+
dmu_names: list[str]
|
|
95
|
+
original_scores: np.ndarray # 原始径向效率 θ
|
|
96
|
+
bootstrap_means: np.ndarray # bootstrap 均值
|
|
97
|
+
biases: np.ndarray # bootstrap 偏差
|
|
98
|
+
corrected_scores: np.ndarray # 偏差校正得分
|
|
99
|
+
standard_errors: np.ndarray # bootstrap 标准误
|
|
100
|
+
confidence_lower: np.ndarray # 百分位区间下限
|
|
101
|
+
confidence_upper: np.ndarray # 百分位区间上限
|
|
102
|
+
efficiency_mask: np.ndarray # 原始效率 = 1
|
|
103
|
+
ranks: np.ndarray # 按校正得分排名
|
|
104
|
+
repetitions: int
|
|
105
|
+
confidence_level: float
|
|
106
|
+
smoothing_bandwidth: float
|
|
107
|
+
returns_to_scale: str
|
|
108
|
+
notes: list[str] = field(default_factory=list)
|
|
109
|
+
|
|
110
|
+
def to_records(self) -> list[dict[str, object]]:
|
|
111
|
+
"""把每个 DMU 展开成一条 CSV 记录。"""
|
|
112
|
+
records = []
|
|
113
|
+
for dmu_index, dmu_name in enumerate(self.dmu_names):
|
|
114
|
+
records.append({
|
|
115
|
+
"dmu": dmu_name,
|
|
116
|
+
"original_score": round_score(self.original_scores[dmu_index]),
|
|
117
|
+
"bias": round_score(self.biases[dmu_index]),
|
|
118
|
+
"corrected_score": round_score(self.corrected_scores[dmu_index]),
|
|
119
|
+
"standard_error": round_score(self.standard_errors[dmu_index]),
|
|
120
|
+
"confidence_lower": round_score(self.confidence_lower[dmu_index]),
|
|
121
|
+
"confidence_upper": round_score(self.confidence_upper[dmu_index]),
|
|
122
|
+
"efficient": int(self.efficiency_mask[dmu_index]),
|
|
123
|
+
"rank": int(self.ranks[dmu_index]),
|
|
124
|
+
})
|
|
125
|
+
return records
|
|
126
|
+
|
|
127
|
+
def write_csv(self, path: str) -> None:
|
|
128
|
+
"""写出 UTF-8-BOM 编码的结果 CSV。"""
|
|
129
|
+
write_csv_records(path, self.to_records())
|
|
130
|
+
|
|
131
|
+
def render_report(self, column_names: ColumnNames,
|
|
132
|
+
source_description: str | None = None) -> str:
|
|
133
|
+
"""生成控制台报表文本。"""
|
|
134
|
+
returns_to_scale_description = (
|
|
135
|
+
"CRS 规模报酬不变" if self.returns_to_scale == "crs" else "VRS 规模报酬可变"
|
|
136
|
+
)
|
|
137
|
+
confidence_percent = int(round(self.confidence_level * 100))
|
|
138
|
+
report_lines = [
|
|
139
|
+
f"模型: Simar-Wilson Bootstrap DEA | 输入导向径向 | "
|
|
140
|
+
f"{returns_to_scale_description} | B={self.repetitions} | "
|
|
141
|
+
f"{confidence_percent}% 百分位区间"
|
|
142
|
+
]
|
|
143
|
+
if source_description:
|
|
144
|
+
report_lines.append(f"数据: {source_description}")
|
|
145
|
+
undesirable_output_description = (
|
|
146
|
+
"、".join(column_names.undesirable_output_columns)
|
|
147
|
+
if column_names.undesirable_output_columns else "无"
|
|
148
|
+
)
|
|
149
|
+
report_lines.append(
|
|
150
|
+
f"变量: 投入[{'、'.join(column_names.input_columns)}] | "
|
|
151
|
+
f"期望产出[{'、'.join(column_names.desirable_output_columns)}] | "
|
|
152
|
+
f"非期望产出[{undesirable_output_description}]"
|
|
153
|
+
)
|
|
154
|
+
report_lines.append(f"DMU 数: {len(self.dmu_names)}")
|
|
155
|
+
bandwidth_description = (
|
|
156
|
+
"不平滑" if self.smoothing_bandwidth <= 0
|
|
157
|
+
else f"h={self.smoothing_bandwidth:.{SCORE_DECIMALS}f}"
|
|
158
|
+
)
|
|
159
|
+
report_lines.append(f"平滑带宽: {bandwidth_description}")
|
|
160
|
+
report_lines.append("")
|
|
161
|
+
|
|
162
|
+
table_header = [
|
|
163
|
+
"DMU", "原始得分", "偏差", "校正得分",
|
|
164
|
+
f"{confidence_percent}% 区间", "排名",
|
|
165
|
+
]
|
|
166
|
+
table_rows = []
|
|
167
|
+
for dmu_index, dmu_name in enumerate(self.dmu_names):
|
|
168
|
+
interval = (
|
|
169
|
+
f"{round_score(self.confidence_lower[dmu_index]):.{SCORE_DECIMALS}f}"
|
|
170
|
+
f" ~ "
|
|
171
|
+
f"{round_score(self.confidence_upper[dmu_index]):.{SCORE_DECIMALS}f}"
|
|
172
|
+
)
|
|
173
|
+
table_rows.append([
|
|
174
|
+
dmu_name,
|
|
175
|
+
f"{round_score(self.original_scores[dmu_index]):.{SCORE_DECIMALS}f}",
|
|
176
|
+
f"{round_score(self.biases[dmu_index]):.{SCORE_DECIMALS}f}",
|
|
177
|
+
f"{round_score(self.corrected_scores[dmu_index]):.{SCORE_DECIMALS}f}",
|
|
178
|
+
interval,
|
|
179
|
+
str(int(self.ranks[dmu_index])),
|
|
180
|
+
])
|
|
181
|
+
report_lines.append(format_table(table_header, table_rows))
|
|
182
|
+
report_lines.append("")
|
|
183
|
+
|
|
184
|
+
efficient_dmu_names = [self.dmu_names[i] for i in np.flatnonzero(self.efficiency_mask)]
|
|
185
|
+
report_lines.append(
|
|
186
|
+
f"原始有效 DMU(θ = 1)共 {len(efficient_dmu_names)} 个: "
|
|
187
|
+
f"{'、'.join(efficient_dmu_names) if efficient_dmu_names else '无'}"
|
|
188
|
+
)
|
|
189
|
+
average_original = round_score(float(np.mean(self.original_scores)))
|
|
190
|
+
average_corrected = round_score(float(np.mean(self.corrected_scores)))
|
|
191
|
+
report_lines.append(
|
|
192
|
+
f"平均原始得分: {average_original:.{SCORE_DECIMALS}f} | "
|
|
193
|
+
f"平均校正得分: {average_corrected:.{SCORE_DECIMALS}f}"
|
|
194
|
+
)
|
|
195
|
+
report_lines.append(
|
|
196
|
+
"说明: 同质 bootstrap 不处理环境变量或异质前沿;"
|
|
197
|
+
"置信区间为 bootstrap 百分位区间"
|
|
198
|
+
)
|
|
199
|
+
if column_names.undesirable_output_columns:
|
|
200
|
+
report_lines.append("说明: 非期望产出按投入方向处理(越少越好)")
|
|
201
|
+
report_lines.extend(f"提示: {note}" for note in self.notes[:10])
|
|
202
|
+
if len(self.notes) > 10:
|
|
203
|
+
report_lines.append(f"提示: 其余 {len(self.notes) - 10} 条类似提示已省略")
|
|
204
|
+
return "\n".join(report_lines)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
class BootstrapDEAModel:
|
|
208
|
+
"""Simar-Wilson 同质平滑 bootstrap。"""
|
|
209
|
+
|
|
210
|
+
def __init__(self, settings: BootstrapSettings | None = None):
|
|
211
|
+
"""校验并保存 bootstrap 设置。"""
|
|
212
|
+
settings = settings if settings is not None else BootstrapSettings()
|
|
213
|
+
returns_to_scale = settings.returns_to_scale.lower()
|
|
214
|
+
if returns_to_scale not in ("crs", "vrs"):
|
|
215
|
+
raise ValueError("returns_to_scale 只能取 'crs' 或 'vrs'")
|
|
216
|
+
if not isinstance(settings.repetitions, int) or settings.repetitions < 1:
|
|
217
|
+
raise ValueError("repetitions 必须为不小于 1 的整数")
|
|
218
|
+
if not 0 < settings.confidence_level < 1:
|
|
219
|
+
raise ValueError("confidence_level 必须在 (0, 1) 内")
|
|
220
|
+
if (settings.smoothing_bandwidth is not None
|
|
221
|
+
and settings.smoothing_bandwidth < 0):
|
|
222
|
+
raise ValueError("smoothing_bandwidth 必须为非负数或 None")
|
|
223
|
+
if settings.efficiency_tolerance <= 0:
|
|
224
|
+
raise ValueError("efficiency_tolerance 必须为正数")
|
|
225
|
+
self.settings = settings
|
|
226
|
+
self.returns_to_scale = returns_to_scale
|
|
227
|
+
self.repetitions = settings.repetitions
|
|
228
|
+
self.confidence_level = float(settings.confidence_level)
|
|
229
|
+
self.random_seed = settings.random_seed
|
|
230
|
+
self.smoothing_bandwidth = settings.smoothing_bandwidth
|
|
231
|
+
self.efficiency_tolerance = float(settings.efficiency_tolerance)
|
|
232
|
+
|
|
233
|
+
def solve(self, data: DEAData) -> BootstrapDEAResult:
|
|
234
|
+
"""计算原始效率、bootstrap 分布、偏差校正与置信区间。
|
|
235
|
+
|
|
236
|
+
处理逻辑:输入导向径向 DEA 求原始得分 → 平滑重抽样并生成伪样本重估 →
|
|
237
|
+
汇总偏差、偏差校正得分与百分位区间。
|
|
238
|
+
"""
|
|
239
|
+
n_dmus = data.input_matrix.shape[1]
|
|
240
|
+
if n_dmus < 2:
|
|
241
|
+
raise ValueError("Bootstrap DEA 至少需要 2 个 DMU")
|
|
242
|
+
radial_model = self._build_radial_model()
|
|
243
|
+
original_scores = radial_model.solve(data).standard_scores
|
|
244
|
+
bandwidth = self._resolve_bandwidth(original_scores)
|
|
245
|
+
bootstrap_scores = self._generate_bootstrap_scores(
|
|
246
|
+
data, original_scores, radial_model, bandwidth
|
|
247
|
+
)
|
|
248
|
+
return self._summarize_bootstrap(
|
|
249
|
+
data, original_scores, bootstrap_scores, bandwidth
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
def _build_radial_model(self) -> RadialModel:
|
|
253
|
+
"""构造输入导向标准径向 DEA 模型。"""
|
|
254
|
+
return RadialModel(
|
|
255
|
+
orientation="input",
|
|
256
|
+
returns_to_scale=self.returns_to_scale,
|
|
257
|
+
score_mode="standard",
|
|
258
|
+
efficiency_tolerance=self.efficiency_tolerance,
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
def _generate_bootstrap_scores(self, data: DEAData, original_scores: np.ndarray,
|
|
262
|
+
radial_model: RadialModel,
|
|
263
|
+
bandwidth: float) -> np.ndarray:
|
|
264
|
+
"""生成 B 次平滑 bootstrap 的伪样本效率。
|
|
265
|
+
|
|
266
|
+
处理逻辑:每次重复重抽样原始效率 → 平滑、双边反射与方差校正 →
|
|
267
|
+
生成伪数据 → 在伪样本上重估 DEA。
|
|
268
|
+
"""
|
|
269
|
+
n_dmus = len(original_scores)
|
|
270
|
+
rng = np.random.default_rng(self.random_seed)
|
|
271
|
+
variance = float(np.var(original_scores, ddof=1)) if n_dmus > 1 else 0.0
|
|
272
|
+
|
|
273
|
+
bootstrap_scores = np.empty((self.repetitions, n_dmus))
|
|
274
|
+
for repetition in range(self.repetitions):
|
|
275
|
+
resampled_scores = rng.choice(original_scores, size=n_dmus, replace=True)
|
|
276
|
+
if bandwidth > 0:
|
|
277
|
+
drawn_scores = resampled_scores + bandwidth * rng.standard_normal(n_dmus)
|
|
278
|
+
drawn_scores = np.where(drawn_scores > 1.0, 2.0 - drawn_scores, drawn_scores)
|
|
279
|
+
drawn_scores = np.where(drawn_scores < 0.0, -drawn_scores, drawn_scores)
|
|
280
|
+
drawn_scores = np.clip(drawn_scores, 1e-12, 1.0)
|
|
281
|
+
correction = (
|
|
282
|
+
np.sqrt(1.0 + bandwidth ** 2 / variance) if variance > 0 else 1.0
|
|
283
|
+
)
|
|
284
|
+
resampled_mean = float(np.mean(resampled_scores))
|
|
285
|
+
smoothed_scores = resampled_mean + (
|
|
286
|
+
drawn_scores - resampled_mean
|
|
287
|
+
) / correction
|
|
288
|
+
smoothed_scores = np.clip(smoothed_scores, 1e-12, 1.0)
|
|
289
|
+
else:
|
|
290
|
+
smoothed_scores = resampled_scores
|
|
291
|
+
|
|
292
|
+
scaling_factors = original_scores / smoothed_scores
|
|
293
|
+
pseudo_data = DEAData(
|
|
294
|
+
data.dmu_names,
|
|
295
|
+
data.input_matrix * scaling_factors,
|
|
296
|
+
data.desirable_output_matrix,
|
|
297
|
+
data.undesirable_output_matrix * scaling_factors,
|
|
298
|
+
)
|
|
299
|
+
bootstrap_scores[repetition] = radial_model.solve(
|
|
300
|
+
pseudo_data
|
|
301
|
+
).standard_scores
|
|
302
|
+
return bootstrap_scores
|
|
303
|
+
|
|
304
|
+
def _summarize_bootstrap(self, data: DEAData, original_scores: np.ndarray,
|
|
305
|
+
bootstrap_scores: np.ndarray,
|
|
306
|
+
bandwidth: float) -> BootstrapDEAResult:
|
|
307
|
+
"""汇总 bootstrap 偏差、校正得分与置信区间。"""
|
|
308
|
+
n_dmus = len(original_scores)
|
|
309
|
+
bootstrap_means = np.mean(bootstrap_scores, axis=0)
|
|
310
|
+
biases = bootstrap_means - original_scores
|
|
311
|
+
corrected_scores = original_scores - biases
|
|
312
|
+
standard_errors = (
|
|
313
|
+
np.std(bootstrap_scores, axis=0, ddof=1) if self.repetitions > 1
|
|
314
|
+
else np.zeros(n_dmus)
|
|
315
|
+
)
|
|
316
|
+
alpha = (1.0 - self.confidence_level) / 2.0
|
|
317
|
+
confidence_lower = np.quantile(bootstrap_scores, alpha, axis=0)
|
|
318
|
+
confidence_upper = np.quantile(bootstrap_scores, 1.0 - alpha, axis=0)
|
|
319
|
+
efficiency_mask = np.asarray(
|
|
320
|
+
original_scores >= 1.0 - self.efficiency_tolerance, dtype=bool
|
|
321
|
+
)
|
|
322
|
+
ranks = assign_ranks_with_ties(corrected_scores)
|
|
323
|
+
|
|
324
|
+
notes: list[str] = []
|
|
325
|
+
if bandwidth <= 0:
|
|
326
|
+
notes.append("平滑带宽为 0:使用经验 bootstrap(不平滑)")
|
|
327
|
+
if np.any(corrected_scores > 1.0 + self.efficiency_tolerance):
|
|
328
|
+
notes.append("部分偏差校正得分超过 1,这是 bootstrap 校正的已知现象")
|
|
329
|
+
|
|
330
|
+
return BootstrapDEAResult(
|
|
331
|
+
dmu_names=data.dmu_names,
|
|
332
|
+
original_scores=original_scores,
|
|
333
|
+
bootstrap_means=bootstrap_means,
|
|
334
|
+
biases=biases,
|
|
335
|
+
corrected_scores=corrected_scores,
|
|
336
|
+
standard_errors=standard_errors,
|
|
337
|
+
confidence_lower=confidence_lower,
|
|
338
|
+
confidence_upper=confidence_upper,
|
|
339
|
+
efficiency_mask=efficiency_mask,
|
|
340
|
+
ranks=ranks,
|
|
341
|
+
repetitions=self.repetitions,
|
|
342
|
+
confidence_level=self.confidence_level,
|
|
343
|
+
smoothing_bandwidth=bandwidth,
|
|
344
|
+
returns_to_scale=self.returns_to_scale,
|
|
345
|
+
notes=notes,
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
def _resolve_bandwidth(self, scores: np.ndarray) -> float:
|
|
349
|
+
"""解析平滑带宽;None 使用 Silverman 经验规则。
|
|
350
|
+
|
|
351
|
+
处理逻辑:用户给定则使用;否则按 Silverman 规则由样本标准差、
|
|
352
|
+
四分位距与样本量计算。
|
|
353
|
+
"""
|
|
354
|
+
if self.smoothing_bandwidth is not None:
|
|
355
|
+
return float(self.smoothing_bandwidth)
|
|
356
|
+
standard_deviation = float(np.std(scores, ddof=1))
|
|
357
|
+
if standard_deviation <= 0:
|
|
358
|
+
return 0.0
|
|
359
|
+
interquartile_range = float(
|
|
360
|
+
np.quantile(scores, 0.75) - np.quantile(scores, 0.25)
|
|
361
|
+
)
|
|
362
|
+
scale = min(standard_deviation, interquartile_range / 1.34) \
|
|
363
|
+
if interquartile_range > 0 else standard_deviation
|
|
364
|
+
return 0.9 * scale * len(scores) ** (-0.2)
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
368
|
+
argument_parser = argparse.ArgumentParser(
|
|
369
|
+
description="Simar-Wilson Bootstrap DEA(输入导向径向,平滑重抽样);"
|
|
370
|
+
"不带参数时使用脚本配置区",
|
|
371
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
372
|
+
epilog=(
|
|
373
|
+
"示例:\n"
|
|
374
|
+
" python bootstrap_dea.py\n"
|
|
375
|
+
" python bootstrap_dea.py --demo --repetitions 50\n"
|
|
376
|
+
" python bootstrap_dea.py data.xlsx --repetitions 1000 --seed 42\n"
|
|
377
|
+
),
|
|
378
|
+
)
|
|
379
|
+
DATA_COMMAND_LINE.add_arguments(argument_parser)
|
|
380
|
+
argument_parser.add_argument("--returns-to-scale", "--rts",
|
|
381
|
+
choices=("crs", "vrs"), default=None,
|
|
382
|
+
help="规模报酬: crs=不变, vrs=可变;缺省用 RETURNS_TO_SCALE")
|
|
383
|
+
argument_parser.add_argument("--repetitions", type=int, default=None,
|
|
384
|
+
help="bootstrap 重复次数;缺省用 BOOTSTRAP_REPETITIONS")
|
|
385
|
+
argument_parser.add_argument("--confidence", type=float, default=None,
|
|
386
|
+
help="置信区间水平;缺省用 CONFIDENCE_LEVEL")
|
|
387
|
+
argument_parser.add_argument("--seed", type=int, default=None,
|
|
388
|
+
help="随机种子;缺省用 RANDOM_SEED")
|
|
389
|
+
argument_parser.add_argument("--bandwidth", type=float, default=None,
|
|
390
|
+
help="平滑带宽;缺省用 SMOOTHING_BANDWIDTH(None=自动,0=不平滑)")
|
|
391
|
+
argument_parser.add_argument("--tolerance", "--tol", type=float, default=None,
|
|
392
|
+
help=f"判定 θ = 1 的容差(默认 {EFFICIENCY_TOLERANCE})")
|
|
393
|
+
return argument_parser
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
397
|
+
args = build_parser().parse_args(argv)
|
|
398
|
+
try:
|
|
399
|
+
prepared = DATA_COMMAND_LINE.prepare(args)
|
|
400
|
+
returns_to_scale = (
|
|
401
|
+
args.returns_to_scale if args.returns_to_scale is not None
|
|
402
|
+
else RETURNS_TO_SCALE
|
|
403
|
+
)
|
|
404
|
+
repetitions = (
|
|
405
|
+
args.repetitions if args.repetitions is not None
|
|
406
|
+
else BOOTSTRAP_REPETITIONS
|
|
407
|
+
)
|
|
408
|
+
confidence_level = (
|
|
409
|
+
args.confidence if args.confidence is not None else CONFIDENCE_LEVEL
|
|
410
|
+
)
|
|
411
|
+
random_seed = args.seed if args.seed is not None else RANDOM_SEED
|
|
412
|
+
smoothing_bandwidth = (
|
|
413
|
+
args.bandwidth if args.bandwidth is not None
|
|
414
|
+
else SMOOTHING_BANDWIDTH
|
|
415
|
+
)
|
|
416
|
+
efficiency_tolerance = (
|
|
417
|
+
args.tolerance if args.tolerance is not None else EFFICIENCY_TOLERANCE
|
|
418
|
+
)
|
|
419
|
+
model = BootstrapDEAModel(
|
|
420
|
+
BootstrapSettings(
|
|
421
|
+
returns_to_scale=returns_to_scale,
|
|
422
|
+
repetitions=repetitions,
|
|
423
|
+
confidence_level=confidence_level,
|
|
424
|
+
random_seed=random_seed,
|
|
425
|
+
smoothing_bandwidth=smoothing_bandwidth,
|
|
426
|
+
efficiency_tolerance=efficiency_tolerance,
|
|
427
|
+
)
|
|
428
|
+
)
|
|
429
|
+
result = model.solve(prepared.data)
|
|
430
|
+
except (ValueError, RuntimeError) as exc:
|
|
431
|
+
print(f"错误: {exc}", file=sys.stderr)
|
|
432
|
+
return 1
|
|
433
|
+
|
|
434
|
+
print(result.render_report(
|
|
435
|
+
prepared.column_names,
|
|
436
|
+
source_description=prepared.source_description,
|
|
437
|
+
))
|
|
438
|
+
if prepared.result_file:
|
|
439
|
+
try:
|
|
440
|
+
result.write_csv(prepared.result_file)
|
|
441
|
+
except OSError as exc:
|
|
442
|
+
print(f"错误: 无法写入 {prepared.result_file}: {exc}", file=sys.stderr)
|
|
443
|
+
return 1
|
|
444
|
+
print(f"\n结果已写入: {prepared.result_file}")
|
|
445
|
+
return 0
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
if __name__ == "__main__":
|
|
449
|
+
sys.exit(main())
|