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.
malmquist_index.py ADDED
@@ -0,0 +1,596 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """Malmquist 与 Malmquist-Luenberger 生产率指数脚本。
4
+
5
+ 面板要求:同一实体在每个期别都有观测(平衡面板);使用期别列与实体列。
6
+
7
+ 标准 Malmquist(Färe et al. 1994,输出导向,CRS/VRS):
8
+ D_o^s(x,y) = 1/φ,其中 φ = max{φ: X_s λ ≤ x, Y_s λ ≥ φ y}
9
+ M = sqrt[(D^t(x_{t+1})/D^t(x_t)) · (D^{t+1}(x_{t+1})/D^{t+1}(x_t))]
10
+ EC = D^{t+1}(x_{t+1}) / D^t(x_t)
11
+ TC = M / EC
12
+ M > 1 表示生产率提高。
13
+
14
+ Malmquist-Luenberger(Chung, Färe & Grosskopf 1997):
15
+ 方向 g=(y, -b),DDF β = max{β: X_s λ ≤ x, Y_s λ ≥ (1+β)y,
16
+ B_s λ ≤ (1-β)b}
17
+ ML = sqrt[((1+β^t_t)/(1+β^t_{t+1})) ·
18
+ ((1+β^{t+1}_{t+1})/(1+β^{t+1}_t))]
19
+ MLECH = (1+β^t_t)/(1+β^{t+1}_{t+1})
20
+ MLTCH = ML / MLECH
21
+ ML > 1 表示环境生产率提高。
22
+ """
23
+
24
+ import argparse
25
+ import os
26
+ import sys
27
+ from collections.abc import Sequence
28
+ from dataclasses import dataclass, field
29
+
30
+ import numpy as np
31
+
32
+ from dea_core import (
33
+ ColumnNames,
34
+ DataCommandLine,
35
+ DataSettings,
36
+ DEAData,
37
+ EFFICIENCY_TOLERANCE,
38
+ MIN_SCALING_FACTOR,
39
+ SCORE_DECIMALS,
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
+
57
+ INDEX_TYPE = "ml" # "malmquist"=标准 Malmquist,"ml"=Malmquist-Luenberger
58
+ FRONTIER_MODE = "adjacent" # "adjacent"=相邻期前沿,"global"=全局前沿
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
+ result_file=RESULT_FILE,
74
+ ),
75
+ script_directory=os.path.dirname(os.path.abspath(__file__)),
76
+ )
77
+
78
+
79
+ @dataclass
80
+ class PanelStructure:
81
+ """平衡面板的期别、实体与按期别分组的矩阵。"""
82
+
83
+ entities: list[str]
84
+ periods: list[str]
85
+ input_matrices: list[np.ndarray]
86
+ desirable_output_matrices: list[np.ndarray]
87
+ undesirable_output_matrices: list[np.ndarray]
88
+ global_inputs: np.ndarray
89
+ global_outputs: np.ndarray
90
+ global_bad_outputs: np.ndarray
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class DistanceContext:
95
+ """参考期矩阵与被评价点向量,供距离函数使用。"""
96
+
97
+ reference_inputs: np.ndarray
98
+ reference_outputs: np.ndarray
99
+ reference_bad_outputs: np.ndarray
100
+ point_inputs: np.ndarray
101
+ point_outputs: np.ndarray
102
+ point_bad_outputs: np.ndarray
103
+
104
+
105
+ @dataclass
106
+ class MalmquistResult:
107
+ """Malmquist / ML 指数结果。"""
108
+
109
+ entities: list[str]
110
+ period_from: list[str]
111
+ period_to: list[str]
112
+ malmquist: np.ndarray
113
+ efficiency_change: np.ndarray
114
+ technical_change: np.ndarray
115
+ valid_mask: np.ndarray
116
+ index_type: str
117
+ frontier_mode: str
118
+ returns_to_scale: str
119
+ notes: list[str] = field(default_factory=list)
120
+
121
+ def to_records(self) -> list[dict[str, object]]:
122
+ """把每个实体-期段展开成一条 CSV 记录。"""
123
+ records = []
124
+ for row_index, entity in enumerate(self.entities):
125
+ records.append({
126
+ "entity": entity,
127
+ "period_from": self.period_from[row_index],
128
+ "period_to": self.period_to[row_index],
129
+ "malmquist": (
130
+ None if not self.valid_mask[row_index]
131
+ else round_score(self.malmquist[row_index])
132
+ ),
133
+ "efficiency_change": (
134
+ None if not self.valid_mask[row_index]
135
+ else round_score(self.efficiency_change[row_index])
136
+ ),
137
+ "technical_change": (
138
+ None if not self.valid_mask[row_index]
139
+ else round_score(self.technical_change[row_index])
140
+ ),
141
+ "valid": int(self.valid_mask[row_index]),
142
+ })
143
+ return records
144
+
145
+ def write_csv(self, path: str) -> None:
146
+ """写出 UTF-8-BOM 编码的结果 CSV。"""
147
+ write_csv_records(path, self.to_records())
148
+
149
+ def render_report(self, column_names: ColumnNames,
150
+ source_description: str | None = None) -> str:
151
+ """生成控制台报表文本。"""
152
+ returns_to_scale_description = (
153
+ "CRS 规模报酬不变" if self.returns_to_scale == "crs" else "VRS 规模报酬可变"
154
+ )
155
+ index_title = (
156
+ "Malmquist-Luenberger(ML)" if self.index_type == "ml"
157
+ else "Malmquist"
158
+ )
159
+ frontier_description = (
160
+ "全局前沿" if self.frontier_mode == "global" else "相邻期前沿"
161
+ )
162
+ report_lines = [
163
+ f"模型: {index_title} 生产率指数 | {frontier_description} | "
164
+ f"输出方向 | {returns_to_scale_description}"
165
+ ]
166
+ if source_description:
167
+ report_lines.append(f"数据: {source_description}")
168
+ report_lines.append(
169
+ f"变量: 投入[{'、'.join(column_names.input_columns)}] | "
170
+ f"期望产出[{'、'.join(column_names.desirable_output_columns)}] | "
171
+ f"非期望产出[{'、'.join(column_names.undesirable_output_columns) or '无'}]"
172
+ )
173
+ report_lines.append(
174
+ f"实体数: {len(set(self.entities))} | 指数记录数: {len(self.malmquist)}"
175
+ )
176
+ report_lines.append("")
177
+
178
+ table_rows = []
179
+ for row_index, entity in enumerate(self.entities):
180
+ if self.valid_mask[row_index]:
181
+ malmquist_value = round_score(self.malmquist[row_index])
182
+ efficiency_value = round_score(self.efficiency_change[row_index])
183
+ technical_value = round_score(self.technical_change[row_index])
184
+ values = [
185
+ f"{malmquist_value:.{SCORE_DECIMALS}f}",
186
+ f"{efficiency_value:.{SCORE_DECIMALS}f}",
187
+ f"{technical_value:.{SCORE_DECIMALS}f}",
188
+ ]
189
+ else:
190
+ values = ["-", "-", "-"]
191
+ table_rows.append([
192
+ entity,
193
+ f"{self.period_from[row_index]}→{self.period_to[row_index]}",
194
+ *values,
195
+ ])
196
+ report_lines.append(format_table(
197
+ ["实体", "期段", "M/ML", "EC", "TC"], table_rows
198
+ ))
199
+ report_lines.append("")
200
+ valid_malmquist = self.malmquist[self.valid_mask]
201
+ if valid_malmquist.size:
202
+ average_malmquist = round_score(float(np.mean(valid_malmquist)))
203
+ report_lines.append(
204
+ f"平均 M/ML: {average_malmquist:.{SCORE_DECIMALS}f} | "
205
+ f"有效指数 {valid_malmquist.size}/{self.malmquist.size}"
206
+ )
207
+ report_lines.append(
208
+ "说明: M/ML > 1 表示生产率提高;EC 为效率变化,TC 为技术变化;"
209
+ "混合期径向 LP 不可行时留空"
210
+ )
211
+ if self.index_type == "ml":
212
+ report_lines.append("说明: ML 使用方向 g=(y, -b),同时扩张期望产出、缩减非期望产出")
213
+ else:
214
+ report_lines.append("说明: 标准 Malmquist 不纳入非期望产出")
215
+ report_lines.extend(f"提示: {note}" for note in self.notes[:10])
216
+ return "\n".join(report_lines)
217
+
218
+
219
+ class MalmquistModel:
220
+ """Malmquist / Malmquist-Luenberger 指数求解器。"""
221
+
222
+ def __init__(self, index_type: str = "ml", returns_to_scale: str = "crs",
223
+ frontier_mode: str = "adjacent",
224
+ efficiency_tolerance: float = EFFICIENCY_TOLERANCE):
225
+ index_type = index_type.lower()
226
+ frontier_mode = frontier_mode.lower()
227
+ returns_to_scale = returns_to_scale.lower()
228
+ if index_type not in ("malmquist", "ml"):
229
+ raise ValueError("index_type 只能取 'malmquist' 或 'ml'")
230
+ if frontier_mode not in ("adjacent", "global"):
231
+ raise ValueError("frontier_mode 只能取 'adjacent' 或 'global'")
232
+ if returns_to_scale not in ("crs", "vrs"):
233
+ raise ValueError("returns_to_scale 只能取 'crs' 或 'vrs'")
234
+ if efficiency_tolerance <= 0:
235
+ raise ValueError("efficiency_tolerance 必须为正数")
236
+ self.index_type = index_type
237
+ self.frontier_mode = frontier_mode
238
+ self.returns_to_scale = returns_to_scale
239
+ self.efficiency_tolerance = float(efficiency_tolerance)
240
+
241
+ def solve(self, data: DEAData) -> MalmquistResult:
242
+ """计算所有实体从 t 到 t+1 的相邻期指数。
243
+
244
+ 处理逻辑:校验平衡面板 → 按期别整理矩阵 → 对每个实体-期段计算四个
245
+ 距离函数 → 汇总 M/ML、EC、TC。
246
+ """
247
+ panel = self._build_panel(data)
248
+ if len(panel.periods) < 2:
249
+ raise ValueError("Malmquist 至少需要 2 个期别")
250
+ if self.index_type == "ml" and panel.undesirable_output_matrices[0].shape[0] == 0:
251
+ raise ValueError("Malmquist-Luenberger 至少需要 1 个非期望产出列")
252
+
253
+ entities, period_from, period_to = [], [], []
254
+ malmquist_values, efficiency_values, technical_values, valid_flags = [], [], [], []
255
+ notes: list[str] = []
256
+ for period_index in range(len(panel.periods) - 1):
257
+ for entity_index, entity in enumerate(panel.entities):
258
+ entities.append(entity)
259
+ period_from.append(panel.periods[period_index])
260
+ period_to.append(panel.periods[period_index + 1])
261
+ if self.index_type == "ml":
262
+ values = self._ml_index(panel, period_index, entity_index)
263
+ else:
264
+ values = self._malmquist_index(panel, period_index, entity_index)
265
+ if values is None:
266
+ malmquist_values.append(np.nan)
267
+ efficiency_values.append(np.nan)
268
+ technical_values.append(np.nan)
269
+ valid_flags.append(False)
270
+ notes.append(
271
+ f"{entity} {period_from[-1]}→{period_to[-1]} 的距离函数不可行"
272
+ )
273
+ else:
274
+ malmquist_values.append(values[0])
275
+ efficiency_values.append(values[1])
276
+ technical_values.append(values[2])
277
+ valid_flags.append(True)
278
+
279
+ return MalmquistResult(
280
+ entities=entities,
281
+ period_from=period_from,
282
+ period_to=period_to,
283
+ malmquist=np.asarray(malmquist_values, dtype=float),
284
+ efficiency_change=np.asarray(efficiency_values, dtype=float),
285
+ technical_change=np.asarray(technical_values, dtype=float),
286
+ valid_mask=np.asarray(valid_flags, dtype=bool),
287
+ index_type=self.index_type,
288
+ frontier_mode=self.frontier_mode,
289
+ returns_to_scale=self.returns_to_scale,
290
+ notes=notes,
291
+ )
292
+
293
+ def _build_panel(self, data: DEAData) -> PanelStructure:
294
+ """校验平衡面板并按期别整理矩阵。"""
295
+ periods = sorted(set(data.periods))
296
+ entities = sorted(set(data.entities))
297
+ if not periods or not entities or any(not value for value in periods + entities):
298
+ raise ValueError("Malmquist 需要非空的期别列与实体列")
299
+ if len(entities) < 2:
300
+ raise ValueError("Malmquist 至少需要 2 个实体")
301
+
302
+ row_lookup: dict[tuple[str, str], int] = {}
303
+ for row_index, (period, entity) in enumerate(zip(data.periods, data.entities)):
304
+ key = (period, entity)
305
+ if key in row_lookup:
306
+ raise ValueError(f"实体 '{entity}' 在期别 '{period}' 存在重复观测")
307
+ row_lookup[key] = row_index
308
+ expected_keys = {(period, entity) for period in periods for entity in entities}
309
+ missing_keys = expected_keys - set(row_lookup)
310
+ if missing_keys:
311
+ preview = sorted(missing_keys)[:5]
312
+ raise ValueError(f"面板不平衡,缺少实体-期别观测: {preview}")
313
+
314
+ input_matrices, desirable_matrices, undesirable_matrices = [], [], []
315
+ for period in periods:
316
+ indices = [row_lookup[(period, entity)] for entity in entities]
317
+ input_matrices.append(data.input_matrix[:, indices])
318
+ desirable_matrices.append(data.desirable_output_matrix[:, indices])
319
+ undesirable_matrices.append(data.undesirable_output_matrix[:, indices])
320
+ return PanelStructure(
321
+ entities=entities,
322
+ periods=periods,
323
+ input_matrices=input_matrices,
324
+ desirable_output_matrices=desirable_matrices,
325
+ undesirable_output_matrices=undesirable_matrices,
326
+ global_inputs=np.hstack(input_matrices),
327
+ global_outputs=np.hstack(desirable_matrices),
328
+ global_bad_outputs=np.hstack(undesirable_matrices),
329
+ )
330
+
331
+ def _malmquist_index(self, panel: PanelStructure, period_index: int,
332
+ entity_index: int) -> tuple[float, float, float] | None:
333
+ """计算标准 Malmquist 的 M、EC、TC。"""
334
+ t0 = period_index
335
+ t1 = period_index + 1
336
+ d_tt = self._output_distance(
337
+ self._distance_context(panel, t0, t0, entity_index)
338
+ )
339
+ d_t1t1 = self._output_distance(
340
+ self._distance_context(panel, t1, t1, entity_index)
341
+ )
342
+ if self.frontier_mode == "global":
343
+ d_g_t = self._output_distance(
344
+ self._global_context(panel, t0, entity_index)
345
+ )
346
+ d_g_t1 = self._output_distance(
347
+ self._global_context(panel, t1, entity_index)
348
+ )
349
+ distances = [d_tt, d_t1t1, d_g_t, d_g_t1]
350
+ if any(value is None or value <= 0 for value in distances):
351
+ return None
352
+ malmquist = float(d_g_t1 / d_g_t)
353
+ else:
354
+ d_tt1 = self._output_distance(
355
+ self._distance_context(panel, t0, t1, entity_index)
356
+ )
357
+ d_t1t = self._output_distance(
358
+ self._distance_context(panel, t1, t0, entity_index)
359
+ )
360
+ distances = [d_tt, d_t1t1, d_tt1, d_t1t]
361
+ if any(value is None or value <= 0 for value in distances):
362
+ return None
363
+ malmquist = float(np.sqrt((d_tt1 / d_tt) * (d_t1t1 / d_t1t)))
364
+ efficiency_change = float(d_t1t1 / d_tt)
365
+ technical_change = float(malmquist / efficiency_change) if efficiency_change > 0 else np.nan
366
+ return malmquist, efficiency_change, technical_change
367
+
368
+ def _ml_index(self, panel: PanelStructure, period_index: int,
369
+ entity_index: int) -> tuple[float, float, float] | None:
370
+ """计算 Malmquist-Luenberger 的 ML、MLECH、MLTCH。"""
371
+ t0 = period_index
372
+ t1 = period_index + 1
373
+ dtt = self._directional_distance(
374
+ self._distance_context(panel, t0, t0, entity_index)
375
+ )
376
+ dt1t1 = self._directional_distance(
377
+ self._distance_context(panel, t1, t1, entity_index)
378
+ )
379
+ if self.frontier_mode == "global":
380
+ d_g_t = self._directional_distance(
381
+ self._global_context(panel, t0, entity_index)
382
+ )
383
+ d_g_t1 = self._directional_distance(
384
+ self._global_context(panel, t1, entity_index)
385
+ )
386
+ distances = [dtt, dt1t1, d_g_t, d_g_t1]
387
+ if any(value is None for value in distances):
388
+ return None
389
+ malmquist = float((1.0 + d_g_t) / (1.0 + d_g_t1))
390
+ else:
391
+ dtt1 = self._directional_distance(
392
+ self._distance_context(panel, t0, t1, entity_index)
393
+ )
394
+ dt1t = self._directional_distance(
395
+ self._distance_context(panel, t1, t0, entity_index)
396
+ )
397
+ distances = [dtt, dt1t1, dtt1, dt1t]
398
+ if any(value is None for value in distances):
399
+ return None
400
+ malmquist = float(np.sqrt(
401
+ ((1.0 + dtt) / (1.0 + dtt1)) * ((1.0 + dt1t1) / (1.0 + dt1t))
402
+ ))
403
+ efficiency_change = float((1.0 + dtt) / (1.0 + dt1t1))
404
+ technical_change = float(malmquist / efficiency_change) if efficiency_change > 0 else np.nan
405
+ return malmquist, efficiency_change, technical_change
406
+
407
+ def _distance_context(self, panel: PanelStructure, reference_period: int,
408
+ point_period: int, entity_index: int) -> DistanceContext:
409
+ """构造参考期矩阵与被评价点向量。"""
410
+ return DistanceContext(
411
+ reference_inputs=panel.input_matrices[reference_period],
412
+ reference_outputs=panel.desirable_output_matrices[reference_period],
413
+ reference_bad_outputs=panel.undesirable_output_matrices[reference_period],
414
+ point_inputs=panel.input_matrices[point_period][:, entity_index],
415
+ point_outputs=panel.desirable_output_matrices[point_period][:, entity_index],
416
+ point_bad_outputs=panel.undesirable_output_matrices[point_period][:, entity_index],
417
+ )
418
+
419
+ def _global_context(self, panel: PanelStructure, point_period: int,
420
+ entity_index: int) -> DistanceContext:
421
+ """构造全局参考集与被评价点向量。"""
422
+ return DistanceContext(
423
+ reference_inputs=panel.global_inputs,
424
+ reference_outputs=panel.global_outputs,
425
+ reference_bad_outputs=panel.global_bad_outputs,
426
+ point_inputs=panel.input_matrices[point_period][:, entity_index],
427
+ point_outputs=panel.desirable_output_matrices[point_period][:, entity_index],
428
+ point_bad_outputs=panel.undesirable_output_matrices[point_period][:, entity_index],
429
+ )
430
+
431
+ def _output_distance(self, context: DistanceContext) -> float | None:
432
+ """构造输出距离函数 D_o = 1/φ。"""
433
+ reference_inputs = context.reference_inputs
434
+ reference_outputs = context.reference_outputs
435
+ x = context.point_inputs
436
+ y = context.point_outputs
437
+ n_inputs = reference_inputs.shape[0]
438
+ n_outputs = reference_outputs.shape[0]
439
+ n_reference_dmus = reference_inputs.shape[1]
440
+ n_variables = n_reference_dmus + 1
441
+ phi_column = n_reference_dmus
442
+ objective_coefficients = np.zeros(n_variables)
443
+ objective_coefficients[phi_column] = -1.0
444
+
445
+ n_constraints = n_inputs + n_outputs
446
+ inequality_matrix = np.zeros((n_constraints, n_variables))
447
+ inequality_rhs = np.zeros(n_constraints)
448
+ inequality_matrix[:n_inputs, :n_reference_dmus] = reference_inputs
449
+ inequality_rhs[:n_inputs] = x
450
+ output_rows = slice(n_inputs, n_inputs + n_outputs)
451
+ inequality_matrix[output_rows, :n_reference_dmus] = -reference_outputs
452
+ inequality_matrix[output_rows, phi_column] = y
453
+ inequality_rhs[output_rows] = 0.0
454
+
455
+ equality_matrix, equality_rhs = self._convexity_constraint(n_variables, n_reference_dmus)
456
+ solution = solve_linear_program(
457
+ objective_coefficients,
458
+ inequality_matrix=inequality_matrix, inequality_rhs=inequality_rhs,
459
+ equality_matrix=equality_matrix, equality_rhs=equality_rhs,
460
+ error_context="Malmquist 输出距离函数求解失败",
461
+ require_success=False,
462
+ )
463
+ if not solution.success:
464
+ return None
465
+ phi = float(solution.x[phi_column])
466
+ if phi <= MIN_SCALING_FACTOR:
467
+ return None
468
+ return 1.0 / phi
469
+
470
+ def _directional_distance(self, context: DistanceContext) -> float | None:
471
+ """构造方向 g=(y,-b) 的 DDF β。"""
472
+ reference_inputs = context.reference_inputs
473
+ reference_outputs = context.reference_outputs
474
+ reference_bad_outputs = context.reference_bad_outputs
475
+ x = context.point_inputs
476
+ y = context.point_outputs
477
+ b = context.point_bad_outputs
478
+ n_inputs = reference_inputs.shape[0]
479
+ n_outputs = reference_outputs.shape[0]
480
+ n_bad_outputs = reference_bad_outputs.shape[0]
481
+ n_reference_dmus = reference_inputs.shape[1]
482
+ n_variables = n_reference_dmus + 1
483
+ beta_column = n_reference_dmus
484
+ objective_coefficients = np.zeros(n_variables)
485
+ objective_coefficients[beta_column] = -1.0
486
+ variable_bounds = (
487
+ [(0.0, None)] * n_reference_dmus + [(-1.0 + 1e-9, None)]
488
+ )
489
+
490
+ n_constraints = n_inputs + n_outputs + n_bad_outputs
491
+ inequality_matrix = np.zeros((n_constraints, n_variables))
492
+ inequality_rhs = np.zeros(n_constraints)
493
+ inequality_matrix[:n_inputs, :n_reference_dmus] = reference_inputs
494
+ inequality_rhs[:n_inputs] = x
495
+
496
+ good_rows = slice(n_inputs, n_inputs + n_outputs)
497
+ inequality_matrix[good_rows, :n_reference_dmus] = -reference_outputs
498
+ inequality_matrix[good_rows, beta_column] = y
499
+ inequality_rhs[good_rows] = -y
500
+
501
+ bad_rows = slice(n_inputs + n_outputs, n_constraints)
502
+ inequality_matrix[bad_rows, :n_reference_dmus] = reference_bad_outputs
503
+ inequality_matrix[bad_rows, beta_column] = b
504
+ inequality_rhs[bad_rows] = b
505
+
506
+ equality_matrix, equality_rhs = self._convexity_constraint(n_variables, n_reference_dmus)
507
+ solution = solve_linear_program(
508
+ objective_coefficients,
509
+ inequality_matrix=inequality_matrix, inequality_rhs=inequality_rhs,
510
+ equality_matrix=equality_matrix, equality_rhs=equality_rhs,
511
+ variable_bounds=variable_bounds,
512
+ error_context="Malmquist-Luenberger 方向距离函数求解失败",
513
+ require_success=False,
514
+ )
515
+ if not solution.success:
516
+ return None
517
+ return float(solution.x[beta_column])
518
+
519
+ def _convexity_constraint(self, n_variables: int, n_reference_dmus: int
520
+ ) -> tuple[np.ndarray | None, np.ndarray | None]:
521
+ """构造 VRS 凸性约束。"""
522
+ if self.returns_to_scale == "crs":
523
+ return None, None
524
+ equality_matrix = np.zeros((1, n_variables))
525
+ equality_matrix[0, :n_reference_dmus] = 1.0
526
+ return equality_matrix, np.array([1.0])
527
+
528
+
529
+ def build_parser() -> argparse.ArgumentParser:
530
+ argument_parser = argparse.ArgumentParser(
531
+ description="Malmquist / Malmquist-Luenberger 生产率指数;"
532
+ "不带参数时使用脚本配置区",
533
+ formatter_class=argparse.RawDescriptionHelpFormatter,
534
+ epilog=(
535
+ "示例:\n"
536
+ " python malmquist_index.py --demo\n"
537
+ " python malmquist_index.py --demo --index malmquist\n"
538
+ ),
539
+ )
540
+ DATA_COMMAND_LINE.add_arguments(argument_parser)
541
+ argument_parser.add_argument("--index", choices=("malmquist", "ml"), default=None,
542
+ help="指数类型: malmquist 或 ml;缺省用 INDEX_TYPE")
543
+ argument_parser.add_argument("--frontier", choices=("adjacent", "global"),
544
+ default=None,
545
+ help="前沿口径: adjacent=相邻期, global=全局;"
546
+ "缺省用 FRONTIER_MODE")
547
+ argument_parser.add_argument("--returns-to-scale", "--rts",
548
+ choices=("crs", "vrs"), default=None,
549
+ help="规模报酬: crs=不变, vrs=可变;缺省用 RETURNS_TO_SCALE")
550
+ argument_parser.add_argument("--tolerance", "--tol", type=float, default=None,
551
+ help=f"数值容差(默认 {EFFICIENCY_TOLERANCE})")
552
+ return argument_parser
553
+
554
+
555
+ def main(argv: Sequence[str] | None = None) -> int:
556
+ args = build_parser().parse_args(argv)
557
+ try:
558
+ prepared = DATA_COMMAND_LINE.prepare(args)
559
+ index_type = args.index if args.index is not None else INDEX_TYPE
560
+ frontier_mode = (
561
+ args.frontier if args.frontier is not None else FRONTIER_MODE
562
+ )
563
+ returns_to_scale = (
564
+ args.returns_to_scale if args.returns_to_scale is not None
565
+ else RETURNS_TO_SCALE
566
+ )
567
+ efficiency_tolerance = (
568
+ args.tolerance if args.tolerance is not None else EFFICIENCY_TOLERANCE
569
+ )
570
+ model = MalmquistModel(
571
+ index_type=index_type,
572
+ returns_to_scale=returns_to_scale,
573
+ frontier_mode=frontier_mode,
574
+ efficiency_tolerance=efficiency_tolerance,
575
+ )
576
+ result = model.solve(prepared.data)
577
+ except (ValueError, RuntimeError) as exc:
578
+ print(f"错误: {exc}", file=sys.stderr)
579
+ return 1
580
+
581
+ print(result.render_report(
582
+ prepared.column_names,
583
+ source_description=prepared.source_description,
584
+ ))
585
+ if prepared.result_file:
586
+ try:
587
+ result.write_csv(prepared.result_file)
588
+ except OSError as exc:
589
+ print(f"错误: 无法写入 {prepared.result_file}: {exc}", file=sys.stderr)
590
+ return 1
591
+ print(f"\n结果已写入: {prepared.result_file}")
592
+ return 0
593
+
594
+
595
+ if __name__ == "__main__":
596
+ sys.exit(main())