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
by_production.py
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""By-production(副产品)DEA:运营效率与环境效率分开建模。
|
|
4
|
+
|
|
5
|
+
模型(Murty–Russell 思路):
|
|
6
|
+
T1(期望产出子技术):全部投入 X → 期望产出 Y,投入导向径向效率 θ1;
|
|
7
|
+
T2(残余生成子技术,简化版):在污染性投入不扩张的约束下,
|
|
8
|
+
最小化非期望产出比率 θ2:
|
|
9
|
+
min θ2
|
|
10
|
+
s.t. P·μ ≤ p_o
|
|
11
|
+
B·μ ≤ θ2·b_o
|
|
12
|
+
Σμ = 1(VRS)
|
|
13
|
+
μ, θ2 ≥ 0
|
|
14
|
+
综合效率 = (θ1 + θ2) / 2。
|
|
15
|
+
|
|
16
|
+
当前使用两个子技术各自独立的强度变量(未加共同投入投影约束),
|
|
17
|
+
污染性投入由配置区 `POLLUTING_INPUT_COLUMNS` 指定。这是 By-production
|
|
18
|
+
思想的简化实现,不是 Murty–Russell 原始模型的完整形式。
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import argparse
|
|
22
|
+
import os
|
|
23
|
+
import sys
|
|
24
|
+
from collections.abc import Sequence
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
|
|
27
|
+
import numpy as np
|
|
28
|
+
|
|
29
|
+
from dea_core import (
|
|
30
|
+
ColumnNames,
|
|
31
|
+
DataCommandLine,
|
|
32
|
+
DataSettings,
|
|
33
|
+
DEAData,
|
|
34
|
+
EFFICIENCY_TOLERANCE,
|
|
35
|
+
SCORE_DECIMALS,
|
|
36
|
+
assign_ranks_with_ties,
|
|
37
|
+
format_table,
|
|
38
|
+
round_score,
|
|
39
|
+
solve_linear_program,
|
|
40
|
+
write_csv_records,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
# =============================== 用户配置区 ===============================
|
|
44
|
+
DATA_FILE = "sample_data.csv"
|
|
45
|
+
EXCEL_SHEET = 0
|
|
46
|
+
|
|
47
|
+
DMU_COLUMNS = ["城市代码", "年份"]
|
|
48
|
+
INPUT_COLUMNS = ["资本投入", "劳动投入"]
|
|
49
|
+
POLLUTING_INPUT_COLUMNS = ["资本投入"]
|
|
50
|
+
DESIRABLE_OUTPUT_COLUMNS = ["GDP", "财政收入"]
|
|
51
|
+
UNDESIRABLE_OUTPUT_COLUMNS = ["工业废水排放量"]
|
|
52
|
+
|
|
53
|
+
RETURNS_TO_SCALE = "vrs" # "crs" 或 "vrs"
|
|
54
|
+
RESULT_FILE = None # 结果 CSV 输出路径;None 表示不导出
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
DATA_COMMAND_LINE = DataCommandLine(
|
|
58
|
+
settings=DataSettings(
|
|
59
|
+
data_file=DATA_FILE,
|
|
60
|
+
excel_sheet=EXCEL_SHEET,
|
|
61
|
+
dmu_columns=tuple(DMU_COLUMNS),
|
|
62
|
+
input_columns=tuple(INPUT_COLUMNS),
|
|
63
|
+
desirable_output_columns=tuple(DESIRABLE_OUTPUT_COLUMNS),
|
|
64
|
+
undesirable_output_columns=tuple(UNDESIRABLE_OUTPUT_COLUMNS),
|
|
65
|
+
result_file=RESULT_FILE,
|
|
66
|
+
),
|
|
67
|
+
script_directory=os.path.dirname(os.path.abspath(__file__)),
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class ByProductionResult:
|
|
73
|
+
"""By-production 结果。"""
|
|
74
|
+
|
|
75
|
+
dmu_names: list[str]
|
|
76
|
+
operational_scores: np.ndarray
|
|
77
|
+
environmental_scores: np.ndarray
|
|
78
|
+
overall_scores: np.ndarray
|
|
79
|
+
efficiency_mask: np.ndarray
|
|
80
|
+
ranks: np.ndarray
|
|
81
|
+
returns_to_scale: str
|
|
82
|
+
notes: list[str] = field(default_factory=list)
|
|
83
|
+
|
|
84
|
+
def to_records(self) -> list[dict[str, object]]:
|
|
85
|
+
"""把每个 DMU 展开成一条 CSV 记录。"""
|
|
86
|
+
records = []
|
|
87
|
+
for dmu_index, dmu_name in enumerate(self.dmu_names):
|
|
88
|
+
records.append({
|
|
89
|
+
"dmu": dmu_name,
|
|
90
|
+
"operational_score": round_score(self.operational_scores[dmu_index]),
|
|
91
|
+
"environmental_score": round_score(
|
|
92
|
+
self.environmental_scores[dmu_index]
|
|
93
|
+
),
|
|
94
|
+
"overall_score": round_score(self.overall_scores[dmu_index]),
|
|
95
|
+
"efficient": int(self.efficiency_mask[dmu_index]),
|
|
96
|
+
"rank": int(self.ranks[dmu_index]),
|
|
97
|
+
})
|
|
98
|
+
return records
|
|
99
|
+
|
|
100
|
+
def write_csv(self, path: str) -> None:
|
|
101
|
+
"""写出 UTF-8-BOM 编码的结果 CSV。"""
|
|
102
|
+
write_csv_records(path, self.to_records())
|
|
103
|
+
|
|
104
|
+
def render_report(self, column_names: ColumnNames,
|
|
105
|
+
source_description: str | None = None) -> str:
|
|
106
|
+
"""生成控制台报表文本。"""
|
|
107
|
+
returns_to_scale_description = (
|
|
108
|
+
"CRS 规模报酬不变" if self.returns_to_scale == "crs" else "VRS 规模报酬可变"
|
|
109
|
+
)
|
|
110
|
+
report_lines = [
|
|
111
|
+
f"模型: By-production DEA | {returns_to_scale_description}"
|
|
112
|
+
]
|
|
113
|
+
if source_description:
|
|
114
|
+
report_lines.append(f"数据: {source_description}")
|
|
115
|
+
report_lines.append(
|
|
116
|
+
f"投入: {'、'.join(column_names.input_columns)} | "
|
|
117
|
+
f"污染性投入: 见配置区 POLLUTING_INPUT_COLUMNS | "
|
|
118
|
+
f"期望产出: {'、'.join(column_names.desirable_output_columns)} | "
|
|
119
|
+
f"非期望产出: {'、'.join(column_names.undesirable_output_columns)}"
|
|
120
|
+
)
|
|
121
|
+
report_lines.append(f"DMU 数: {len(self.dmu_names)}")
|
|
122
|
+
report_lines.append("")
|
|
123
|
+
|
|
124
|
+
table_rows = []
|
|
125
|
+
for dmu_index, dmu_name in enumerate(self.dmu_names):
|
|
126
|
+
table_rows.append([
|
|
127
|
+
dmu_name,
|
|
128
|
+
f"{round_score(self.operational_scores[dmu_index]):.{SCORE_DECIMALS}f}",
|
|
129
|
+
f"{round_score(self.environmental_scores[dmu_index]):.{SCORE_DECIMALS}f}",
|
|
130
|
+
f"{round_score(self.overall_scores[dmu_index]):.{SCORE_DECIMALS}f}",
|
|
131
|
+
str(int(self.ranks[dmu_index])),
|
|
132
|
+
])
|
|
133
|
+
report_lines.append(format_table(
|
|
134
|
+
["DMU", "运营效率", "环境效率", "综合效率", "排名"], table_rows
|
|
135
|
+
))
|
|
136
|
+
report_lines.append("")
|
|
137
|
+
efficient_names = [self.dmu_names[i] for i in np.flatnonzero(self.efficiency_mask)]
|
|
138
|
+
report_lines.append(
|
|
139
|
+
f"综合有效 DMU 共 {len(efficient_names)} 个: "
|
|
140
|
+
f"{'、'.join(efficient_names) if efficient_names else '无'}"
|
|
141
|
+
)
|
|
142
|
+
report_lines.append("说明: 综合效率 = (运营效率 + 环境效率) / 2")
|
|
143
|
+
return "\n".join(report_lines)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class ByProductionModel:
|
|
147
|
+
"""By-production DEA 求解器。"""
|
|
148
|
+
|
|
149
|
+
def __init__(self, polluting_input_indices: Sequence[int],
|
|
150
|
+
returns_to_scale: str = "vrs",
|
|
151
|
+
efficiency_tolerance: float = EFFICIENCY_TOLERANCE):
|
|
152
|
+
if not polluting_input_indices:
|
|
153
|
+
raise ValueError("By-production 需要至少一个污染性投入")
|
|
154
|
+
returns_to_scale = returns_to_scale.lower()
|
|
155
|
+
if returns_to_scale not in ("crs", "vrs"):
|
|
156
|
+
raise ValueError("returns_to_scale 只能取 'crs' 或 'vrs'")
|
|
157
|
+
if efficiency_tolerance <= 0:
|
|
158
|
+
raise ValueError("efficiency_tolerance 必须为正数")
|
|
159
|
+
self.polluting_input_indices = list(polluting_input_indices)
|
|
160
|
+
self.returns_to_scale = returns_to_scale
|
|
161
|
+
self.efficiency_tolerance = float(efficiency_tolerance)
|
|
162
|
+
|
|
163
|
+
def solve(self, data: DEAData) -> ByProductionResult:
|
|
164
|
+
"""求解运营效率、环境效率与综合效率。"""
|
|
165
|
+
if data.undesirable_output_matrix.shape[0] == 0:
|
|
166
|
+
raise ValueError("By-production 至少需要 1 个非期望产出列")
|
|
167
|
+
if any(
|
|
168
|
+
index < 0 or index >= data.input_matrix.shape[0]
|
|
169
|
+
for index in self.polluting_input_indices
|
|
170
|
+
):
|
|
171
|
+
raise ValueError("污染性投入下标超出投入矩阵范围")
|
|
172
|
+
X = data.input_matrix
|
|
173
|
+
Y = data.desirable_output_matrix
|
|
174
|
+
B = data.undesirable_output_matrix
|
|
175
|
+
P = X[self.polluting_input_indices]
|
|
176
|
+
n_dmus = X.shape[1]
|
|
177
|
+
operational = np.empty(n_dmus)
|
|
178
|
+
environmental = np.empty(n_dmus)
|
|
179
|
+
for dmu_index in range(n_dmus):
|
|
180
|
+
operational[dmu_index] = self._operational_score(X, Y, dmu_index)
|
|
181
|
+
environmental[dmu_index] = self._environmental_score(P, B, dmu_index)
|
|
182
|
+
overall = 0.5 * (operational + environmental)
|
|
183
|
+
efficiency_mask = np.asarray(
|
|
184
|
+
overall >= 1.0 - self.efficiency_tolerance, dtype=bool
|
|
185
|
+
)
|
|
186
|
+
return ByProductionResult(
|
|
187
|
+
dmu_names=data.dmu_names,
|
|
188
|
+
operational_scores=operational,
|
|
189
|
+
environmental_scores=environmental,
|
|
190
|
+
overall_scores=overall,
|
|
191
|
+
efficiency_mask=efficiency_mask,
|
|
192
|
+
ranks=assign_ranks_with_ties(overall),
|
|
193
|
+
returns_to_scale=self.returns_to_scale,
|
|
194
|
+
notes=[],
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
def _operational_score(self, X: np.ndarray, Y: np.ndarray,
|
|
198
|
+
dmu_index: int) -> float:
|
|
199
|
+
"""T1:投入导向径向效率。"""
|
|
200
|
+
n_inputs, n_dmus = X.shape
|
|
201
|
+
n_outputs = Y.shape[0]
|
|
202
|
+
n_variables = n_dmus + 1
|
|
203
|
+
theta_column = n_dmus
|
|
204
|
+
objective = np.zeros(n_variables)
|
|
205
|
+
objective[theta_column] = 1.0
|
|
206
|
+
inequality = np.zeros((n_inputs + n_outputs, n_variables))
|
|
207
|
+
inequality[:n_inputs, :n_dmus] = X
|
|
208
|
+
inequality[:n_inputs, theta_column] = -X[:, dmu_index]
|
|
209
|
+
inequality[n_inputs:, :n_dmus] = -Y
|
|
210
|
+
rhs = np.zeros(n_inputs + n_outputs)
|
|
211
|
+
rhs[n_inputs:] = -Y[:, dmu_index]
|
|
212
|
+
equality_matrix, equality_rhs = self._convexity(n_variables, n_dmus)
|
|
213
|
+
solution = solve_linear_program(
|
|
214
|
+
objective,
|
|
215
|
+
inequality_matrix=inequality, inequality_rhs=rhs,
|
|
216
|
+
equality_matrix=equality_matrix, equality_rhs=equality_rhs,
|
|
217
|
+
error_context=f"By-production 运营效率求解失败(第 {dmu_index + 1} 个 DMU)",
|
|
218
|
+
)
|
|
219
|
+
return float(solution.x[theta_column])
|
|
220
|
+
|
|
221
|
+
def _environmental_score(self, P: np.ndarray, B: np.ndarray,
|
|
222
|
+
dmu_index: int) -> float:
|
|
223
|
+
"""T2(简化):污染性投入不扩张下最小化非期望产出比率。"""
|
|
224
|
+
n_polluting, n_dmus = P.shape
|
|
225
|
+
n_bad = B.shape[0]
|
|
226
|
+
n_variables = n_dmus + 1
|
|
227
|
+
theta_column = n_dmus
|
|
228
|
+
objective = np.zeros(n_variables)
|
|
229
|
+
objective[theta_column] = 1.0
|
|
230
|
+
n_constraints = n_polluting + n_bad
|
|
231
|
+
inequality = np.zeros((n_constraints, n_variables))
|
|
232
|
+
inequality[:n_polluting, :n_dmus] = P
|
|
233
|
+
inequality[n_polluting:, :n_dmus] = B
|
|
234
|
+
inequality[n_polluting:, theta_column] = -B[:, dmu_index]
|
|
235
|
+
inequality_rhs = np.zeros(n_constraints)
|
|
236
|
+
inequality_rhs[:n_polluting] = P[:, dmu_index]
|
|
237
|
+
equality_matrix, equality_rhs = self._convexity(n_variables, n_dmus)
|
|
238
|
+
solution = solve_linear_program(
|
|
239
|
+
objective,
|
|
240
|
+
inequality_matrix=inequality, inequality_rhs=inequality_rhs,
|
|
241
|
+
equality_matrix=equality_matrix, equality_rhs=equality_rhs,
|
|
242
|
+
error_context=f"By-production 环境效率求解失败(第 {dmu_index + 1} 个 DMU)",
|
|
243
|
+
)
|
|
244
|
+
return float(solution.x[theta_column])
|
|
245
|
+
|
|
246
|
+
def _convexity(self, n_variables: int, n_dmus: int
|
|
247
|
+
) -> tuple[np.ndarray | None, np.ndarray | None]:
|
|
248
|
+
"""构造 VRS 凸性约束。"""
|
|
249
|
+
if self.returns_to_scale == "crs":
|
|
250
|
+
return None, None
|
|
251
|
+
equality = np.zeros((1, n_variables))
|
|
252
|
+
equality[0, :n_dmus] = 1.0
|
|
253
|
+
return equality, np.array([1.0])
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
257
|
+
argument_parser = argparse.ArgumentParser(
|
|
258
|
+
description="By-production DEA(运营效率 + 环境效率);"
|
|
259
|
+
"不带参数时使用脚本配置区",
|
|
260
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
261
|
+
epilog=(
|
|
262
|
+
"示例:\n"
|
|
263
|
+
" python by_production.py --demo\n"
|
|
264
|
+
" python by_production.py data.xlsx --polluting-input-columns 资本投入\n"
|
|
265
|
+
),
|
|
266
|
+
)
|
|
267
|
+
DATA_COMMAND_LINE.add_arguments(argument_parser)
|
|
268
|
+
argument_parser.add_argument("--polluting-input-columns", nargs="+",
|
|
269
|
+
metavar="列名", default=None,
|
|
270
|
+
help="污染性投入列;缺省用 POLLUTING_INPUT_COLUMNS")
|
|
271
|
+
argument_parser.add_argument("--returns-to-scale", "--rts",
|
|
272
|
+
choices=("crs", "vrs"), default=None,
|
|
273
|
+
help="规模报酬: crs=不变, vrs=可变;缺省用 RETURNS_TO_SCALE")
|
|
274
|
+
argument_parser.add_argument("--tolerance", "--tol", type=float, default=None,
|
|
275
|
+
help=f"判定有效性的容差(默认 {EFFICIENCY_TOLERANCE})")
|
|
276
|
+
return argument_parser
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
280
|
+
args = build_parser().parse_args(argv)
|
|
281
|
+
try:
|
|
282
|
+
prepared = DATA_COMMAND_LINE.prepare(args)
|
|
283
|
+
polluting_names = (
|
|
284
|
+
args.polluting_input_columns
|
|
285
|
+
if args.polluting_input_columns is not None
|
|
286
|
+
else POLLUTING_INPUT_COLUMNS
|
|
287
|
+
)
|
|
288
|
+
input_columns = list(prepared.column_names.input_columns)
|
|
289
|
+
try:
|
|
290
|
+
polluting_indices = [input_columns.index(name) for name in polluting_names]
|
|
291
|
+
except ValueError as exc:
|
|
292
|
+
raise ValueError(f"污染性投入列不在投入列中: {exc}") from exc
|
|
293
|
+
returns_to_scale = (
|
|
294
|
+
args.returns_to_scale if args.returns_to_scale is not None
|
|
295
|
+
else RETURNS_TO_SCALE
|
|
296
|
+
)
|
|
297
|
+
efficiency_tolerance = (
|
|
298
|
+
args.tolerance if args.tolerance is not None else EFFICIENCY_TOLERANCE
|
|
299
|
+
)
|
|
300
|
+
polluting_input_indices = polluting_indices
|
|
301
|
+
model = ByProductionModel(
|
|
302
|
+
polluting_input_indices,
|
|
303
|
+
returns_to_scale=returns_to_scale,
|
|
304
|
+
efficiency_tolerance=efficiency_tolerance,
|
|
305
|
+
)
|
|
306
|
+
result = model.solve(prepared.data)
|
|
307
|
+
except (ValueError, RuntimeError) as exc:
|
|
308
|
+
print(f"错误: {exc}", file=sys.stderr)
|
|
309
|
+
return 1
|
|
310
|
+
|
|
311
|
+
print(result.render_report(
|
|
312
|
+
prepared.column_names,
|
|
313
|
+
source_description=prepared.source_description,
|
|
314
|
+
))
|
|
315
|
+
if prepared.result_file:
|
|
316
|
+
try:
|
|
317
|
+
result.write_csv(prepared.result_file)
|
|
318
|
+
except OSError as exc:
|
|
319
|
+
print(f"错误: 无法写入 {prepared.result_file}: {exc}", file=sys.stderr)
|
|
320
|
+
return 1
|
|
321
|
+
print(f"\n结果已写入: {prepared.result_file}")
|
|
322
|
+
return 0
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
if __name__ == "__main__":
|
|
326
|
+
sys.exit(main())
|