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,313 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """权重约束(Assurance Region)CCR 乘数模型。
4
+
5
+ 对每个 DMU o:
6
+ max Σ_r u_r·Y_ro
7
+ s.t. Σ_i v_i·X_io = 1
8
+ Σ_r u_r·Y_rj - Σ_i v_i·X_ij ≤ 0(所有 j)
9
+ u, v ≥ 0
10
+ 可选的保证域(Assurance Region)约束以第一项指标为基准:
11
+ L_i ≤ v_i/v_1 ≤ U_i, L_r ≤ u_r/u_1 ≤ U_r
12
+ 分别加入
13
+ v_i - U_i·v_1 ≤ 0, L_i·v_1 - v_i ≤ 0
14
+ 以及产出侧的同类约束。当前为 CRS 乘数模型,不处理非期望产出。
15
+ """
16
+
17
+ import argparse
18
+ import os
19
+ import sys
20
+ from collections.abc import Sequence
21
+ from dataclasses import dataclass, field
22
+
23
+ import numpy as np
24
+
25
+ from dea_core import (
26
+ ColumnNames,
27
+ DataCommandLine,
28
+ DataSettings,
29
+ DEAData,
30
+ EFFICIENCY_TOLERANCE,
31
+ SCORE_DECIMALS,
32
+ assign_ranks_with_ties,
33
+ format_table,
34
+ round_score,
35
+ solve_linear_program,
36
+ write_csv_records,
37
+ )
38
+
39
+ # =============================== 用户配置区 ===============================
40
+ DATA_FILE = "sample_data.csv"
41
+ EXCEL_SHEET = 0
42
+
43
+ DMU_COLUMNS = ["城市代码", "年份"]
44
+ INPUT_COLUMNS = ["资本投入", "劳动投入"]
45
+ DESIRABLE_OUTPUT_COLUMNS = ["GDP", "财政收入"]
46
+ UNDESIRABLE_OUTPUT_COLUMNS = [] # 权重约束模型当前不处理非期望产出
47
+
48
+ # 权重比例保证域:每项指标对应一个 None 或 (lower, upper),相对第一项指标。
49
+ # 例如 [None, (0.5, 2.0)] 表示 v2/v1 ∈ [0.5, 2.0];None 表示不限制。
50
+ INPUT_WEIGHT_BOUNDS = [None, (0.5, 2.0)]
51
+ OUTPUT_WEIGHT_BOUNDS = [None, (0.5, 2.0)]
52
+
53
+ RESULT_FILE = None # 结果 CSV 输出路径;None 表示不导出
54
+
55
+
56
+ DATA_COMMAND_LINE = DataCommandLine(
57
+ settings=DataSettings(
58
+ data_file=DATA_FILE,
59
+ excel_sheet=EXCEL_SHEET,
60
+ dmu_columns=tuple(DMU_COLUMNS),
61
+ input_columns=tuple(INPUT_COLUMNS),
62
+ desirable_output_columns=tuple(DESIRABLE_OUTPUT_COLUMNS),
63
+ undesirable_output_columns=tuple(UNDESIRABLE_OUTPUT_COLUMNS),
64
+ result_file=RESULT_FILE,
65
+ ),
66
+ script_directory=os.path.dirname(os.path.abspath(__file__)),
67
+ )
68
+
69
+
70
+ @dataclass
71
+ class WeightRestrictedResult:
72
+ """权重约束 CCR 结果。"""
73
+
74
+ dmu_names: list[str]
75
+ scores: np.ndarray
76
+ efficiency_mask: np.ndarray
77
+ ranks: np.ndarray
78
+ notes: list[str] = field(default_factory=list)
79
+
80
+ def to_records(self) -> list[dict[str, object]]:
81
+ """把每个 DMU 展开成一条 CSV 记录。"""
82
+ return [
83
+ {
84
+ "dmu": dmu_name,
85
+ "score": round_score(self.scores[index]),
86
+ "efficient": int(self.efficiency_mask[index]),
87
+ "rank": int(self.ranks[index]),
88
+ }
89
+ for index, dmu_name in enumerate(self.dmu_names)
90
+ ]
91
+
92
+ def write_csv(self, path: str) -> None:
93
+ """写出 UTF-8-BOM 编码的结果 CSV。"""
94
+ write_csv_records(path, self.to_records())
95
+
96
+ def render_report(self, column_names: ColumnNames,
97
+ source_description: str | None = None) -> str:
98
+ """生成控制台报表文本。"""
99
+ report_lines = ["模型: 权重约束 CCR(Assurance Region 乘数模型) | CRS"]
100
+ if source_description:
101
+ report_lines.append(f"数据: {source_description}")
102
+ report_lines.append(
103
+ f"投入: {'、'.join(column_names.input_columns)} | "
104
+ f"期望产出: {'、'.join(column_names.desirable_output_columns)}"
105
+ )
106
+ report_lines.append(f"DMU 数: {len(self.dmu_names)}")
107
+ report_lines.append("")
108
+
109
+ table_rows = [
110
+ [
111
+ dmu_name,
112
+ f"{round_score(self.scores[index]):.{SCORE_DECIMALS}f}",
113
+ str(int(self.ranks[index])),
114
+ ]
115
+ for index, dmu_name in enumerate(self.dmu_names)
116
+ ]
117
+ report_lines.append(format_table(["DMU", "得分", "排名"], table_rows))
118
+ report_lines.append("")
119
+ efficient_names = [self.dmu_names[i] for i in np.flatnonzero(self.efficiency_mask)]
120
+ report_lines.append(
121
+ f"有效 DMU 共 {len(efficient_names)} 个: "
122
+ f"{'、'.join(efficient_names) if efficient_names else '无'}"
123
+ )
124
+ report_lines.append(
125
+ "说明: 权重比例上下界以第一项指标为基准;当前为 CRS 乘数模型"
126
+ )
127
+ report_lines.extend(f"提示: {note}" for note in self.notes[:10])
128
+ return "\n".join(report_lines)
129
+
130
+
131
+ class WeightRestrictedModel:
132
+ """权重约束 CCR 求解器。"""
133
+
134
+ def __init__(self, input_weight_bounds: Sequence[tuple[float, float] | None],
135
+ output_weight_bounds: Sequence[tuple[float, float] | None],
136
+ efficiency_tolerance: float = EFFICIENCY_TOLERANCE):
137
+ if efficiency_tolerance <= 0:
138
+ raise ValueError("efficiency_tolerance 必须为正数")
139
+ self.input_weight_bounds = list(input_weight_bounds)
140
+ self.output_weight_bounds = list(output_weight_bounds)
141
+ self.efficiency_tolerance = float(efficiency_tolerance)
142
+ self._validate_bounds(self.input_weight_bounds, "投入权重界")
143
+ self._validate_bounds(self.output_weight_bounds, "产出权重界")
144
+
145
+ @staticmethod
146
+ def _validate_bounds(bounds: Sequence[tuple[float, float] | None],
147
+ label: str) -> None:
148
+ """校验比例界:非负且 lower ≤ upper。"""
149
+ for lower_upper in bounds:
150
+ if lower_upper is None:
151
+ continue
152
+ lower, upper = lower_upper
153
+ if lower < 0 or upper < lower:
154
+ raise ValueError(f"{label}必须满足 0 ≤ lower ≤ upper")
155
+
156
+ def solve(self, data: DEAData) -> WeightRestrictedResult:
157
+ """求解所有 DMU 的权重约束 CCR 模型。"""
158
+ X = data.input_matrix
159
+ Y = data.desirable_output_matrix
160
+ n_dmus = X.shape[1]
161
+ n_inputs = X.shape[0]
162
+ n_outputs = Y.shape[0]
163
+ if len(self.input_weight_bounds) != n_inputs:
164
+ raise ValueError(
165
+ f"投入权重界数量 ({len(self.input_weight_bounds)}) 与投入数 ({n_inputs}) 不一致"
166
+ )
167
+ if len(self.output_weight_bounds) != n_outputs:
168
+ raise ValueError(
169
+ f"产出权重界数量 ({len(self.output_weight_bounds)}) 与产出数 ({n_outputs}) 不一致"
170
+ )
171
+
172
+ scores = np.empty(n_dmus)
173
+ notes: list[str] = []
174
+ for dmu_index in range(n_dmus):
175
+ scores[dmu_index] = self._solve_dmu(X, Y, dmu_index)
176
+ efficiency_mask = np.asarray(
177
+ scores >= 1.0 - self.efficiency_tolerance, dtype=bool
178
+ )
179
+ if data.undesirable_output_matrix.shape[0]:
180
+ notes.append("权重约束模型暂未纳入非期望产出;当前期非期望产出已被忽略")
181
+ return WeightRestrictedResult(
182
+ dmu_names=data.dmu_names,
183
+ scores=scores,
184
+ efficiency_mask=efficiency_mask,
185
+ ranks=assign_ranks_with_ties(scores),
186
+ notes=notes,
187
+ )
188
+
189
+ def _solve_dmu(self, X: np.ndarray, Y: np.ndarray, dmu_index: int) -> float:
190
+ """求解单个 DMU 的权重约束 CCR。"""
191
+ n_inputs, n_dmus = X.shape
192
+ n_outputs = Y.shape[0]
193
+ n_variables = n_inputs + n_outputs
194
+ v_slice = slice(0, n_inputs)
195
+ u_slice = slice(n_inputs, n_variables)
196
+
197
+ objective = np.zeros(n_variables)
198
+ objective[u_slice] = -Y[:, dmu_index]
199
+ equality_matrix = np.zeros((1, n_variables))
200
+ equality_matrix[0, v_slice] = X[:, dmu_index]
201
+ equality_rhs = np.array([1.0])
202
+ inequality_rows = []
203
+ inequality_rhs = []
204
+
205
+ for dmu in range(n_dmus):
206
+ row = np.zeros(n_variables)
207
+ row[v_slice] = -X[:, dmu]
208
+ row[u_slice] = Y[:, dmu]
209
+ inequality_rows.append(row)
210
+ inequality_rhs.append(0.0)
211
+
212
+ self._append_assurance_rows(
213
+ inequality_rows, inequality_rhs, self.input_weight_bounds,
214
+ n_variables, offset=0,
215
+ )
216
+ self._append_assurance_rows(
217
+ inequality_rows, inequality_rhs, self.output_weight_bounds,
218
+ n_variables, offset=n_inputs,
219
+ )
220
+
221
+ solution = solve_linear_program(
222
+ objective,
223
+ inequality_matrix=np.asarray(inequality_rows),
224
+ inequality_rhs=np.asarray(inequality_rhs),
225
+ equality_matrix=equality_matrix, equality_rhs=equality_rhs,
226
+ error_context=f"权重约束 CCR 求解失败(第 {dmu_index + 1} 个 DMU)",
227
+ )
228
+ return -float(solution.fun)
229
+
230
+ @staticmethod
231
+ def _append_assurance_rows(rows: list[np.ndarray], rhs: list[float],
232
+ bounds: Sequence[tuple[float, float] | None],
233
+ n_variables: int, offset: int) -> None:
234
+ """添加相对第一项指标的上下界约束。"""
235
+ if not bounds or (len(bounds) > 0 and all(bound is None for bound in bounds)):
236
+ return
237
+ base_index = offset
238
+ for index, lower_upper in enumerate(bounds):
239
+ if index == 0 or lower_upper is None:
240
+ continue
241
+ lower, upper = lower_upper
242
+ variable_index = offset + index
243
+ upper_row = np.zeros(n_variables)
244
+ upper_row[variable_index] = 1.0
245
+ upper_row[base_index] = -upper
246
+ rows.append(upper_row)
247
+ rhs.append(0.0)
248
+ lower_row = np.zeros(n_variables)
249
+ lower_row[variable_index] = -1.0
250
+ lower_row[base_index] = lower
251
+ rows.append(lower_row)
252
+ rhs.append(0.0)
253
+
254
+
255
+ def build_parser() -> argparse.ArgumentParser:
256
+ argument_parser = argparse.ArgumentParser(
257
+ description="权重约束 CCR(Assurance Region);当前权重界在配置区设置",
258
+ formatter_class=argparse.RawDescriptionHelpFormatter,
259
+ epilog=(
260
+ "示例:\n"
261
+ " python weight_restricted_dea.py --demo\n"
262
+ " python weight_restricted_dea.py data.xlsx\n"
263
+ ),
264
+ )
265
+ DATA_COMMAND_LINE.add_arguments(argument_parser)
266
+ argument_parser.add_argument("--tolerance", "--tol", type=float, default=None,
267
+ help=f"判定有效性的容差(默认 {EFFICIENCY_TOLERANCE})")
268
+ return argument_parser
269
+
270
+
271
+ def main(argv: Sequence[str] | None = None) -> int:
272
+ args = build_parser().parse_args(argv)
273
+ try:
274
+ prepared = DATA_COMMAND_LINE.prepare(args)
275
+ efficiency_tolerance = (
276
+ args.tolerance if args.tolerance is not None else EFFICIENCY_TOLERANCE
277
+ )
278
+ input_bounds = [
279
+ None if bound is None else (float(bound[0]), float(bound[1]))
280
+ for bound in INPUT_WEIGHT_BOUNDS
281
+ ]
282
+ output_bounds = [
283
+ None if bound is None else (float(bound[0]), float(bound[1]))
284
+ for bound in OUTPUT_WEIGHT_BOUNDS
285
+ ]
286
+ input_weight_bounds = input_bounds
287
+ output_weight_bounds = output_bounds
288
+ model = WeightRestrictedModel(
289
+ input_weight_bounds,
290
+ output_weight_bounds,
291
+ efficiency_tolerance=efficiency_tolerance,
292
+ )
293
+ result = model.solve(prepared.data)
294
+ except (ValueError, RuntimeError) as exc:
295
+ print(f"错误: {exc}", file=sys.stderr)
296
+ return 1
297
+
298
+ print(result.render_report(
299
+ prepared.column_names,
300
+ source_description=prepared.source_description,
301
+ ))
302
+ if prepared.result_file:
303
+ try:
304
+ result.write_csv(prepared.result_file)
305
+ except OSError as exc:
306
+ print(f"错误: 无法写入 {prepared.result_file}: {exc}", file=sys.stderr)
307
+ return 1
308
+ print(f"\n结果已写入: {prepared.result_file}")
309
+ return 0
310
+
311
+
312
+ if __name__ == "__main__":
313
+ sys.exit(main())
window_analysis.py ADDED
@@ -0,0 +1,330 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """窗口分析(Window Analysis)DEA 脚本。
4
+
5
+ 方法:
6
+ 1. 按时间顺序滑动宽度为 w 的窗口;
7
+ 2. 每个窗口内把所有实体-期别观测作为 DMU,计算投入导向径向 DEA;
8
+ 3. 同一观测在多个窗口中的得分取平均,得到窗口分析效率。
9
+
10
+ 模型(投入导向径向,CRS/VRS):
11
+ min θ
12
+ s.t. X_ref·λ ≤ θ·x_o
13
+ Y_ref·λ ≥ y_o
14
+ λ ≥ 0(VRS 加 Σλ = 1)
15
+ 非期望产出按投入方向并入投入块(越少越好)。
16
+ """
17
+
18
+ import argparse
19
+ import os
20
+ import sys
21
+ from collections.abc import Sequence
22
+ from dataclasses import dataclass, field
23
+
24
+ import numpy as np
25
+
26
+ from dea_core import (
27
+ ColumnNames,
28
+ DataCommandLine,
29
+ DataSettings,
30
+ DEAData,
31
+ EFFICIENCY_TOLERANCE,
32
+ SCORE_DECIMALS,
33
+ assign_ranks_with_ties,
34
+ format_table,
35
+ round_score,
36
+ solve_linear_program,
37
+ write_csv_records,
38
+ )
39
+
40
+ # =============================== 用户配置区 ===============================
41
+ DATA_FILE = "sample_data.csv"
42
+ EXCEL_SHEET = 0
43
+
44
+ DMU_COLUMNS = ["城市代码", "年份"]
45
+ PERIOD_COLUMN = "年份"
46
+ ENTITY_COLUMNS = ["城市代码"]
47
+ INPUT_COLUMNS = ["资本投入", "劳动投入"]
48
+ DESIRABLE_OUTPUT_COLUMNS = ["GDP", "财政收入"]
49
+ UNDESIRABLE_OUTPUT_COLUMNS = ["工业废水排放量"]
50
+
51
+ WINDOW_WIDTH = 3 # 窗口宽度(期数)
52
+ RETURNS_TO_SCALE = "crs" # "crs" 或 "vrs"
53
+ RESULT_FILE = None # 结果 CSV 输出路径;None 表示不导出
54
+
55
+
56
+ DATA_COMMAND_LINE = DataCommandLine(
57
+ settings=DataSettings(
58
+ data_file=DATA_FILE,
59
+ excel_sheet=EXCEL_SHEET,
60
+ dmu_columns=tuple(DMU_COLUMNS),
61
+ input_columns=tuple(INPUT_COLUMNS),
62
+ desirable_output_columns=tuple(DESIRABLE_OUTPUT_COLUMNS),
63
+ undesirable_output_columns=tuple(UNDESIRABLE_OUTPUT_COLUMNS),
64
+ period_column=PERIOD_COLUMN,
65
+ entity_columns=tuple(ENTITY_COLUMNS),
66
+ result_file=RESULT_FILE,
67
+ ),
68
+ script_directory=os.path.dirname(os.path.abspath(__file__)),
69
+ )
70
+
71
+
72
+ @dataclass
73
+ class WindowAnalysisResult:
74
+ """窗口分析结果。"""
75
+
76
+ dmu_names: list[str]
77
+ entities: list[str]
78
+ periods: list[str]
79
+ average_scores: np.ndarray
80
+ window_counts: np.ndarray
81
+ ranks: np.ndarray
82
+ efficiency_mask: np.ndarray
83
+ returns_to_scale: str
84
+ window_width: int
85
+ notes: list[str] = field(default_factory=list)
86
+
87
+ def to_records(self) -> list[dict[str, object]]:
88
+ """把每个观测展开成一条 CSV 记录。"""
89
+ records = []
90
+ for index, dmu_name in enumerate(self.dmu_names):
91
+ records.append({
92
+ "dmu": dmu_name,
93
+ "entity": self.entities[index],
94
+ "period": self.periods[index],
95
+ "average_score": round_score(self.average_scores[index]),
96
+ "window_count": int(self.window_counts[index]),
97
+ "efficient": int(self.efficiency_mask[index]),
98
+ "rank": int(self.ranks[index]),
99
+ })
100
+ return records
101
+
102
+ def write_csv(self, path: str) -> None:
103
+ """写出 UTF-8-BOM 编码的结果 CSV。"""
104
+ write_csv_records(path, self.to_records())
105
+
106
+ def render_report(self, column_names: ColumnNames,
107
+ source_description: str | None = None) -> str:
108
+ """生成控制台报表文本。"""
109
+ returns_to_scale_description = (
110
+ "CRS 规模报酬不变" if self.returns_to_scale == "crs" else "VRS 规模报酬可变"
111
+ )
112
+ report_lines = [
113
+ f"模型: 窗口分析 Window Analysis | 宽度 {self.window_width} | "
114
+ f"{returns_to_scale_description}"
115
+ ]
116
+ if source_description:
117
+ report_lines.append(f"数据: {source_description}")
118
+ report_lines.append(
119
+ f"变量: 投入[{'、'.join(column_names.input_columns)}] | "
120
+ f"期望产出[{'、'.join(column_names.desirable_output_columns)}] | "
121
+ f"非期望产出[{'、'.join(column_names.undesirable_output_columns) or '无'}]"
122
+ )
123
+ report_lines.append(f"观测数: {len(self.dmu_names)}")
124
+ report_lines.append("")
125
+
126
+ table_rows = []
127
+ for index, dmu_name in enumerate(self.dmu_names):
128
+ table_rows.append([
129
+ dmu_name,
130
+ self.entities[index],
131
+ self.periods[index],
132
+ f"{round_score(self.average_scores[index]):.{SCORE_DECIMALS}f}",
133
+ str(int(self.window_counts[index])),
134
+ str(int(self.ranks[index])),
135
+ ])
136
+ report_lines.append(format_table(
137
+ ["DMU", "实体", "期别", "平均得分", "窗口数", "排名"], table_rows
138
+ ))
139
+ report_lines.append("")
140
+
141
+ efficient_names = [self.dmu_names[i] for i in np.flatnonzero(self.efficiency_mask)]
142
+ report_lines.append(
143
+ f"窗口平均有效观测共 {len(efficient_names)} 个: "
144
+ f"{'、'.join(efficient_names) if efficient_names else '无'}"
145
+ )
146
+ report_lines.append(
147
+ "说明: 得分为观测在包含它的所有窗口中的投入导向效率均值;"
148
+ "窗口数表示参与平均的窗口数量"
149
+ )
150
+ if column_names.undesirable_output_columns:
151
+ report_lines.append("说明: 非期望产出按投入方向处理(越少越好)")
152
+ report_lines.extend(f"提示: {note}" for note in self.notes[:10])
153
+ return "\n".join(report_lines)
154
+
155
+
156
+ class WindowAnalysisModel:
157
+ """窗口分析求解器(投入导向径向)。"""
158
+
159
+ def __init__(self, window_width: int = 3, returns_to_scale: str = "crs",
160
+ efficiency_tolerance: float = EFFICIENCY_TOLERANCE):
161
+ if not isinstance(window_width, int) or window_width < 2:
162
+ raise ValueError("window_width 必须为不小于 2 的整数")
163
+ returns_to_scale = returns_to_scale.lower()
164
+ if returns_to_scale not in ("crs", "vrs"):
165
+ raise ValueError("returns_to_scale 只能取 'crs' 或 'vrs'")
166
+ if efficiency_tolerance <= 0:
167
+ raise ValueError("efficiency_tolerance 必须为正数")
168
+ self.window_width = window_width
169
+ self.returns_to_scale = returns_to_scale
170
+ self.efficiency_tolerance = float(efficiency_tolerance)
171
+
172
+ def solve(self, data: DEAData) -> WindowAnalysisResult:
173
+ """对面板执行窗口分析。
174
+
175
+ 处理逻辑:按时间排序期别 → 滑动窗口 → 每个窗口内求所有观测的投入导向
176
+ 径向效率 → 对每个观测跨窗口取平均。
177
+ """
178
+ periods = sorted(set(data.periods))
179
+ if not periods or any(not period for period in periods):
180
+ raise ValueError("窗口分析需要非空的期别列")
181
+ if any(not entity for entity in data.entities):
182
+ raise ValueError("窗口分析需要非空的实体列")
183
+ if len(periods) < self.window_width:
184
+ raise ValueError(
185
+ f"期别数 {len(periods)} 小于窗口宽度 {self.window_width}"
186
+ )
187
+
188
+ n_undesirable = data.undesirable_output_matrix.shape[0]
189
+ model_inputs = (
190
+ np.vstack([data.input_matrix, data.undesirable_output_matrix])
191
+ if n_undesirable else data.input_matrix
192
+ )
193
+ outputs = data.desirable_output_matrix
194
+ period_array = np.asarray(data.periods)
195
+ windows = [
196
+ periods[start:start + self.window_width]
197
+ for start in range(len(periods) - self.window_width + 1)
198
+ ]
199
+ score_sums = np.zeros(len(data.dmu_names))
200
+ score_counts = np.zeros(len(data.dmu_names), dtype=int)
201
+ for window in windows:
202
+ reference_indices = np.flatnonzero(np.isin(period_array, window))
203
+ for dmu_index in reference_indices:
204
+ score_sums[dmu_index] += self._solve_radial(
205
+ model_inputs, outputs, reference_indices, int(dmu_index)
206
+ )
207
+ score_counts[dmu_index] += 1
208
+
209
+ average_scores = np.divide(
210
+ score_sums, score_counts,
211
+ out=np.full_like(score_sums, np.nan), where=score_counts > 0,
212
+ )
213
+ if np.any(np.isnan(average_scores)):
214
+ raise RuntimeError("部分观测不属于任何窗口,无法计算平均效率")
215
+ efficiency_mask = np.asarray(
216
+ average_scores >= 1.0 - self.efficiency_tolerance, dtype=bool
217
+ )
218
+ return WindowAnalysisResult(
219
+ dmu_names=data.dmu_names,
220
+ entities=list(data.entities),
221
+ periods=list(data.periods),
222
+ average_scores=average_scores,
223
+ window_counts=score_counts,
224
+ ranks=assign_ranks_with_ties(average_scores),
225
+ efficiency_mask=efficiency_mask,
226
+ returns_to_scale=self.returns_to_scale,
227
+ window_width=self.window_width,
228
+ notes=[],
229
+ )
230
+
231
+ def _solve_radial(self, model_inputs: np.ndarray, outputs: np.ndarray,
232
+ reference_indices: np.ndarray, dmu_index: int) -> float:
233
+ """求解指定参考集下的投入导向径向效率。"""
234
+ reference_inputs = model_inputs[:, reference_indices]
235
+ reference_outputs = outputs[:, reference_indices]
236
+ n_inputs = model_inputs.shape[0]
237
+ n_outputs = outputs.shape[0]
238
+ n_reference_dmus = reference_indices.size
239
+ n_variables = n_reference_dmus + 1
240
+ theta_column = n_reference_dmus
241
+ dmu_inputs = model_inputs[:, dmu_index]
242
+ dmu_outputs = outputs[:, dmu_index]
243
+
244
+ objective_coefficients = np.zeros(n_variables)
245
+ objective_coefficients[theta_column] = 1.0
246
+ inequality_matrix = np.zeros((n_inputs + n_outputs, n_variables))
247
+ inequality_rhs = np.zeros(n_inputs + n_outputs)
248
+ inequality_matrix[:n_inputs, :n_reference_dmus] = reference_inputs
249
+ inequality_matrix[:n_inputs, theta_column] = -dmu_inputs
250
+ inequality_matrix[n_inputs:, :n_reference_dmus] = -reference_outputs
251
+ inequality_rhs[n_inputs:] = -dmu_outputs
252
+
253
+ equality_matrix = None
254
+ equality_rhs = None
255
+ if self.returns_to_scale == "vrs":
256
+ equality_matrix = np.zeros((1, n_variables))
257
+ equality_matrix[0, :n_reference_dmus] = 1.0
258
+ equality_rhs = np.array([1.0])
259
+
260
+ solution = solve_linear_program(
261
+ objective_coefficients,
262
+ inequality_matrix=inequality_matrix, inequality_rhs=inequality_rhs,
263
+ equality_matrix=equality_matrix, equality_rhs=equality_rhs,
264
+ error_context=f"窗口分析径向求解失败(第 {dmu_index + 1} 个观测)",
265
+ )
266
+ return float(solution.x[theta_column])
267
+
268
+
269
+ def build_parser() -> argparse.ArgumentParser:
270
+ argument_parser = argparse.ArgumentParser(
271
+ description="窗口分析 Window Analysis(投入导向径向);"
272
+ "不带参数时使用脚本配置区",
273
+ formatter_class=argparse.RawDescriptionHelpFormatter,
274
+ epilog=(
275
+ "示例:\n"
276
+ " python window_analysis.py --demo\n"
277
+ " python window_analysis.py --demo --window 2 --returns-to-scale vrs\n"
278
+ ),
279
+ )
280
+ DATA_COMMAND_LINE.add_arguments(argument_parser)
281
+ argument_parser.add_argument("--window", type=int, default=None,
282
+ help="窗口宽度(期数);缺省用 WINDOW_WIDTH")
283
+ argument_parser.add_argument("--returns-to-scale", "--rts",
284
+ choices=("crs", "vrs"), default=None,
285
+ help="规模报酬: crs=不变, vrs=可变;缺省用 RETURNS_TO_SCALE")
286
+ argument_parser.add_argument("--tolerance", "--tol", type=float, default=None,
287
+ help=f"判定有效性的容差(默认 {EFFICIENCY_TOLERANCE})")
288
+ return argument_parser
289
+
290
+
291
+ def main(argv: Sequence[str] | None = None) -> int:
292
+ args = build_parser().parse_args(argv)
293
+ try:
294
+ prepared = DATA_COMMAND_LINE.prepare(args)
295
+ window_width = (
296
+ args.window if args.window is not None else WINDOW_WIDTH
297
+ )
298
+ returns_to_scale = (
299
+ args.returns_to_scale if args.returns_to_scale is not None
300
+ else RETURNS_TO_SCALE
301
+ )
302
+ efficiency_tolerance = (
303
+ args.tolerance if args.tolerance is not None else EFFICIENCY_TOLERANCE
304
+ )
305
+ model = WindowAnalysisModel(
306
+ window_width=window_width,
307
+ returns_to_scale=returns_to_scale,
308
+ efficiency_tolerance=efficiency_tolerance,
309
+ )
310
+ result = model.solve(prepared.data)
311
+ except (ValueError, RuntimeError) as exc:
312
+ print(f"错误: {exc}", file=sys.stderr)
313
+ return 1
314
+
315
+ print(result.render_report(
316
+ prepared.column_names,
317
+ source_description=prepared.source_description,
318
+ ))
319
+ if prepared.result_file:
320
+ try:
321
+ result.write_csv(prepared.result_file)
322
+ except OSError as exc:
323
+ print(f"错误: 无法写入 {prepared.result_file}: {exc}", file=sys.stderr)
324
+ return 1
325
+ print(f"\n结果已写入: {prepared.result_file}")
326
+ return 0
327
+
328
+
329
+ if __name__ == "__main__":
330
+ sys.exit(main())