File size: 12,639 Bytes
13a1073 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | """Family-aware fixed-panel protocol for the balanced Caption diagnostic."""
from __future__ import annotations
from typing import Any
PROTOCOL_VERSION = "caption-family-panel-v2"
NATURAL_PROTOCOL_VERSION = "caption-family-panel-v3-natural"
PANEL_SIZE = 16
SPLIT_ORDER = ("univar", "bivar", "multivar")
FAMILY_ORDER = ("overall", "pattern", "stability", "risk")
# Selection depends only on the public split and prompt family. It must never
# depend on a record's ground-truth values or on whether a metric is defined.
PANELS: dict[str, dict[str, tuple[str, ...]]] = {
"univar": {
"overall": (
"median",
"std",
"iqr",
"min",
"max",
"robust_slope",
"acf_lag1",
"dominant_period",
"seasonal_strength",
"spectral_entropy",
"mean_abs_change",
"num_peaks",
"num_troughs",
"max_peak_prominence",
"anomaly_count",
"change_point_count",
),
"pattern": (
"std",
"iqr",
"min",
"max",
"robust_slope",
"acf_lag1",
"dominant_period",
"seasonal_strength",
"spectral_entropy",
"mean_abs_change",
"sign_changes",
"num_peaks",
"num_troughs",
"max_peak_prominence",
"main_peak_position",
"main_trough_position",
),
"stability": (
"std",
"iqr",
"min",
"max",
"robust_slope",
"acf_lag1",
"dominant_period",
"seasonal_strength",
"spectral_entropy",
"mean_abs_change",
"sign_changes",
"num_peaks",
"num_troughs",
"max_peak_prominence",
"anomaly_count",
"change_point_count",
),
"risk": (
"median",
"std",
"iqr",
"min",
"max",
"robust_slope",
"acf_lag1",
"spectral_entropy",
"mean_abs_change",
"sign_changes",
"max_peak_prominence",
"main_peak_position",
"main_trough_position",
"anomaly_count",
"strongest_anomaly_position",
"change_point_count",
),
},
"bivar": {
"overall": (
"mean_x",
"mean_y",
"std_x",
"std_y",
"beta_x",
"beta_y",
"r2_x",
"r2_y",
"pearson_raw",
"pearson_detrended",
"period_x",
"period_y",
"power_ratio_x",
"power_ratio_y",
"vol_corr",
"corr_structure_stability",
),
"pattern": (
"beta_x",
"beta_y",
"pearson_raw",
"pearson_detrended",
"period_x",
"period_y",
"power_ratio_x",
"power_ratio_y",
"spectral_entropy_x",
"spectral_entropy_y",
"acf_lag1_x",
"acf_lag1_y",
"ccf_peak_lag",
"ccf_peak_value",
"vol_corr",
"corr_structure_stability",
),
"stability": (
"acf_lag1_x",
"acf_lag1_y",
"spectral_entropy_x",
"spectral_entropy_y",
"r2_x",
"r2_y",
"power_ratio_x",
"power_ratio_y",
"pearson_raw",
"pearson_detrended",
"change_point_count_x",
"change_point_count_y",
"corr_structure_stability",
"vol_corr_std",
"pc1_period_strength",
"pc1_spectral_entropy",
),
"risk": (
"beta_x",
"beta_y",
"mean_abs_change_x",
"mean_abs_change_y",
"pearson_raw",
"anomaly_ratio_x",
"anomaly_ratio_y",
"pc1_anomaly_ratio",
"pc1_max_abs_z",
"change_point_count_x",
"change_point_count_y",
"joint_extreme_ratio",
"tail_concordance",
"vol_corr",
"vol_corr_std",
"corr_structure_stability",
),
},
"multivar": {
"overall": (
"pca_k",
"pca_expl_ratio_1",
"effective_rank",
"sys_sync_avg_r2_topk",
"sys_sync_std_r2_topk",
"sync_ratio",
"leader_ratio",
"lag_mean",
"pc1_trend_r2",
"pc1_regime_shift",
"pc1_period_strength",
"pc1_seasonality_strength",
"pc1_mean_abs_change",
"volatility_correlation_mean",
"corr_structure_stability",
"mahal_outlier_ratio",
),
"pattern": (
"pca_k",
"pca_expl_ratio_1",
"effective_rank",
"loading_ipr_pc1",
"r2_topk_skew",
"sys_sync_avg_r2_topk",
"sys_sync_std_r2_topk",
"sync_ratio",
"leader_ratio",
"lag_mean",
"lag_range",
"pc1_trend_r2",
"pc1_period_strength",
"pc1_seasonality_strength",
"seasonality_consistency",
"pc1_mean_abs_change",
),
"stability": (
"pca_expl_ratio_1",
"effective_rank",
"sys_sync_avg_r2_topk",
"sys_sync_std_r2_topk",
"corr_structure_stability",
"corr_dynamics_mean_std",
"corr_frobenius_change_mean",
"sync_stability",
"volatility_correlation_mean",
"volatility_correlation_std",
"volatility_sync_index",
"pc1_trend_r2",
"pc1_regime_shift",
"pc1_period_strength",
"pc1_seasonality_strength",
"seasonality_consistency",
),
"risk": (
"pca_expl_ratio_1",
"effective_rank",
"sys_sync_avg_r2_topk",
"sys_sync_std_r2_topk",
"pc1_trend_r2",
"pc1_regime_shift",
"pc1_anomaly_ratio",
"pc1_max_abs_z",
"mahal_outlier_ratio",
"mahal_max_distance",
"corr_structure_stability",
"corr_dynamics_mean_std",
"corr_frobenius_change_mean",
"volatility_correlation_mean",
"volatility_correlation_max",
"high_vol_correlation_ratio",
),
},
}
PERCENT_TO_FRACTION_KEYS = frozenset(
{
"acf_lag1",
"seasonal_strength",
"spectral_entropy",
"r2_x",
"r2_y",
"pearson_raw",
"pearson_detrended",
"power_ratio_x",
"power_ratio_y",
"vol_corr",
"corr_structure_stability",
"spectral_entropy_x",
"spectral_entropy_y",
"acf_lag1_x",
"acf_lag1_y",
"ccf_peak_value",
"vol_corr_std",
"pc1_period_strength",
"pc1_spectral_entropy",
"anomaly_ratio_x",
"anomaly_ratio_y",
"pc1_anomaly_ratio",
"joint_extreme_ratio",
"tail_concordance",
"pca_expl_ratio_1",
"sys_sync_avg_r2_topk",
"sys_sync_std_r2_topk",
"sync_ratio",
"leader_ratio",
"pc1_trend_r2",
"pc1_regime_shift",
"pc1_seasonality_strength",
"volatility_correlation_mean",
"mahal_outlier_ratio",
"seasonality_consistency",
"sync_stability",
"volatility_correlation_std",
"volatility_sync_index",
"volatility_correlation_max",
"high_vol_correlation_ratio",
}
)
# These clarify collisions in the short shared metric-definitions file without
# changing the underlying scorer key or ground truth.
DEFINITION_OVERRIDES = {
"corr_structure_stability": "滚动相关结构的稳定性",
"sync_stability": "系统同步关系随时间的稳定性",
"vol_corr_std": "滚动波动率相关系数的标准差",
}
PROMPT_APPENDIX = """
为回答上述问题,请先计算下面全部 {panel_size} 个相关统计属性(key — 含义):
{metric_lines}{scope_note}
输出要求:
1. 先输出“统计属性”,每个 key 单独一行并严格使用:
[STAT]<metric_key> = <number>[/STAT]
2. 必须依次报告上面全部 {panel_size} 个 key;metric_key 必须逐字复制。
3. 若属性对该序列不适用或无法定义,使用:
[STAT]<metric_key> = NA[/STAT]
4. number 只能使用十进制或科学计数法,不写单位;比例统一写成 0–1 小数。
5. 随后输出“分析描述”,围绕开头问题综合解释关键现象;不要逐项复述统计量。
6. 不要复述原始时间序列。
"""
NATURAL_PROMPT_APPENDIX = """
请围绕开头的问题,从{analysis_aspects}等角度分析上述时间序列。{scope_note}请直接输出连贯的分析描述,并将有助于判断的关键数值自然融入正文,解释其反映的主要现象和变量关系;不要逐项列出统计量,不要使用表格或清单,不要展示计算过程,也不要复述原始时间序列。
"""
def panel_for(split: str, family: str) -> tuple[str, ...]:
try:
panel = PANELS[split][family]
except KeyError as error:
raise ValueError(f"Unknown split/family: {split!r}/{family!r}") from error
if len(panel) != PANEL_SIZE or len(set(panel)) != PANEL_SIZE:
raise AssertionError(f"Invalid panel size or duplicate key: {split}/{family}")
return panel
def metric_description(key: str, definitions: dict[str, str]) -> str:
description = DEFINITION_OVERRIDES.get(key, definitions.get(key))
if not isinstance(description, str) or not description.strip():
raise ValueError(f"Missing metric definition for {key!r}")
return description.strip()
def candidate_specs(
split: str,
family: str,
definitions: dict[str, str],
) -> list[dict[str, Any]]:
return [
{
"key": key,
"description": metric_description(key, definitions),
"percent_to_fraction": key in PERCENT_TO_FRACTION_KEYS,
"allow_na": True,
}
for key in panel_for(split, family)
]
def build_prompt(
source_prompt: str,
split: str,
family: str,
definitions: dict[str, str],
) -> str:
if "<ts> </ts>" not in source_prompt and "<ts></ts>" not in source_prompt:
raise ValueError("Source prompt does not contain a time-series placeholder")
specs = candidate_specs(split, family, definitions)
metric_lines = "\n".join(
f"- `{spec['key']}` — {spec['description']}" for spec in specs
)
scope_note = ""
if split == "bivar":
scope_note = "\n其中 X=Series1,Y=Series2。"
elif split == "multivar":
scope_note = "\nSeries1、Series2、……对应输入中的各个通道。"
appendix = PROMPT_APPENDIX.format(
panel_size=PANEL_SIZE,
metric_lines=metric_lines,
scope_note=scope_note,
)
return source_prompt.rstrip() + appendix
def build_natural_prompt(
source_prompt: str,
split: str,
family: str,
definitions: dict[str, str],
) -> str:
if "<ts> </ts>" not in source_prompt and "<ts></ts>" not in source_prompt:
raise ValueError("Source prompt does not contain a time-series placeholder")
specs = candidate_specs(split, family, definitions)
analysis_aspects = "、".join(spec["description"] for spec in specs)
scope_note = ""
if split == "bivar":
scope_note = "其中 X=Series1,Y=Series2。"
elif split == "multivar":
scope_note = "Series1、Series2、……对应输入中的各个通道。"
appendix = NATURAL_PROMPT_APPENDIX.format(
analysis_aspects=analysis_aspects,
scope_note=scope_note,
)
return source_prompt.rstrip() + appendix
def validate_protocol(definitions: dict[str, str]) -> None:
if tuple(PANELS) != SPLIT_ORDER:
raise AssertionError("Split order is not frozen")
for split in SPLIT_ORDER:
if tuple(PANELS[split]) != FAMILY_ORDER:
raise AssertionError(f"Family order is not frozen for {split}")
for family in FAMILY_ORDER:
for key in panel_for(split, family):
metric_description(key, definitions)
|